<?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 Sarvesh Khetan on Medium]]></title>
        <description><![CDATA[Stories by Sarvesh Khetan on Medium]]></description>
        <link>https://medium.com/@khetansarvesh?source=rss-ff946da4f2c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EWSBchQChOcmky7l6p0QaA.jpeg</url>
            <title>Stories by Sarvesh Khetan on Medium</title>
            <link>https://medium.com/@khetansarvesh?source=rss-ff946da4f2c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:50:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khetansarvesh/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[Evaluating Agents]]></title>
            <link>https://khetansarvesh.medium.com/evaluating-agents-a9f6e9378952?source=rss-ff946da4f2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9f6e9378952</guid>
            <dc:creator><![CDATA[Sarvesh Khetan]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 20:32:59 GMT</pubDate>
            <atom:updated>2026-07-08T03:53:50.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Evaluating Single — Agent Architecture</h3><p>To evaluate an agent we evaluate it along 3 axes !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RP4nzWaOmZNH9gjlXDBDgA.png" /><figcaption>Now once we evaluate along each axes we do a weighted combination of each of them to get a single score</figcaption></figure><p>Now below there will be some guidelines on how to evaluate each of these components but we should keep one rule in mind — <strong>always try to add as many deterministic steps to evaluation compared to non — deterministic (llm-as-a-judge) steps</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0V4g7qFLPqFFD18Ib5Tog.png" /></figure><h3>Final Answer Evaluation</h3><p>We should evaluate the final answer along multiple axes !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14IYON8IZFENBhfDTumXIw.png" /><figcaption>Now to get one final score you should do weighted average</figcaption></figure><p>Now there are many ways to <strong>compare the final answer with the ground truth</strong>, depending on the answer type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0K22wovCZI04CiI8VTNPwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0V4g7qFLPqFFD18Ib5Tog.png" /></figure><h3>Agent Trace Evaluation</h3><p>Now here we evaluate the trace on two axes :</p><ul><li><strong>Trace Correctness : </strong>Was the trace right / wrong ?</li><li><strong>Trace Correctness Efficiency :</strong> If the trace was right, how efficient was it ? eg a trace can be right trace but take 100 turns to be right vs 5 turns to be right !</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xShb6HrZ-R1xf-Hk45zSnQ.png" /></figure><h3>Trace Correctness</h3><p>Now to evaluate this we need to think about from where does the agent get information ? from tools / RAG chunks. Hence we need to evaluate</p><ul><li>if the tool used to answer a particular question was the right tool or not.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knICW7cqRUXt9wH6UIcB_A.png" /></figure><ul><li>if the chunks retrieved for a particular question were right chunks or not.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xShb6HrZ-R1xf-Hk45zSnQ.png" /></figure><h3>Trace Correctness Efficiency</h3><p>For this we should track things like</p><ul><li>latency</li><li>tool failure rate</li><li>#turns</li><li>#tool_calls</li><li>#total_tokens_used</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0V4g7qFLPqFFD18Ib5Tog.png" /></figure><h3>Agent Trace v/s Final Answer Evaluation</h3><p>Here we use <strong><em>Checklist based method</em></strong> to see if the final answer is grounded in the gathered information. Let’s understand this via say citations as source that the agent gathered during it’s run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxlUbZ_QGRYUK8izzfWfwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Evaluating Multi — Agent Architecture</h3><p>Now for a multi agent architecture, we do the above three steps i.e. Answer Eval + Trace Eval + Trace vs Answer Eval for each agent in the multi-agent system. Few examples are given below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*yDkg6_coRiBnxecbRRgbeQ.png" /></figure><ul><li><strong>Planner Agent :</strong> For the planner agent in above architecture the output is sub_queries, so we can check what subqueries are being created, is it correct or not, … etc etc.</li><li><strong>Evidence Checker Agent : </strong>For evidence checker agent we can check if in each iteration it is reducing or not i.e. in first iteration it gives 5 information is missing, in second iteration it gives 2 evidence missing and finally it says nothing missing. This shows that evidence checker is working great !</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9f6e9378952" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding KV Cache / Prompt Cache in Auto-Regressive Models]]></title>
            <link>https://khetansarvesh.medium.com/understanding-kv-cache-prompt-cache-in-auto-regressive-models-27a33044afab?source=rss-ff946da4f2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/27a33044afab</guid>
            <dc:creator><![CDATA[Sarvesh Khetan]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 20:24:00 GMT</pubDate>
            <atom:updated>2026-06-17T22:09:58.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*L1PBwplSSpyMCFW6mPhPug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KndIlWyrPubRmAh1VWwwLg.png" /></figure><p>As we can see that for subsequent token prediction we only need the K and V and hence those are cached !!</p><ul><li><strong>KV Cache is reducing</strong> as model architecture keeps improving from MHA =&gt; GQA =&gt; MHLA</li><li><strong>LM Cache</strong> is a good open source repo for best KV Cache! VLM / SGLang can make use of LM Cache.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0V4g7qFLPqFFD18Ib5Tog.png" /></figure><h3>Code Implementation</h3><pre>class MultiHeadedAttention(nn.Module):<br><br>    def __init__(self):<br>       super().__init__()<br>       self.linear_1 = nn.Linear(768, 8*64, bias=True)<br>       self.linear_2 = nn.Linear(768, 8*64, bias=True)<br>       self.linear_3 = nn.Linear(768, 8*64, bias=True)<br>       self.output_proj = nn.Linear(8*64, 768)<br><br>       ###################################################<br>       # NEW FOR KV CACHING : defining the two non-persistent buffers,<br>       # which will hold concatenated keys and values across steps<br>       self.register_buffer(&quot;cache_k&quot;, None, persistent=False)<br>       self.register_buffer(&quot;cache_v&quot;, None, persistent=False)<br>       ###################################################<br><br>   def forward(self, query, key, value, use_cache = False):<br>       B = x.shape[0] # X =&gt; Batch Size x M x N (=768)<br>       <br>      &#39;&#39;&#39;Projecting X to get K Q and V&#39;&#39;&#39;<br>       q = self.linear_1(query) # Batch Size x M x 512<br>       k = self.linear_2(key) # Batch Size x M x 512<br>       v = self.linear_3(value) # Batch Size x M x 512<br>      <br>      &#39;&#39;&#39;Splitting&#39;&#39;&#39;# Batch Size x Number of Patches x (8 * 64) =&gt; Batch Size x 8 x Number of Patches x 64<br>       q = rearrange(q, &#39;b n (n_h h_dim) -&gt; b n_h n h_dim&#39;, n_h=8, h_dim=64)<br>       k = rearrange(k, &#39;b n (n_h h_dim) -&gt; b n_h n h_dim&#39;, n_h=8, h_dim=64)<br>       v = rearrange(v, &#39;b n (n_h h_dim) -&gt; b n_h n h_dim&#39;, n_h=8, h_dim=64)<br>       &#39;&#39;&#39; Calculating Attention &#39;&#39;&#39;<br>       <br>      ###################################################<br>       # NEW FOR KV CACHING USED ONLY DURING INFERENCE, use_cache == True only during inference<br>       if use_cache == True:<br>            # updating the cache by adding newly generated k and v<br>            if self.cache_k is None: <br>                self.cache_k, self.cache_v = k, v<br>            else:<br>                self.cache_k = torch.cat([self.cache_k, k], dim=1)<br>                self.cache_v = torch.cat([self.cache_v, v], dim=1)<br>            # retrieving the k and v information from cache<br>            k, v = self.cache_k, self.cache_v<br>       ###################################################<br>       att = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(64) # B x H x N x Head Dimension @ B x H x Head Dimension x N =&gt; B x H x N x N<br>       <br>       &#39;&#39;&#39; Passing Attention to Softmax&#39;&#39;&#39;<br>       att = torch.nn.functional.softmax(att, dim=-1)<br>       <br>       &#39;&#39;&#39; Multiplying attention and value vector&#39;&#39;&#39;       <br>       out = torch.matmul(att, v) #  B x H x N x N @ B x H x N x Head Dimension -&gt; B x H x N x Head Dimension<br>       <br>       &#39;&#39;&#39;Concatenation&#39;&#39;&#39;      <br>       out = rearrange(out, &#39;b n_h n h_dim -&gt; b n (n_h h_dim)&#39;) # B x N x (8 * 64) =&gt; B x N x 512<br>       <br>       &#39;&#39;&#39;Projecting back to original dimension&#39;&#39;&#39;<br>       out = self.output_proj(out)<br><br>       return out, att</pre><pre>class TransformerEncoderLayer(nn.Module):<br>    <br>    def __init__(self):<br>       super().__init__()<br>       # Attention Block<br>       self.att_norm = nn.LayerNorm(768, elementwise_affine = False, eps = 1E-6)<br>       self.attn_block = MultiHeadedAttention()<br>       &#39;&#39;&#39;<br>        Instead of self implementation, you can use pytorch based implementation<br>        also for attention layer<br>        nn.MultiheadAttention(embed_dim=768, num_heads=8, batch_first=True)<br>       &#39;&#39;&#39;<br>       <br>       # FFNN block<br>       self.ff_norm = nn.LayerNorm(768, elementwise_affine = False, eps = 1E-6)<br>       self.mlp_block = nn.Sequential( nn.Linear(768, 4 * 768), <br>                                       nn.GELU(approximate=&#39;tanh&#39;), <br>                                       nn.Linear(4 * 768, 768)<br>                                      )<br>   def forward(self, x, use_cache = False):<br>       # attention block<br>       attn_norm_output = self.att_norm(x)<br>       attn_output, _ = self.attn_block(query = attn_norm_output,<br>                                        key = attn_norm_output,<br>                                        value = attn_norm_output,<br>                                        use_cache = use_cache)<br>       out = x + attn_output<br>       <br>       # FFNN block<br>       mlp_norm_output = self.ff_norm(out)<br>       out = out + self.mlp_block(mlp_norm_output)<br>       return out<br><br>transformer_encoder_layer = TransformerEncoderLayer()</pre><p>Above I have only implemented KV Caching with Multi headed Attention (MHA) but similarly you can do KV Caching with <strong><em>MoE / MQA / GQA / MHLA / SWA</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0V4g7qFLPqFFD18Ib5Tog.png" /></figure><h3><em>Attention Time Complexity After KV Cache</em></h3><p>So previoulys we saw that attention is quadratic time complecity here, but given that we have reduced the duplicate work so much, did this reduce the time complexity ??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0V4g7qFLPqFFD18Ib5Tog.png" /></figure><h3>Disadvantages of KV Cache</h3><p>It is huge and now needs to be stored in the GPU(s) memory ! It can be distributed amongst multiple GPUs incase we have multiGPU setup but it is. huge for that too !!</p><p><strong>Solution ??</strong> Now people have started to offload KV cache storage to other storage like SSDs / CPU / Object Store — they are okay with the network latency cost i.e. a slight reduced in inference speed</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27a33044afab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inference Engines (vLLMs / SGLang)]]></title>
            <link>https://khetansarvesh.medium.com/inference-engines-vllms-sglang-2a47c5c6d4af?source=rss-ff946da4f2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a47c5c6d4af</guid>
            <dc:creator><![CDATA[Sarvesh Khetan]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 01:52:44 GMT</pubDate>
            <atom:updated>2026-07-10T20:19:59.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>A. Optimize Single Requests</h3><p>There are several levers we can pull to improve inference for single request. Firstly you can re-utilize the optimizations did during training like <strong>Kernel Optimization</strong> / <strong>Parallelism</strong> (Tensor / Pipeline / data / expert). But there are certain test time optimizations that can also be done, like : -</p><ul><li><strong>Model Compression : </strong>Quantization / Pruning / NAS / Distillation</li><li><a href="https://medium.com/p/27a33044afab?postPublishedType=initial"><strong>KV Cache / Prompt Cache</strong></a><strong> </strong>(specific to auto-regressive models)</li><li><a href="https://www.youtube.com/watch?v=VkWlLSTdHs8"><strong>Speculative Decoding</strong></a><strong> / Multi Token Prediction </strong>(specific to auto-regressive models) : vLLMs have a very good <a href="https://github.com/vllm-project/speculators">repo</a> where they have build good sepculator models</li></ul><h3>B. Optimize Multiple Requests</h3><ul><li><a href="#1979">Architecture 1</a> : Base Architecture</li><li><a href="#823b">Architecture 2</a> : <strong>Paged Attention</strong> for better KV cache storage</li><li><a href="#e78a">Architecture 3</a>: <strong>Chunked Prefill</strong> for long prompts</li><li><a href="#7d63">Architecture 4</a>: <strong>Prefix Caching</strong> for shared prompts</li><li><a href="#2608">Architecture 5</a> : <strong>Disaggregated P/D</strong> for Continuous Batching</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Architecture 1</h3><p>LLM inference is no longer just about loading a model and calling <a href="https://huggingface.co/docs/transformers/main/en/main_classes/text_generation">generate()</a>. That works for a single request, but the moment we move toward real serving workloads, the problem becomes much more interesting. Now the system has to handle many requests (<strong>high throughput</strong>) at <strong>low latency</strong>.</p><p>Above we saw techniques to improve individual model requests but can we gain some more efficiencies when we serve multiple requests together ??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtEQ3vF-HcTSBkox2vpKlQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0V4g7qFLPqFFD18Ib5Tog.png" /></figure><h3>Metrics to Evaluate an Inference Engine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ksp12RRHFByK8A8-LF2pjQ.png" /></figure><p><strong>Prefill Stage is compute bound</strong> because here a lot of calculations happen to perform attention and hence the KV cache is generated.</p><ul><li><strong>Time to First Token (TTFT)</strong> measures how long Prefill stage takes, directly impacting user experience since this is the wait time before seeing 1st output.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ksp12RRHFByK8A8-LF2pjQ.png" /></figure><p><strong>The Generation Stage is memory bound</strong> since here GPU spends most time loading the memory rather than performing calculations.</p><ul><li><strong>Inter-Token Latency (ITL)</strong> measures the time between consecutive token generations in the decode phase. This metric determines how fast text streams to the user after generation begins.</li><li><strong>Time Per Output Token (TPOT)</strong> is the average ITL across all output tokens in a request.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEfcFbeQiwgI67m3wFuHCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0V4g7qFLPqFFD18Ib5Tog.png" /></figure><h3>Scheduler + KV Cache Manager</h3><p>So based on above architecture, we have two engines — ‘prefill’ and ‘decode’. We need a service which can orchestrate workloads to these engines cause a workload can only pass to a decode engine after it has completed the prefill stage !! This orchestrator is called <strong>SCHEDULER</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7KiVDYwZiQ1e3yQh3ZQoJA.png" /></figure><p>Scheduler prioritizes decode requests over prefill requests. Now both these request would need memory ( prefill to store the KV cache and decode to use stored KV cache ). Hence scheduler also talks to the <strong>KV Cache Manager service</strong> which provides information like :-</p><ul><li>What memory blocks are free currently to store KV cache (for prefill stage).</li><li>For a particular request where it’s KV cache is stored in the memory (for decode stage)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Architecture 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0V4g7qFLPqFFD18Ib5Tog.png" /></figure><h3>Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Inxp-WQAa_ZpWIxbKcyIEg.png" /></figure><p>Now we will process the 1st Batch of requests</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvMb8SDw1fLja5QdOVlpGQ.png" /></figure><p>After this 1st batch is processed, let’s say we get rid of KV1 and KV3, cause it is no more needed. Hence now our GPU cluster looks like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*1PII2Y6pG01-RGVR47_3yw.png" /></figure><p>Now, let’s say we process Batch2 of input queries / prompts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fojKa8lB3zXyjKEmBhQb0g.png" /></figure><p>Hence, you can see that even though we have the gpu memory space to store the new KV cache, we are not able to since we don’t have a <strong>continuous space</strong> to store it !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0V4g7qFLPqFFD18Ib5Tog.png" /></figure><h3>Solution : Paged Attention</h3><p>Instead of storing KV cache as one large contiguous memory region per request, we divide KV cache into smaller blocks. The <strong>KV cache manager</strong> is the heart of paged KV caching since it owns memory for KV caching.</p><ul><li><strong>Before Paged Attention,</strong> KV cache manager handed each request one giant contiguous memory buffer to store the KVs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-eo8k4-Ly3BbFsxKvycavg.png" /></figure><ul><li><strong>After Paged Attention,</strong> KV cache manager breaks the cache into fixed size KV blocks measured in tokens per block and keeps a <strong>global free block pool</strong>, and gives each request a small <strong>block table</strong> that maps its logical blocks to physical blocks in GPU memory. When a request grows, new blocks are taken from the pool and appended to its table. When a request finishes, its blocks go back to the pool and can be reused immediately by any other request.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLX8bK3kE9-ZU21d96RRKg.png" /></figure><p>Below is a good example, suppose the prompt has 7 tokens and Block size = 4 tokens. We need ⌈7÷4⌉=2 KV blocks. The manager pops two identifiers from the free block pool and writes them into the request’s block table. Each entry tracks the physical block id, a small reference count, and often a block hash (later used in prefill caching). During decode, new tokens are written into the next free slots. When the last block fills, one more block is appended and the table grows by one entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UdXd5_UsFuqd3j6tfKsF5w.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Architecture 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ksp12RRHFByK8A8-LF2pjQ.png" /></figure><h4>Problem : Long Prompts</h4><ul><li>Now since this is a really long prompt, it will take a lot of time to process !! Thus, postponing all other requests in the batch and increase their <strong>TTFT.</strong></li><li>All other prompts in the batch needs to be padded to the longest sequence in the batch and thus we waste a lot of compute.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ksp12RRHFByK8A8-LF2pjQ.png" /></figure><h4>Solution : Chunked Prefill</h4><p>Chunked prefill is a technique for handling long prompts by splitting their prefill step into smaller chunks. Let’s understand it with the following example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GtqMYRX8oO8tjXg87HZ-dw.png" /></figure><p>Before Chunked Prefill, we would have passed this prompt entirely to the transformer as follows : —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*er0UnEBFV3cfnxOCZWxnfg.png" /></figure><p>But had we used chunked prefill we would have seen such a workflow : —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cx5XlNmS0Huiw9k6Lz0UQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Architecture 4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ksp12RRHFByK8A8-LF2pjQ.png" /></figure><h4>Problem : Shared Prompts</h4><p>Because LLMs are autoregressive, the queries [“I”, “like”, “dogs”] and [“I”, “like”, “cats”] produce KV caches that are identical in the first two tokens. What this means is that, in principle, if we compute the “I like dogs” cache first and then the “I like cats” cache, we only need to do 1 / 3 of the compute again. We can save most of the work by reusing the cache !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ksp12RRHFByK8A8-LF2pjQ.png" /></figure><h4>Solution : Prefix Caching</h4><p>Instead of recomputing the KV cache for the same prefix again and again, we store and reuse shared prefixes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gk05BVB86BY2KVe_VwWtHA.png" /></figure><p>SGLang introduced a very efficient implementation of this called <strong>Radix Attention</strong> using <strong>radix-tree-based cache</strong>. You should read more about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7FXzYTP7SoXBrTEw8qEfA.gif" /><figcaption>This is an example of how memory sharing would look like with initially two prompts that share the same prefix or prompt. When later they want to produce new tokens the <strong>KV cache manager</strong> allocates a fresh block for that request and does a copy on write, copying the same KV caches to another area which then allows each request to have its own “copy” and block which is used to place its new tokens.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Architecture 5</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ksp12RRHFByK8A8-LF2pjQ.png" /></figure><h4>Problem : Prefill and Decode Performance Profiles</h4><ul><li>Now we already know that <strong>Prefill stage</strong> is <strong>compute bound</strong> so it would require a better GPU for its process eg H200 over H100. On the other hand, we know that <strong>Decode stage</strong> is <strong>memory bound</strong> so it would require a machine which has more memory eg 100GB over 50GB. So both these stages have <strong>different machine requirements </strong>then why run them both on same machine? It is a waste of resource.</li><li>Another issue of both of them being on same machine (and we only have 1 instance of it) is that when the server is performing a prefill, the decode stage pauses.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ksp12RRHFByK8A8-LF2pjQ.png" /></figure><h4>Solution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQXmxo8Xm0D0b62vHOsRAg.png" /></figure><p>Since we are separating Prefill and Decode stages on different instance types, this is called <strong>P/D Disaggregation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qjp7eDJ0KdEEwoBTzuBCyw.png" /></figure><p>Now this architecture allows our inference engine to support a critical feature called <strong>Continuous Batching</strong>. Before understanding continuous batching it is important to understand what <strong>static batching</strong> is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*zsfURevC-xwf-65p7KItMQ.png" /><figcaption>Static Batching</figcaption></figure><p>Now as you can see in above image, Step 2 for batch 2 happens only after Step 2 for batch 1 is completely finished ! <strong><em>Do you see that during Step 2 of Batch 1 though Q2 completed in 3 generations it had to wait for Q3 to complete ??</em></strong> Hence we can optimize this !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*tjxwfOMyeKPxTLB_-4xBvw.png" /><figcaption>Continuous Batching ( improves throughput and ITL)</figcaption></figure><p>As you can see here that we have optimized our system, though generation for Q3 is not done yet but we have already started generation for Q4, which was not the case previously. This is called<strong> continuous batching.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a47c5c6d4af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Communication Primitives between Distributed GPUs]]></title>
            <link>https://khetansarvesh.medium.com/communication-primitives-between-distributed-gpus-475592742a3d?source=rss-ff946da4f2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/475592742a3d</guid>
            <dc:creator><![CDATA[Sarvesh Khetan]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 00:22:02 GMT</pubDate>
            <atom:updated>2026-06-08T00:22:02.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Broadcast</h3><p>Say you have some data on GPU1 and you want to share it with all the other GPUs so they can do some computation with the data. The broadcast operation does just that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAOoLtTSUs4rtVZ4B1rlsw.png" /></figure><p>We first need to initialize a process group with dist.initi_process_group which sets up the communication backend (NCCL here), it determines how many workers (aka nodes / gpus) exists and assigns a rank to each one (which we can get with dist.get_rank). Finally, it establishes a connection between the workers.</p><p>There are several libraries that implement collective communication and are support by PyTorch. They all provide similar functionality in terms of collective communication patterns but are optimized for different hardware setups. PyTorch provides a <a href="https://pytorch.org/docs/stable/distributed.html#which-backend-to-use">great guide</a> to decide which one to use</p><ul><li>Message Passing Interface (<strong><em>MPI</em></strong>) : efficient for CPU-CPU communication</li><li><strong><em>Gloo</em></strong> by Meta : efficient for CPU-GPU communication</li><li>NVIDIA Collective Communications Library (NCCL) by Nvidia : efficient for GPU-GPU communication</li></ul><pre>import torch<br>import torch.distributed as dist</pre><pre># initialing process group<br>dist.init_process_group(backend=&#39;nccl&#39;)</pre><pre># getting rank<br>torch.cuda.set_device(dist.get_rank())</pre><pre># defining tensors in gpus<br>if dist.get_rank() == 0: # in gpu0 defining a tensor [1,2,3,4,5]<br>    tensor = torch.tensor([1, 2, 3, 4, 5], dtype=torch.float32).cuda()<br>else: # in other gpus defining a tensor of zeroes<br>    tensor = torch.zeros(5, dtype=torch.float32).cuda()</pre><pre># printing tensors present in each gpu before broadcast operation<br>print(f&quot;Before broadcast on rank {dist.get_rank()}: {tensor}&quot;)</pre><pre># performing broadcast operation from gpu0 to other gpus<br>dist.broadcast(tensor, src=0)</pre><pre># printing tensors present in each gpu after broadcast operation<br>print(f&quot;After broadcast on rank {dist.get_rank()}: {tensor}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*kUu4wn7ymSrrdNbA5WQiig.png" /><figcaption>Boardcast Operation Code Output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Reduce and AllReduce</h3><p>If you want to combine the data present on each node through a function f() which can be summation / averaging and send it to the root node, this can be done via Reduce Operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*A0Uc6XyJ0wBdLI-vNQ_t3g.png" /></figure><pre>import torch<br>import torch.distributed as dist</pre><pre># initialing process group<br>dist.init_process_group(backend=&#39;nccl&#39;)</pre><pre># getting rank<br>torch.cuda.set_device(dist.get_rank())</pre><pre># defining tensors on each gpu<br>tensor = torch.tensor([dist.get_rank() + 1] * 5, dtype=torch.float32).cuda()</pre><pre># printing tensors before reduce operation<br>print(f&quot;Before reduce on rank {dist.get_rank()}: {tensor}&quot;)</pre><pre># performing reduce (sum) operation and storing it in Gpu0<br># if you want to do other operation you can refer to pytorch do here<br># <a href="https://pytorch.org/docs/stable/distributed.html#torch.distributed.ReduceOp">https://pytorch.org/docs/stable/distributed.html#torch.distributed.ReduceOp</a><br>dist.reduce(tensor, dst=0, op=dist.ReduceOp.SUM)</pre><pre># printing tensors after reduce operation<br>print(f&quot;After reduce on rank {rank}: {tensor}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*mjJMiPNRpmah0wRmpZKRXg.png" /><figcaption>Reduce Operation Output</figcaption></figure><p>If after combining on the root node you want to broadcast it to all the nodes then it is called AllReduce Operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*1GCcfp4zlatOUKE9jz2yjA.png" /></figure><pre>import torch<br>import torch.distributed as dist</pre><pre># initialing process group<br>dist.init_process_group(backend=&#39;nccl&#39;)</pre><pre># getting rank<br>torch.cuda.set_device(dist.get_rank())</pre><pre># defining tensors on each gpu<br>tensor = torch.tensor([dist.get_rank() + 1] * 5, dtype=torch.float32).cuda()</pre><pre># printing tensors before reduce operation<br>print(f&quot;Before reduce on rank {dist.get_rank()}: {tensor}&quot;)</pre><pre># performing all reduce (sum) operation<br>dist.all_reduce(tensor, op=dist.ReduceOp.SUM)</pre><pre># printing tensors after reduce operation<br>print(f&quot;After reduce on rank {rank}: {tensor}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*Wh5o2hXdlW4TN93jNvcVTQ.png" /><figcaption>All Reduce Operation Output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Gather and AllGather</h3><p>Now let’s turn to our next distributed communication operation. In many real cases, each node individually perform many complex computations and we need to share the final results among nodes. Gather and AllGather are the operations we want to use in this case. Let’s take a look!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*YeQnNnEaAxlDxCFj6bYjIg.png" /><figcaption>Note : <strong>Dashed Lines</strong> indicate that some data actually doesn’t move at all (since it’s already present on the node).</figcaption></figure><pre>import torch<br>import torch.distributed as dist</pre><pre># initialing process group<br>dist.init_process_group(backend=&#39;nccl&#39;)</pre><pre># getting rank<br>torch.cuda.set_device(dist.get_rank())</pre><pre># creating tensors in each gpu<br>tensor = torch.tensor([dist.get_rank() + 1] * 5, dtype=torch.float32).cuda()</pre><pre># defining a variable(list) which will store the gathered information<br>if dist.get_rank() == 0:<br>    gather_list = [<br>        torch.zeros(5, dtype=torch.float32).cuda()<br>        for _ in range(dist.get_world_size())<br>        ]<br>else:<br>    gather_list = None</pre><pre># printing tensors in each gpu before gather opeartion<br>print(f&quot;Before gather on rank {dist.get_rank()}: {tensor}&quot;)</pre><pre># performing gather operation and storing it in gpu0<br>dist.gather(tensor, gather_list, dst=0)</pre><pre># printing tensors in gpu0 after gather operation<br>if dist.get_rank() == 0:<br>    print(f&quot;After gather on rank 0: {gather_list}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*s5hJnEvCM7ucy7URuy2ETg.png" /><figcaption>Gather Operation Output</figcaption></figure><p>For allgather the entire code remains same except you use following funtion dist.all_gather(gather_list, tensor)Output for all gather is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*dPw5UfsRTQbraztx7BUyMA.png" /><figcaption>All Gather Operation Output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Scatter</h3><p>Now what about the inverse of a gather? As the name subtly suggests, the goal of the Scatter operation is to take data on one node and distribute slices of it to all other nodes. <strong>It’s thus different from the Broadcast operation which copy data without slicing and it’s the logical the inverse of the Gather operation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*TQ-GpcwrjGisoj3lP-CcLw.png" /></figure><pre>import torch<br>import torch.distributed as dist</pre><pre># initialing process group<br>dist.init_process_group(backend=&#39;nccl&#39;)</pre><pre># getting rank<br>torch.cuda.set_device(dist.get_rank())</pre><pre># defining tensors in gpus<br>if dist.get_rank() == 0:<br>    scatter_list = [<br>        torch.tensor([i + 1] * 5, dtype=torch.float32).cuda()<br>        for i in range(dist.get_world_size())<br>        ]<br>    print(f&quot;Rank 0: Tensor to scatter: {scatter_list}&quot;)<br>else:<br>    scatter_list = None<br>tensor = torch.zeros(5, dtype=torch.float32).cuda()</pre><pre># printing tensors present in each gpu before broadcast operation<br>print(f&quot;Before scatter on rank {dist.get_rank()}: {tensor}&quot;)</pre><pre># performing scatter operation from gpu0 to other gpus<br>dist.scatter(tensor, scatter_list, src=0)</pre><pre># printing tensors present in each gpu after broadcast operation<br>print(f&quot;After scatter on rank {dist.get_rank()}: {tensor}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*MB_8pHTNMEYphlYuMG8wMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>ReduceScatter</h3><p>The ReduceScatter pattern is slightly more complex than Scatter. Imagine you apply an operation like in the Reduce case but instead of moving the result to just one node we also distribute it evenly to all nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*O63pBt5zIJBTxvRRbcNsQQ.png" /></figure><pre>import torch<br>import torch.distributed as dist</pre><pre># initialing process group<br>dist.init_process_group(backend=&#39;nccl&#39;)</pre><pre># getting rank<br>torch.cuda.set_device(dist.get_rank())<br></pre><pre>rank = dist.get_rank()<br>world_size = dist.get_world_size()</pre><pre># on each gpu creating a list of 2-elements vector with a power exponent <br># and an offset function of the node rank<br>input_tensor = [<br>    torch.tensor([(rank + 1) * i for i in range(1, 3)], dtype=torch.float32).cuda()**(j+1) <br>    for j in range(world_size)<br>    ]</pre><pre>output_tensor = torch.zeros(2, dtype=torch.float32).cuda()</pre><pre># printing tensors present in each gpu before broadcast operation<br>print(f&quot;Before ReduceScatter on rank {rank}: {input_tensor}&quot;)</pre><pre># performing scatter operation<br>dist.reduce_scatter(output_tensor, input_tensor, op=dist.ReduceOp.SUM)</pre><pre># printing tensors present in each gpu after broadcast operation<br>print(f&quot;After ReduceScatter on rank {rank}: {output_tensor}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*8Ij2hR9uPkDmC70zAwa_RQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=475592742a3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variable Recursion in Strings]]></title>
            <link>https://khetansarvesh.medium.com/variable-recursion-in-strings-9eca7a3e2bff?source=rss-ff946da4f2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eca7a3e2bff</guid>
            <dc:creator><![CDATA[Sarvesh Khetan]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 16:44:18 GMT</pubDate>
            <atom:updated>2026-02-11T19:12:36.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Largest Number in K Swaps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObjUjE1DTQut-VLGaMlqWA.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHAWAG7nil9o%3Flist%3DPL_z_8CaSLPWdbOTog8Jxk9XOjzUs3egMP&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHAWAG7nil9o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHAWAG7nil9o%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/49614969cc9d451264009529d662c66e/href">https://medium.com/media/49614969cc9d451264009529d662c66e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bi25NkKa0HbjJYB1XJ975g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eca7a3e2bff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Input Output — String Controlled Recursion]]></title>
            <link>https://khetansarvesh.medium.com/input-output-string-controlled-recursion-b9eaba0bd813?source=rss-ff946da4f2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9eaba0bd813</guid>
            <dc:creator><![CDATA[Sarvesh Khetan]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 05:49:04 GMT</pubDate>
            <atom:updated>2026-02-09T20:26:36.720Z</atom:updated>
            <content:encoded><![CDATA[<h3>Input Output — String Controlled Recursion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3><a href="https://leetcode.com/problems/letter-case-permutation/description/">‘Print’ all Letter Case Permutations of a String</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*tDbcPZu3kgm-PXr0mQCM8Q.png" /></figure><p>What we saw above is a great method to solve but it uses extra space since we are using a list to store all the outputs, but what if we need to get rid of this extra space ?? <strong>Hence we will use Input Output Method</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CweW0D95qAt1UoQud5wqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIhks4G78UxghicLfZnjFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3><a href="https://leetcode.com/problems/generate-parentheses/description/">‘Print’ all balanced parentheses</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hcz-9SmdC2ZEo80PpaLoBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ePDSZjuIPdnNyi_FxTfIA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9eaba0bd813" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strings — DP]]></title>
            <link>https://khetansarvesh.medium.com/strings-dp-b0135bd81379?source=rss-ff946da4f2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0135bd81379</guid>
            <dc:creator><![CDATA[Sarvesh Khetan]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 05:46:12 GMT</pubDate>
            <atom:updated>2026-02-11T17:32:50.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>Strings — DP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Longest Common Subsequence</h3><p>We saw the recursive code for this <a href="https://skhetan.substack.com/i/186653211/1-length-of-longest-common-subsequence-lcs">here</a>, now let’s try to memoise it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IVRM3jfom6tPd8X8N1nWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Palindrome Partitioning</h3><p>We saw the recursive code for this <a href="https://khetansarvesh.medium.com/variable-size-recursion-strings-23fa9fca5193#3182">here</a>, now let’s try to memoise it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbX4ZJnHZc69sACGKYG3Iw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Boolean Parenthesis</h3><p>We saw the recursive code for this <a href="https://khetansarvesh.medium.com/variable-size-recursion-strings-23fa9fca5193#f943">here</a>, now let’s try to memoise it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfrTMMv5Pk7y6hLCvj9pzQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0135bd81379" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variable Size Recursion — Strings]]></title>
            <link>https://khetansarvesh.medium.com/variable-size-recursion-strings-23fa9fca5193?source=rss-ff946da4f2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/23fa9fca5193</guid>
            <dc:creator><![CDATA[Sarvesh Khetan]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 23:29:37 GMT</pubDate>
            <atom:updated>2026-02-11T16:44:11.249Z</atom:updated>
            <content:encoded><![CDATA[<h3>Variable Size Recursion — Strings</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3><a href="https://www.youtube.com/watch?v=szKVpQtBHh8&amp;t=1s">Palindrome Partitioning</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AaqEiX9X5Qb-UWae3vRfg.png" /></figure><p>Hence we can see just like in MCM, how we had to partition the array by placing brackets here also we need to partition the string by placing brackets !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D-FiQrguQGzHHSt06HkpKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6P8MsLbnlVtebrt-jf3uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3><a href="https://www.youtube.com/watch?v=pGVguAcWX4g">Boolean Parenthesis</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*o8FYTy1D3gvL5rtLO2qAYA.png" /></figure><p>Hence we can see just like in MCM, how we had to partition the array by placing brackets here also we need to partition the string by placing brackets !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6nm4HW9BRmZswimaoVYTw.png" /></figure><p>Hence to break into correct subproblems so that inputs are valid for the subproblem we should ensure that inputs don’t have operators at start or at end. How should we ensure this? By breaking on the operator itself !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L76jaYWGG2CP4Og_xq-H6Q.png" /><figcaption>In above diagram, when we combine subprobs, I have written take minimum of them instead, it should be (+) operation between them</figcaption></figure><p>Now above we concluded that we need to calculate if an expression is both T or F hence we will introduce a new parameter in our recursion !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zj23pSYuXofUgYU4e8WRHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90okfVaIVOfmKq9c1hairw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23fa9fca5193" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String Recursion — Input Output Method — Toy Problems]]></title>
            <link>https://khetansarvesh.medium.com/string-recursion-input-output-method-toy-problems-6b8e4d1cb5e7?source=rss-ff946da4f2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b8e4d1cb5e7</guid>
            <dc:creator><![CDATA[Sarvesh Khetan]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 16:52:36 GMT</pubDate>
            <atom:updated>2026-02-01T16:52:36.532Z</atom:updated>
            <content:encoded><![CDATA[<h3>String Recursion — Input Output Method — Toy Problems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Remove duplicates from String given that all the duplicates of an element occur together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDU0tg95CDqtodZe8roqnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6XKSgJmN8qJXKPNSHhLIiA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b8e4d1cb5e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String Recursion — Toy Problems]]></title>
            <link>https://khetansarvesh.medium.com/string-recursion-toy-problems-1343a06e5957?source=rss-ff946da4f2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1343a06e5957</guid>
            <dc:creator><![CDATA[Sarvesh Khetan]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 16:10:49 GMT</pubDate>
            <atom:updated>2026-02-01T16:51:20.930Z</atom:updated>
            <content:encoded><![CDATA[<h3>String Recursion — Toy Problems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Reverse a String</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGoSJ0dEEDJkOrUDNLidBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*CoG8_YD-02FOeluDn1xDfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Print Even Position Characters of a string in reverse</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8ZFA0-cWVkg3aG_aw19sw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*oqW80fiQk4FcFO95iFimHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Check Palindrome or Not</h3><p>One simple method to solve this can be just reverse the string and see if the original string and the reverse string are same or not. But since we are learning recursion here, we will try to solve this using recursion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RYB2BYCZ1cEbDVmSlZRtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bs4-zNj8EpmLJeEGxWKbhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOikCJLJO7YynTH4i98FCA.png" /></figure><h3>Replace ‘pi’ with ‘3.14’</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ow1pE_X4Ss325gj22TASbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFD0O8oX039MSMci8s1kVQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1343a06e5957" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>