<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mihir Deshpande on Medium]]></title>
        <description><![CDATA[Stories by Mihir Deshpande on Medium]]></description>
        <link>https://medium.com/@deshpande.mihir7?source=rss-a01eb589324b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EWs4xcVckNS3SqhCuljQJQ.jpeg</url>
            <title>Stories by Mihir Deshpande on Medium</title>
            <link>https://medium.com/@deshpande.mihir7?source=rss-a01eb589324b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:05:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deshpande.mihir7/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deepwalking in Clojure]]></title>
            <link>https://medium.com/@deshpande.mihir7/deepwalking-in-clojure-0b2c4eacd4e0?source=rss-a01eb589324b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b2c4eacd4e0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clojure]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Mihir Deshpande]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 10:40:08 GMT</pubDate>
            <atom:updated>2024-09-11T05:02:03.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y_aD5dwd02dWI8ph" /></figure><h3>Intuition</h3><p>If you were to guess the missing part of the sentence — “My name __ John Doe” what would you guess? Most people would answer this with an “is.” (A few interesting breeds would go for a “was” as well) You essentially guess a word that has the highest probability of being there. Interestingly enough, machines also work the same way. However, they don’t understand these words in their textual form. These words need to be converted into numbers for a machine to understand. How do we do it? The answer is Word embeddings.</p><p>Consider the below sentences -</p><ol><li>Hi, how are you?</li><li>Hello, how is it going?</li></ol><p>In this context, “Hi” and “Hello” carry the same meaning. If we were to organize words based on their semantic roles, “Hi” and “Hello” would naturally be grouped together.</p><p>This semantic similarity can be represented mathematically as well. If somehow plotted in an n-dimensional space, these words would be plotted closer to each other.</p><p>If n = 3, It would look something like this -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*Dl8QnOqH3jmjFGgfE_XoHQ.png" /></figure><p>Each word here must have an (x,y,z) coordinate. These sets of coordinates are nothing but Word Embeddings. By a technique called <em>Word2Vec</em>, we can transform these words into corresponding embeddings, so that these can be fed to a Neural Network.</p><p>We can apply the same logic to graphs as well, where the nodes that are in proximity would appear closer in the vector space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*lPlX7Xg-7lUE_UR81XQmlw.png" /></figure><p>Word2Vec when applied on graphs, is called <a href="https://arxiv.org/abs/1403.6652">DeepWalk</a>, developed by Bryan Perozzi, Rami Al-Rfou, and Steven Skiena.</p><p>DeepWalk, like word2vec, is an unsupervised learning approach that captures the neighborhood similarity of nodes in a graph. Let’s create a simple implementation of this technique in Clojure.</p><h3>Graph representation</h3><p>We will use a representation similar to an adjacency list.</p><pre>(defn create-graph<br>  &quot;Create a graph from a sequence of edges&quot;<br>  [edges]<br>  (reduce (fn [graph [u v]]<br>            (-&gt; graph<br>                (update u (fnil conj #{}) v)<br>                (update v (fnil conj #{}) u)))<br>          {}<br>          edges))<br>          <br> =&gt; (create-graph [[:a :b] [:a :c] [:b :c] [:b :d]])<br> =&gt; {:a #{:c :b}, :b #{:c :d :a}, :c #{:b :a}, :d #{:b}}</pre><p>It is a map containing the nodes as keys and corresponding values being the set of connected nodes.</p><h3>Initializing embeddings</h3><p>We will initialize the embeddings with random values and by a <a href="https://math.stackexchange.com/questions/1470686/in-laymans-terms-what-is-a-stochastic-process">stochastic</a>, unsupervised process, we will gradually make our way towards more accurate values.</p><pre>(defn init-embedding<br>  &quot;Creates random embedding for size m x n where m = # of nodes, n =  vector-size&quot;<br>  [vector-size vocab-size]<br>  (-&gt;&gt; rand<br>       ((partial repeatedly vector-size))<br>       (partial vec)<br>       ((partial repeatedly vocab-size))<br>       vec))</pre><h3>Random walk</h3><p>It’s like taking a stroll through the city, where buildings represent the nodes and edges represent the roads. We decide how many buildings we want in the walk and start walking from a fixed building. At the end of each walk, we attempt to make sense of which buildings were close to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*uk7ntEuM1yasCKJSf5Pv9g.png" /></figure><p>For the undirected graph above, let’s say the starting node is “a” and the walk length is 3. The random walks will be —</p><ol><li>a → b → c</li><li>a → c → b</li><li>a → b → d</li></ol><pre>(defn get-neighbors<br>  &quot;Get neighbors of a node in the graph&quot;<br>  [graph node]<br>  (get graph node))<br>  <br>  <br>(defn random-walk<br>  &quot;Generate a random walk of length &#39;walk-length&#39; starting from &#39;start-node&#39;&quot;<br>  [graph start-node walk-length]<br>  (loop [walk [start-node]<br>         current-node start-node<br>         steps-left (dec walk-length)]<br>    (if (zero? steps-left)<br>      walk<br>      (let [neighbors (get-neighbors graph current-node)<br>            next-node (rand-nth (seq neighbors))]<br>        (recur (conj walk next-node)<br>               next-node<br>               (dec steps-left))))))</pre><p>For each walk, we will train the model on the words appearing in the random walk. The objective is to maximize the dot product between the vector representations of nodes that appear nearby within these walks. This approach leverages the fact that the dot product is proportional to the cosine similarity between vectors. By increasing the dot product of vectors representing nearby nodes, we encode the graph’s local structure into the embedding space. Nodes that frequently co-occur in random walks will develop similar vector representations, effectively capturing the graph’s topology in a continuous vector space.</p><h3>Training process</h3><p>For this example, we are considering only positive samples, hence the error is calculated as — (- 1 (sigmoid dot_product))</p><p>The gradients are calculated using this error and the current vectors. Both the word vector and the context vector are updated in the direction that reduces the error.</p><pre>(defn train-pair<br>  &quot;Train on a single word pair&quot;<br>  [word context learning-rate vocab vectors]<br>  (let [word-idx (get vocab word)<br>        context-idx (get vocab context)<br>        word-vec (get vectors word-idx)<br>        context-vec (get vectors context-idx)<br>        dot-product (reduce + (map * word-vec context-vec))<br>        error (- 1 (sigmoid dot-product))<br>        word-delta (mapv #(* learning-rate error %) context-vec)<br>        context-delta (mapv #(* learning-rate error %) word-vec)]<br>    (-&gt; vectors<br>        (update word-idx #(mapv + % word-delta))<br>        (update context-idx #(mapv + % context-delta)))))<br>        <br>        <br>(defn process-walk<br>  &quot;trains the skip gram model for one random walk&quot;<br>  [{:keys [walk embedding vocab window-size learning-rate]}]<br>  (reduce<br>   (fn [embedding [idx word]]<br>     (let [context-words (get-context-words idx walk window-size)]<br>       (reduce<br>        #(train-pair word %2 learning-rate vocab %1)<br>        embedding<br>        context-words)))<br>   embedding<br>   (map-indexed vector walk)))</pre><p>This function is typically called many times during training, gradually refining the word vectors to capture semantic relationships between words based on their co-occurrence patterns in the text.</p><h3>Results</h3><pre>(defn deepwalk<br>  &quot;Run DeepWalk algorithm on the given graph&quot;<br>  {:opts [:vector-size<br>          :walk-length<br>          :num-walks<br>          :window-size<br>          :learning-rate]}<br>  [edges &amp; opts]<br>  (let [graph (gc/create-graph edges)<br>        trained-vectors (mc/train-deepwalk graph (apply hash-map opts))]<br>    {:graph graph<br>     :vectors trained-vectors}))</pre><pre>=&gt; (deepwalk [[:a :b] [:a :c] [:b :c] [:b :d]]<br>             :vector-size 3<br>             :learning-rate 0.025)</pre><pre>=&gt; {:graph {:a #{:c :b}, :b #{:c :d :a}, :c #{:b :a}, :d #{:b}},<br>	 :vectors<br>	 [[1.9573999686062304 0.5519261864300776 1.2504320597448482]<br>	  [2.2479788168874233 0.6338604247877525 1.4360605023739048]<br>	  [2.0522495736710527 0.5786708383394699 1.311024166074367]<br>	  [1.8370678722080205 0.5179962609496533 1.1735611526405794]]}</pre><p>This is a basic idea of implementing DeepWalk. A thing to note is that this implementation is a simplified version of <em>Word2Vec</em>. These results won’t be the most accurate ones. A full implementation would include negative sampling (training for nodes that are farther away from each other), and subsampling of frequent words, and would be optimized for efficiency.</p><p>Please find the full source code here — <a href="https://github.com/mihirrd/clj-deepwalk">https://github.com/mihirrd/clj-deepwalk</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b2c4eacd4e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Man with a 40 years old Backpack.]]></title>
            <link>https://medium.com/@deshpande.mihir7/a-man-with-a-40-years-old-backpack-8a4fbf990121?source=rss-a01eb589324b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a4fbf990121</guid>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[gratitude]]></category>
            <dc:creator><![CDATA[Mihir Deshpande]]></dc:creator>
            <pubDate>Sat, 29 Jun 2024 04:51:28 GMT</pubDate>
            <atom:updated>2024-06-29T05:04:44.706Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Man with a 40 years old Backpack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPEXY_NlHkWraDVwET-Klg.jpeg" /></figure><p>On a Wednesday evening, as I stood in the parking lot after our weekly office football game, my eyes landed on my colleague’s backpack — a weathered relic that looked like it had stories to tell.</p><p>“Hey, your backpack’s open,” I called out, noticing a broken zipper.</p><p>He shrugged. “Yeah, it needs repairing again.”</p><p>I was about to suggest he replace it when he added, “It’s 40 years old, you know. I’m never getting rid of it.”</p><p>This from a man who has spent two decades in the US, climbing the corporate ladder from Software Engineer at Amazon to Engineering manager at Meta, to the Head of Engineering at the company I work for. Someone who could easily afford the most luxurious bags money could buy. Yet here he was, cherishing this worn-out piece of fabric like a treasure.</p><p>He said, “It belonged to my cousin. She gave it to me when I first went to college. I was a poor kid in America at that time, and people did whatever they could to help me save money. I have been using it since then. I’ve gotten it repaired multiple times and this time as well, I am going to do the same.”</p><p>That day, I witnessed a remarkable example of respect and gratefulness. I think of it as a homage he is paying to something that helped him in his tough times. After all, isn’t that the essence of being human? To remember, to be grateful, and to honor the things and people that have shaped us — no matter how worn or humble they may appear to others.</p><p>Upon parting ways, I could not help but imagine a picture where all our cool, shiny bags were enviously looking at their old, battered companion, realising what wealth truly looks like!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a4fbf990121" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How artists are made]]></title>
            <link>https://medium.com/@deshpande.mihir7/how-artists-are-made-5eee681d0407?source=rss-a01eb589324b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eee681d0407</guid>
            <category><![CDATA[musicians]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[artist]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Mihir Deshpande]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 14:12:09 GMT</pubDate>
            <atom:updated>2024-02-11T03:58:15.910Z</atom:updated>
            <content:encoded><![CDATA[<p>It has been around six years since I started learning to play the sitar. It’s not too long considering people spend 20–30 years in the process. But now when I look back, I see that the part where I was learning “how to play the sitar” was just the initial 2 to 3 years. After that, it has been more about learning how to create quality music.</p><p>Teaching someone how to create good music is exponentially more difficult than teaching them how to play the instrument. Playing the instrument is a craft while weaving melodies is an art. There’s simply no defined framework following which one reaches the finish line. There’s no finish line at all!</p><p>The only possible way to develop this artistry is through meticulous observation. By observing the Guru, the masters, by going further deep into the question of what makes good music good, one cultivates a deeper understanding of its multifaceted aspects. The idea of “good music” becomes more and more transparent as you actively listen to more and more maestros.</p><p>In my opinion, this is the most effective path to achieve mastery in any pursuit. As a programmer, I find it oddly disturbing how numerous online tutorials claim to help you “master node.js in 6 hours”, obscuring the entire complexity of the subject. While coding tutorials teach you the technique, observing high-quality code will impart wisdom.</p><p>Observe the masters!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wH3IBiv8_BDrz7PL" /><figcaption>Photo by <a href="https://unsplash.com/@birminghammuseumstrust?utm_source=medium&amp;utm_medium=referral">Birmingham Museums Trust</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eee681d0407" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Essence of Apache Kafka]]></title>
            <link>https://medium.com/@deshpande.mihir7/essence-of-apache-kafka-3e1837275d1e?source=rss-a01eb589324b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e1837275d1e</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mihir Deshpande]]></dc:creator>
            <pubDate>Thu, 14 Dec 2023 15:47:05 GMT</pubDate>
            <atom:updated>2023-12-18T06:16:53.108Z</atom:updated>
            <content:encoded><![CDATA[<h4>Conceptually building an event-driven architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OZTjOxo0aF1_FCWp" /><figcaption>Photo by <a href="https://unsplash.com/@nixcreative?utm_source=medium&amp;utm_medium=referral">Tyler Nix</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Defining the problem</h3><p>Imagine that you go to your usual coffee place and encounter a gigantic queue. Going a little further, you realize that each individual has to wait in line until the coffee is prepared and handed over to them, as opposed to just placing the order at the counter and moving on. The latter approach seems pretty obvious since we know that order placement and the subsequent preparation process can be done as distinct, independent activities. The orders can be listed on a board and the barista<em> </em>can prepare them one after another. This idea is called asynchronous communication, where entities do not necessarily wait for each other to complete a task before initiating another.</p><p>This problem is not so uncommon in software systems either. For example, when you post a picture of your cat wearing Santa’s costume, other people don’t need to receive a notification about the same immediately (no matter how cute the cat looks). Otherwise, you could find yourself in a situation where the app is loading for hours because a lot notifications are still pending to be sent. The ‘notification service’ can do its job at its own pace; it just needs to receive the ‘<strong><em>message</em></strong>’ to do so from the ‘upload service’. (Services are basically software components that are responsible for carrying out certain tasks).</p><p>Now let’s see how we can establish the asynchronous communication between them.</p><h3>Message queues in software systems</h3><p>We realized that similar to how there was a board in the coffee shop where all the orders were listed, we require a data structure that would store the messages from the upload service so that the notification service can obtain and process them. Since these messages are to be processed one by one as they arrive, let’s store them in a <strong>Queue</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*ebcfQa_PRp8KD9iww55J9A.png" /><figcaption>Messages are being sent out by the upload service to be consumed by the notification service</figcaption></figure><p>In this scenario, the upload service is called a <strong><em>Publisher, </em></strong>and the notification service is called <strong><em>Subscriber </em></strong>which has subscribed to the message queue. This type of model is called the <strong>Pub-sub</strong> model.</p><h3>Limitations of Queues and the idea of multiple producers and subscribers</h3><p>Perfect, we now have one service giving out messages and one service listening to those messages. Now let’s say we want to incorporate another service — an ‘analytics service’ that also wants to use these messages to find out how many of these uploads are done by teenagers. Can this service listen to the same queue to which the notification service is listening?</p><p>Well, theoretically it can. However, the queue is a <em>transient data structure.</em> meaning that the items pushed into the queue have to be popped out. More specifically, these messages will be popped out once they are processed or consumed. Thus, there’s a fair chance that one of the services might miss out on messages.</p><h3><strong>Event logs to the rescue</strong></h3><p>What we need here is something that’ll store these messages perpetually (at least for a configured amount of time). The appropriate data structure would be something like a “<em>Log</em>”. We know that a log is an append-only data structure. Therefore, multiple services can consume messages from this log at their own pace and no message would get lost.</p><p>Since these messages are not intended for a particular service, but rather something that any relevant service can consume, we will call them “<strong>Events</strong>”. Finally uploading a picture is an Event! (The cat finally got justice)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*o_a4o4IQtO-yUhGCEBYnQA.png" /></figure><h3>Coming to the Topic…</h3><p>As our application becomes more complex, we’ll have multiple services interacting with each other and producing events. Not all events will be relevant for a particular service. This is why we logically segregate these events into separate <strong>Topics. </strong>Each service can now listen to the topics that are relevant to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*vk1Xk7QYPPeU8hE4zhq1fw.png" /></figure><h3>Handling the traffic…</h3><p>Everything looks good until here, mainly because we have been dealing with just one server doing all the event logging. As the traffic to our application increases, the volume of generated events also increases. To handle this increasing load, we have to scale up our event-driven architecture. One possible way is to increase the capacity of our machine to handle more load. But at some point, even that will fall short, and there comes a limit to how much you can increase the capacity. So the obvious choice that comes to mind is adding more servers and making them all work together as a <strong>cluster</strong>. In other words, making it distributed!</p><h4>How do we store logs in a distributed way?</h4><p>Now that we have multiple nodes working together, we have to find a way to store this log on these servers. One option could be distributing topics among the nodes. This would work well until the topic sizes vary drastically. It’ll fail when the topic is too large to be stored on a single machine. We have to distribute these topics evenly to all the nodes in our <strong>cluster</strong>. The way we do that is by dividing these topics into multiple <strong>partitions<em>.</em></strong></p><h4>Partitioning</h4><p>Now, each node will have small partitions of all the topics. Just to make this system function properly even when one of the servers in the cluster is down (to make it <em>fault-tolerant</em>), we can also create multiple copies of the same partition and store them across the nodes. This way, if one node fails, the rest of the nodes will have the necessary event data. This is how our system will somewhat look like -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*Q7BbLOz5xCJdf8cUOhEBFg.png" /></figure><p>Whenever an event is published into the system, the publishing services can decide which partition it should go to by mentioning the partition ID. If it’s not mentioned, then the events will get distributed among the partitions in a round-robin manner.</p><h4>Remembering progress with offsets</h4><p>In order to make sure that the events are consumed in the right order, and no event is consumed multiple times or even skipped altogether, It’s important to keep track of the progress of a consumer in reading events from a topic. The way we do it is by using <strong>offsets.</strong></p><p>When a consumer reads messages from a topic, it consumes them in order and advances its offset to keep track of the last successfully processed event. Consumers can specify the offset from which they want to start consuming messages. This flexibility allows consumers to resume processing from a specific point.</p><h3>Putting it all together…</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R271EaNc81GlHEBCAwVj9g.png" /></figure><p>We now have our basic distributed event-driven architecture in place. The system that we built here to handle all the event processing is nothing but <strong>Apache Kafka</strong>, developed by <em>Jay Kreps</em>, <em>Neha Narkhede</em>, and <em>Jun Rao</em> at LinkedIn. The project was later open-sourced in 2011 and became part of the Apache Software Foundation. It has since gained widespread adoption in various industries for building scalable and reliable real-time data streaming platforms.</p><p>In today’s highly complex distributed systems, Kafka serves as the backbone, gracefully processing an endless stream of real-time data. It’s one of the most well-engineered innovations in the world of modern computing with a wide spectrum of applications. While this was just an overview of it, there’s still a lot to talk about Apache Kafka.</p><p>I hope reading this article was ‘eventful’ for you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e1837275d1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>