<?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 Anandha L Ranganathan on Medium]]></title>
        <description><![CDATA[Stories by Anandha L Ranganathan on Medium]]></description>
        <link>https://medium.com/@analog76?source=rss-d7923640d91c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bVZTb7jy0YZB-OOq.jpeg</url>
            <title>Stories by Anandha L Ranganathan on Medium</title>
            <link>https://medium.com/@analog76?source=rss-d7923640d91c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:02:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@analog76/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[PyTorch AMP from First Principles]]></title>
            <link>https://medium.com/@analog76/pytorch-amp-from-first-principles-3c99b52a1e9c?source=rss-d7923640d91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c99b52a1e9c</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[mixed-precision]]></category>
            <dc:creator><![CDATA[Anandha L Ranganathan]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 19:46:01 GMT</pubDate>
            <atom:updated>2026-11-24T19:46:01.719Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Mixed Precision Makes Training Faster Without Breaking It</h3><p>If you’ve trained a neural network in PyTorch, you’ve probably seen two lines show up in “make it faster” tutorials: torch.autocast and GradScaler. Together they&#39;re called <strong>AMP, Automatic Mixed Precision</strong>. They often give a large speedup and a big memory saving for very little code, but they can look like magic.</p><p>This post builds AMP from the ground up. We start with the hardware, look at what goes wrong when you naively use smaller numbers, and then see how PyTorch’s design fixes each problem, one piece at a time.</p><h3>1. Start with the hardware: tensor cores</h3><p>Modern NVIDIA GPUs have two kinds of math units:</p><ul><li><strong>CUDA cores</strong> are general-purpose units that do one multiply-add at a time.</li><li><strong>Tensor cores</strong> are specialized units that multiply small <em>matrices</em> in a single instruction.</li></ul><p>Deep learning is mostly matrix multiplication. A linear layer is a matmul, a convolution is computed as a matmul, and attention is a couple of matmuls. So tensor cores are where most of the speed is.</p><p>The catch is that tensor cores are fastest on <strong>lower-precision numbers</strong> such as 16-bit floats. Hand them 32-bit floats and you leave much of the hardware’s throughput unused.</p><h3>2. Why float32 is slow and memory-hungry</h3><p>By default, PyTorch stores every tensor as <strong>float32</strong>: 4 bytes per number, with about 7 decimal digits of precision.</p><p>That’s comfortable for accuracy, but it costs you twice:</p><ol><li><strong>Compute.</strong> float32 matmuls can’t use the fastest tensor-core paths.</li><li><strong>Memory and bandwidth.</strong> Every activation saved for the backward pass takes 4 bytes. GPUs often spend more time <em>moving</em> data than computing on it, so bigger numbers mean more time waiting on memory.</li></ol><h3>3. Why float16 is fast</h3><p><strong>float16</strong> (half precision) uses 2 bytes per number. That gives you:</p><ul><li><strong>Tensor-core speed:</strong> matmuls and convolutions run on the fast half-precision paths.</li><li><strong>Half the memory:</strong> activations take half the space, so you can fit bigger batches or bigger models.</li><li><strong>Half the bandwidth:</strong> moving half as many bytes means less waiting.</li></ul><p>So why not run everything in float16? Because float16 has sharp limits.</p><h3>4. float16’s limits: range and precision</h3><p>A float has a sign bit, an exponent (which sets the <em>range</em>) and a mantissa (which sets the <em>precision</em>). float16 has only 5 exponent bits and 10 mantissa bits, and that gives it three hard limits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLARIPw6-dd3jSkuZfxyug.png" /></figure><p>(float16 can go a little smaller using “subnormal” numbers, down to about (6 \times 10^{-8}), but with very little precision left.)</p><p>Three things go wrong as a result:</p><ul><li><strong>Overflow:</strong> anything above 65,504 becomes inf. For example, exp(12) is already about 162,755.</li><li><strong>Underflow:</strong> tiny values round to exactly <strong>0</strong>. In float16, 1e-8 becomes 0.</li><li><strong>Rounding:</strong> with about 3 digits, 1.0001 rounds to 1.0. Small updates can simply vanish.</li></ul><h3>5. The real danger: gradients underflow in the backward pass</h3><p>Forward-pass activations usually sit in a reasonable range. <strong>Gradients are different.</strong> Backprop multiplies many small numbers together through the chain rule, and gradients for many weights end up tiny, often around (10^{-6}) to (10^{-8}) or smaller.</p><p>In float16 many of those values fall below the representable range and become <strong>exactly zero</strong>. A zero gradient means no update, so that part of the network silently stops learning. Nothing crashes; the model just trains worse.</p><p>So we have two problems to solve:</p><ol><li>Some <em>operations</em> are numerically sensitive and shouldn’t run in float16.</li><li><em>Gradients</em> are too small for float16 to represent.</li></ol><p>AMP solves the first with <strong>autocast</strong> and the second with <strong>GradScaler</strong>.</p><h3>6. The AMP design: mixed, not half</h3><p>The key idea is in the name: <strong>mixed</strong> precision. Don’t convert the whole model to float16. Choose per operation.</p><ul><li><strong>Downcast to float16</strong> the heavy, well-behaved ops where tensor cores shine: matmul, mm, bmm, linear, convolutions (conv1d, conv2d, conv3d), and scaled dot-product attention.</li><li><strong>Keep in float32</strong> the numerically sensitive ops: softmax, exp, log, pow, layer_norm, group_norm, logsumexp, and <strong>loss functions</strong> such as mse_loss, nll_loss, cross_entropy and binary_cross_entropy_with_logits.</li></ul><p>Why those? Matmuls are many multiply-adds whose results fit comfortably in float16, and the tensor cores accumulate internally at higher precision. Exponentials, logs, normalizations and losses involve big ranges, sums over many elements, or tiny differences, which is exactly where float16’s overflow, underflow and rounding hurt.</p><p>Also important: the <strong>model weights stay in float32</strong>. Autocast only casts <em>copies</em> of them to float16 for the heavy ops. The optimizer updates the float32 originals, so small updates aren’t rounded away.</p><h3>7. Autocast: a context manager with per-op casting tables</h3><p>You turn this on with a context manager:</p><pre>with torch.autocast(device_type=&quot;cuda&quot;, dtype=torch.float16):<br>    output = model(input)<br>    loss = loss_fn(output, target)<br><br></pre><p>What happens inside?</p><ol><li><strong>Entering</strong> the with block just flips a few thread-local flags: &quot;autocast is on for CUDA, and the fast dtype is float16.&quot; <strong>Exiting</strong> restores the previous state and clears a small cache.</li><li><strong>The real decision happens per operation.</strong> PyTorch’s dispatcher routes every op through an <em>autocast layer</em> first. Each op is registered with a <strong>casting policy</strong> from a <strong>hard-coded table for each device type</strong> (CUDA, CPU, MPS and others):</li></ol><ul><li><strong>lower precision:</strong> cast all inputs to float16 (matmul, conv, linear…).</li><li><strong>fp32:</strong> cast all inputs to float32 (exp, log, layer_norm, losses…).</li><li><strong>fp32 with an output-dtype argument:</strong> for ops like softmax, run in float32 unless you asked for a specific output dtype.</li><li><strong>promote:</strong> for ops that take several inputs (like addcmul, dot, index_put, scatter_add), run in the widest dtype among the inputs so nothing is silently truncated.</li><li><strong>Not in any table:</strong> run in whatever dtype the inputs already have.</li></ul><p>3. After casting, the op <strong>redispatches</strong> to the normal kernel.</p><p><strong>4. Caching:</strong> casting the same float32 weight to float16 every time would waste work, so autocast casts each weight once per autocast region and reuses the float16 copy.</p><p>Two practical notes. On CPU, the default lower-precision type is <strong>bfloat16</strong> rather than float16. Also, autocast should wrap the <strong>forward pass and the loss</strong>, not the backward pass: backward ops automatically run in the same dtype their forward ops used.</p><h3>8. GradScaler: rescuing gradients from underflow</h3><p>Autocast decides which ops run in float16, but gradients can still underflow. The fix is simple:</p><blockquote><em>If gradients are too small to represent, make them bigger first, then shrink them back before using them.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8IwZK3J_rcSacLg6Wdwb5g.png" /></figure><p>That’s comfortably representable. After backward, divide by 65,536 (in float32) and you get the true gradient back.</p><p>Here’s what GradScaler does at each stage:</p><ol><li><strong>Scale:</strong> before backward(), multiply the loss by the scale factor. The default starting value is (2^{16} = 65{,}536).</li><li><strong>Unscale:</strong> after backward and <em>before</em> the optimizer step, multiply every gradient by (1/S). In the same fused pass, check every gradient element for inf or NaN.</li><li><strong>Skip on overflow:</strong> if <em>any</em> gradient is inf or NaN, the scale was too big and something overflowed. GradScaler <strong>skips the optimizer step</strong> for that iteration, so the bad gradients never touch the weights.</li><li><strong>Adjust the scale automatically:</strong></li></ol><ul><li>On overflow, <strong>halve the scale</strong> (backoff factor 0.5) and reset a counter.</li><li>After <strong>2,000 consecutive clean steps</strong> (the growth interval), <strong>double the scale</strong> (growth factor 2.0), since there’s probably room to go bigger.</li></ul><p>The result is a scale that hovers near the largest safe value: big enough to keep tiny gradients alive, small enough not to overflow. The occasional skipped step early in training is normal; it’s the scaler calibrating itself.</p><h3>9. Putting it together: the four calls</h3><pre>scaler = torch.amp.GradScaler(&quot;cuda&quot;)<br><br>for input, target in loader:<br>    optimizer.zero_grad()<br><br>    # 1. Forward and loss under autocast<br>    with torch.autocast(device_type=&quot;cuda&quot;, dtype=torch.float16):<br>        output = model(input)<br>        loss = loss_fn(output, target)<br><br>    # 2. Scale the loss, then backward<br>    scaler.scale(loss).backward()<br><br>    # 3. Unscale grads, check for inf/NaN, step only if clean<br>    scaler.step(optimizer)<br><br>    # 4. Adjust the scale factor for the next iteration<br>    scaler.update()</pre><ol><li><strong>torch.autocast(...)</strong> picks float16 or float32 per op during forward and loss.</li><li><strong>scaler.scale(loss).backward()</strong> multiplies the loss by the scale and runs backward, so gradients come out scaled.</li><li><strong>scaler.step(optimizer)</strong> unscales the gradients, checks for inf and NaN, and calls optimizer.step() only if they&#39;re all finite.</li><li><strong>scaler.update()</strong> halves the scale after an overflow or doubles it after 2,000 clean steps.</li></ol><p>If you clip gradients, call <strong>scaler.unscale_(optimizer)</strong> first, so you clip the <em>true</em> gradients rather than the scaled ones:</p><pre>scaler.scale(loss).backward()<br>scaler.unscale_(optimizer)<br>torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)<br>scaler.step(optimizer)<br>scaler.update()<br><br></pre><h3>10. The payoff</h3><p>With roughly five extra lines of code you get:</p><ul><li><strong>Speed:</strong> matmuls and convolutions run on tensor cores at half precision, often giving a substantial end-to-end speedup on modern GPUs (the exact gain depends on the model and the hardware).</li><li><strong>Memory:</strong> activations saved for backward take about half the space.</li><li><strong>Scale:</strong> that freed memory goes into <strong>larger batches or larger models</strong> on the same GPU.</li><li><strong>Accuracy:</strong> float32 master weights, float32 sensitive ops and dynamic loss scaling mean accuracy usually matches full float32 training.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c99b52a1e9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[torch.compile() in PyTorch]]></title>
            <link>https://medium.com/@analog76/torch-compile-in-pytorch-bddfa2af388d?source=rss-d7923640d91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bddfa2af388d</guid>
            <category><![CDATA[dynamo]]></category>
            <category><![CDATA[inductor]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[gpu-kernel]]></category>
            <category><![CDATA[pytorch-compile]]></category>
            <dc:creator><![CDATA[Anandha L Ranganathan]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 11:36:01 GMT</pubDate>
            <atom:updated>2026-11-22T01:43:30.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Dynamo, AOTAutograd and Inductor each do, and how they work together — A beginners guide.</h3><h3>1. Eager mode: the starting point</h3><p><strong>The problem.</strong> We need a baseline to understand what “compiling” improves on.</p><p><strong>What it does.</strong> By default, PyTorch runs in <strong>eager mode</strong>, just like normal Python. It sees one statement, runs it right away, returns to Python, and only then sees the next statement. It <strong>never sees ahead</strong>, so it can’t combine work across statements.</p><p>Each operation is still fast: the multiply runs in optimized C++ or GPU code, not slow Python math. What’s missing is the <strong>big picture</strong>.</p><pre>y = x * 2     # launch kernel 1, write the result to memory<br>y = y + 1     # launch kernel 2, read it back, write again<br>y = relu(y)   # launch kernel 3, read again, write again</pre><p>A <strong>kernel</strong> is one small program that runs on the GPU (or CPU) for one operation. Three statements mean three kernels and three trips through memory.</p><p>So when people say “we wrote a custom kernel” or “this is kernel-bound,” they mean the actual GPU code that performs the arithmetic, not the Python-level training loop or the parallelism strategy</p><p><strong>Everyday analogy.</strong> A cook gets the recipe by phone, <strong>one instruction at a time</strong>. “Take the milk out.” The cook walks to the fridge, gets the milk, and puts it on the counter. “Add sugar.” Walk to the pantry, come back. “Heat it.” Each step is done well, but because the cook never knows the next step, they can’t plan to fetch everything in one trip.</p><p><strong>Remember.</strong> <em>Eager mode is one statement at a time with no look-ahead: each step is fast, but nothing is planned across steps.</em></p><h3>2. Why compile at all?</h3><p><strong>The problem.</strong> Running one statement at a time has three hidden costs, paid on <strong>every</strong> operation, every time:</p><ol><li><strong>Python and dispatch overhead.</strong> Each x * 2 is a Python call. Inside PyTorch, a component called the <strong>dispatcher</strong> then works out which version to run: CPU or GPU, which number type, whether gradients are needed. That bookkeeping happens again for every op.</li><li><strong>Kernel launch overhead.</strong> On a GPU, the CPU has to “launch” each kernel, which means queueing it to run. Each launch has a fixed cost. With small tensors the GPU can finish the work faster than the CPU can queue the next launch, so the GPU sits waiting.</li><li><strong>Memory traffic for every intermediate.</strong> This is usually the biggest cost. Every intermediate result is written to memory and read back by the next op. GPUs can do arithmetic much faster than they can move data, so simple ops like add, multiply, and relu spend most of their time <strong>moving bytes</strong>, not computing.</li></ol><p><strong>A worked example (arithmetic only).</strong> Take relu(x*2 + 1) on 1,000,000 float32 numbers. Each float32 is 4 bytes, so one tensor is 4 MB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ghap7p--5jBMoSnW.png" /></figure><p>Both versions do exactly the same math (3 million small operations). The fused one simply moves <strong>3× fewer bytes</strong> and launches 1 kernel instead of 3.</p><p><strong>When compiling does NOT help:</strong></p><ul><li><strong>Tiny workloads or scripts that run once.</strong> Compiling itself takes time (often seconds). If the code runs only briefly, you never earn that time back.</li><li><strong>Lots of graph breaks</strong> (section 4). Each break splits the work into pieces that can’t be combined.</li><li><strong>Shapes that change constantly.</strong> These can cause repeated recompiles (section 5).</li><li><strong>Work dominated by one big matrix multiply.</strong> That already uses a highly tuned library, so there’s little left to gain.</li></ul><p><strong>Everyday analogy.</strong> Batch your errands. Going to the store once for the whole list beats three trips for three items, even if each trip is quick.</p><p><strong>Remember.</strong> <em>Compiling saves the per-op overhead and the memory trips between ops, but it only pays off for code you run many times.</em></p><h3>3. Dynamo: someone has to see the whole function</h3><p><strong>The problem.</strong> To combine work, someone must look at the <strong>whole function before it runs</strong>. And it should do that <strong>without making you rewrite your Python</strong> in a special language. Older approaches (such as TorchScript) often asked users to change their code.</p><p><strong>What it does.</strong> When you write torch.compile(f), <strong>Dynamo</strong> steps in just before Python runs f. It reads the function&#39;s <strong>bytecode</strong> (the low-level instructions Python compiles your code into) and follows it step by step. As it goes:</p><ul><li>every <strong>tensor operation</strong> is recorded into a <strong>graph</strong>, a list of ops and how data flows between them (mul → add → relu);</li><li>ordinary <strong>non-tensor Python</strong> (integer math, fixed loops, lists) is simply worked out during this reading. It doesn’t need to appear in the graph.</li></ul><p>While reading, Dynamo uses <strong>fake tensors</strong>: stand-ins that carry only a shape and a type, no actual numbers. So reading the function is cheap and computes nothing real.</p><p>Dynamo <strong>does not</strong> make anything faster by itself. It captures the graph and hands it to the next stages.</p><p><strong>Everyday analogy.</strong> A chef <strong>reads the whole recipe before starting</strong>: “milk, sugar, heat. I’ll get the milk and sugar in one trip and use one pot.”</p><p><strong>Tiny example .</strong> A custom “backend” (the function that receives Dynamo’s graph) just prints what it gets:</p><pre>import torch<br><br># 1. A custom &quot;backend&quot;: torch.compile hands it the graph Dynamo captured.<br>def print_graph_backend(graph_module, example_inputs):<br>    print(&quot;=== Graph that Dynamo captured ===&quot;)<br>    print(graph_module.code)          # the graph, shown as Python code<br>    return graph_module.forward       # run it as-is (no real compiling)<br><br># 2. The plain Python function we want to compile.<br>def my_function(x, w):<br>    y = x * w        # multiply<br>    y = y + 1        # add<br>    return torch.relu(y)<br><br># 3. Compile it with our backend, then call it once to trigger capture.<br>compiled_fn = torch.compile(my_function, backend=print_graph_backend)<br><br>x = torch.randn(4)<br>w = torch.randn(4)<br>result = compiled_fn(x, w)<br><br># 4. Check it gives the same answer as normal (eager) PyTorch.<br>print(&quot;Result:      &quot;, result)<br>print(&quot;Same as eager:&quot;, torch.allclose(result, my_function(x, w)))=== Graph that Dynamo captured ===<br>def forward(self, L_x_ : torch.Tensor, L_w_ : torch.Tensor):<br>    l_x_ = L_x_<br>    l_w_ = L_w_<br>    y = l_x_ * l_w_;  l_x_ = l_w_ = None<br>    y_1 = y + 1;  y = None<br>    relu = torch.relu(y_1);  y_1 = None<br>    return (relu,)<br><br>Result:       tensor([0.8938, 1.2449, 0.0000, 1.4425])<br>Same as eager: True</pre><p>Three Python operations became <strong>one graph</strong> with three steps.</p><p><strong>Remember.</strong> <em>Dynamo reads your whole function ahead of time and writes down the tensor math as one graph, without you changing your code.</em></p><h3>4. Graph breaks: when Dynamo has to stop</h3><p><strong>The problem.</strong> Dynamo can only record <strong>tensor math</strong> into the graph. Sometimes it reaches something it can’t record. It doesn’t crash. It <strong>stops the current graph</strong>, lets normal Python run that part, and then <strong>starts a new graph</strong> afterwards. That is a <strong>graph break</strong>.</p><p><strong>What happens, in plain words.</strong> You get two (or more) smaller graphs with ordinary Python between them. Each piece is still compiled, but nothing can be combined <strong>across</strong> the break.</p><p><strong>Everyday analogy.</strong> The chef is following the recipe smoothly and reaches “taste and decide whether to add salt”. They can’t plan past that line without tasting. So they cook up to that point, stop and taste, then plan the rest.</p><p>Common scenarios (all Verified with torch._dynamo.explain)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8m3zU1LnIuPwPcJk.png" /></figure><p><strong>Things that do NOT break (Verified):</strong></p><ul><li>for _ in range(3): x = x*2 gives <strong>1 graph, 0 breaks</strong>. The loop count is a fixed Python number, so Dynamo simply <strong>unrolls</strong> it (writes the body out 3 times).</li><li>if x.shape[0] &gt; 4: gives <strong>1 graph, 0 breaks</strong>. The shape is known while reading, so Dynamo picks the branch and records a <strong>guard</strong> (&quot;this was compiled for size &gt; 4&quot;; see section 5).</li></ul><p><strong>The cost.</strong> No fusion across the break, so you get extra kernels, extra memory trips, and a return to Python between graphs.</p><p><strong>How to find them:</strong></p><ul><li>torch._dynamo.explain(f)(x) reports the graph count, break count, and reasons.</li><li>Running with <strong>TORCH_LOGS=&quot;graph_breaks&quot;</strong> prints each break as it happens.</li><li>torch.compile(f, fullgraph=True) turns any break into an error.</li></ul><h3>5. Guards: is this compiled code still valid?</h3><p><strong>The problem.</strong> The compiled code was built under certain <strong>assumptions</strong>: input shape (say, 8 elements), number type (float32), device (CPU or GPU), whether gradients are needed, whether the model is in training mode. If any of those change, the old compiled code could be <strong>wrong</strong>. Something must check before reusing it.</p><p><strong>What it does.</strong> For every assumption it relied on, Dynamo records a <strong>guard</strong>: a small, cheap check. Before each call, the guards run:</p><ul><li><strong>all pass</strong>: use the cached compiled code (the fast path);</li><li><strong>any fails</strong>: compile again for the new situation and keep both versions.</li></ul><p><strong>Everyday analogy.</strong> A dinner planned for <strong>4 guests</strong>: if 8 show up, you re-plan the recipe instead of serving half portions.</p><h3>6. AOTAutograd: plan the way back before you leave</h3><p><strong>The problem.</strong> Dynamo’s graph only covers the <strong>forward</strong> pass (computing the answer). Training also needs the <strong>backward</strong> pass (computing gradients). In eager mode, autograd builds the backward <strong>while</strong> the forward runs: each op leaves a note such as MulBackward0 and <strong>saves the tensors</strong> it will need later, as in your autograd lessons. We want the backward <strong>compiled and optimized too</strong>, so it has to be known <strong>ahead of time</strong> (that is what &quot;AOT&quot; means).</p><p><strong>What it does:</strong></p><ul><li><strong>Traces autograd ahead of time.</strong> It runs the forward on fake tensors with autograd turned on, and writes out both a <strong>forward graph</strong> and a <strong>backward graph</strong>.</li><li><strong>Turns in-place ops into normal ones.</strong> c += 1 changes c in place, which bumps its version counter: the cause of the &quot;modified by an inplace operation&quot; error from your lessons. In-place changes make reordering risky, so AOTAutograd rewrites them as &quot;make a new tensor&quot;. Verified earlier: add_ became aten.add.Tensor. This is called <strong>functionalization</strong>.</li><li><strong>Breaks big ops into basic ones</strong>, so the next stage has fewer kinds of op to handle. Verified earlier: silu became sigmoid + mul.</li><li><strong>Decides what to save vs recompute.</strong> Keeping a value for the backward costs memory, while recomputing it costs a little math. It picks a good balance. Verified earlier: for silu(x*2) it saved only x*2 and recomputed the sigmoid in the backward.</li></ul><p>It still does the first three (minus the backward graph) when you run inference under torch.no_grad().</p><p><strong>Everyday analogy.</strong> <strong>Planning the return trip before you leave.</strong> As you drive out, you decide which landmarks to note (save) and which turns you can just figure out again (recompute), so the way home is already planned.</p><pre>FORWARD:  mul, add, relu, detach<br>          returns (relu, primals_1, primals_2, detach)   # output + tensors saved for backward<br>BACKWARD: detach, threshold_backward, mul_1, mul_2<br>          returns (mul_2, mul_1)                         # gradients for x and w</pre><p>The gradients matched eager mode. The saved primals_1, primals_2 (x and w) are the compiled version of what MulBackward0 saves in eager mode.</p><p><strong>Remember.</strong> <em>AOTAutograd writes the backward pass ahead of time, cleans up in-place ops, and chooses what to save, so the backward can be compiled too.</em></p><h3>7. Inductor: turning the graph into fast code</h3><p><strong>The problem.</strong> A graph is just a description. By itself it isn’t faster. Someone has to turn it into <strong>efficient machine code</strong>.</p><p><strong>What it does:</strong></p><ul><li><strong>Fuses</strong> ops: mul → add → relu becomes <strong>one kernel</strong>, removing the 24 MB → 8 MB memory trips from section 2.</li><li><strong>Plans memory</strong>: fused intermediates never get stored at all, and leftover buffers are reused.</li><li><strong>Generates code</strong>: <strong>Triton</strong> for GPUs (a Python-like language for GPU kernels) and <strong>C++</strong> for CPUs.</li><li><strong>Uses vendor libraries</strong> for the hard parts, such as matrix multiply (cuBLAS on NVIDIA), instead of writing its own.</li><li><strong>Autotunes</strong>: tries a few settings and keeps the fastest.</li><li><strong>Caches</strong> the results on disk, so a later run can skip recompiling.</li></ul><p><strong>Everyday analogy.</strong> A <strong>factory manager</strong> sees three stations (mix, add, bake), each carrying the product to the warehouse and back. They merge them into <strong>one station</strong> where the product never leaves the belt.</p><pre>fast = torch.compile(lambda x: torch.relu(x * 2 + 1))   # default backend = inductor</pre><p>In plain words, the generated code is <strong>one loop (one kernel)</strong>: for each element, load x, compute max(0, x*2 + 1), store y. There are no intermediate tensors.</p><p><strong>Remember.</strong> <em>Inductor is the part that actually makes things fast: it merges ops into fewer kernels and writes the machine code.</em></p><h3>8. How they work together</h3><p>On the <strong>first call</strong>, Dynamo intercepts the function, reads it, and builds the graph. It hands the graph to AOTAutograd, which produces clean forward and backward graphs. Inductor turns those into fast kernels. The result is stored in Dynamo’s <strong>cache</strong> together with its <strong>guards</strong>. On <strong>later calls</strong>, the guards run (a quick checklist); if they pass, the cached fast code runs straight away. When the result is used in training, loss.backward() runs the compiled backward. If the <strong>shape changes</strong>, a guard fails and the function is recompiled once; after a second new shape, that size becomes symbolic so it stops recompiling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1-TpMkKmnqPz6uN5.png" /></figure><p><strong>Everyday analogy.</strong> A restaurant: the head chef reads the recipe (Dynamo), the planner works out prep and cleanup (AOTAutograd), the kitchen manager sets up efficient stations (Inductor), and the recipe card is filed with a note like “for 4 guests, vegetarian” (cache + guards).</p><p><strong>Remember.</strong> <em>Dynamo captures, AOTAutograd prepares forward and backward, Inductor makes it fast, and guards decide when to reuse.</em></p><h3>9. One-page recap and self-check</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I1f_YRS4I5JhD3Yp.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bddfa2af388d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyTorch Autograd -beginners guide.]]></title>
            <link>https://medium.com/@analog76/pytorch-autograd-beginners-guide-81933ef1ab98?source=rss-d7923640d91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/81933ef1ab98</guid>
            <category><![CDATA[autograd]]></category>
            <category><![CDATA[pytorch-tutorial]]></category>
            <category><![CDATA[pytorch-autograd]]></category>
            <category><![CDATA[tensor]]></category>
            <dc:creator><![CDATA[Anandha L Ranganathan]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-11-02T08:01:02.435Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>How PyTorch builds a graph during the forward pass and walks it backward to compute gradients, step by step with pictures.</em></blockquote><blockquote><em>When you call </em><em>loss.backward(), PyTorch computes the gradient of every weight for you. That feature is called </em><strong><em>Autograd</em></strong><em>. It isn&#39;t magic: during the forward pass PyTorch quietly records a small graph of &quot;backward nodes&quot;, and </em><em>backward() walks that graph in reverse, applying the chain rule at each node.</em></blockquote><blockquote><em>In this post we build that graph by hand with tiny numbers (2, 3 and 4) so you can see every node, every saved value and every gradient. Each step has a diagram followed by the code that produces it.</em></blockquote><blockquote><strong><em>How to read the diagrams:</em></strong><em> green boxes are leaf tensors that require gradients, yellow is a leaf that doesn’t, tan is an intermediate result, and blue boxes are Autograd’s backward nodes. Orange dashed arrows are gradients flowing back.</em></blockquote><h3>Step 1 — Basic forward</h3><blockquote><em>We create two tensors. </em><em>a has </em><em>requires_grad=True, which tells PyTorch &quot;I want a gradient for this one&quot;. </em><em>b doesn&#39;t.</em></blockquote><pre>a = torch.tensor(2.0, requires_grad=True)<br>b = torch.tensor(3.0)<br>c = a * b</pre><p>It looks very simple and let’s look how to visualize this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhszhV0zmfuwcDCoqypKuQ.png" /></figure><blockquote><em>A few things to notice:</em></blockquote><ul><li>a and b are <strong>leaf</strong> tensors: we created them directly, so grad_fn is None.</li><li>c is not a leaf. It came from an operation, so it remembers how it was made: grad_fn = MulBackward0.</li><li>c.requires_grad is True automatically, because one of its inputs (a) requires a gradient.</li></ul><blockquote><strong><em>Remember:</em></strong><em> leaves are the tensors you create; everything computed from them carries a </em><em>grad_fn.</em></blockquote><h3>Step 2 — Backward graph built, no gradient yet</h3><blockquote><em>Nothing has been computed backward yet. But the moment </em><em>c = a * b ran, Autograd already built the backward graph. Let&#39;s peek at it with </em><em>next_functions.</em></blockquote><pre>a = torch.tensor(2.0, requires_grad=True)<br>b = torch.tensor(3.0)<br>c = a * b<br>print(c.grad_fn.next_functions)<br># ((&lt;AccumulateGrad&gt;, 0), (None, 0))</pre><p>here is the visualization part of this code..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVbMtjnuuhN3Dty8hAbg5w.png" /></figure><ul><li>While running the multiply, PyTorch saved what it will need later (ctx.save_for_backward). For c = a × b, the slope with respect to a is b, so b is saved.</li><li>c.grad_fn is a <strong>MulBackward0</strong> node. Its next_functions say where gradients go next: (AccumulateGrad, 0) for a, and None for b, because b doesn&#39;t need a gradient.</li><li><strong>AccumulateGrad</strong> is the node that finally writes into a.grad.</li><li>All grad fields are still None; this is just the plan, not the computation.</li></ul><blockquote><strong><em>Remember:</em></strong><em> the backward graph is built during the forward pass, not when you call </em><em>backward().</em></blockquote><h3>Step 3 — c.backward(): gradient flows</h3><pre>c.backward()<br>print(a.grad)  # tensor(3.)<br>print(b.grad)  # None<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVBIEXwVTToY_YWrCu9YGw.png" /></figure><blockquote><em>Now we call </em><em>backward() on </em><em>c. Autograd starts with a gradient of 1.0 (dc/dc = 1) and walks the graph we just saw.</em></blockquote><ul><li>MulBackward0 receives 1.0.</li><li>It multiplies by the saved b: 1.0 × 3 = <strong>3.0</strong>. That&#39;s dc/da.</li><li>AccumulateGrad adds 3.0 into a.grad, so a.grad = 3.0.</li><li>b.grad stays None, because it never asked for a gradient.</li></ul><blockquote><strong><em>Remember:</em></strong><em> for multiplication, each input’s gradient is the </em>other<em> input’s value.</em></blockquote><h3>Step 4 — Complex graph, no gradient yet</h3><p>Let’s add some complexity into the graph..</p><pre>a = torch.tensor(2.0, requires_grad=True)<br>b = torch.tensor(3.0, requires_grad=True)<br>c = a * b    # 6.0<br><br>d = torch.tensor(4.0, requires_grad=True)<br><br>e = c * d    # 24.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCEa7Mx7TUirOjoYhIRIOw.png" /></figure><blockquote><em>Now there are two multiplications, so there are two MulBackward0 nodes chained together:</em></blockquote><ul><li>e.grad_fn (MulBackward0 for e) points to <strong>MulBackward0 for </strong><strong>c</strong> and to <strong>AccumulateGrad for </strong><strong>d</strong>.</li><li>c.grad_fn points to <strong>AccumulateGrad for </strong><strong>a</strong> and <strong>AccumulateGrad for </strong><strong>b</strong>.</li><li>Each MulBackward0 saved its own two inputs: a, b for the first and c, d for the second.</li></ul><blockquote><em>The graph is basically a linked list of callback objects. </em><em>backward() just walks it from </em><em>e back to the leaves.</em></blockquote><h3>Step 5 — e.backward(): chain rule in numbers</h3><pre>e.backward()<br>print(a.grad, b.grad, d.grad)<br># tensor(12.) tensor(8.) tensor(6.)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TW9dw5cqgbf_Bz8Dwb1CYQ.png" /></figure><blockquote><em>Follow the orange numbers from top to bottom:</em></blockquote><ul><li>Start: de/de = <strong>1.0</strong>.</li><li>At e = c × d: d gets 1.0 × c = <strong>6.0</strong>, so d.grad = 6. c gets 1.0 × d = <strong>4.0</strong>.</li><li>At c = a × b, the incoming 4.0 is multiplied again: a gets 4 × b = <strong>12</strong>, and b gets 4 × a = <strong>8</strong>.</li></ul><blockquote><em>That’s the chain rule: multiply the gradients along the path.</em></blockquote><blockquote>de/da = de/dc × dc/da = 4 × 3 = 12.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*Jp3tqNZi4_9uxYTkzDuapg.png" /></figure><blockquote><strong><em>Remember:</em></strong><em> gradients flow backward and get multiplied at each node; each AccumulateGrad stores the final value in </em><em>.grad.</em></blockquote><h3>Corner cases</h3><p>This section explains why changing a tensor after the forward pass breaks backward, when it’s fine, and how to fix it.</p><h3><strong><em>Corner case 1: Modifying c in place after the forward pass (c += 1)</em></strong></h3><blockquote>Here’s the trap: we compute e = c * d, then change c in place before calling backward().</blockquote><pre>a = torch.tensor(2.0, requires_grad=True)<br>b = torch.tensor(3.0, requires_grad=True)<br>d = torch.tensor(4.0, requires_grad=True)<br>c = a * b      # 6.0, not a leaf<br>e = c * d      # MulBackward0 saves c (version 0)<br>c += 1         # in-place: c = 7.0, version 1<br>e.backward()   # RuntimeError</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0NVMQUOxtR_uBhvJgY5jA.png" /></figure><blockquote><strong><em>Why does this fail?</em></strong></blockquote><ul><li>MulBackward0 needs the <em>original</em> c to compute d&#39;s gradient (de/dd = c = 6). It saves a <strong>reference</strong> to c, not a copy, to save memory.</li><li>Every tensor has a version counter, _version. When c was saved it was at version <strong>0</strong>.</li><li>c += 1 writes into the <strong>same memory</strong>: c becomes 7.0 and _version becomes <strong>1</strong>.</li><li>During backward(), PyTorch compares the saved version (0) with the current one (1). They differ, so it stops with: <em>&quot;one of the variables needed for gradient computation has been modified by an inplace operation.&quot;</em></li><li>If PyTorch allowed it, d.grad would silently come out as <strong>7</strong> instead of the correct <strong>6</strong>. A loud error is better than a wrong gradient.</li></ul><blockquote><em>Java developers will recognize this: it’s the same idea as </em><em>ArrayList&#39;s </em><em>modCount, which throws </em><em>ConcurrentModificationException when the list changes under an iterator.</em></blockquote><blockquote><strong><em>How to fix it</em></strong></blockquote><ul><li>Use an out-of-place op: c = c + 1 creates a new tensor, the saved c stays 6, and d.grad = 6.</li><li>Or modify a copy: c2 = c.clone(); c2 += 1.</li><li>Or do the in-place change <strong>before</strong> c is used in the forward pass.</li></ul><h3>Step 6: Unbind</h3><h3>Introduction: what does unbind do?</h3><ol><li>a.unbind(dim=0) removes dimension 0 and returns a <strong>tuple</strong> of tensors, one per index: for a = [1., 2., 3.] you get three 0-d tensors b = 1.0, c = 2.0, d = 3.0.</li><li>They are <strong>views</strong>, not copies: they share a’s storage (offsets 0, 1, 2) and b._base is a (verified).</li><li>Autograd records <strong>one</strong> UnbindBackward0 node for the whole call. Each output remembers its slot in that node (output_nr 0, 1, 2).</li><li>In backward, UnbindBackward0 is just <strong>stack</strong>: it collects one gradient per slot and stacks them into a single tensor shaped like a.</li></ol><p><strong>Remember:</strong> unbind splits forward; UnbindBackward0 stacks backward.</p><pre>import torch<br>a = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)<br>b, c, d = a.unbind()<br>e = b * c * d   # 6.0<br>e.backward()<br>print(a.grad)   # tensor([6., 3., 2.])</pre><h3>The math</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mIkhmXFkfMxGCJIIxWQrEA.png" /></figure><h3>Step 6.1 — Forward: b, c, d = a.unbind()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AM4HxFg-bgjrAmlNag5sdw.png" /></figure><ol><li>a is a <strong>leaf</strong> (you created it) with requires_grad=True. Its storage holds 1.0, 2.0, 3.0.</li><li>a.unbind() (dim 0) splits it into three tensors b = 1.0, c = 2.0, d = 3.0. No numbers are copied: each is a <strong>view</strong> into a&#39;s storage at offset 0, 1, 2, and b._base is a.</li><li>b, c, d are <strong>non-leaves</strong>: is_leaf=False, requires_grad=True, grad_fn=UnbindBackward0.</li><li>All three share the <strong>same</strong> UnbindBackward0 node. What tells them apart is output_nr = 0, 1, 2 (which output slot of the node they are).</li><li>The node remembers only dim = 0 (_saved_dim), and its next_functions = ((AccumulateGrad, 0),) points back to a&#39;s AccumulateGrad.</li><li>Nothing has a gradient yet: every .grad is None.</li></ol><p><strong>Remember:</strong> One op with N outputs = ONE backward node with N input slots. Each output knows its slot through output_nr.</p><pre>import torch<br>a = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)<br>b, c, d = a.unbind()            # dim=0 -&gt; three 0-d tensors<br>print(b.grad_fn is c.grad_fn is d.grad_fn)      # True  (ONE node)<br>print(b.output_nr, c.output_nr, d.output_nr)    # 0 1 2<br>print(b.grad_fn.next_functions)                 # ((&lt;AccumulateGrad&gt;, 0),)<br>print(b._base is a, b.storage_offset())         # True 0   (a view, no copy)</pre><h3>Step 6.2— Forward continued: tmp = b·c, then e = tmp·d</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c2FoGwegHSd2LtLWiMn5AQ.png" /></figure><p><strong><em>Key takeaways</em></strong></p><ul><li>The forward pass builds the backward graph; backward() only walks it.</li><li>Leaf tensors get .grad through AccumulateGrad; intermediate tensors don&#39;t keep one unless you call retain_grad().</li><li>For multiplication, each input’s gradient is the other input’s value, times the gradient flowing in.</li><li>Don’t modify in place a tensor that backward saved; PyTorch’s version counter will catch it.</li></ul><blockquote><em>Next in this series: </em><strong><em>Autograd hooks</em></strong><em>, and how DDP uses them to overlap gradient sync with the backward pass.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81933ef1ab98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regularization with Gradient descent]]></title>
            <link>https://medium.com/@analog76/regularization-with-gradient-descent-fbd6aaa4a6e3?source=rss-d7923640d91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbd6aaa4a6e3</guid>
            <category><![CDATA[l2-regularization]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Anandha L Ranganathan]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 07:01:02 GMT</pubDate>
            <atom:updated>2026-11-01T07:01:02.393Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@analog76/d38998c7ba41">Please read here the gradient descent — introduction</a></p><p>Here is the quick recap.</p><h3>1. A quick primer: how a model learns (gradient descent)</h3><p>A model is a function with adjustable numbers called <strong>weights</strong>. Training means finding the weights that make its predictions as accurate as possible.</p><p><strong>Step 1: measure how wrong the model is.</strong> A <strong>loss function</strong> turns the error into one number. Lower is better.</p><p><strong>Step 2: find which direction is “downhill”.</strong> The <strong>slope</strong> (gradient) tells us how the loss changes if we nudge a weight. In PyTorch, loss.backward() computes it for every weight.</p><p><strong>Step 3: take a small step downhill.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*zkP0r9E3Obve9-vCRkeCSw.png" /></figure><p>​​​</p><ul><li><strong>Positive slope:</strong> increasing the weight raises the loss, so we decrease the weight.</li><li><strong>Negative slope:</strong> increasing the weight lowers the loss, so we increase the weight.</li><li><strong>lr (learning rate)</strong> controls the step size, typically small, e.g. 1e-3 = 0.001.</li></ul><p><strong>Step 4: repeat</strong> over many batches and <strong>epochs</strong> until the loss stops improving.</p><p>Gradient descent is very good at one thing: <strong>making the training loss small.</strong> And that’s exactly where the trouble starts.</p><h3>2. Overfitting and underfitting: the classic problem</h3><p>Minimizing training loss is not the real goal. The real goal is to do well on <strong>new data the model has never seen</strong>. Two things can go wrong.</p><h3>The classic example</h3><p>Imagine 10 data points that roughly follow a gentle curve, plus a bit of random noise. We try three models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b39S8hkHKBn1_nvsAO-qPA.png" /></figure><blockquote><em>🎓 </em><strong><em>Student analogy:</em></strong></blockquote><blockquote><strong><em>Underfitter</em></strong><em>: the underfitter didn’t study enough and fails both the practice test and the real exam.</em></blockquote><blockquote><strong><em>Overfitter</em></strong><em>: The overfitter </em><strong><em>memorized the answer key</em></strong><em> to the practice test, so they score 100% on practice but fail the real exam because the questions are slightly different.</em></blockquote><blockquote><strong><em>Good fitter</em></strong><em>: The good student learned the </em><strong><em>concepts</em></strong><em>.</em></blockquote><h3><strong>Why does underfitting happen?</strong></h3><ul><li>The model is <strong>too simple</strong> for the problem (e.g. a straight line for curved data).</li><li><strong>Not trained long enough</strong>: too few epochs, or a learning rate that’s too small.</li><li><strong>Too much regularization</strong>: weights are forced so small that the model can’t express the pattern.</li><li><strong>Missing useful features</strong>: the input doesn’t contain the information needed.</li></ul><h3>Why does overfitting happen?</h3><ul><li>The model is <strong>too complex / too flexible</strong> for the amount of data (many parameters, few examples).</li><li><strong>Too little training data</strong>, so noise looks like a pattern.</li><li><strong>Trained too long</strong>: after learning the real pattern, it starts memorizing the noise.</li><li><strong>Noisy data</strong>: random errors get learned as if they were real.</li><li>A common fingerprint: <strong>some weights grow very large</strong> as the model bends itself to hit every point.</li></ul><h3>How do we spot them?</h3><p>Watch training loss and <strong>validation loss</strong> (loss on held-out data) after every epoch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyvZwC-4GHyeSIHR1gD1uA.png" /></figure><h3>How do we fix them?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgvFrJY5I8DwvlzOoYw-oQ.png" /></figure><p>More data isn’t always available, and a smaller model may lose accuracy. <strong>Regularization</strong> is the tool that lets you keep a powerful model while stopping it from memorizing. That’s why it’s used in almost every modern neural network.</p><h3>3. Why regularization is the answer</h3><p>Recall the fingerprint of overfitting: <strong>large weights.</strong> The model leans too hard on a few features to fit every little bump in the training data.</p><p>Plain gradient descent has no reason to stop that. It only cares about training loss. So we change <strong>what it’s minimizing</strong>: fit the data <strong>and</strong> keep the weights small. That’s regularization.</p><h3>4. What is regularization?</h3><p><strong>Regularization</strong> is any technique that discourages a model from becoming too complex, so it <strong>generalizes</strong> better to unseen data.</p><p>The most common form adds a <strong>penalty</strong> to the loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8G3XNRdsUIW38MGtCY0cg.png" /></figure><ul><li><strong>λ (lambda)</strong> controls the strength. λ = 0 means no regularization; a large λ means very strong regularization.</li><li>λ is a <strong>hyperparameter</strong>: you choose it by checking performance on a <strong>validation set</strong>.</li></ul><p>Popular regularizers: <strong>L2 (Ridge)</strong>, <strong>L1 (Lasso)</strong> and <strong>Dropout</strong>. This post covers <strong>L2</strong>.</p><h3>5. Ridge “regression” or “regularization”? Getting the names right</h3><p>These terms are mixed up all the time. Here’s the standard usage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0d_nrBnPQNZ98tFiQd5MDQ.png" /></figure><p><strong>Regression</strong> is a <em>task</em> (predicting a number). <strong>Regularization</strong> is a <em>tool</em> you can add to almost any model. “Ridge regression” is just the historical name for the combination of the two.</p><p>👉 <strong>Say “L2 regularization”</strong> in general, “ridge regression” only for linear regression, and “weight decay” when talking about PyTorch optimizers.</p><h3>6. The L2 penalty</h3><p>L2 penalizes the <strong>sum of squared weights</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CowXJCTaIplDEO2RCqCJsA.png" /></figure><p>Squaring means <strong>big weights are punished much more than small ones</strong>: a weight of 10 costs 100, while a weight of 1 costs only 1. So the model is strongly pushed away from relying on a few huge weights.</p><h3>7. Back to plain gradient descent: what is missing?</h3><p>The update rule from section 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*zhCP21OuDLRQ0kRl01n3cA.png" /></figure><p><strong>The problem:</strong> this rule only cares about fitting the training data. If making a weight huge reduces training loss, even by fitting noise, gradient descent happily does it. Nothing pulls the weights back.</p><h3>8. The total slope with L2</h3><p>Take the derivative of the new total loss. The derivative of λw² is 2λw, so the slope now has <strong>two parts</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPJ2BCOX0wzZjI0UvaSUcQ.png" /></figure><ul><li>The <strong>data slope</strong> says “move to fit the data better.”</li><li>The <strong>L2 slope</strong> says “move toward zero,” and it’s <strong>proportional to the weight itself</strong>, so the bigger the weight, the harder the pull.</li></ul><h3>9. The improved update rule</h3><p>Plug the total slope into gradient descent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avElgBQKQ0Jktubp5APYFQ.png" /></figure><p>Every step, the weight is first <strong>multiplied by a number slightly less than 1</strong> (it decays), and then the normal gradient step is applied.</p><h3>10. A worked example with numbers</h3><p>Let <strong>w = 7</strong>, <strong>lr = 0.1</strong>, <strong>λ = 0.5</strong>, and suppose backward() gives a <strong>data slope of 4</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8q70UMSUhVv-zWWXtraoxg.png" /></figure><p>L2 pulled the weight down an <strong>extra 0.7</strong>. That’s exactly the decay factor at work: 2 × 0.1 × 0.5 = 0.1, and 10% of 7 = 0.7.</p><p><strong>GD vs GD + L2 on five weights</strong> (same lr = 0.1, λ = 0.5, and the same data slope of 4 for each, to keep it simple):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78n4htSw8wLYFHpHNek_xg.png" /></figure><p>Two things to notice:</p><ol><li><strong>Big weights lose the most</strong>: L2 targets exactly the weights that cause overfitting.</li><li><strong>No weight ever reaches exactly zero</strong>: multiplying by 0.9 only gets you closer. (That’s the key difference from L1, which can set weights to exactly zero.)</li></ol><h3>11. L2 in PyTorch</h3><p>You don’t write the penalty by hand. Pass weight_decay to the optimizer:</p><pre>import torch<br>optimizer = torch.optim.SGD(model.parameters(), lr=0.1, weight_decay=0.01)</pre><pre><br>for x, y in train_loader:<br>    optimizer.zero_grad()<br>    loss = loss_fn(model(x), y)   # data loss only<br>    loss.backward()               # computes the data slope<br>    optimizer.step()              # adds the weight-decay slope, then updates</pre><blockquote><em>📝 </em><strong><em>Two practical notes</em></strong></blockquote><ul><li>PyTorch’s weight_decay=wd adds wd × w to the gradient, which matches the formula above with wd = 2λ. Same idea, the constant just absorbs the 2.</li><li>With Adam, prefer <strong>torch.optim.AdamW</strong>, which applies weight decay the &quot;decoupled&quot; way and generally works better than Adam(weight_decay=...).</li></ul><h3>12. How to choose λ</h3><p>Use the <strong>validation set</strong>, never the test set:</p><ol><li>Try a few values on a log scale, e.g. 1e-2, 1e-3, 1e-4 (0.01, 0.001, 0.0001).</li><li>Train with each and compare <strong>validation loss</strong>.</li><li>Pick the best, then evaluate <strong>once</strong> on the test set.</li></ol><ul><li>λ too small: little effect, so overfitting remains.</li><li>λ too large: weights are crushed toward zero, so the model <strong>underfits</strong>.</li></ul><p><em>Next in this series: </em><strong><em>L1 regularization (Lasso)</em></strong><em>, and why it can switch features off completely.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbd6aaa4a6e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradient descent -Part1]]></title>
            <link>https://medium.com/@analog76/gradient-descent-part1-d38998c7ba41?source=rss-d7923640d91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d38998c7ba41</guid>
            <category><![CDATA[gradient]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm-training]]></category>
            <category><![CDATA[stochastic-gradient]]></category>
            <dc:creator><![CDATA[Anandha L Ranganathan]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 07:01:03 GMT</pubDate>
            <atom:updated>2026-10-27T07:08:59.052Z</atom:updated>
            <content:encoded><![CDATA[<h3>How does a machine learn from its mistakes using gradient descent ?</h3><h3>Why gradient descent at all?</h3><p>Picture a machine with one knob. You feed it a 2. It is supposed to output a 10. The knob is at 3, and the machine multiplies, so it outputs 6. The expected value is 10. but it returned 6. The output needs to climb by 4.</p><p>The part that trips people: you know the right <em>answer</em>, but not the right <em>knob setting</em>. Those are different things. “The output should be 10” is given. “The knob should be at 5” is what you have to find. The answer key talks about the output. It says nothing about the knob.</p><p>You also cannot look inside. A real network has millions of knobs wired to each other, and you have no map. All you can do is turn a knob a little and see whether the output got better or worse.</p><p>A useful picture: you are on a hillside in thick fog. You want the valley floor. You cannot see the valley, the hill, or three feet ahead. You can feel which way the ground tilts under your feet.</p><p>So you take a small step downhill. Feel again. Step again. Repeat.</p><p>You reach the bottom not because you knew where it was, but because “downhill” was available at every point.</p><p>Gradient descent is that walk, done with arithmetic. The tilt is the <strong>gradient</strong>. Everything else is detail.</p><h3>What would you do instead?</h3><p>The alternatives are why this looks less like a clever trick and more like the only door out of the room.</p><p><strong>Option 1: guess randomly.</strong> Set the knob, check the error, keep the change if it helped. One knob: you might stumble into something decent. A thousand knobs: you will never hit a good combination in the lifetime of the universe. Random guessing dies as soon as you have more than a couple of knobs.</p><p><strong>Option 2: try every value.</strong> Sweep from −1000 to +1000 in steps of 0.001 and keep the best. Two million tries; a computer does that instantly. Solved for <em>one</em> knob. Every new knob multiplies the work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hXnTeI642KfMpKC6NoQ4g.png" /></figure><p>A small network has thousands of knobs. A language model has hundreds of billions. Trying combinations is not slow. It is not a thing that can happen.</p><p><strong>Option 3: solve it with algebra.</strong> For the toy machine you can. “Find the knob where the error is zero” is one line and gives w=5w = 5w=5 exactly.</p><p>Stack a few layers with nonlinear functions between them and “solve for the knobs” becomes billions of tangled equations with no closed form.</p><p>What is left is the fog. You cannot see the landscape, but you can always measure the slope <em>where you are standing</em>. That measurement is cheap, exact, and — this is the crucial part — its cost does not explode as you add knobs. One pass through the network gives the slope for every knob at once. A hundred billion of them, in one go.</p><p>That is the trade. Give up the global view. Keep the local slope. Take a lot of steps.</p><h3>The formula</h3><p>In words, before symbols:</p><pre>new setting  =  old setting  −  (step size × slope)</pre><p>That’s it. That’s gradient descent. In symbols:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GhY6DdIR4_-hyKdTQQD_Cw.png" /></figure><p>Four pieces:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mHD68mupaWp9Dm9j50HNQ.png" /></figure><p>Three things to notice, because they’re where the cleverness hides.</p><p><strong>The minus sign does the thinking.</strong> You never decide whether to add or subtract. The slope comes out signed, and subtracting it always moves downhill:</p><ul><li><strong>Positive slope</strong>: increasing the weight raises the loss, so we decrease the weight. ✓</li><li><strong>Negative slope</strong>: increasing the weight lowers the loss, so we increase the weight. ✓</li><li>(Here weight means the model that stays inside that black box)</li></ul><p>Same line of code, both directions, no if statement. That&#39;s the trick.</p><p><strong>The step is not the learning rate.</strong> The step is the <strong>learning rate <em>times the slope</em></strong>. On a steep slope the step is large. Near the bottom the slope shrinks, so the steps shrink with it. Gradient descent brakes on its own. Nobody programs that in. It falls out of multiplying by the slope.</p><p><strong>The learning rate is temperament.</strong> The ground tells you how steep it is. That part is not yours. The learning rate is how much stride you give per unit of steepness.</p><p>Send three hikers down the same hill, feeling the same ground:</p><blockquote><em>🐢 </em><strong><em>The timid one</em></strong><em> (η too small) </em>The timid one uses a learning rate that is too small. Even where the ground plunges away, they inch forward. They will reach the bottom — sometime next week<em>.</em></blockquote><blockquote><em>🚶 </em><strong><em>The sensible one</em></strong><em> (η about right) </em>The sensible one uses a learning rate that is about right. They stride out where it is steep and shorten up as it levels off. Down in a dozen steps<em>.</em></blockquote><blockquote><em>🏃 </em><strong><em>The reckless one</em></strong><em> (η too big) </em>The reckless one uses a learning rate that is too large. They feel a steep patch and leap. They sail clean over the valley and land higher up the far side than where they started. They feel an even steeper patch there. They leap again, harder. They are now going up the mountain, at speed, forever</blockquote><p>Nobody handed them different information. The hill was the same for all three, and all three read the slope correctly. The only difference is how aggressively each one converts “steep” into “stride.”</p><p>The gradient can be computed perfectly and training can still fail. Learning rate is not smarter information about the loss surface. It is only how aggressively you turn “this way is downhill” into a change in the weights. Too small, and you crawl. About right, and you descend. Too large, and you overshoot the valley and diverge. Same hill. Same slope. Different temperament.</p><p><strong>The slope is measured, not guessed.</strong> This isn’t a heuristic or an estimate. Calculus gives the exact tilt at the exact point you’re standing. The only guesswork in the entire system is where you started and how big</p><h3>Watching it actually run</h3><p>Let’s make the fog concrete. Here’s our error, as a function of the knob:</p><p>L(w)=(w−4)²</p><p>Its slope at any point is 2(w−4). We’ll use a step size of η=0.3.</p><p>You can see the valley is at w = 4. <strong>The algorithm cannot.</strong> It only ever gets to ask one question: <em>what&#39;s the slope right here?</em></p><h3>Starting too low, at w = 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-eN-N2sJ24hWEuTUk_PRQ.png" /></figure><p>The Knob is converging at 4.</p><h3>Starting too high, at w = 10</h3><p>Same formula. Nothing changed. We just dropped it somewhere else on the hill.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zxbFMMg86QEcRxO9fJW4Xw.png" /></figure><p><strong>Both runs land on 4, from opposite directions, with identical code.</strong> One walked up, one walked down. Neither was told which way to go, and neither was told where 4 was. The slope handled it.</p><p>Look at the error columns: 9 → 1.44 → 0.23 → 0.037, and 36 → 5.76 → 0.92 → 0.147. Both collapsing fast, and both decelerating as they arrive, exactly as promised.</p><p>Here’s the whole thing, runnable:</p><pre>w, eta = 1.0, 0.3            # try 10.0 too<br><br>for step in range(6):<br>    error = (w - 4) ** 2<br>    slope = 2 * (w - 4)<br>    print(f&quot;step {step}:  w={w:7.4f}   error={error:8.4f}   slope={slope:+7.3f}&quot;)<br>    w = w - eta * slope      # ← the entire algorithm</pre><p>Every neural network ever trained is that last line, wearing a lot of scaffolding.</p><h3>Learning rate : The one thing you actually choose</h3><p>The slope is handed to you. The step size η is yours, and it’s the difference between training working and training exploding. Same starting point, same problem, six different <em>η</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zd2Powrrt1y9FQ-z4U3L5g.png" /></figure><p>That last row is the one to burn into memory. <strong>The slope was correct on every single step.</strong> The math was perfect. The steps were just too big, so each one flew past the valley and landed further up the opposite side than where it started — and then did it again, worse. This is what people mean when a training run “goes to NaN.” Nothing was wrong except one number that a human picked.</p><p>That’s our reckless hiker, in a table.</p><p>If you have ever overcorrected a car, you already know this failure.</p><p>You drift a little to the right, so you yank the wheel left — too hard. Now you are pointed at the other lane, so you yank right, even harder. Every fix is bigger than the mistake that caused it. Half a minute later you are in a ditch.</p><p>Your reading of the road was not the problem. Each time, you knew which way you were off. The problem was how hard you turned the wheel.</p><p>Engineers call that hardness <strong>gain</strong>. Too much gain and a correcting system starts to swing, then blows up.</p><p>The <strong>learning rate</strong> is that gain. That is all it is.</p><p>And if one special value of it happens to land on the exact answer in a single step, that is luck for that one curved bowl. Change the problem and the same number can explode.</p><p>There is no learning rate that works for every job. That is why people tune it. That is why most training runs start with bigger steps and finish with smaller ones: bold early, careful near the bottom.</p><h3>Two knobs, and where the chain rule comes in</h3><p>One knob was a warm-up. Real models have more, and the moment you have two, something new is needed.</p><p>Give our neuron a second knob — a bias that just shifts the output up or down:</p><p>y=w⋅x+b</p><p>With input x = 2, target t = 10, starting at w = 3, b = 0.</p><h3>Why one slope isn’t enough any more</h3><p>We need to know how the error responds to w, <em>and</em> separately how it responds to b. Two knobs, two slopes. And here&#39;s the wrinkle:</p><p><strong>Neither knob touches the error directly.</strong> The knobs make a prediction. The <em>prediction</em> makes the error. Nothing connects w to L except by going through y first:</p><pre>    w ──┐<br>        ├──▶  y_hat  ──▶  L (y-y_hat)<br>    b ──┘   (prediction)  (error)</pre><p>So “how does the error respond to w?&quot; can&#39;t be answered in one move. It has to be answered in two hops, and that&#39;s precisely what the chain rule is for.</p><h3>The chain rule, in one sentence</h3><blockquote><em>To get the slope across a chain, multiply the slopes of each link.</em></blockquote><p>That’s it. If the error is twice as sensitive to the prediction, and the prediction is three times as sensitive to the knob, then the error is six times as sensitive to the knob. Sensitivities <strong>multiply</strong> as they pass down a chain.</p><h3>How to picture it</h3><p>Think of gears. Turn a small gear by one tooth; the gear it drives turns by three; the gear <em>that</em> one drives turns by two. Turn the first gear one tooth and the last one moves 3 × 2 = 6. You never needed a direct connection between first and last — you just multiplied along the linkage.</p><p>Or think of it as a message passed backwards. The error announces how upset it is, and that message travels back up the wires, getting scaled by each link it crosses:</p><pre>w  ◀────────  y  ◀────────  L<br>        &quot;×2&quot;          &quot;−8&quot;<br>     (a 1 change     (raising y by 1<br>      in w moves      drops the error<br>      y by 2)         by 8)</pre><p>Start at the error. Walk backwards. Multiply as you go. By the time you reach a knob, you have its slope: −8 × 2 = <strong>−16</strong>.</p><p>In derivative, this can be written as. We need to find ∂L/∂w but we can’t find, but using chaing rule in derivate we identify them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XkmEAbYdQNe4nkLHvi1Dhw.png" /></figure><p>That backwards walk has a name. It’s <strong>backpropagation</strong>. It isn’t a separate idea from the chain rule — it’s the chain rule, applied to a whole network, organised so that no work gets repeated.</p><h3>Both knobs, in one pass</h3><p>The beautiful part: the backwards message −8 gets computed <strong>once</strong>, then reused by every knob feeding into that point. Each knob just scales it by its own local link:</p><ul><li>w is connected through the input, so: −8 × <strong>2</strong> = −16</li><li>b is connected directly, so: −8 × <strong>1</strong> = −8</li></ul><p>Now update both, same formula, same step size (η=0.01):</p><p><strong>Work out the slopes.</strong> Starting at w = 3, b = 0:</p><pre>prediction   y = w × 2 + b  =  3 × 2 + 0  =  6<br>we wanted    t = 10         →  4 short</pre><pre>slope on the prediction  =  2 × (6 − 10)  =  −8      ← computed once<br>      slope for w  =  −8 × 2  =  −16      (w is multiplied by the input 2)<br>      slope for b  =  −8 × 1  =   −8      (b is added on directly)</pre><p><strong>Turn each knob.</strong> Same line, twice, with a step size of 0.01:</p><pre>w:   3 − 0.01 × (−16)  =  3 − (−0.16)  =  3 + 0.16  =  3.16<br>b:   0 − 0.01 × (−8)   =  0 − (−0.08)  =  0 + 0.08  =  0.08</pre><p>Look closely at what just happened. The rule says <strong>subtract</strong> — always, no exceptions. But the slope is <strong>negative</strong>, and subtracting a negative adds. Minus times minus makes plus, and the knob goes <em>up</em>, without a single line of code ever deciding to increase it.</p><p>Had the prediction come out too <em>high</em> instead — say 14 — the slope would have been +16, and the identical line gives 3 − 0.16 = 2.84. Down. Same arithmetic, opposite direction, nobody choosing.</p><p>Do that four times and you get the table above. The w knob:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OC4IJzO2CRzQjHw7xJ9tQA.png" /></figure><p>The turns shrink every step — 0.160, 0.144, 0.130, 0.117 — with nothing arranging that. As the prediction closes in on 10 the slope shrinks, and the step is the slope times 0.01. The self-braking from earlier, visible as a column of numbers.</p><p>Here it is in code:</p><pre>x, t, eta = 2.0, 10.0, 0.01<br>w, b = 3.0, 0.0</pre><pre>for step in range(4):<br>    y     = w * x + b              # forward:  make a prediction<br>    error = (y - t) ** 2           # how wrong</pre><pre>    dL_dy = 2 * (y - t)            # backward: one message...<br>    dL_dw = dL_dy * x              #   ...scaled for w<br>    dL_db = dL_dy * 1              #   ...scaled for b</pre><pre>    w = w - eta * dL_dw            # update, same line as before<br>    b = b - eta * dL_db            # ...once per knob</pre><p>Two details worth pointing out:</p><p><strong>w moves faster than </strong><strong>b.</strong> Look at the columns — w travels 3.000 → 3.434 while b only goes 0.000 → 0.217, exactly twice as slow. That&#39;s the input x = 2 doing it: w gets multiplied by the input on its way to the prediction, so it has twice the leverage, so it gets twice the slope, so it takes twice the step. Knobs with more influence get moved more. Automatically.</p><p><strong>Two knobs beat one.</strong> With only w, the error would have gone 16 → 13.54. With both, it goes 16 → 12.96. More knobs, more ways down, faster descent.</p><h3>Picturing two knobs at once</h3><p>With one knob, the error was a curve and you walked left or right along it.</p><p>With two, it’s a <strong>surface</strong> — a bowl, with w running east-west and b running north-south, and height being the error. You&#39;re a marble on the inside of that bowl.</p><p>The two slopes are the tilt in each direction. Put them together and you get an arrow pointing straight downhill on the surface — and that arrow is what “the gradient” really means. Not a number: a <strong>direction in knob-space</strong>.</p><p>Add a third knob and the bowl becomes something in 4D that nobody can picture, which is fine, because the arithmetic never needed you to picture it. The gradient is just a list of slopes, one per knob, and the update is applied to each one independently:</p><pre>for every knob i:<br>    knob[i] = knob[i] - eta * slope_for_knob_i</pre><p>One knob or a hundred billion — that loop is unchanged.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d38998c7ba41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Residual connections in Transformers]]></title>
            <link>https://medium.com/@analog76/residual-connections-in-transformers-6b5e87510dc1?source=rss-d7923640d91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b5e87510dc1</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[residual-connection]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[deep-neural-networks]]></category>
            <dc:creator><![CDATA[Anandha L Ranganathan]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 07:01:04 GMT</pubDate>
            <atom:updated>2026-10-14T07:01:04.666Z</atom:updated>
            <content:encoded><![CDATA[<p>A residual connection keeps a clean copy of its input. The layer does not rewrite the whole note. It only writes a short list of edits, and those edits are added to the clean copy.</p><h3>Why do we need residual connection ?</h3><p>Picture a note passed down a line of editors.</p><p>Without a clean copy, each editor must rewrite the whole note. By the tenth person, the original meaning is gone. When someone at the end says “this is wrong,” that complaint has to travel back through every rewrite. It arrives too faint to help the first editor. That faint complaint is a vanishing gradient.</p><p>With a clean copy, two things travel forward: the original note, unchanged, and a short list of edits from this person. The next person receives the original plus those edits. If an editor has nothing useful to add, they add nothing, and the note still arrives intact. A complaint can follow the clean copy backward and reach the early editors at full strength.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUc-shJFn5B0P6gGonD_PQ.png" /></figure><h3>What a Transformer does</h3><p>A Transformer uses this after every major step.</p><ol><li>Attention reads the sentence and writes a list of edits.</li><li>Those edits are added to the clean copy. Layer norm then smooths the result.</li><li>The feed-forward step writes another list of edits.</li><li>Those edits are added to the new clean copy, and layer norm smooths that too.</li></ol><p>This pair of steps is called Add &amp; Norm. Add means “put the edits on the clean copy.” Norm means “smooth the result.” The lists stay the same length, usually 512 numbers per word, because you can only add two lists that match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXzcJndqpQfOX8-vYXMDPw.jpeg" /></figure><h3>What if residual connection doesn’t exists ?</h3><p>Without a residual connection, there is no clean copy. Every layer has to rewrite the whole note.</p><p>Picture the same line of editors. Each person throws away the page they received and writes a new one from memory. By the tenth editor, the original meaning is blurred. A deep Transformer does the same thing to each word: attention and the feed-forward step replace the word’s numbers instead of adding a small change.</p><p>Training then fails in two ways.</p><ul><li><strong>The meaning gets lost on the way forward.</strong> Early information has no protected path. Later layers never see a faithful copy of the input, so they cannot build on it. They only see a heavily rewritten version.</li><li><strong>The correction gets lost on the way back.</strong> A complaint about the final result must pass through every rewrite. Each pass multiplies it by small random weights, so it shrinks. By the time it reaches the first layers, it is nearly zero. Those layers stop learning. That is the vanishing gradient.</li></ul><p>What you would see in practice:</p><ul><li>A shallow stack of 2 or 4 layers might still train, because the note has not been rewritten many times.</li><li>A deep stack, the kind used in GPT, stalls. The loss stays high or blows up. Adding more layers makes the model worse, not better.</li><li>The early layers barely change, because almost no correction reaches them.</li></ul><p>The layer also cannot take the easy option, “change nothing.” With a clean copy, doing nothing is allowed: add an empty list of edits and the original note goes through. Without it, “change nothing” means the layer must perfectly reproduce its input. That is a hard thing to learn, so the network cannot fall back to a safe pass-through.</p><p>That is why every Transformer block adds the edits back onto a clean copy. Remove that add, and a deep model cannot keep the original signal or teach its early layers.</p><h3>Limitation</h3><p>The clean copy and the list of edits must be the same length. If a later step needs a different length, the clean copy has to be resized first. Transformers avoid that. They keep one length all the way through the block.</p><h3>In one line</h3><p>A residual connection is a clean copy of the input, kept beside the layer’s edits. The layer only has to say what should change, and a correction can still travel back along that clean copy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b5e87510dc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Compression with Quantization]]></title>
            <link>https://medium.com/@analog76/model-compression-with-quantization-7029989938f7?source=rss-d7923640d91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7029989938f7</guid>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[model-compression]]></category>
            <category><![CDATA[quantization]]></category>
            <dc:creator><![CDATA[Anandha L Ranganathan]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 01:11:47 GMT</pubDate>
            <atom:updated>2026-09-24T01:11:47.605Z</atom:updated>
            <content:encoded><![CDATA[<p>Quantization is one of the most important model compression techniques used to make neural networks smaller, faster, and more memory-efficient. It works by mapping continuous, high-precision numerical values (such as floating-point parameters) into a smaller, discrete set of lower-precision values.</p><h3>The Core Concept: Lowering Bit Precision</h3><p>When deep learning models (LLMs, CNNs, Diffusion Models, etc.) are trained, their weights and activations are typically stored in high-precision formats:</p><ul><li><strong>FP32</strong> (32-bit Floating Point) — Full single-precision. Highest accuracy, but expensive in memory and compute.</li><li><strong>FP16 / BF16</strong> (16-bit Floating Point) — The standard mixed-precision formats used in modern training.</li></ul><p>Quantization converts these values into lower-bit representations:</p><ul><li><strong>INT8</strong> (8-bit Integer) — Reduces memory footprint by <strong>4×</strong> compared to FP32.</li><li><strong>INT4 / FP4</strong> (4-bit) — Reduces memory by <strong>8×</strong> compared to FP32. This is currently the sweet spot for running large language models on consumer GPUs, laptops, and edge devices.</li><li><strong>Extreme schemes</strong> (2-bit, 1.58-bit, ternary, binary) — Used in specialized research and hardware.</li></ul><h3>Why Quantization Matters</h3><ol><li><strong>Dramatically reduced memory footprint</strong> A 70-billion-parameter model in FP16 requires ~140 GB of VRAM just to load. Quantizing it to 4-bit (via GGUF, AWQ, etc.) brings the requirement down to roughly <strong>35–40 GB</strong>, making it runnable on a single high-end consumer GPU.</li><li><strong>Faster inference</strong> Modern CPUs, GPUs, and NPUs execute integer arithmetic (especially INT8) significantly faster than 32-bit floating-point operations, increasing throughput and lowering latency.</li><li><strong>Lower power consumption and edge deployment</strong> Fewer bits mean less data movement between memory and compute units, which directly reduces energy use — critical for smartphones, IoT devices, and robotics.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_33bwhAZ0xUks5Gdu-NQyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bc4yX2RSdiH2qcoUXUjxMg.png" /></figure><h3>Primary Approaches to Quantization</h3><p>(will dive deep in later session).</p><ol><li><strong>Post-Training Quantization (PTQ)</strong></li></ol><p>Takes a finished model and compresses it after the fact to smaller size.</p><ul><li><strong>Dynamic Quantization</strong>: Weights are quantized offline; activation ranges are computed on-the-fly during inference.</li></ul><p><strong>Static Quantization</strong>: A calibration dataset is run through the model in advance to fix activation scales, enabling faster runtime.</p><p><em>Pros</em>: Fast to apply, no need to retrain.<br><em>Cons</em>: Can cause noticeable accuracy loss when pushing to very low bit-widths (especially INT4 and below).</p><p><strong>2. Quantization-Aware Training (QAT)</strong><br>Quantization is simulated during training or fine-tuning.</p><ul><li>The forward pass uses “fake quantization” so the model learns to compensate for the reduced precision.</li><li>Gradients flow through the simulated quantization steps during backpropagation.</li></ul><p><em>Pros</em>: Maintains much higher accuracy even at 4-bit or 2-bit precision.<br><em>Cons</em>: Requires more compute and access to training (or fine-tuning) data.</p><p>Here’s a clear breakdown of how model size (in parameters) translates into memory usage under different precisions.</p><h3>​</h3><h3>​</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7029989938f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Softmax function]]></title>
            <link>https://medium.com/@analog76/softmax-function-3e144f82c76e?source=rss-d7923640d91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e144f82c76e</guid>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[self-attention]]></category>
            <category><![CDATA[softmax]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Anandha L Ranganathan]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 01:27:57 GMT</pubDate>
            <atom:updated>2026-09-23T01:35:36.156Z</atom:updated>
            <content:encoded><![CDATA[<h3>The formula</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*JzGAlVemJWyVo8y_kyGd9A.png" /></figure><p>In three steps:</p><ol><li>Take each score and raise e to that power.</li><li>Add up all those results.</li><li>Divide each one by the total.</li></ol><p>That’s it. The output is a set of numbers that are all positive and add up to exactly 1 — in other words, percentages.</p><h3>Example: three contestants</h3><p>Three contestants get judged. Their raw scores — in machine learning these raw scores are called <strong>logits</strong> — are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5PdEfvKcLH7mN3sR.png" /></figure><p>We want to turn those into percentages.</p><h3>The obvious way (standard normalization)</h3><p>Add them up: 5 + 3 + 2 = 10. Divide each by 10.<br>Simple. Intuitive. And as we’ll see in a minute, quietly broken.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SGBQnBKvmCnQjlQi.png" /></figure><h3>The softmax way — step by step</h3><p><strong>Step 1: Exponentiate each score.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SBb8gh-IThVQYxKS.png" /></figure><p>(If you want to follow along: e is about 2.71828. So e⁵ means 2.71828 multiplied by itself 5 times.)</p><p><strong>Step 2: Add them up.</strong></p><pre>148.4131591 + 20.0855369 + 7.3890561 = 175.8877521</pre><p><strong>Step 3: Divide each one by the total.</strong></p><pre>A:  148.4131591 / 175.8877521 = 0.843795  →  84.38%<br>B:   20.0855369 / 175.8877521 = 0.114195  →  11.42%<br>C:    7.3890561 / 175.8877521 = 0.042010  →   4.20%</pre><p>Sanity check — they should add to 1:</p><pre>0.843795 + 0.114195 + 0.042010 = 1.000000</pre><h3>Side by side</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z6DRJ5saM3TxWyYy.png" /></figure><p>The first thing you notice: <strong>softmax is opinionated.</strong></p><p>Plain normalization is a democratic accountant — it splits the pie strictly by share. Softmax is a rich-get-richer amplifier. A modest lead of 2 points became a landslide. That’s often exactly what you want from a model that has to commit to an answer.</p><p>But that amplification is the <em>shallow</em> difference. Here’s the one that actually matters.</p><h3>The harsh judge problem</h3><p>A grumpy judge shows up and docks <strong>1 point from everybody</strong>. New scores: <strong>4, 2, 1</strong>.</p><p>Stop and think about what changed in reality. Nothing. Same contestants. Same ranking. Same gaps between them. One judge was in a bad mood, uniformly.</p><p><strong>The percentages should not move.</strong></p><h3>What plain normalization does</h3><p>New total: 4 + 2 + 1 = 7.</p><pre>A: 4/7 = 57.14%<br>B: 2/7 = 28.57%<br>C: 1/7 = 14.29%</pre><p>A jumped from 50% to <strong>57.14%</strong>. Because a judge was grumpy. Nothing real changed and the answer moved by 7 percentage points. <strong>That’s broken.</strong></p><h3>What softmax does</h3><p><strong>Step 1:</strong> <br>e⁴ = 54.5981500, e² = 7.3890561, e¹ = 2.7182818</p><p><strong>Step 2:</strong> total = 64.7054980</p><p><strong>Step 3:</strong></p><pre>A: 54.5981500 / 64.7054980 = 0.843795  →  84.38%<br>B:  7.3890561 / 64.7054980 = 0.114195  →  11.42%<br>C:  2.7182818 / 64.7054980 = 0.042010  →   4.20%</pre><p><strong>Identical to before. To six decimal places.</strong> Not approximately — exactly.</p><h3>Why this happens</h3><p>Because of one schoolbook rule about exponents:</p><pre>e^(z+c) = e^z.e^c</pre><p>Adding a constant c to every score <strong>multiplies every exponentiated value by the same factor</strong> e^c. And a common factor on the top and bottom of a fraction cancels out. The shift vanishes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fe0FjEUXapft5bz7D8Mv-w.png" /></figure><p>In our case, subtracting 1 from everything multiplied every e^score by e⁻¹ ≈ 0.3679. Top and bottom both shrank by the same 36.79%, so the ratio didn’t budge.</p><h3>And here’s the kicker</h3><p><strong>No other function does this.</strong> Not squaring. Not absolute values. Not “shift everything up until it’s positive, then divide.”</p><p>If you write down the requirement — <em>“adding the same number to every score must not change the output”</em> — and solve it mathematically, the exponential function is the <strong>unique</strong> answer. It falls out as the only possibility.</p><h3>Why you should care</h3><p>The scores coming out of a neural network have <strong>no fixed baseline.</strong> Nothing in the training process pins down where “zero” is. The whole layer can drift up or down by some constant and it means absolutely nothing about the prediction.</p><p>Softmax is immune to that drift by looking at algebric equation above. Plain normalization would have your model’s confidence wobbling around based on a meaningless number. So the e^x isn’t cosmetic. It’s the thing that makes the output trustworthy.</p><h3>The flip side: softmax cares how loudly you shout</h3><p>Plain normalization only sees <strong>ratios</strong>. Softmax sees <strong>gaps after an exponential</strong>, so stretching the scores changes the output.</p><p><strong>Plain normalization</strong> (unchanged if you double)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5lLFB9D1AlJnHFmsqwYUw.png" /></figure><p>Now let’s go the other direction. Keep the original scores <strong>5, 3, 2</strong> and <strong>double</strong> them: <strong>10, 6, 4</strong>.</p><p><strong>Softmax</strong> (changes if you double)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5fZRPwXSiD84Lr_fwvXUg.png" /></figure><p>The 2 does <strong>not</strong> factor out of the sum. You are no longer cancelling a common multiplier; you are squaring each term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJf1RPbpN7xFMpNKvN-VxA.png" /></figure><p><strong>calculation for 10,6,4</strong></p><pre>e^10 = 22026.4658<br>e^6  =   403.4288<br>e^4  =    54.5982<br>total = 22484.4927<br><br>A: 22026.4658 / 22484.4927  →  97.96%<br>B:   403.4288 / 22484.4927  →   1.79%<br>C:    54.5982 / 22484.4927  →   0.24%</pre><p>A went from 84% to <strong>98%</strong>. Same scores, doubled.So the two functions are <strong>exactly inverted</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ex5_cJFoN65thVaS.png" /></figure><p>Softmax throws away the one thing that’s meaningless (the baseline) and pays attention to the one thing that carries information (the spread).</p><h3>Temperature in LLM: That sensitivity is a feature</h3><p>While querying the LLM you pass that same knob as a parameter: temperature. The model still emits one logit vector Z for the next token. The API divides by T and softmaxes before it samples. temperature=0.2 is the ice-cold row in the table; temperature=2 is the hedge; you never changed the scores, only how sharp they become.</p><p>Softmax’s reaction to scaling isn’t a bug — it’s a <strong>volume knob</strong>. The standard way to write it:</p><pre>softmax(Z/T)</pre><p>T is called the <strong>temperature</strong>. Dividing the scores by T before exponentiating. Replace a temperature T&gt;0 in the exponent and you get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYCJOLmrhtx0eaHkkUvKtA.png" /></figure><p>Let’s turn the knob on our original <strong>5, 3, 2</strong>:</p><p>Let me show the T = 2 row worked out, since it’s the least obvious:</p><pre>Scores divided by 2:  2.5, 1.5, 1.0<br>e^2.5 = 12.1824940<br>e^1.5 =  4.4816891<br>e^1.0 =  2.7182818<br>total = 19.3824649<br><br>A: 12.1824940 / 19.3824649 = 0.628532  →  62.85%<br>B:  4.4816891 / 19.3824649 = 0.231224  →  23.12%<br>C:  2.7182818 / 19.3824649 = 0.140244  →  14.02%</pre><p>Sum: 0.628532 + 0.231224 + 0.140244 = 1.000000 ✓</p><p><strong>This is the same temperature setting you’ve adjusted in an LLM API.</strong> Crank it up and the model divides its scores down, flattening the distribution, so unlikely words get a real chance — output feels creative or unhinged. Turn it down and the distribution sharpens toward the single most likely token — output feels safe and repetitive. Same model, same scores, different personality, entirely because softmax is scale-sensitive.</p><p>Here is example of temperature with same dataset but results different personalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6c3lYFHNWwB-Gxkg.png" /></figure><h3>Self Attention calculation to find the related words</h3><p>If you’ve read the attention formula, you’ve seen a mysterious division:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZ1MYbG0tWs6xRqj_9zyrA.png" /></figure><p>That √d_k is <strong>exactly this volume knob.</strong> Raw attention scores come out too loud, and a too-loud softmax becomes a dictator: one option sits at 99.99% and everything else is effectively zero. When that happens there’s almost no useful feedback signal left for the network to learn from — training stalls. The division is a volume limiter, keeping softmax in the range where it still responds to changes.</p><p>If softmax really were “just normalization,” that √d_k would do nothing at all. It would cancel out. The fact that it’s load-bearing is proof the e^x matters.</p><h3>Softmax can never say “none of the above”</h3><p>Every softmax output is <strong>strictly greater than zero.</strong> Always. Because e^x is never zero, no matter how negative x gets.</p><p>A probability can be one in a trillion. It can never be <em>actually</em> zero.</p><p>Usually harmless. Occasionally it causes something genuinely weird. Inside a Transformer, an attention head that wants to say <em>“nothing in this sentence is relevant to me right now”</em> <strong>has no way to express that.</strong> It is forced to hand out 100% of its attention somewhere.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e144f82c76e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReLU]]></title>
            <link>https://medium.com/@analog76/relu-9b0720f14dd9?source=rss-d7923640d91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b0720f14dd9</guid>
            <dc:creator><![CDATA[Anandha L Ranganathan]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 02:28:02 GMT</pubDate>
            <atom:updated>2026-09-22T03:05:54.922Z</atom:updated>
            <content:encoded><![CDATA[<pre>ReLU(x)=max(0,x)</pre><p>That’s the whole function. If the number is positive, keep it. If it’s negative, replace it with zero. Done.</p><p>ReLU is an activation function applied in Neurons inside the NeuralNet. In neuron, you first form the pre-activation</p><p>In a neuron you first form the pre-activation</p><pre> Z = W.X +b  </pre><p>and then you apply ReLU .</p><p>The name stands for <strong>Re</strong>ctified <strong>L</strong>inear <strong>U</strong>nit — three words that each earn their place, which I’ll come back to at the end.</p><p>Most people’s reaction on first seeing this is some version of <em>“that can’t be it.”</em> It looks like it does almost nothing. No curves, no e^x, no division. You could implement it in your head.</p><p>And yet it’s the reason depth became trainable at all. Before ReLU, networks deeper than a handful of layers were basically untrainable. After it, they weren’t. It wasn’t the only thing that had to go right — GPUs, more data, dropout, better initialization, and later residual connections all mattered — but it was the one that removed the wall.</p><p>Here’s the claim I want to defend with arithmetic:</p><p><strong>Remove ReLU from a 50-layer network and you don’t get a slightly worse 50-layer network. You get a 1-layer network.</strong> Not metaphorically — algebraically, provably, the same function.</p><p>Let’s show that.</p><h3>First, a worked example</h3><p>Feed ReLU a list of six numbers. In a real network these input would be the outputs of a layer, before the activation is applied. They’re called <strong>pre-activations</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rIzs-Ns__EA_BcuQ.png" /></figure><p>Notice two things.</p><p><strong>The positive numbers are untouched.</strong> Not squashed, not scaled, not compressed. 7.2 comes out as 7.2. This matters enormously and we’ll come back to it.</p><p><strong>Half the outputs are now exactly zero.</strong> Three of six. In a real network with random weights it’s roughly half the neurons, on every input. Your layer’s output just became <strong>sparse</strong> — mostly zeros.</p><h3>The analogy: a one-way valve</h3><p>ReLU is a <strong>diode</strong>. Or if you prefer plumbing, a one-way valve.</p><p>Push water forward through a one-way valve and it passes through at full pressure — the valve doesn’t restrict it at all. Try to push water backward and it slams shut. Nothing gets through. Not “a reduced amount.” Nothing.</p><p>That’s ReLU exactly. Positive signal passes through <strong>at full strength, undistorted</strong>. Negative signal is blocked <strong>completely</strong>.</p><p>Hold onto the “at full strength” part. The functions ReLU replaced — sigmoid and tanh — were more like a narrow nozzle: they let signal through but squashed it into a small range no matter how hard you pushed. That squashing turned out to be fatal, for reasons we’ll get to.</p><h3>Why ReLU exists at all: layers collapse without it</h3><p>This is the part most tutorials skip, and it’s the only part that really explains ReLU.</p><p>A neural network layer does two things: multiply by some weights, add a bias. In one dimension, that’s just a straight line:</p><p>output = w · input + b.</p><p>Let’s stack two of them and see what happens.</p><ul><li><strong>Layer 1:</strong> h = 3x + 1</li><li><strong>Layer 2:</strong> y = 2h − 5</li></ul><p>Feed in x = 2:</p><pre>Layer 1:  h = 3(2) + 1 = 7<br>Layer 2:  y = 2(7) − 5 = 9</pre><p>Output: <strong>9</strong>.</p><p>Now let’s do the algebra instead of the arithmetic. Substitute layer 1 into layer 2: call this the singleLine formulae.</p><pre>y = 2(3x + 1) − 5<br>  = 6x + 2 − 5<br>  = 6x − 3</pre><p>y = 6x − 3<strong>.</strong> One line. One layer. Check it: 6(2) − 3 = 9. Same answer.</p><p>Let’s verify across several inputs: Here the singleLine and twoLayerOutput values are same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AnnLzmgrz0jdCYtY.png" /></figure><p><strong>Identical, every time.</strong> Your two-layer network was never a two-layer network. It was 6x − 3 wearing a costume.</p><p>And this doesn’t stop at two. Stack a hundred layers and you can collapse them the same way, one substitution at a time, until you’re left with a <strong>single </strong>y = wx + b. All those millions of parameters buy you exactly two numbers’ worth of expressive power.</p><blockquote><strong><em>The real version.</em></strong><em> With matrices instead of single numbers it’s the same story: two layers </em><em>W₂(W₁x + b₁) + b₂ collapse to one layer with </em><em>W = W₂W₁ and </em><em>b = W₂b₁ + b₂. I ran a 2×2 example and got the collapsed weights </em><em>[[2, 11], [−4, 11]] and bias </em><em>[−7, −3] — which reproduce the two-layer output exactly. Nothing about the collapse depends on the dimensions.</em></blockquote><h3>The 50-layer version, actually run</h3><p>I promised 50 layers, so here it is. I built a network with 8 inputs, 49 hidden layers of width 64, and 3 outputs — <strong>200,451 parameters</strong> — with no activation functions at all. Then I collapsed all 50 weight matrices into a single W and b by repeated substitution, which leaves <strong>27 parameters</strong> (a 3×8 matrix plus a 3-vector).</p><p>Running 2,000 random inputs through both:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DTheGyu_cYp2KNNo.png" /></figure><p>The disagreement is floating-point rounding noise accumulated over fifty matrix multiplications. The two functions are the same function.</p><p><strong>200,451 parameters bought exactly 27 parameters’ worth of expressive power.</strong> The other 200,424 were decoration.</p><p>Now insert ReLU between every pair of layers and change nothing else. The same network diverges from that collapsed line by up to <strong>6.62</strong> on the same inputs — the same size as the outputs themselves. On one sample input the linear version gives [−0.882, 3.053, 0.384] and the ReLU version gives [−0.070, −0.016, −0.134]. Not a small correction. A different function.</p><h3>Now put ReLU in the middle</h3><p>Same two layers. One change: apply ReLU to layer 1’s output before passing it on.</p><ul><li><strong>Layer 1:</strong> h = ReLU(3x + 1)</li><li><strong>Layer 2:</strong> y = 2h − 5</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8-w8I0qiSF7srYrk.png" /></figure><p>Look at the bottom two rows. For positive inputs the network still behaves like 6x − 3 — ReLU wasn’t blocking anything, so nothing changed. But once 3x + 1 goes negative, ReLU clamps it to zero and the output <strong>flatlines at −5</strong> instead of continuing down to −9, −21, and beyond.</p><p>You can find the exact turning point. 3x + 1 = 0 when x = −1/3. So the function is:</p><ul><li>y = 6x − 3 for x &gt; −1/3</li><li>y = −5 for x ≤ −1/3</li></ul><p><strong>That’s a bend.</strong> A kink — a point where the function is continuous but its slope jumps, from 0 on the left to 6 on the right. And a bend is something no single straight line can ever produce, no matter how you choose w and b. The collapse is broken. Your two-layer network is finally, genuinely, two layers.</p><p><strong>That’s what ReLU is for.</strong> Not to “add nonlinearity” as an abstract virtue — to stop your layers from algebraically eating each other.</p><p>A warning worth absorbing: forgetting an activation function is <strong>silent</strong>. Nothing crashes, the loss goes down, the model trains. You’ve just shipped linear regression with two hundred thousand extra parameters.</p><h3>ReLU units are hinges</h3><p>One ReLU gives you one bend. Combine a few and you can build shapes.</p><p>Take three ReLUs, offset from each other, and add them with these weights:</p><p>Let’s evaluate it by hand at x = 1.5:</p><pre>ReLU(1.5)     = 1.5      → contributes  +1.5<br>ReLU(1.5 − 1) = 0.5      → contributes  −1.0   (weight −2)<br>ReLU(1.5 − 2) = 0        → contributes   0<br>                            total =  0.5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TijATpvSq0ioMsct.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ir8chi-OdX4OC1NE.png" /></figure><p>That’s a <strong>triangle</strong> — up from 0 to a peak of 1 at x = 1, back down to 0 at x = 2, flat everywhere else. Built out of three copies of the world’s dumbest function.</p><p>Look at the last row before you move on. At x = 10 the three terms are 10, −18 and 8. Three large numbers that sum to exactly zero. The triangle isn’t flat out there because the units have finished and gone quiet — <strong>every one of them is still running at full volume, and they cancel.</strong></p><p>That’s why the middle weight is −2 and not −1. Each ReLU is an instruction: <em>from my threshold onward, change the slope by my weight.</em> The slope at any point is the running total of every instruction switched on so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cIdtnEFpI0zLSatD.png" /></figure><p>If you find that mechanism familiar, it’s the same one as progressive income tax. With a 0% band to 10,000, 10% to 30,000, and 25% above that, your total tax is exactly 0.10·ReLU(I − 10000) + 0.15·ReLU(I − 30000) — and the weights are 0.10 and 0.15, the <em>increments</em> in the marginal rate, not the rates themselves. At an income of 40,000 both the formula and the bracket-by-bracket calculation give 4,500.</p><p>This is the whole game. Every ReLU contributes one hinge. Stack enough hinges and you can approximate any shape you like, the way a paper fan approximates a curve with straight folds. The network’s job during training is learning <em>where to put the hinges</em> — the thresholds are the biases and the slope changes are the weights.</p><p>It also tells you exactly what kind of function a ReLU network is: <strong>piecewise linear.</strong> Straight pieces joined at bends. Never a true curve — just enough straight segments, small enough, to be indistinguishable from one at the scale you care about. (Strictly the pieces are <em>affine</em>, not linear: 6x − 3 doesn’t pass through the origin. “Piecewise linear” is the universal term anyway.)</p><p>One consequence worth knowing: a ReLU network has zero second derivative almost everywhere. If you ever need genuine curvature — physics-informed networks, for instance — this is a real obstruction, not a technicality.</p><h3>Why ReLU beat sigmoid: the gradient survives</h3><p>Before roughly 2011, the standard activations were <strong>sigmoid</strong> (an S-curve squashing everything into 0 to 1) and <strong>tanh</strong> (the same shape, squashing into −1 to 1). Both were smooth, differentiable everywhere, and looked more biologically plausible. Both also made deep networks impossible to train.</p><p>Here’s why, and you need one idea first.</p><p>Networks learn by <strong>backpropagation</strong>: an error signal travels backward from the output through every layer, and each layer multiplies it by its own local slope. Ten layers means the signal gets multiplied by ten slopes in a row.</p><p>Now — <strong>sigmoid’s slope never exceeds 0.25.</strong> That’s its maximum, right at the center. Everywhere else it’s smaller, and out in the tails it’s nearly zero.</p><p>So multiply 0.25 by itself repeatedly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r05sj1zSiKzfwIRr.png" /></figure><p>And remember 0.25 is the <strong>best case</strong>. Realistically a sigmoid neuron sits somewhere in its tails: sigmoid(6) has a slope of about <strong>0.0025</strong>. Multiply <em>that</em> ten times and you’re at 10⁻²⁶.</p><h3>The derivative, and the awkward question at zero</h3><p>ReLU’s slope is trivial:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wjmyRhrSVqM-5rfX.png" /></figure><p>Note what’s missing: x = 0. The function has a sharp corner there and <strong>the derivative genuinely does not exist</strong> — the slope is 0 approaching from the left and 1 approaching from the right, and there’s no third answer that reconciles them.</p><p>And finally</p><p><strong>Re</strong>ctified <strong>L</strong>inear <strong>U</strong>nit.</p><p>Three words, and each one is doing real work:</p><p><strong>Rectified.</strong> Borrowed straight from electrical engineering. A <em>rectifier</em> is a circuit that converts alternating current to direct current by blocking the negative half of the waveform and letting the positive half through. That is exactly max(0, x). The archetypal rectifier is a <strong>diode</strong>.</p><p><strong>Linear.</strong> The positive half is a genuine straight line — y = x, slope exactly 1. No squashing, no saturation, no curve. This is the word that distinguishes ReLU from everything it replaced: sigmoid and tanh are nonlinear <em>everywhere</em>, which is what made their slopes shrink and gradients die. ReLU is linear on the part it lets through.</p><p><strong>Unit.</strong> Old neural-network vocabulary for a single neuron — “hidden units,” “output units.” Strictly, the <em>unit</em> is the neuron and max(0, x) is its activation function, so calling the function “ReLU” .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b0720f14dd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chunking is the hidden design decision in RAG]]></title>
            <link>https://medium.com/@analog76/chunking-is-the-hidden-design-decision-in-rag-62ec22cbf28d?source=rss-d7923640d91c------2</link>
            <guid isPermaLink="false">https://medium.com/p/62ec22cbf28d</guid>
            <category><![CDATA[document-embedding]]></category>
            <category><![CDATA[chunking-strategies]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[chunking]]></category>
            <dc:creator><![CDATA[Anandha L Ranganathan]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 17:48:32 GMT</pubDate>
            <atom:updated>2026-09-22T02:58:50.345Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to index a long book without overwhelming your model — or losing the passages that matter.</em></p><p>Open Benjamin Franklin’s <em>Autobiography</em> from Project Gutenberg. It is far too long to place wholesale into a model prompt — and even if the context window allowed it, doing so would be inefficient. If someone asks why Franklin thought Britain should retain Canada, the useful answer may be contained in only two or three passages. The rest of the book would consume context and obscure the evidence.</p><p>This is the problem retrieval-augmented generation, or RAG, is designed to solve. Rather than sending an entire source document to a language model, a RAG system finds the passages most relevant to a question and sends only those passages as context.</p><p>The book stays in storage. Retrieval selects the evidence.</p><h3>The RAG flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfgKHEqvtJnDNGxYrq6_aQ.png" /></figure><h3>From text to vectors</h3><p>RAG begins by turning sections of text into embeddings: numerical representations of meaning. Texts with similar meaning tend to be positioned near one another in a high-dimensional vector space, even when they do not use the same words.</p><p>At query time, the system embeds the user’s question, searches for the nearest stored vectors, and returns the corresponding source passages. The vector helps find the text; the text is what the model actually reads.</p><p>A book cannot be represented by one embedding. A single vector for all of Franklin’s life would average together Boston childhood, printing, experiments with electricity, <em>Poor Richard</em>, and his parliamentary testimony. It would be a weak representation of every subject in the book.</p><p>So the document must be split into chunks before it is embedded.</p><h3>Chunk size and overlap</h3><p>A practical default might be:</p><pre>DEFAULT_CHUNK_SIZE = 800      # characters<br>DEFAULT_CHUNK_OVERLAP = 150   # characters</pre><p>These settings are often mistaken for two independent controls. In practice, they define a single decision: how far the chunking window advances.</p><pre>stride = chunk_size − chunk_overlap<br>       = 800 − 150<br>       = 650 characters</pre><p>The stride determines how much new text each successive chunk contributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FzAuqnG7c-TYUs6H.png" /></figure><p>Chunk size is a ceiling, not a target. Most text splitters try to break at a paragraph, line, sentence, or word boundary before reaching the limit. A requested size of 800 characters may therefore yield chunks of 640, 731, or 800 characters.</p><p>Overlap is the text repeated between neighboring chunks. It is not empty space.</p><p>Without overlap, a split can leave a fragment such as:</p><pre>&quot;…but left school at the age of ten.&quot;</pre><p>That sentence may make little sense by itself. With overlap, the next chunk retains enough preceding context to remain readable and retrievable.</p><p>This becomes especially important when a source contains long sentences or tightly connected arguments. Franklin’s letter on Canada, for example, contains a sustained clause chain that may cross a chunk boundary. If the split falls mid-thought, one chunk may end before the argument is complete and the next may begin without its premise. A small overlap preserves the connection in both records.</p><p>The cost is duplication: neighboring chunks may retrieve together because they contain some of the same language. That is normal. If duplicate results crowd out useful evidence, use a diversity-aware retrieval method such as maximal marginal relevance (MMR).</p><h3>What a vector-store record contains</h3><p>Each chunk should store three things:</p><pre>id<br>document<br>embedding<br>metadata</pre><p>For example:</p><pre>id         7c2a1e90-4b11-4d3e-9f08-12a6c0e84b21<br><br>document   &quot;His boyhood in Boston was a stern beginning of the habit<br>            of hard work and rigid economy which marked the man. For<br>            a year he went to the Latin Grammar School on School<br>            Street, but left off at the age of ten to help his father<br>            in making soap and candles.&quot;<br><br>embedding  384 floats — [-0.0412, 0.0187, 0.0621, -0.0094, 0.0330, …]<br>           norm = 1.0<br><br>metadata   {<br>             book: &quot;Franklin&#39;s Autobiography&quot;,<br>             source: &quot;https://www.gutenberg.org/cache/epub/36151/pg36151-images.html&quot;,<br>             gutenberg_id: 36151,<br>             page_label: &quot;5&quot;,<br>             chunk_index: 2<br>           }</pre><p>The embedding is for search. The original document string is for reading, quoting, and citing.</p><p>Metadata matters. If the edition includes printed page labels such as [Pg 5], preserve them. A citation should point readers to the page they can actually find in the edition they are reading.</p><p>Before indexing, remove low-value material: title pages, boilerplate, licence text, repeated headers, and footnote dumps. These fragments create poor embeddings and can dilute retrieval quality.</p><h3>Why normalisation matters</h3><p>Embedding vectors are commonly L2-normalised, meaning their length is scaled to 1:</p><pre>‖v‖ = √(v₁² + v₂² + … + vₙ²)</pre><p>Once both vectors have length 1, cosine similarity and dot-product similarity become the same calculation:</p><pre>cos θ = (a · b) / (‖a‖ ‖b‖)</pre><pre>If ‖a‖ = ‖b‖ = 1:<br>cos θ = a · b</pre><p>This makes retrieval fast and meaningful: results are ranked by the alignment of their semantic direction, rather than by the raw magnitude of a vector.</p><h3>The token limit you cannot see</h3><p>Character-based chunk settings can hide a critical constraint: embedding models work in tokens, not characters.</p><p>For example, all-MiniLM-L6-v2 has a maximum sequence length of 256 tokens. If a chunk exceeds that limit, the model may silently truncate it. The full text can still appear in the database, but the embedding represents only its opening portion. The unembedded tail will be difficult—or impossible—to retrieve.</p><p>A conservative rule of thumb is:</p><pre>maximum safe chunk size in characters<br>≈ model token limit × 4</pre><p>For a 256-token model, that suggests a ceiling of roughly 1,000 characters. Use four characters per token as a safety margin; dialogue, abbreviations, punctuation, and formatted text can tokenize more densely than ordinary prose.</p><p>Newer embedding models may support far larger input windows, but chunking still matters. A larger window does not eliminate the retrieval problem: overly broad chunks can combine several unrelated topics into one vague vector.</p><h3>Code snippets</h3><p><strong>1. Chunk</strong></p><pre>from rag_qa.gutenberg import load_pages<br>from rag_qa.chunk import chunk_documents<br>from rag_qa.config import load_settings<br><br>s = load_settings()<br>print(s.summary())<br># {<br>#   &#39;chunk_size_chars&#39;: 800,<br>#   &#39;chunk_overlap_chars&#39;: 150,<br>#   &#39;stride_chars&#39;: 650,            # size − overlap; this sets chunk count<br>#   &#39;model&#39;: &#39;all-MiniLM-L6-v2&#39;,<br>#   &#39;model_max_tokens&#39;: 256,        # hard cap; overflow is silent<br>#   &#39;embedding_dims&#39;: 384,<br>#   &#39;max_safe_chunk_chars&#39;: 1024,   # 256 × 4<br>#   &#39;book&#39;: &quot;Franklin&#39;s Autobiography&quot;,<br>#   &#39;gutenberg_id&#39;: 36151,<br># }<br>pages = load_pages()<br>chunks = chunk_documents(pages, s.chunk_size, s.chunk_overlap)<br>print(len(pages), len(chunks), s.stride)</pre><p><strong>2. Token limit</strong></p><pre>from sentence_transformers import SentenceTransformer<br>from rag_qa.tokens import check_chunk<br><br>m = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br>print(m.max_seq_length)                    # 256<br>for c in chunks:<br>    r = check_chunk(c)<br>    if r.truncated:<br>        print(&quot;silent truncate:&quot;, r.n_chars, &quot;chars /&quot;, r.n_tokens, &quot;tokens&quot;)</pre><p>Safe ceiling: max_chunk_size_chars ≈ 256 × 4 ≈ 1,000.</p><p>That script prints the model’s max length, then <strong>only the chunks that would be silently cut</strong>.</p><p>Typical run:</p><pre>256</pre><p>If every chunk already fits (tokens ≤ 256), that is the <strong>whole</strong> output. Nothing else.</p><p>If some chunks are too long:</p><pre>256<br>silent truncate: 1820 chars / 412 tokens<br>silent truncate: 960 chars / 301 tokens</pre><p>Meaning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uG9H8FeXpWhEDG6F.png" /></figure><p><strong>2. What is Stored</strong></p><pre>from rag_qa.store import ingest, open_store<br><br>store = open_store()<br>ingest(chunks, store)<br>row = store.get(limit=1)<br>print(row[&quot;ids&quot;][0])<br>print(row[&quot;documents&quot;][0][:200])<br>print(len(row[&quot;embeddings&quot;][0]), row[&quot;metadatas&quot;][0])<br># 384 floats, norm 1.0, metadata.page_label == printed [Pg N]</pre><p>That snippet is peeking at <strong>one stored chunk</strong> after ingest. The prints are three lines; they look like this:</p><pre>doc-12-p3-c0<br>She left school at the age of ten. The next sentence continues on the same page…<br>384 {&#39;page_label&#39;: &#39;3&#39;, &#39;source&#39;: &#39;notes.pdf&#39;}</pre><p><strong>4. How to retrieve</strong></p><pre>from rag_qa.retrieve import search, search_mmr<br><br>q = &quot;why did Franklin want Britain to keep Canada&quot;<br><br>for hit in search(q, k=5):<br>    print(f&quot;{hit[&#39;score&#39;]:.3f}  p.{hit[&#39;metadata&#39;][&#39;page_label&#39;]}  {hit[&#39;document&#39;][:120]}&quot;)<br># overlap makes near-duplicate hits; MMR trades a little score for diversity<br><br>for hit in search_mmr(q, k=5):<br>    print(hit[&quot;metadata&quot;][&quot;page_label&quot;], hit[&quot;score&quot;])</pre><p>Here is the output</p><pre>0.812  p.7  I have long been of opinion that the foundations of the future grandeur and stability of the British empire lie in America<br>0.781  p.7  they are, nevertheless, broad and strong enough to support the greatest political structure that human wisdom ever yet<br>0.744  p.7  I am, therefore, by no means for restoring Canada. If we keep it all the country from the St. Lawrence to the Mississippi<br>0.691  p.8  I left England about the end of August, 1762, in company with ten sail of merchant ships<br>0.640  p.6  In this Autobiography Franklin tells of his own life to the year 1757, when he went to England</pre><p>First three hits are often the <strong>same page</strong> — that is overlap. Adjacent chunks of one clause all match.</p><h3>Addendum</h3><h3>A. Same passage, overlap off and on</h3><p>Passage from the introduction (~190 characters), chunk_size=60. Real splitter output.</p><blockquote><em>His boyhood in Boston was a stern beginning of the habit of hard work and rigid economy which marked the man. For a year he went to the Latin Grammar School on School Street, but left off at the age of ten.</em></blockquote><p><strong>Without overlap (0)</strong></p><pre>[0] 59  His boyhood in Boston was a stern beginning of the habit of<br>[1] 55  hard work and rigid economy which marked the man. For a<br>[2] 58  year he went to the Latin Grammar School on School Street,<br>[3] 31  but left off at the age of ten.</pre><p>[0] dies on the habit of. [1] starts at hard work with no link back. Chunk 3 still has a subject — lucky: that cut landed near a clause.</p><p>Without overlap, The splitter still breaks at chunk_size. If that break lands mid-sentence, chunk N ends on a fragment and chunk N+1 starts mid-clause. Each vector then represents half an idea. A query that needs the whole sentence matches both halves poorly.</p><p><strong>With overlap (15)</strong></p><pre>[0] 59  His boyhood in Boston was a stern beginning of the habit of<br>[1] 57  ⟦the habit of⟧ hard work and rigid economy which marked the<br>[2] 55  ⟦marked the⟧ man. For a year he went to the Latin Grammar<br>[3] 58  ⟦Latin Grammar⟧ School on School Street, but left off at the<br>[4] 22  ⟦off at the⟧ age of ten.</pre><pre>⟦…⟧ = text repeated from the previous chunk</pre><p>On the Boston line: without overlap, chunk 0 dies on the “habit of” and chunk 1 starts at “hard work”. “Habit of hard work” is not in any single chunk.</p><p>No chunk is 60 characters. Size is a ceiling.</p><p>What you gain by skipping overlap? a smaller index, no duplicate hits. What you lose: anything the splitter happened to cut in half. Overlap is insurance for those seams, not extra context for fun.</p><h3>B. Libraries for building RAG, and where vectors go</h3><p>RAG is four jobs: load text, cut it, embed it, store and search vectors. No single library is “RAG.”</p><p><strong>Cutting and orchestration</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBx4d6fg4Jz6y2RdfYaOiQ.png" /></figure><p>Embedding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfmGfnGlK5a1pQQ1FdPFFA.png" /></figure><p>Vector Database</p><p>Subset of the vector database that are widely used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XFrA5yvw9SK5ndByTqiSA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62ec22cbf28d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>