<?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 Prashant Saksena on Medium]]></title>
        <description><![CDATA[Stories by Prashant Saksena on Medium]]></description>
        <link>https://medium.com/@saksenaprashant06?source=rss-91d2d320b983------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9W-u-UuBxSujUAmkyeOtkw.jpeg</url>
            <title>Stories by Prashant Saksena on Medium</title>
            <link>https://medium.com/@saksenaprashant06?source=rss-91d2d320b983------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:30:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saksenaprashant06/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[LLMs through the kaleidoscope of Randomness]]></title>
            <link>https://medium.com/@saksenaprashant06/llms-through-the-kaleidoscope-of-randomness-46997ebe9921?source=rss-91d2d320b983------2</link>
            <guid isPermaLink="false">https://medium.com/p/46997ebe9921</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[randomized-algorithm]]></category>
            <dc:creator><![CDATA[Prashant Saksena]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 17:02:42 GMT</pubDate>
            <atom:updated>2026-08-06T17:02:42.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oCFS6cYURVbzenP8" /><figcaption>Photo by <a href="https://unsplash.com/@salcrocejpg?utm_source=medium&amp;utm_medium=referral">Salvus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>​Is the universe inherently deterministic or probabilistic? Perhaps more importantly — can we tell the difference between the two? Humanity has pondered the meaning and utility of randomness for millennia.</blockquote><blockquote><a href="https://en.wikipedia.org/wiki/Avi_Wigderson">Avi Wigderson</a> (Abel Prize &amp; Turing Award Winner)</blockquote><p>This blog is a thought experiment whose purpose is to explore Large Language Models (LLMs) through a kaleidoscope of randomness, where each probabilistic lens reveals a different perspective.</p><p>Although LLMs are often perceived as deterministic systems that follow learned patterns, their outputs are influenced by probabilistic mechanisms that introduce variation and uncertainty.</p><h4>What is a Large Language Model</h4><p>A <strong>language model</strong> is a type of artificial intelligence (AI) designed to understand, interpret, and generate human language. Mathematically, a language model is the probability distribution over a sequence of tokens, i.e. given a set of tokens {x ₁, x₂, …, xₙ} ∈ V, where V is the complete vocabulary, a language model would assign a probability, P(x ₁, x₂, …, xₙ) to this sequence of tokens.</p><p>The joint probability distribution of the given token sequence can be defined using the chain rule of probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*jpVzl_n6ZyX78i0UJ8e1xA.png" /></figure><p>The autoregressive class of language models is the one in which each conditional probability distribution can be effectively computed via feed-forward neural network. Autoregressive models predict the next text token based on prior token sequence, referred to as context.</p><p><strong>Large Language Models (LLM)</strong> are the most advanced, modern versions of language models. Powered by deep learning and neural network architectures (like Transformers), LLMs analyse billions of parameters to perform highly complex tasks.</p><p>The Transformer architecture, introduced in the landmark paper, <em>“Attention Is All You Need”</em>, has fundamentally reshaped the field of artificial intelligence, particularly in natural language processing and, increasingly, in vision and multimodal tasks. The transformer departs from traditional sequential models by relying entirely on attention mechanisms to model relationships within data. This blog assumes that the reader is already familiar with the Transformer architecture in detail.</p><p>Let us explore the world of LLMs through ever-shifting patterns of randomness, adopting different probabilistic lenses to gain new insights.</p><h4>Monte Carlo Method</h4><p>A transformer predicts the next token based on the given sequence of input tokens by producing a set of logits (scores) for all possible next tokens. These logits are then passed through a <strong>softmax</strong> function to convert them into a probability distribution over the vocabulary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*wu4E_lMexCavCc_YF4JXWg.png" /></figure><p>During decoding, the next token is selected according to the chosen decoding strategy; in the simplest case, the token with the highest probability is selected.</p><p>Instead of using greedy decoding, <em>random sampling</em> techniques such as Temperature scaling, Top-K sampling, and Top-P (nucleus) sampling, etc. are employed to select the next token based on the model’s output probability distribution. These methods introduce randomness into the decoding process, resulting in more diverse, creative, and contextually varied text generation.</p><p>Let us look at Temperature scaling. The softmax function is modified to introduce Temperature variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*nRdieK54L2pI4yruS9q0Yg.png" /></figure><p>When the LLM’s decoding parameters are set higher to allow more randomness, such as with Temperature &gt; 0, the LLM acts like a <em>Monte Carlo method</em>, because each token is randomly sampled from a probability distribution. However, this is not the <em>Monte Carlo method</em> in strict sense, because only a single sample is drawn at each decoding step, and the process does not involve repeated independent trials.</p><p>Because the output is sampled from a probability distribution, running the exact same prompt multiple times yields different paths. In case of <em>Monte Carlo method</em>, if the algorithm is run repeatedly with independent random choices each time, the failure probability can be made arbitrary small. LLMs, however, provide no such theoretical guarantee, that the repeated sampling reduces the probability of an incorrect answer. For example, if an LLM answers a math problem incorrectly 30% of the time, the repeated samples may all make the same mistake because they are generated from the same learned distribution.</p><p>An interesting observation is that when the Temperature is set to 0, the randomness in the sampling process disappears. In this case, the LLM behaves similar to a <em>Las Vegas algorithm</em>.</p><h4>Random Walk</h4><p>A random walk is a stochastic process that describes a path that consists of a succession of random steps on some mathematical space, where the next state depends on the current state plus some random choice.</p><p>Mathematically, suppose that X₁, X₂, . . . is a sequence of Rᵈ-valued independent and identically distributed random variables. A random walk started at z ∈Rᵈ is the sequence (Sₙ), n≥0 where,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*OrPwtHwo3cV111YemCqW8w.png" /></figure><p>The quantities (Xₙ) are referred to as steps of the random walk.</p><p><em>Is an LLM a Random Walk over the Complete Vocabulary?</em></p><p>Perhaps not. A LLM is not a pure random walk in the strict sense. In a standard random walk, the next step depends only on the current state and has no memory of where the process was several steps earlier.</p><p>By contrast, an LLM uses the Transformer architecture with an attention mechanism. The probability distribution over the next token is conditioned on the entire preceding context, not just the most recent token.</p><p>As a result, the model inherently retains information about previous tokens. For example, if an LLM generates an opening parenthesis “(”, the attention mechanism helps ensure that the probability of generating the corresponding closing parenthesis “)” remains high after the intervening tokens. A standard random walk cannot enforce such long-range dependencies because it does not look back at its history.</p><h4>Markov Chains</h4><p>A Markov chain is a discrete-time stochastic process defined over a set of states in terms of a matrix of transition probabilities. A Markov chain is defined by the memorylessness property:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*0WY0TDYKPRASqhzYXcCBTw.png" /></figure><p>This is a first order Markov Chain. A <em>k</em>-th order Markov chain is the one in which probability of any state depends only on the probability of the preceding <em>k</em> states.</p><p>Perhaps not a first-order Markov chain (it is closer to a random walk in that sense), but LLMs more closely resemble a <em>k</em>-th order Markov chain, since the next token depends on the preceding <em>k</em> tokens. For a good explanation on this perspective, check out this link, “<a href="https://workshopping.hlrs.de/transformers-as-markov-processes/">Transformers as Markov processes</a>”.</p><p>Consider the sample space consisting of all possible sequences from the vocabulary of tokens. Let us consider only sequences up to the defined <em>context length</em>, which in LLM is the maximum number of tokens, the model can read, remember, and process at one time.</p><p>Suppose an LLM generates tokens x₁,x₂,…,xₙ. During inference, it predicts Pr(xₜ | x₁,x₂,…,xₜ_₁). Since the model has a finite context window of length <em>k</em>, in practice this becomes approximately, Pr(xₜ | xₜ_ₖ,…,xₜ_₁).</p><p>At each decoding step, the output distribution is conditioned on the model’s context, which consists of up to <em>k</em> previous tokens (the <em>context window</em>). Therefore, from the perspective of the observable token sequence, an autoregressive LLM behaves similarly to a <em>k</em>-th order Markov process.</p><h4>Principle of Deferred Decisions</h4><p>The idea behind the “Principle of Deferred Decisions” is that the entire set of random choices by the randomized algorithm are not made in advance. Instead, the choices are fixed only as they are revealed to the algorithm. For detailed explanation, refer to the medium blog, <a href="https://medium.com/@saksenaprashant06/principle-of-deferred-decisions-9a29c7996426">Principle of Deferred Decisions</a>.</p><p>Given a prompt, an LLM generates text by sequentially estimating conditional probabilities:</p><p>first <em>Pr⁡(token₁ | prompt)</em>, then <em>Pr⁡(token₂ | prompt, token1)</em>, and so forth. This generation process can be viewed as a form of deferred decision-making. By the chain rule of probability, the model incrementally commits to each token choice, conditioning every subsequent decision on those made earlier. In this sense, LLM text generation closely mirrors the principle of deferred decisions.</p><h4>Reasoning via Random Sampling</h4><p>Many prompting techniques have been introduced as promising strategies for improving the reasoning abilities of LLMs.</p><p><em>Chain-of-Thought</em> (CoT) is one such prompting approach in which the model decomposes a problem into a sequence of intermediate reasoning steps before producing the final answer. CoT can be viewed as a single, linear randomized path, where at each step the model generates tokens through random sampling (e.g., using a temperature greater than zero or other sampling strategies), resulting in a single thread of reasoning.</p><p><em>Tree-of-Thought</em> (ToT) is another reasoning approach that enables the model to explore multiple reasoning alternatives at each step. ToT explicitly structures the reasoning as a tree, a random sampling-based search tree of reasoning paths. Each tree node corresponds to an intermediate thought and each edge represents a transition to a subsequent thought generated through random sampling.</p><p>If we try to build the search tree deterministically (using greedy decoding where Temperature = 0), the tree would instantly collapse into a single, highly rigid path. Random sampling makes the search tree effective because sampling allows the tree to branch into fundamentally different problem-solving methodologies and it prevents the search from getting trapped in high-probability semantic loops or dead-ends.</p><h4>Mathematical Reasoning via Random Sampling (MCTS)</h4><p>In my opinion, mathematical reasoning represents the pinnacle of reasoning challenges for LLMs, owing to its inherent complexity and rigorous logical structure. The following paper uses a novel idea of integrating <a href="https://en.wikipedia.org/wiki/Monte_Carlo_tree_search">Monte Carlo Tree Search</a>(MCTS) with LLM to enhance performance in complex mathematical reasoning tasks:</p><p>“Accessing GPT-4 level Mathematical Olympiad Solutions via Monte Carlo Tree Self-refine with LLaMa-3 8B”, Di Zhang, Xiaoshui Huang, Dongzhan Zhou, Yuqiang Li, Wanli Ouyang. (<a href="https://arxiv.org/abs/2406.07394">https://arxiv.org/abs/2406.07394</a>)</p><p>Monte Carlo tree search (MCTS) is a heuristic tree search algorithm for decision processes. The focus of MCTS is on the analysis of the most promising moves, expanding the search tree based on <strong>random sampling</strong> of the search space. MCTS is used mainly in gaming, Google used this in <a href="https://en.wikipedia.org/wiki/AlphaGo">AlphaGo</a>, which became the first Computer Go program to beat a professional human Go player, <a href="https://en.wikipedia.org/wiki/Lee_Sedol">Lee Sedol</a>.</p><p>MCTS consists of four steps, (1) <em>Selection</em>: Start from root and select successive child nodes until a leaf node (may not be terminal ) is reached, (2) <em>Expansion: </em>create child nodes if the leaf node is not terminal and choose node from one of them (child nodes are any valid moves), (3) <em>Simulation</em>: Complete one random playout from the chosen child node (this is based on <strong>random sampling</strong>), (4) <em>Backpropagation</em>: Use the result of the playout to update information in the nodes on the path from this child to root node.</p><p>The paper describes an algorithm which integrates MCTS with LLM by converting mathematical reasoning problem solution into a search tree, wherein the nodes of the tree represent different versions of answers &amp; the edges denote attempts at improvement.</p><p>In this modified algorithm, an additional S<em>elf-Refine</em> step is introduced. During this stage, the selected answer is optimised using feedback generated by the model itself, which guides the refinement process and results in an improved final answer. In the <em>Simulation</em> (also referred to as <em>Self-Evaluation</em>) step, the refined answer is scored to sample a reward value and compute its worth. Each visit to a search tree node involves the <em>repeated sampling</em> of the node’s rewards to enhance the reliability of this evaluation. Post sampling, the worth value of the answer is calculated. The paper demonstrates that this modified MCTS algorithm enhances the capability of LLMs to solve complex mathematical problems.</p><p><strong>To conclude</strong>, randomness is the subtle ingredient that infuses LLM-generated language with flexibility, creativity, and depth. The kaleidoscope metaphor reminds us that intelligence, whether artificial or human, is rarely a matter of perfect determinism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46997ebe9921" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Principle of Deferred Decisions]]></title>
            <link>https://medium.com/@saksenaprashant06/principle-of-deferred-decisions-9a29c7996426?source=rss-91d2d320b983------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a29c7996426</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[randomized-algorithm]]></category>
            <category><![CDATA[randomness]]></category>
            <dc:creator><![CDATA[Prashant Saksena]]></dc:creator>
            <pubDate>Wed, 04 Feb 2026 17:25:30 GMT</pubDate>
            <atom:updated>2026-02-04T17:25:30.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Aa3eYcgFr4_5ZCm3" /><figcaption>Photo by <a href="https://unsplash.com/@themaker?utm_source=medium&amp;utm_medium=referral">Leon-Pascal Jc</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>“I believe that we do not know anything for certain, but everything probably.”</blockquote><blockquote><a href="https://en.wikipedia.org/wiki/Christiaan_Huygens">Christiaan Huygens</a></blockquote><p>There is a saying, “Work smart, not hard” and the Principle of Deferred Decisions in Probability Theory fits the bill perfectly.</p><h4>Principle of Deferred Decisions</h4><p>The idea behind the “Principle of Deferred Decisions” is that the entire set of random choices by the randomized algorithm are not made in advance. Instead, the choices are fixed only as they are revealed to the algorithm.</p><p>Let us look at few examples:</p><h4>Coin Toss Example</h4><p>A coin is tossed 10 times. What is the probability that the number of heads is odd ?</p><p>If we consider the sample space for this problem, there are 2¹⁰ equally likely outcomes.</p><p>Probability, P(odd number of heads) = (¹⁰C₁+¹⁰C₃+¹⁰C₅+¹⁰C₇+¹⁰C₉)/2¹⁰</p><p>This can be cumbersome to compute. So, lets use Principle of Deferred Decisions to compute the probability:</p><ul><li>Assume 9 coin tosses results in x number of heads</li><li>The last coin toss, the tenth one, is equally likely to be heads or tails</li><li>If x is even, the probability of last toss must be head is 1/2</li><li>If x is odd, the probability of last toss must be tail is 1/2</li></ul><p>Hence, the probability that the number of heads is odd is 1/2.</p><h4>Clock Solitaire</h4><p>Clock Solitaire is a solitaire card game where a standard pack of 52 cards are randomly shuﬄed and split into 13 piles of 4 cards each. The piles are labelled as {A,2,. . . , 10, J, Q, K}. These piles are placed in a clock-like layout.</p><p>Draw the first card from “K” pile, draw the next card from pile “X”, where X is the value of the previously drawn card.</p><p>Repeat until:</p><ul><li>either all 52 cards have been drawn. In this case, you win.</li><li>or you get stuck, i.e. when an attempt is made to draw a card from empty pile. In this case, you lose.</li></ul><p>Following video explains the Clock Solitaire game:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAw7vIwqhDTc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAw7vIwqhDTc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAw7vIwqhDTc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae7522cd786109618d8bf040517cb372/href">https://medium.com/media/ae7522cd786109618d8bf040517cb372/href</a></iframe><p>We are interested in the Probability of Winning this game. An interesting observation: The game terminates in a win if the 52nd card drawn is a King, which implies that 51 cards already drawn contain all 3 other Kings.</p><p>The sample space for this problem will contain all 52! possible deck permutations, wherein each permutation corresponds to some partition of 52 cards into 13 distinct piles and ordering for 4 cards in each pile. Computing probability of a win, in this case, is a formidable task.</p><p>Since every card in the deck is equally likely to be in the last position, at each draw any unseen card is equally likely to appear, we can calculate the probability by looking at the Kings specifically. The probability that a specific type of card (a King) occupies the very last slot in the deck is 4/52, i.e. 1/13.</p><p>By “deferring the decision” of where the Kings are located, we realise that the complex movement between piles doesn’t actually change the randomness. The game is mathematically equivalent to laying out all 52 cards in a line and stopping when you hit the 4th King.</p><p>Hence, using the principle of deferred decisions, the probability of winning is 1/13.</p><h4>Conclusion</h4><p>The Principle of Deferred Decisions is a very good intuitive way to compute probability of various problems. Formally, the Law of Total Probability forms the mathematical basis for Principle of Deferred Decisions. Those interested in exploring this concept in detail can refer to the Law of Total Probability for the math behind this principle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a29c7996426" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Online Algorithms]]></title>
            <link>https://medium.com/@saksenaprashant06/online-algorithms-2626b3a33e38?source=rss-91d2d320b983------2</link>
            <guid isPermaLink="false">https://medium.com/p/2626b3a33e38</guid>
            <category><![CDATA[lru-cache]]></category>
            <category><![CDATA[paging]]></category>
            <category><![CDATA[randomized-algorithm]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Prashant Saksena]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 16:02:34 GMT</pubDate>
            <atom:updated>2025-12-31T16:02:34.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EiHav2agiLu2jx27" /><figcaption>Photo by <a href="https://unsplash.com/@pastorthomasbwilson?utm_source=medium&amp;utm_medium=referral">Tom Wilson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Computer Science is a science of abstraction-creating the right model for a problem and devising the appropriate mechanisable techniques to solve it</blockquote><blockquote><a href="https://en.wikipedia.org/wiki/Alfred_Aho">Alfred Aho</a></blockquote><h4>Online Algorithms</h4><p>When the entire input is not available from the start, the class of algorithms that process the input in the order it is fed to the algorithm, is classified as <strong>Online Algorithms</strong>.</p><p>An online algorithm responds to a sequence of service requests, each request with an associated cost. An online algorithm processes the sequence of input request piece by piece, i.e. it should process the received request completely before it can receive the next request in the sequence. If the entire sequence of input request is known in advance to the algorithm, then the algorithm is called as <strong>Offline Algorithm</strong>.</p><h4>Competitive Analysis</h4><p>Competitive Analysis is the technique used to analyze an online algorithm, where the online algorithm <em>A </em>is compared to an optimal offline algorithm (<em>OPT</em>). Given a sequence P = {p₁, p₂, …, pₙ} of input requests, let <em>cost</em>(<em>A</em>, P) be the cost of online algorithm <em>A</em> on P, and let the <em>cost</em>(<em>OPT</em>, P) be the cost of the optimal offline algorithm <em>OPT</em> on P.</p><p>Algorithm <em>A</em> is said to be <em>c</em>-competitive for P if:</p><p><em>cost</em>(<em>A</em>, P) ≤ <em>c</em>.<em>cost</em>(<em>OPT</em>, P) + b, where b ≥0</p><p>If <em>A</em> is <em>c</em>-competitive for every sequence P, then we say that <em>c</em> is the competitive ratio of <em>A</em>.</p><h4>Competitive Analysis of LRU Cache</h4><p>Consider a web application which requests different pages. It is often advantageous to cache a set of these pages, in case the page is present in cache, it is served from the cache. There are many policies that can be used to determine which page to evict in case of a cache miss, when the cache has reached its maximum size.</p><p><strong>Least Recently Used (LRU)</strong> is one such policy which evicts the page whose last request occurred furthest in the past.</p><p>The LRU Cache eviction algorithm is perhaps an online algorithm that takes the decision of eviction based on current request as it does not have knowledge of the future requests. The cost of this algorithm (let&#39;s call it <em>A)</em> will be the number of cache misses on a sequence of requests.</p><p>For this case, the optimal <em>Offline Algorithm</em> would be the one, which on a cache miss, evicts that item from the cache whose next request occurs furthest in the future.</p><p>Assume, both LRU algorithm, <em>A, </em>and the <em>Offline Algorithm </em>have a cache capacity of <em>k </em>elements. Consider a sequence P = {p₁, p₂, …, pₙ} of page requests where all requests are distinct.</p><ul><li>To start with, both the algorithms have the same set of <em>k </em>items in the cache for the first <em>k </em>requests from the sequence P.</li><li>Since all requests in P are distinct, so from then on, the algorithm <em>A </em>misses on every request as every subsequent request is for a unique item not in <em>A’</em>s cache.</li><li>But since the <em>Offline Algorithm </em>evicts that item from the cache whose next request occurs furthest in the future, so for the next set of <em>k</em> requests, the algorithm misses for the first request, evicts an item from cache and ensures there are no further misses for the batch of next <em>k</em> requests.</li><li>So, for the sequence of <em>n</em> page requests, in the worst case, the number of misses of <em>Offline Algorithm </em>are <em>n</em>/<em>k</em>, whereas the number of misses of <em>A</em> are <em>n</em>.</li></ul><p>Hence the competitive ratio of LRU Algorithm is <em>c</em> = <em>n</em>/(<em>n</em>/<em>k</em>) = <em>k</em>.</p><h4>Randomization</h4><p>Let us also consider a randomized policy for eviction. In this policy, evict the page randomly selected from the set of pages in the cache which have not be accessed so far. In case, all pages have been accessed, select a random page to evict.</p><p>Fascinatingly, the competitive ratio of this randomized algorithm is at most 2<em>logk, </em>which is better than the LRU algorithm. Those interested can explore the proof in the book, Randomized Algorithms, by Motwani and Raghavan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2626b3a33e38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis Sorted Set Internals]]></title>
            <link>https://medium.com/@saksenaprashant06/redis-sorted-set-internals-fd8840efa9d9?source=rss-91d2d320b983------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd8840efa9d9</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[set]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[redis-sorted-set]]></category>
            <category><![CDATA[skip-list]]></category>
            <dc:creator><![CDATA[Prashant Saksena]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 06:06:05 GMT</pubDate>
            <atom:updated>2024-03-24T06:06:05.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_C838WxAFRCiIlaZ" /><figcaption>Photo by <a href="https://unsplash.com/@austris_a?utm_source=medium&amp;utm_medium=referral">Austris Augusts</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>A set is a Many that allows itself to be thought of as a One</em></blockquote><blockquote>- <a href="https://en.wikipedia.org/wiki/Georg_Cantor">Georg Cantor</a></blockquote><p>Redis provides different data structures that help solve variety of problems. Redis Sorted Sets is one such data structure. According to the Redis documentation:</p><p>“A Redis sorted set is a collection of unique strings (members) ordered by an associated score. When more than one string has the same score, the strings are ordered lexicographically”.</p><p>Some use cases for sorted sets include leaderboard, rate limiting, etc. We will try to explore the internal implementation of Redis Sorted Sets.</p><h4>Internal Implementation</h4><p>Redis Sorted Sets are implemented as a combination of both two data structures:</p><p><strong>Hash Table</strong>: A <a href="https://en.wikipedia.org/wiki/Hash_table">hash table</a> maps Redis objects to scores. This is an in-memory hash table which will auto-resize if needed, collisions are handled by chaining.</p><p><strong>Skip List: </strong>A <a href="https://en.wikipedia.org/wiki/Skip_list">skip list</a> maps scores to Redis objects. So, objects are sorted by scores in this view. SkipList is a probabilistic data structure that allows <em>O(log n)</em> average time complexity for search and insertion. A Skip List consists of a series of lists {S₀,S₁,…,Sₙ}, where list Sᵢ is randomly generated subset of the entries in the list Sᵢ₋₁.</p><p>Redis uses augmented Skip List. Each redis skip list node consists of:</p><ul><li>Redis object</li><li>Score</li><li>Forward Pointer</li><li>Backward Pointer at level 1 (i.e. its a doubly linked list at level 1)</li><li>Span (denoting the number of nodes to be traversed to reach this node)</li></ul><h4>Salient Features</h4><ul><li>Each skip list node can have multiple levels which is implemented as an array of forward pointer, span combination. Both head and tail pointers are available for the list.</li><li>The maximum number of levels in the skip list are capped at 32</li><li>The probability to insert a node at the next level is chosen as 0.25</li><li>The <a href="https://redis.io/docs/reference/internals/internals-sds/">SDS</a> string representing the object in skip list is the same as in hash table to save memory.</li><li>The skip-list can be traversed in forward direction (used in ZRANGE command) and in backward direction as it is a doubly linked list at level 1 (used in ZREVRANGE command)</li><li>ZRANK uses the span field to compute the rank after the element has been found in the skip list.</li></ul><h4>References</h4><ul><li><a href="https://redis.io/docs/data-types/sorted-sets/">https://redis.io/docs/data-types/sorted-sets/</a></li><li><a href="https://github.com/redis/redis/blob/unstable/src/t_zset.c">https://github.com/redis/redis/blob/unstable/src/t_zset.c</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd8840efa9d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Java’s random UUID unique ?]]></title>
            <link>https://medium.com/@saksenaprashant06/is-javas-random-uuid-unique-051af669f6e7?source=rss-91d2d320b983------2</link>
            <guid isPermaLink="false">https://medium.com/p/051af669f6e7</guid>
            <category><![CDATA[uuid]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Prashant Saksena]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 16:24:32 GMT</pubDate>
            <atom:updated>2024-02-20T16:24:32.925Z</atom:updated>
            <content:encoded><![CDATA[<h3>Is Java’s random UUID unique ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7XgsFC9BHP8amO_L" /><figcaption>Photo by <a href="https://unsplash.com/@vlisidis?utm_source=medium&amp;utm_medium=referral">Terry Vlisidis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>“Randomness is the true foundation of mathematics”</blockquote><blockquote>— <a href="https://en.wikipedia.org/wiki/Gregory_Chaitin">Gregory Chaitin</a></blockquote><p>Java’s <a href="https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html">java.util.UUID</a> represents an immutable universally unique identifier (UUID). In particular the static <a href="https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html#randomUUID--">randomUUID()</a> method of this class generates UUID which can be used as a unique identifier in distributed systems. But, is this UUID unique ? What are the chances that multiple calls to randomUUID() method will generate the same UUID ? What are the chances that such calls in distributed systems will result in duplicate identifiers ? Lets find out !</p><h4>UUID</h4><p><a href="https://www.ietf.org/rfc/rfc4122.txt">RFC4122</a> details out the complete UUID specification. A Universally Unique Identifier (UUID) represents a 128-bit value, i.e. 16 octets. Two most important fields determine the structure of UUID:</p><ul><li><strong>Variant</strong>: The variant field determines the layout of the UUID. The variant field consists of a variable number of the most significant bits of octet 8 of the UUID. Java’s java.util.UUID class implements, variant 2 (Leach-Salz variant) as default variant. Hence, pattern <strong>10x</strong> of the MSB of octet 8 represents this variant.</li><li><strong>Version</strong>: The version number of the UUID is in the most significant 4 bits of the 7th byte of the UUID. The different versions denoting different types of UUID are: time-based (version 1), DCE Security (version 2), name-based (version 3), randomly or pseudo-<br> randomly generated (version 4), name-based used SHA-1 (version 5).</li></ul><p>Java’s java.util.UUID.randomUUID() generates a type 4 (pseudo randomly generated) UUID. This UUID is generated using a cryptographically strong pseudo random number generator (using SecureRandom class in Java). An example UUID generated is “c6725645-ccbf-<strong>4</strong>f98-<strong>a</strong>e9e-e91eddb3d6b2”. The character “4” in bold represents version 4 &amp; character “a” in bold represents variant 2.</p><p>Version 4 UUID is randomly generated. As we have seen, out of a total of 128 bits in UUID, a total of 6 bits (2 bits for variant + 4 bits for version) are fixed. Hence, the randomly generated part consists of 122 bits, which implies that there can be 2¹²² such possible UUIDs.</p><h4>Birthday Problem</h4><p>The answer to this question of uniqueness lies in the famous problem in probability theory, the <a href="https://en.wikipedia.org/wiki/Birthday_problem#:~:text=The%20birthday%20paradox%20refers%20to,that%20probability%20to%20exceed%2050%25.&amp;text=The%20birthday%20paradox%20is%20a,is%2C%20in%20fact%2C%20true.">Birthday Problem</a>: What is the probability that in a set of <em>n</em> randomly selected people, at least two people have the same birthday.</p><p>Suppose there are 30 people in the room. Let us define two events:</p><p><em>A</em>: Two people among these 30 people share their birthdays</p><p><em>B</em>: No two people in the room have the same birthday</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*Iwv4UAmWPvh5okl1eAK1kw.png" /></figure><p>Let us generalise this result, if we have <em>n</em> people in the room and total of <em>m</em> birthdays, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*tb3S7OvV6wcDDpk0Fh4o6A.png" /></figure><p>Since, we are interested in uniqueness of version 4 random UUIDs, the birthday problem can be used to find a relation between the number of UUIDs which must be generated, which is <em>n</em>, and the probability of finding a duplicate UUID, which is <em>p</em>. Note, the total number of bits randomly generated in UUID is <em>m</em> = 2¹²².</p><p>Taking log on both sides of the relation defined above, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*_VMZa8d9eEvdpMmsGZ50WQ.png" /></figure><h4>Uniqueness of UUID</h4><p>Let us look at few combination of <em>n</em> and <em>p</em> values using the relation we derived in the previous section:</p><ul><li><em>n</em> = 2³⁵ , <em>p</em> = 1.1 * 10⁻¹⁶</li><li><em>n</em> = 2⁴¹, <em>p </em>= 4.5 * 10⁻¹³</li><li><em>n</em> = 2⁴⁶, <em>p</em> = 4.6 * 10⁻¹⁰</li></ul><p>Interestingly, the annual risk of a given person being hit by a meteorite is estimated to be one chance in 17 billion (which is 6*10⁻¹¹) which is approximately the probability of generating tens of trillions of UUIDs having one duplicate.</p><p>The probability to find a duplicate within 103 trillion UUIDs is one in a billion. The number of UUIDs that need to be generated in order to have 50% probability of duplication is approximately 2.71*10¹⁸, i.e. 2.71 quintillion, which is approximately equivalent to generating one billion UUIDs every second for around 86 years(2.71*10⁹ seconds).</p><p>Hence, we have seen that the UUID generated by Java’s java.util.UUID’s randomUUID() is a variant-2 version-4 random UUID. We can say that the probability that these UUIDs will be duplicated is close enough to zero such that it can be considered negligible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=051af669f6e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Algorithm behind Rsync]]></title>
            <link>https://medium.com/@saksenaprashant06/the-algorithm-behind-rsync-76c66a278152?source=rss-91d2d320b983------2</link>
            <guid isPermaLink="false">https://medium.com/p/76c66a278152</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[unix]]></category>
            <category><![CDATA[rsync]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Prashant Saksena]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 12:58:06 GMT</pubDate>
            <atom:updated>2023-11-28T13:08:11.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NhlMtcCG8j_Ep2Ob" /><figcaption>Photo by <a href="https://unsplash.com/@jordanharrison?utm_source=medium&amp;utm_medium=referral">Jordan Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>“we want algorithms that are good in some loosely defined aesthetic sense”</blockquote><blockquote>— <a href="https://en.wikipedia.org/wiki/Donald_Knuth">Donald Knuth</a></blockquote><p><a href="https://linux.die.net/man/1/rsync">Rsync</a> (or remote synchronization) is a tool in Linux (and other Unix like operating systems) that is used to sync files between two remote hosts. It is famous for its <strong><em>delta-transfer algorithm</em></strong>, which reduces the amount of data sent over the network by sending only the differences between the source files and the existing files in the destination.</p><p>Let us try to explore the algorithm behind rsync. This algorithm has been discussed by <a href="https://en.wikipedia.org/wiki/Andrew_Tridgell">Andrew Tridgell</a> in his Phd Thesis:</p><p>Tridgell, Andrew, <a href="https://rsync.samba.org/~tridge/phd_thesis.pdf"><em>Efficient Algorithms for Sorting and Synchronization</em></a>, February 1999, retrieved 29 September 2009</p><h4>Problem Statement</h4><p>There are two computer systems A &amp; B connected via network link. A has a file of <em>n</em> bytes in size, each byte denoted by <em>a</em>ᵢ. Similarly, B has a file of n bytes in size, each byte denoted by <em>b</em>ᵢ. So, we assume that each file is n bytes long.</p><p>The aim of the algorithm is to transfer a copy of file from A to B.</p><h4>Rsync Algorithm</h4><p>The basic outline of the algorithm consists of B sending some data to A, A subsequently matches received data with its own data &amp; sends the delta to B, which B uses to construct the file at its end. A simple way is to send signature computed on each block from B to A. But, byte boundaries should also be considered while computing these signatures.</p><p>Hence, two signatures are chosen, say <em>R</em> and <em>H. R </em>is very cheap &amp; will be computed for all byte offsets. <em>H </em>is expensive, but has very low probability of collision, will be computed by A at byte offsets only, where cheap signature matches with the cheap signature at B.</p><p>Algorithm for Rsync can be summarised as:</p><p>1. B divides bᵢ into N sized blocks bᵏ <br>2. B computes signatures Rᵏ and Hᵏ on each block<br>3. B sends these signatures to A<br>4. For each byte offset i, A computes Rˡ on the corresponding block aᵢ<br>5. A compares Rˡ with Rᵏ received from B<br>6. For each i, If Rˡ matches with Rᵏ, A computes Hˡ and compares with Hᵏ<br>7. If Hˡ matches Hᵏ, A sends a token to B indicating a block match<br>8. Otherwise, A sends a literal byte to B<br>9. B receives literal bytes &amp; tokens from A and uses these to construct aᵢ</p><h4>Conclusion</h4><p>Rsync is a very efficient utility for transferring and synchronizing files between remote computers. The choice of signatures is very important, for example, MD4 is sometimes used as the strong signature due its properties. Similarly, a cheap signature should be fast &amp; should be chosen accordingly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76c66a278152" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RabbitMq: Garbage Collection]]></title>
            <link>https://medium.com/@saksenaprashant06/rabbitmq-garbage-collection-23f122ab78c8?source=rss-91d2d320b983------2</link>
            <guid isPermaLink="false">https://medium.com/p/23f122ab78c8</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[garbage-collector]]></category>
            <dc:creator><![CDATA[Prashant Saksena]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 17:25:55 GMT</pubDate>
            <atom:updated>2023-07-24T17:25:55.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4xr30m5Sbhmnndnu" /><figcaption>Photo by <a href="https://unsplash.com/@ptrikutam?utm_source=medium&amp;utm_medium=referral">Pavan Trikutam</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Although computer memory is no longer expensive, there’s always a finite size buffer somewhere. When a big piece of news arrives, everybody sends a message to everybody else, and the buffer fills</blockquote><blockquote>— <a href="https://en.wikipedia.org/wiki/Benoit_Mandelbrot">Benoit Mandelbrot</a></blockquote><p>RabbitMq is an open source message broker widely used in the industry. It implements a variety of messaging protocols, <a href="https://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol">AMQP</a> being the primary one. In this post, we will try to explore how RabbitMq manages its garbage collection and hence reclaim memory which is no longer in use.</p><h4>Garbage Collection in Erlang</h4><p>RabbitMq is written in <a href="https://en.wikipedia.org/wiki/Erlang_(programming_language)">Erlang</a>. Erlang is a high level, concurrent programming language and has its own garbage collected runtime system. We need to firstly understand how Erlang manages memory and hence its garbage collection.</p><p><strong>Cheney’s Algorithm</strong></p><p>Erlang has a tracing garbage collector, i.e. garbage collection is performed per Erlang process using <a href="https://en.wikipedia.org/w/index.php?title=Cheney%27s_algorithm&amp;oldid=1142473777">Cheney’s</a> copy collection algorithm.</p><ul><li>Cheney’s algorithm uses breadth-first search to traverse reachable data.</li><li>Firstly, root data is copied from “From” space to “To” space, and then other data reachable from the root data is copied.</li><li>Cheney’s algorithm uses no external stack, it uses the “To” space as the queue for its breadth-first search.</li></ul><p><strong>Collection Algorithm</strong></p><p>Each Erlang process has its own stack &amp; heap, which grow towards each other and when the stack and the heap meet, the garbage collector is triggered and memory is reclaimed. The following figure explains the process of collection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*vR1oH44EQhxvgfN0hO7OoA.jpeg" /></figure><p><strong>Generational Collection</strong></p><p>Erlang garbage collection also supports generational garbage collection, wherein another memory area, called old heap, is used for long lived objects. The generational garbage collection is explained in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Q2koounliQw3-_0H1nUoQ.png" /></figure><p>A detailed description of Erlang garbage collection is given in this <a href="https://www.erlang-solutions.com/blog/erlang-garbage-collector/">blog</a>.</p><h4>Garbage Collection in RabbitMq</h4><p>RabbitMq documentation provides details of memory distribution across different components like connections, queues, quorum queues, mirrored queues, message store, binary heap, etc.</p><p>Each RabbitMq queue is backed by an Erlang process. Memory used by the queue majorly consists of message metadata and payload. We have seen Erlang uses generational garbage collection for each Erlang process, hence garbage collection is done per queue, independently of all other Erlang processes.</p><p><strong>Simulations</strong></p><p>Let us try to simulate garbage collection behaviour. Create a Queue (with Direct exchange). Produce 100k string messages, few bytes in size. After some time, consume messages and then again produce some messages. Monitor garbage collection stats for this queue using:</p><p><em>rabbitmqctl eval ‘[erlang:process_info(Pid,[registered_name,garbage_collection_info]) || Pid &lt;- processes()].’</em></p><p>Erlang provides GC statistics in following format:</p><ul><li><em>old_heap_size</em>: The size of the used part of the old heap.</li><li><em>heap_size</em>: The size of the used part of the heap.</li><li><em>heap_block_size</em>: The size of the memory block used for storing the heap and the stack.</li><li><em>old_heap_block_size</em>: The size of the memory block used for storing the old heap.</li><li><em>stack_size</em>: The size of the stack.</li><li><em>recent_size</em>: The size of the data that survived the previous garbage collection.</li><li><em>mbuf_size</em>: The combined size of message buffers associated with the process.</li><li><em>bin_vheap_size</em>: The total size of unique off-heap binaries referenced from the process heap.</li><li><em>bin_vheap_block_size</em>: The total size of binaries allowed in the virtual heap in the process before doing a garbage collection.</li><li><em>bin_old_vheap_size</em>: The total size of unique off-heap binaries referenced from the process old heap.</li><li><em>bin_old_vheap_block_size</em>: The total size of binaries allowed in the virtual old heap in the process before doing a garbage collection.</li></ul><p>The result of simulations are shown in following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*ZSMx9hbSG2-W9A8g2KCrwQ.jpeg" /></figure><h3>Conclusion</h3><p>RabbitMq efficiently manages memory using generational garbage collection. However, there are few points to note with respect to garbage collection in RabbitMq:</p><ul><li>Since the collection is based on Cheney’s copy algorithm, the memory in use is copied before unused memory is deallocated. This can result in process using double the used memory in worst case. Rabbitmq provides alarms for high watermark setting for memory usage.</li><li>Cheney’s algorithm uses breadth-first search, pointers copied by breadth-first search have poor locality of reference. Since computer systems use virtual memory or memory cache, good locality of reference holds significance.</li></ul><p>For detailed description on memory usage in RabbitMq refer <a href="https://www.rabbitmq.com/memory-use.html">RabbitMq documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23f122ab78c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PRAM: Parallel Random Access Machine]]></title>
            <link>https://medium.com/@saksenaprashant06/pram-parallel-random-access-machine-7649f3b07d20?source=rss-91d2d320b983------2</link>
            <guid isPermaLink="false">https://medium.com/p/7649f3b07d20</guid>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Prashant Saksena]]></dc:creator>
            <pubDate>Wed, 18 Jan 2023 16:39:56 GMT</pubDate>
            <atom:updated>2023-01-24T12:44:29.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*gZKz6WVMz17_5ZOlqUtmWQ.jpeg" /></figure><p>Theoretical models of parallel computations are often used by algorithm designers and developers. These models can be applied to obtain performance bounds on parallel computers and are also useful in scalability analysis. The Parallel Random Access Machine (PRAM) model is one such abstract model for parallel computation.</p><h3>PRAM Model</h3><p>The Parallel Random Access Machine (PRAM) model was developed for modelling idealised parallel computers. The model was developed by Fortune and Wyllie:</p><p>S. Fortune and J. Wyllie, “Parallelism in Random Access Machines”, <em>Proc. ACM Symp. Theory of Computing</em>, pp. 114–118, 1978.</p><p>An n-processor PRAM consists of global shared memory. We can assume that there is no memory or synchronisation overhead in these parallel computers, hence the n-processors operate on a synchronized shared memory. Following memory update operations are possible:</p><ul><li>Exclusive read: This allows at most one processor to read from any memory location at a time.</li><li>Exclusive write: This allows at most one processor to write into memory location at a time</li><li>Concurrent read: This allows multiple processors to read same memory location at the same time</li><li>Concurrent write: This allows simultaneous writes to the same memory location.</li></ul><h3>PRAM Variants</h3><p>Based on combinations of memory update operation, following are the variants of the PRAM model:</p><ol><li><strong>EREW model</strong>: More than one processor cannot read or write the same memory location simultaneously.</li><li><strong>CREW model</strong>: Concurrent reads to same memory location allowed but exclusive writes are allowed.</li><li><strong>ERCW model</strong>: Exclusive reads but concurrent writes to same memory location.</li><li><strong>CRCW model</strong>: Allows either concurrent reads or concurrent writes at the same time.</li></ol><p>Conflicting writes are resolved by one of following policies:</p><ul><li>Common Policy: Simultaneous writes store the same value to the given memory location.</li><li>Arbitrary Policy: Any one of the written values is retained and other values are discarded</li><li>Minimum Policy: The value written by processor with minimum index is retained</li><li>Priority Policy: Values written are combined by summing them or taking maximum, etc.</li></ul><p>CRCW PRAM algorithm is quite powerful. As an example, suppose we have a Boolean Array and ask is to compute OR of all the bits in the array. We take an output bit and assign the value 0 to it. Next, we assign a processor to each bit in the array. Then each processor that has been assigned value 1 will write the value 1 to the output bit using any of the above policies to resolve write conflicts. This way, we compute the OR of n-bits in O(1) time using n processors in CRCW PRAM model. CRCW model is generally considered unrealistic, hence the other models are more popular in practical sense.</p><h3>Conclusion</h3><p>PRAM models are ideal models for parallel computing where all memory references and executions by multiple processors are synchronized with no extra cost. PRAM model is well suited for discovering parallelism in the given problem and for developing efficient parallel algorithms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7649f3b07d20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrent Markings in Garbage Collection]]></title>
            <link>https://medium.com/@saksenaprashant06/concurrent-markings-in-garbage-collection-457c7a0730eb?source=rss-91d2d320b983------2</link>
            <guid isPermaLink="false">https://medium.com/p/457c7a0730eb</guid>
            <dc:creator><![CDATA[Prashant Saksena]]></dc:creator>
            <pubDate>Tue, 26 Jul 2022 16:57:25 GMT</pubDate>
            <atom:updated>2023-01-18T16:36:10.867Z</atom:updated>
            <content:encoded><![CDATA[<p>The most troublesome task that I can remember when writing C programs was to specially deallocate the previously allocated memory. Java language’s one of the finest achievement is its built in garbage collection.</p><p>The basic idea is Mark-And-Sweep algorithm for collection. The program variables and heap allocated objects form a directed graph. A graph search algorithm like Depth First Search can mark all the reachable nodes and nodes not marked are reclaimed by a sweep of the entire heap. Mark-Sweep collection is almost as old as languages with pointers [5].</p><p>Java uses generational garbage collection, taking advantage of the fact that newer objects die quickly and there are few old to new pointers. Java offers various garbage collectors namely Serial, Parallel, Concurrent Mark-Sweep(CMS) and Garbage-First(G1) collector. Old generation collection algorithms in Serial and Parallel collectors are stop the world, whereas CMS and G1 interleave garbage collection work concurrently with the program execution to minimize pause time.</p><p>Old generation marking phase in G1 and CMS are focused on majorly three states: Initial Mark(stop the world), Concurrent Marking and Remark(stop the world). Of course there are many other states also, like Root Region Scanning in G1, etc., but in this post the focus is to give an essence of concurrent marking scheme with few references to G1 collector.</p><p>Let us define few terms:</p><ul><li><strong>Mutator</strong>: During the concurrent marking phase, the collector tries to collect the garbage objects, meanwhile the program keeps mutating the graph of reachable objects, hence it is called the mutator.</li><li><strong>Tri-color marking</strong> — In concurrent garbage collection, there are three types of objects in the graph: a) White objects: objects that have not yet been visited, b) Gray objects: objects that have been visited, i.e. marked but their children have not yet been examined, c) Black objects: objects that have been marked and their children have also been marked.</li></ul><p>In concurrent marking phase, the collector starts with all objects white and marks live objects, blackening gray objects and graying their white children. While the collector marks objects, the mutator creates new objects and updates pointer fields of existing objects.</p><p>There are two ways in which garbage collection’s concurrent traversal will fail:</p><ol><li>mutator writes a pointer to a white object into a black object</li><li>mutator destroys a pointer before the collector has examined it</li></ol><p>The garbage collector must assume that it has marked all black objects and can continue to traverse gray objects and move forward. Due to the two conditions, the collector may not be able to locate object and hence the object may be deemed garbage and reclaimed.</p><p>To solve this, there are two classes of algorithms:</p><ul><li><em>read barrier</em>: this detects when the mutator tries to read the a pointer to white object and immediately colors the object gray, hence the mutator will not be able to write a white object into black object since it can’t read pointers to white object.</li><li><em>write barrier</em>: each write by the mutator must be checked to ensure that these two conditions never happen.</li></ul><p>G1 garbage collector uses Snapshot-at-the-beginning(SATB) algorithm, a write barrier, which is much faster than what was used in the CMS collector. SATB ensures that the second condition cannot happen. At the beginning, SATB creates a logical “snapshot” of the object graph existing at that point. To ensure that second condition does not happen, i.e. mutator does not remove a pointer, SATB marking enforces mutator threads to save the values of pointer fields in separate data-structure before the field is overwritten. Also, Objects allocated during marking are necessarily considered live, hence they are marked and need not be traced, they are not part of the object graph that exists at the start of marking. Java’s Garbage-First (G1) collector is a server-style garbage collector, is planned as the long term replacement for the Concurrent Mark-Sweep Collector (CMS).</p><p>To conclude, the article gives a birds eye view of the concurrent marking scheme in concurrent garbage collectors like CMS &amp; G1. More detailed explanation can be obtained from the references, as:</p><p><em>An algorithm must be seen to be believed: Donald Knuth</em></p><h4>References</h4><p>[1] Getting Started with the G1 Garbage Collector, <a href="http://www.oracle.com/technetwork/tutorials/tutorials-1876574.html">http://www.oracle.com/technetwork/tutorials/tutorials-1876574.html</a></p><p>[2] Andrew W. Appel, Modern Compiler Implementation in Java, Cambridge University Press.</p><p>[3] Paul R. Wilson, Uniprocessor Garbage Collection Techniques, IWMM ’92 Proceedings of the International Workshop on Memory Management, Pages 1–42</p><p>[4] Detlefs, D., Flood, C., Heller, S., and Printezis, T. 2004. Garbage-first garbage collection. In Proceedings of the 4th international Symposium on Memory Management (Vancouver, BC, Canada, October 24–25, 2004)</p><p>[5] McCarthy, J. 1960. Recursive functions of symbolic expressions and their computation by machine — I. Commun. ACM 3(1), 184–195.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=457c7a0730eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PetriNets: Modelling Concurrent Systems]]></title>
            <link>https://medium.com/@saksenaprashant06/petrinets-modelling-concurrent-systems-28b1ab62e431?source=rss-91d2d320b983------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b1ab62e431</guid>
            <category><![CDATA[petri-nets]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Prashant Saksena]]></dc:creator>
            <pubDate>Wed, 25 May 2022 17:25:19 GMT</pubDate>
            <atom:updated>2023-03-23T18:10:18.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*uonijxfS2HgCqnFrGoeAaw.jpeg" /><figcaption>PetriNet</figcaption></figure><p>There are many ways to mathematically model a system. Formal models are used to check the correctness of the system by representing the system mathematically. In this post, we take a look at PetriNets, which can be used to mathematically model behavior of distributed systems. Specifically, we will look at how PetriNets can be used to model concurrent systems.</p><h4>Introduction to Petri Nets</h4><p>PetriNets is formal language/graphical language for modelling systems. PetriNets were introduced by Carl Adam Petri in 1962 as part of his Ph.d. Thesis, although there are stories that he had discovered them at the age of 13 for the purpose of describing chemical processes.</p><p>Mathematically, a Petri Net is a <strong>bipartite graph</strong> with two vertex types, Places and Transitions. Places denote the conditions and Transitions denote the events/activities. Since, this is a bipartite graph, Places and Transitions are connected via directed edges, called Arcs from places to transitions and from transitions to places. Tokens are the basic entities in the system that circulate between places.</p><p>If there is a directed arc from place P to transition T, then P is called Input Place of T &amp; if there is a directed arc from transition T to place P, then P is called Output Place of T. Weights (Integers) can be associated with the arcs. If nothing is attached to the arc, its weight is 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*ni_SraFYHtxDBlfnFa0gZQ.jpeg" /><figcaption>Figure-1: Description of a PetriNet</figcaption></figure><p>Hence, the PetriNet is defined by:</p><ul><li>Set of Places, denoted graphically by circles</li><li>Set of Transitions, denoted graphically by bars or rectangles</li><li>Input Places associated with corresponding Transitions</li><li>Output Places associated with corresponding Transitions</li></ul><p>The system state can be defined as the set of number of tokens in different places, some places having more than one token and some having zero tokens. The token distribution in all places is called <em>Marking</em> of a PetriNet.</p><p>Markings of a PetriNet at time t: m(t) = {m₁(t), m₂(t), ….., mᵣ(t)}</p><p>where, mᵢ(t) = number of tokens in place i at time t. m(t₀) denotes the Marking at time t₀, i.e. initial state of PetriNet.</p><h4>Firing of a transition</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*ZW21d5uQggMzFv8k1EzIQA.jpeg" /><figcaption>Figure-2: Firing of a Transition</figcaption></figure><p>PetriNet can go from one marking to another via transition firing. When the number of tokens in the input place becomes more than the weight of the arc joining this place with the transition, the transition becomes firable. When the transition is fired, its firing defines the next marking of the PetriNet.</p><p>Firing of a transition is defined by following process:</p><ol><li>A transition is enabled when the place connecting to this transition has n tokens, where n is more than or equal to k, the weight of the corresponding arc connecting this place with the transition.</li><li>During a firing, k tokens are withdrawn from the input place containing n tokens (n &gt;= k), i.e. the number of tokens corresponding to the weight of the arc are withdrawn from the input place.</li><li>And m tokens are added to the output place connected to this transition, where m is the weight of the arc connecting this transition to the output place.</li></ol><h4>Readers-Writers Problem</h4><p>Let us look at the classic problem: the readers-writers problem. The problem states that there is a data area shared among a number of processes, some of these processes can only read the data area (called readers) and the others can only write to the data area (called writers).</p><p>The readers and writers must satisfy the following conditions:</p><ol><li>Only one writer at a time can write to the shared data, i.e. there should be mutual exclusion among the writer processes.</li><li>Any number of readers can simultaneously read the data, i.e. since the reader processes do not modify the data, the readers can read in parallel without exclusion.</li><li>There must be mutual exclusion among the reader and the writer processes, i.e. if a writer is writing to the data, no reader can read it and vice-versa.</li></ol><p>Hence, the readers and writers must be synchronized for updating the shared data area. Let us try to model this problem using PetriNets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*vaqnltVincFS6uITF2lXiA.jpeg" /><figcaption>Figure-3: Readers-Writers Problem modelled using PetriNets</figcaption></figure><p>Figure-3 gives a PetriNet model for reader-writer semantics. This PetriNet can be explained as follows:</p><ul><li>PLR and PLW are the entry places for readers and writers respectively, i.e. readers and writers make the requests when PLR and PLW are marked.</li><li>Place RES is marked with N tokens, which defines the number of readers that can read in parallel.</li><li>A reader is initiated when place PLR is marked, i.e. when alloc-lec is fired. This firing removes a token from RES and adds a token to LEC.</li><li>Note that alloc-lec can be fired N times, i.e. N readers can read in parallel.</li><li>When at least one reader reads, at least one token has been removed from RES. This means that marking of RES is lower than N, hence if the writer is initiated when place PLW is marked, the transition authorizing the writing, namely alloc-ecr, cannot be fired (as the arc joining RES with alloc-ecr has weight N). This ensures mutual exclusion between readers and writers.</li><li>If no reading is in progress, alloc-ecr can be fired if PLW is marked. In this case, N tokens are removed from RES and RES becomes empty ensuring that alloc-lec is unfirable and hence no reader can start reading. This ensures mutual exclusion between readers and writers.</li><li>In the previous case, when RES is empty due to writer process, alloc-ecr cannot be fired ensuring mutual exclusion between writers.</li><li>When the writing is completed, l-ecr is fired and N tokens are returned to RES. Similarly, whenever a reader finishes reading, l-lec is fired and a token is returned to RES. This re-initialises the given Petrinet.</li></ul><h4>Conclusion</h4><p>PetriNets are used for modelling behavior of varied kind of systems like computer systems, communication systems, manufacturing and production systems, etc. There are many variations of PetriNets like Colored PetriNets, Sochastic PetriNets, etc that can be used to model different kinds of systems. Since multiple transitions can be enabled at the same point in time and multiple tokens can be present anywhere in the net, PetriNets are well suited to model concurrent systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b1ab62e431" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>