<?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 Tushar Aggarwal on Medium]]></title>
        <description><![CDATA[Stories by Tushar Aggarwal on Medium]]></description>
        <link>https://medium.com/@tushar.aggarwal53?source=rss-95e55ae43c18------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h1cgh1_P2wxDYPo4nuVewQ.jpeg</url>
            <title>Stories by Tushar Aggarwal on Medium</title>
            <link>https://medium.com/@tushar.aggarwal53?source=rss-95e55ae43c18------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:47:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tushar.aggarwal53/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[How Hyperparameters Scale, and When the Rules Break]]></title>
            <link>https://medium.com/@tushar.aggarwal53/how-hyperparameters-scale-and-when-the-rules-break-ee8042d4226e?source=rss-95e55ae43c18------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee8042d4226e</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Tushar Aggarwal]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 09:02:29 GMT</pubDate>
            <atom:updated>2026-11-03T13:35:22.469Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 of my CS 312 series: how the best learning rate, weight decay, and batch size change as you scale up data, batch, and width, and what µP does and doesn’t buy you.</em></p><p>In <a href="https://medium.com/@tushar.aggarwal53/what-a-35m-parameter-language-model-taught-me-about-doing-empirical-ml-research-216e158c7b10">Part 1</a>, I covered the basics of empirical ML on a small language model: which hyperparameters matter, and how large run-to-run noise is. Assignment 2 of Stanford’s CS 312: Deep Learning Alchemy asks the next question: <strong>when you scale up, how should the hyperparameters change?</strong></p><p>That question matters because nobody can afford to tune a large run directly. You tune small and hope the settings carry over. Assignment 2 tests that hope in four ways:</p><ol><li>Can a learning rate tuned on less data guide a run on more data?</li><li>How should learning rate and weight decay change together?</li><li>What should change when you change the batch size?</li><li>Can µP let you tune once and reuse the same learning rate at every width?</li></ol><h3>The setup</h3><p>The model is the same 35M-parameter <strong>d8</strong> from Part 1, trained with AdamW. Its defaults are a peak learning rate (LR, written η) of 3e-3, weight decay (WD, written λ) of 0.1, and a batch of 64 sequences. I write D for the number of training tokens.</p><p>What’s new is that the scale varies: training budgets from 153.6M to 4.9B tokens, batch sizes from 8 to 256, and widths from 128 to 1,024.</p><h3>1. Don’t extrapolate the learning rate from very small budgets</h3><p>At 153.6M, 307.2M, and 614.4M tokens, I fit a curve of loss against LR to find the best LR at each budget. The optimum rose steadily (0.0024 → 0.0030 → 0.0032), which a power law summarizes as η* ∝ D⁰²¹³. I wrote down that rule’s predictions for 1.2B, 1.8B, and 2.5B tokens before looking at those runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3aGcRn0Yk3-z-kjqMOdb5w.png" /><figcaption><em>Fitted optimal LR at each training budget. Open circles: the three small budgets. Filled circles: the three larger budgets. The two lines are power laws fit to all six budgets and to only the three larger ones, both extended to 4.9B tokens.</em></figcaption></figure><p>The trend reversed:</p><ul><li><strong>Predicted:</strong> 0.0038, 0.0041, 0.0044.</li><li><strong>Actual:</strong> 0.0039, 0.0034, 0.0029.</li></ul><p>The prediction was accurate one step out (about 2% off at 1.2B), then wrong in direction. At 2.5B it was about 1.5× too high.</p><p>I then fit two power laws, one to all six budgets and one to only the three larger ones, and used each to predict the best LR at 4.9B tokens. The best LR there turned out to be about 0.0019:</p><ul><li><strong>All six budgets</strong> predicted 0.0037, about 2× too high. The small budgets’ upward trend pulled the fit the wrong way.</li><li><strong>Only the three larger budgets</strong> predicted 0.0022, close to the actual optimum.</li></ul><p>In loss, the six-budget prediction was about 0.003 worse than the best sampled LR, and the three-budget prediction about 0.001 worse. With single runs, those gaps are near the noise floor, so the clearer evidence is how far each predicted LR missed.</p><blockquote><strong>Takeaway:</strong> More data points don’t make a scaling fit more trustworthy if the trend changes. Fit on the budgets closest to your target, and extrapolate as little as you can. (Most optima here come from fits through only three LRs, so treat the exact values as approximate.)</blockquote><h3>What about a norm-constrained optimizer?</h3><p>Can a different optimizer make the LR scale more predictably? Hyperball is a small change to Adam. It uses Adam’s update direction, sizes each step relative to the weight matrix’s own size, and then rescales the matrix back to its starting norm. Because weight norms can’t grow, it uses <strong>no weight decay</strong> at all. Embeddings, normalization gains, and biases still use plain Adam.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YzMgSl4xMEnWuZsm-6vjA.png" /><figcaption><em>Hyperball’s fitted optimal LR at three training budgets, with the power law extended to 1.2B tokens (star).</em></figcaption></figure><ul><li><strong>Its best LR moved the opposite way from AdamW’s.</strong> Over the same three budgets it fell smoothly (0.0137 → 0.0129 → 0.0121, ∝ D^−0.089).</li><li><strong>The prediction held one step out.</strong> The fit predicted 0.0114 at 1.2B tokens. Of the three LRs I ran there, the predicted one gave the lowest loss: 2.8290, against 2.8310 at 0.008 and 2.8358 at 0.015.</li><li><strong>Its loss matched AdamW’s.</strong> AdamW’s best at 1.2B tokens, with weight decay tuned, was about 2.836, so the two are within noise.</li></ul><p>A 2× step can’t separate the optimizers, though: AdamW’s rule was also only 2% off there. The real test is where AdamW’s rule failed. So I extended the same three-budget Hyperball rule to 4.9B tokens, 8× past its largest fitted budget (not shown in the figure above):</p><ul><li><strong>AdamW’s rule, fit on the same three budgets,</strong> predicted about 0.005 at 4.9B, roughly 2.6× the actual optimum of about 0.0019.</li><li><strong>Hyperball’s rule predicted 0.0101.</strong> A single run at that LR reached 2.7099, the lowest loss of any run at 4.9B tokens. AdamW’s best sampled LR there gave 2.7157.</li></ul><p>From the same three budgets, AdamW’s trend reversed and its extrapolation missed badly, while Hyperball’s trend stayed smooth and still pointed to a good LR 8× out.</p><h3>2. Weight decay is the knob that scales cleanly</h3><p>Part 1 showed that, at one fixed budget, the best weight decay scales as 1/LR, so η·λ is what matters. The new question is how that optimum moves as the budget grows. I tuned LR and WD together on a 3 × 3 grid at four budgets, fitting a smooth surface to find the best pair at each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhgswwwMT4hFHoUMLp83aQ.png" /><figcaption><em>Fitted loss over LR × weight decay at four training budgets. Stars mark the fitted optimum, and the dashed line keeps η·λ at the optimum’s value. The star moves toward lower weight decay as the budget grows.</em></figcaption></figure><p>At every budget the low-loss region runs along the dashed line, as in Part 1. But the optimum itself shifts, and the three quantities move very differently:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FISfpDnxAG_A1hWaV133A.png" /><figcaption><em>Fitted optima vs. training budget. Left: learning rate. Middle: weight decay. Right: their product η·λ.</em></figcaption></figure><ul><li><strong>The best learning rate alone is noisy.</strong> It went 0.0019, 0.0016, 0.0025, 0.0027, and a power law fit it poorly (R² = 0.68).</li><li><strong>The best weight decay fell smoothly</strong>, from 0.85 at 153.6M tokens to 0.16 at 1.2B. It followed a clean power law, WD* ∝ D^−0.82 (R² = 0.99).</li><li><strong>The product η·λ also fell steadily</strong> (∝ D^−0.59, R² = 0.97).</li></ul><p>So the more you train, the less weight decay you want, and the trend is regular enough to extrapolate. That also explains a second pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJ0FSyTVBtaPjbyM89t-hQ.png" /><figcaption><em>Best measured loss with weight decay fixed at 0.1 vs. tuned jointly with LR. Bottom: the gain from tuning weight decay.</em></figcaption></figure><p>Tuning weight decay gained 0.045 at 153.6M tokens but only 0.0017 at 1.2B. The default of 0.1 happens to sit close to the optimum at larger budgets (0.16 at 1.2B), so tuning has less to fix there. At small budgets, the default is far too low.</p><p>To test the product rule, I fit it on the four budgets and predicted the weight decay at 2.5B tokens with the LR fixed at 0.003. The rule gave 0.0927:</p><ul><li><strong>The predicted WD reached 2.7674.</strong> The best of WD 0.05, 0.1, and 0.2 at the same LR reached 2.7683.</li><li><strong>Reusing the best pair from 153.6M tokens</strong> (LR 0.0015, WD 1.6) without retuning reached 2.8533, which is <strong>0.086 worse</strong>.</li></ul><blockquote><strong>Takeaway:</strong> never carry a tuned weight decay from a small run to a large one. Scale it down as the data grows. Here, the best weight decay followed a cleaner power law than the best learning rate.</blockquote><h3>3. Batch size: scale up, then stop</h3><h3>What a toy model predicts</h3><p>The assignment uses a noisy quadratic model (NQM): a two-dimensional quadratic loss with one flat and one steep direction, plus noisy gradients whose variance shrinks as 1/B for batch size B. The total number of training examples is fixed at 8,192, so a bigger batch means fewer steps.</p><p>For plain SGD, the classic rule says to double the LR when you double the batch. In the NQM it held almost exactly (η* ∝ B^.99), but only up to about B = 64–128:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47uWw-tH8mQBR3RDidPdzQ.png" /><figcaption><em>Optimal LR vs. batch size for SGD on the NQM. Filled points were used for the fit; open points are larger batches tested afterward. The dotted line marks the stability limit.</em></figcaption></figure><p>The rule stops when it runs into the curvature. A step larger than 2 / (largest curvature), here 0.2, makes training diverge (will be discussed in detail in the next assignment). Past that point the LR can’t keep growing, and a bigger batch just means fewer updates. At B = 256 the rule predicted 0.157 against a tuned 0.125, giving 1.6× the tuned loss. At B = 512 it predicted 0.31, which diverged.</p><p>Adam behaves differently, because it divides each update by the gradient’s typical size:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2RWd0-g1lx5jdm_QUNRzg.png" /><figcaption><em>Fitted exponent p in η</em> ∝ B^p for Adam and RMSProp on the NQM, as gradient noise σ increases.*</figcaption></figure><p>With little gradient noise, Adam’s best LR grew almost linearly with batch size (p ≈ 0.91). When noise dominated, it grew like the <strong>square root</strong> of the batch size (p ≈ 0.50–0.55). The reason: once noise dominates, Adam’s normalization already makes the effective step grow as √B, so the LR itself only needs to supply the other √B. Since language-model gradients are usually noise-dominated, this predicts something closer to a square-root rule than a linear one.</p><h3>What the language model did</h3><p>I tuned the LR at batch sizes 8 to 64, keeping the token budget fixed at 614.4M:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZr1gKZQygxExXLdKttM6Q.png" /><figcaption><em>Language model at 614.4M tokens. Left: fitted optimal LR vs. batch size. Right: best measured loss vs. batch size.</em></figcaption></figure><ul><li><strong>The best LR roughly doubled with each doubling of batch size up to 32</strong> (0.00097 → 0.00172 → 0.00334), then flattened at 64 (0.00319). A single power law across all four batches gives η* ∝ B^.58, which looks close to a square root. But that exponent averages two different regimes. From B = 8 to 32 alone, the exponent is 0.89, close to the toy model’s low-noise value (0.91). After that, it is about zero. A square root would raise the LR by about 1.4× per doubling, and no step here did that. The flat part agrees with Part 1, where the best LR stayed at 3e-3 for batches 32 to 128.</li></ul><p>Then I compared two ways of predicting settings for batches of 128 and 256:</p><ol><li><strong>Scale the LR</strong> with batch size (∝ B^.58) and keep WD at 0.1.</li><li><strong>Keep the LR at 0.0015</strong> and scale the WD with batch size. On batches 8–64, the best WD followed WD* ∝ B^.93.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUeBNTHwAKwpf_sJ90yFMQ.png" /><figcaption><em>Top: loss vs. LR (left) and vs. weight decay (right) at the source batch sizes. Bottom: the fitted rules and their predictions at B = 128 and 256.</em></figcaption></figure><ul><li><strong>Scaling the LR overshot.</strong> Half the predicted LR did better at both B = 128 (2.9525 vs. 2.9618) and B = 256 (3.0238 vs. 3.1449).</li><li><strong>Scaling the weight decay worked better.</strong> Its predicted WD gave the lowest loss of the values tested at both sizes: 2.9351 at B = 128 and 2.9721 at B = 256.</li><li><strong>Big batches still cost loss</strong> at a fixed token budget (2.9721 at B = 256 vs. about 2.92 at B = 32), because there are 8× fewer updates.</li></ul><p>The NQM has no weight decay, so it can’t explain why scaling WD worked. One explanation comes from how AdamW’s decay works:</p><ul><li><strong>Each step shrinks the weights by a fraction η·λ.</strong> AdamW’s weight decay is scaled by the learning rate: each step multiplies the weights by (1 − η·λ) before adding the new update. An update made k steps ago has been shrunk k times since, so only (1 − η·λ)^k of it remains.</li><li><strong>Losing a fraction η·λ per step means a memory of about 1/(η·λ) steps.</strong> It’s the same logic as losing 1% per step, where it takes about 100 steps (1/0.01) for something to wear down substantially. Because η·λ is tiny, (1 − η·λ)^k is very close to e^(−η·λ·k). Writing N = 1/(η·λ), that is e^(−k/N): the fraction left depends only on how many windows of N steps have passed. After one window (k = N), an update keeps e^(−1) ≈ 37% of its weight, and after three windows only e^(−3) ≈ 5%. Adding up what remains of every past update, 1 + (1 − η·λ) + (1 − η·λ)² + …, gives exactly 1/(η·λ). So the weights carry as much as an equal-weight average of the last 1/(η·λ) updates would. That is the sense in which they are a moving average over that window.</li><li><strong>In numbers:</strong> with the peak LR of 0.0015 and WD of 0.1, η·λ = 0.00015, so the window is 1/0.00015 ≈ 6,700 steps. A run at batch 64 and 614.4M tokens is only about 9,400 steps long, so the window covers most of training.</li><li><strong>Bigger batches mean fewer steps.</strong> At a fixed token budget, doubling the batch halves the number of updates. To keep the averaging window the same share of training with the LR held at 0.0015, the window must halve too, so λ has to double: λ ∝ B.</li></ul><p>The measured exponent, 0.93, is close to that predicted 1.</p><h3>Momentum matters more at large batch</h3><p>Momentum averages recent gradients. By the same logic as weight decay’s window above, Adam’s β1 averages over roughly the last 1/(1 − β1) gradients: 10 steps for β1 = 0.9 and 100 for 0.99. SGD’s momentum µ works the same way. 0 means no momentum.</p><p>In the toy model, I retuned the LR separately for every momentum setting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPkUdD6zFCl1jAa5QEkieA.png" /><figcaption><em>Toy model (NQM): best final loss at each momentum setting, with the LR tuned for each. Left: Adam. Right: SGD. Blue: B = 16 (512 updates). Orange: B = 256 (32 updates). Log scale.</em></figcaption></figure><ul><li><strong>At a small batch, momentum barely mattered.</strong> At B = 16, the best setting improved the final loss only 1.18× for Adam and about 1.1× for SGD.</li><li><strong>At a large batch, it helped a lot.</strong> At B = 256, it improved the loss 6.8× for Adam (β1 = 0.8) and 2.5× for SGD (µ = 0.7). Plain SGD can’t raise its LR past the stability limit, so with few updates it can’t travel far. Momentum builds up speed along flat directions while staying stable at a higher LR.</li><li><strong>Too much momentum hurt once its window covered a large share of training.</strong> At B = 256 (32 updates), a 10-step window (β1 or µ = 0.9) is about 30% of training, and both did worse than no momentum. At B = 16 (512 updates), Adam failed only from β1 = 0.99, whose 100-step window is about 20% of training.</li></ul><p>In the language model, I swept β1 at B = 8 and 256, keeping each batch’s LR and weight decay fixed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*znuDVX93PnXwKeJe5ZDhEg.png" /><figcaption><em>Final loss vs. Adam’s β1 at B = 8 and B = 256, with each batch’s LR and weight decay held fixed.</em></figcaption></figure><ul><li><strong>At B = 8</strong>, the best β1 (0.98) beat no momentum by 0.045.</li><li><strong>At B = 256</strong>, the best β1 (0.95) beat no momentum by 0.214, about 5× more. That matches the toy model.</li><li><strong>Too much momentum also hurt at the large batch, but much sooner than the toy model suggests.</strong> At B = 256, β1 = 0.99 reached 3.1751, almost as bad as no momentum (3.1853) and far worse than the best β1 (2.9712). At B = 8 it cost almost nothing (2.9333 vs. the best 2.9265). Yet its 100-step window is only about 4% of the 2,343 updates at B = 256 (and about 0.1% of the 75,000 at B = 8). In the toy model, failures began only around 20–30% of training, so I expected β1 = 0.99 to be harmless here. These runs show that the damage depends on the batch size, but not why it starts so early.</li></ul><p>One caveat: in the language model, the LR was tuned with β1 = 0.9 and not retuned for β1 = 0, so the small-batch gain there is probably overstated.</p><blockquote><strong>Takeaway:</strong> the “double the batch, double the LR” rule works only while gradient noise is the bottleneck. Past that, the LR stops growing and extra batch mostly costs updates. When moving to a bigger batch, try scaling the weight decay, and keep momentum on, but not too high.</blockquote><h3>4. µP buys you transfer, not a better model</h3><p>µP (Maximal Update Parametrization) changes how each layer is initialized and how its LR scales with width, so that one tuned LR should work at every width. I compared it against the standard setup (SP, the course’s default) at widths 128, 256, and 512, training on 153.6M tokens. The source LR was 0.003, the best sampled LR from the width-512 sweep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14Z6dPBJ4NexzdD8qQH5eQ.png" /><figcaption><em>Left: fitted optimal LR vs. width. Middle: tuned loss vs. loss at the transferred LR of 0.003. Right: the same losses relative to tuned µP.</em></figcaption></figure><ul><li><strong>µP kept the best LR in place.</strong> It stayed between 0.0020 and 0.0031 at every width, while SP’s best LR fell roughly as 1/width (∝ n^−0.86).</li><li><strong>Transfer mostly paid off.</strong> At width 128, reusing 0.003 cost SP 0.072 and µP nothing. At width 256 the cost was small for both (SP 0.003, µP 0.016).</li><li><strong>Tuned loss was the same.</strong> With each setup at its own best LR, the two tied within 0.001 at widths 256 and 512, and SP was 0.013 better at 128.</li></ul><p>A separate five-step stress test at much larger widths (640 to 5,120, depth 2) showed the transfer even more clearly. Over 8× the width, µP’s best LR moved only 1.07×, while a standard (Kaiming) initialization’s fell 27×.</p><p>Then I held out width 1,024 and predicted its best LR in two ways for each setup: reuse 0.003 directly, or fit a power law to the best LRs at widths 128–512.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gt2_tobDHIGYkXJOdRbSFA.png" /><figcaption><em>Width 1,024. Diamonds: the LR predicted by a power-law fit across widths. Squares: the reused LR of 0.003. Gaps are relative to the best sampled LR.</em></figcaption></figure><ul><li><strong>SP with a fitted power law</strong> predicted 0.00131, which landed on the best sampled loss (+0.000). Reusing 0.003 cost <strong>0.120</strong>.</li><li><strong>µP</strong> cost 0.017 when reusing 0.003, and 0.012 with its own power law.</li></ul><p>So µP made reusing one LR much safer: at worst it cost 0.017, against 0.120 for SP. For SP, fitting a simple width trend also found a good LR, so transfer isn’t the only way to get there.</p><p>The gaps above are each measured from that setup’s own best run, which hides one more result: <strong>at width 1,024, µP also reached a lower loss.</strong> Its best run reached about 3.089, against about 3.110 for SP’s best (values read from the figure), a gap of about 0.02. Even µP at the reused LR (about 3.106) did slightly better than SP’s best. At widths 128–512 the tuned losses tied, so 1,024 is the first width where µP pulled ahead by more than the ~0.01 noise threshold.</p><h3>Healthy-looking activations can hide a problem</h3><p>A five-step stress test at extreme depths (2, 100, and 1,000 layers, at width 64) showed something worth remembering for any deep model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwZSEKlC4qExK2FJkdaJhg.png" /></figure><p><em>Top: size (RMS) of the residual stream before the final normalization, over five updates. Bottom: final-block branch outputs. Columns: standard µP, Depth-µP, CompleteP. Log scale.</em></p><p>Everything a normalized layer sees looked the same at every depth: normalized features stayed at RMS 0.94–1.01, and logits ended at RMS 1.6–2.0. But under standard µP, the raw residual stream was already 9.4 at depth 100 and 33 at depth 1,000 at initialization, and reached <strong>863 and 8,159</strong> after five updates. The depth corrections (Depth-µP and CompleteP), which shrink each block’s contribution as depth grows, kept it between 5 and 8, close to the 9.6 seen at depth 2. Every block reads a normalized copy of the stream, so this growth is invisible unless you log the stream itself.</p><p>At realistic depths the depth corrections mattered much less. In full training at depths 4–16, standard µP’s best LR drifted only 1.3×. CompleteP helped only slightly, and Depth-µP over-corrected, with its best LR drifting more than standard µP’s.</p><blockquote><strong>Takeaway:</strong> µP’s value is not having to retune, not a better final loss. And if you monitor a deep network, log the raw residual stream, not just normalized activations.</blockquote><h3>What I’d tell any ML researcher</h3><ol><li><strong>Don’t extrapolate a learning rate far from where you measured it.</strong> The best LR rose with data and then fell. Fit on budgets near your target.</li><li><strong>Retune weight decay when you scale data.</strong> The best WD fell steadily as the budget grew (∝ D^−0.82 here), and reusing a small-budget WD cost 0.086 at 16× the data. Optimizers that fix weight norms, like Hyperball, remove this knob altogether.</li><li><strong>Scale the batch size with care.</strong> The LR can grow with the batch only while gradient noise is the bottleneck. Past that, it levels off and fewer updates hurt.</li><li><strong>For Adam, the batch-size rule depends on gradient noise.</strong> In the toy model it ranged from near-linear to square-root. In the language model it was near-linear up to B = 32 and then flat.</li><li><strong>When you increase the batch, try scaling weight decay</strong> instead of, or as well as, the LR.</li><li><strong>Momentum matters most at large batch.</strong> Keep it on, but don’t push β1 so high that its memory spans a large share of training.</li><li><strong>Use µP to avoid retuning, not to get a better model.</strong> A fitted width trend for SP did as well here.</li><li><strong>Log the raw residual stream.</strong> Normalized activations can look healthy while the stream underneath explodes.</li></ol><p>The common thread: a hyperparameter rule fit at small scale is a hypothesis, not a recipe. Write down what it predicts at the next scale, run that scale, and only then trust the rule.</p><p><em>This post is based on my write-up for Assignment 2 of Stanford’s </em><a href="https://deep-learning-alchemy.github.io/"><em>CS 312: Deep Learning Alchemy</em></a><em> (Fall 2026). Experiments used the course’s d8 model and codebase. Thanks again to the course staff (full acknowledgments in </em><a href="https://medium.com/@tushar.aggarwal53/what-a-35m-parameter-language-model-taught-me-about-doing-empirical-ml-research-216e158c7b10"><em>Part 1</em></a><em>).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee8042d4226e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What a 35M-Parameter Language Model Taught Me About Doing Empirical ML Research]]></title>
            <link>https://medium.com/@tushar.aggarwal53/what-a-35m-parameter-language-model-taught-me-about-doing-empirical-ml-research-216e158c7b10?source=rss-95e55ae43c18------2</link>
            <guid isPermaLink="false">https://medium.com/p/216e158c7b10</guid>
            <category><![CDATA[scaling-law]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Tushar Aggarwal]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 13:10:18 GMT</pubDate>
            <atom:updated>2026-11-01T13:20:58.364Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Lessons from more than a hundred small training runs from CS312 course at Stanford: hyperparameters that must be tuned together, scaling laws that look perfect and then fail, a noise floor you need to know, and a single token that makes a run behave like a different seed.</em></p><p><strong>I took CS312: Deep Learning Alchemy</strong> in Fall 2026. The course has an unusual premise. Instead of reading about deep learning phenomena, you build intuition for them by running hundreds of experiments on one small, standard model until you know its behavior well. The quizzes then ask you to <em>predict</em> the outcome of experiments you haven’t run.</p><p>Assignment 1 covered the basic skills of empirical ML. It was organized around four questions every researcher keeps running into:</p><ol><li>When do hyperparameters matter, and which ones?</li><li>Will it scale?</li><li>When is method A actually better than method B?</li><li>What’s going on with my model, and why isn’t it training?</li></ol><p>This post covers the findings that I think generalize beyond the course.</p><blockquote><strong>A caveat up front.</strong> Everything here was measured on one small model in one setting, and the course is explicit that results on this model will often disagree with published results. Treat the numbers as a rough guide, and the methods as the real takeaway.</blockquote><h3>The model organism</h3><p>Every experiment uses a model the course calls <strong>d8</strong>. It’s a Llama-style, decoder-only Transformer with 8 layers, hidden size 512, RMSNorm, QK-norm, and about <strong>35M parameters</strong>, trained to predict the next token on a subset of the DCLM dataset.</p><p>The default recipe uses the AdamW optimizer with a peak learning rate (LR) of 3e-3, weight decay (WD) of 0.1, 1% warmup, and a linear decay of the LR to zero. The batch size is 64 sequences of 1,024 tokens (65,536 tokens per step), and training covers 614.4M tokens in about 9,400 steps. A run takes 10–15 minutes on a single H100 and reaches a validation loss of about <strong>2.926</strong>.</p><p>Runs this short are what make the rest of this post possible. You can afford to sweep, repeat, and check your own claims.</p><h3>1. Hyperparameters: which matter, and which move together</h3><h3>Not all hyperparameters are equal</h3><p>I varied learning rate, batch size, weight decay, and warmup one at a time, each on a log-spaced grid around the default, with the total compute held fixed.</p><ul><li><strong>Learning rate mattered most.</strong> Plotted against LR, final loss formed a lopsided valley. Too low left the model undertrained. Too high was much gentler: 3× the default cost +0.03, 9× cost +0.09, and nothing diverged.</li><li><strong>Weight decay came next.</strong> Loss improved slowly up to 0.3, then rose steeply.</li><li><strong>Batch size</strong>, with the total number of tokens fixed, was flat near the default and about 0.03–0.04 worse at both extremes.</li><li><strong>Warmup mattered only when it was too short.</strong> A 0.1% warmup reached 2.990, but everything from 3% to 39% landed between 2.918 and 2.925.</li></ul><p>They also fail in different directions: LR punishes going too low, weight decay punishes going too high, and warmup only punishes going too short. So spend your tuning budget on a fine grid for LR, a coarser one for weight decay, and leave warmup at a sensible default.</p><h3>The most useful finding: learning rate and weight decay move together</h3><p>Next I varied learning rate (η) and weight decay (λ) together on a 2-D grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bm6A4v_ZVG8zCXTHPImdMg.png" /><figcaption><em>Final validation loss across a learning-rate × weight-decay grid on d8. The best weight decay in each column shrinks as the learning rate grows.</em></figcaption></figure><p>The best weight decay in each LR column scaled as <strong>1/LR</strong>, so their product η·λ stayed almost constant:</p><ul><li>LR 3e-4 → best WD 2.7 (edge of the grid) → η·λ ≈ 8.1e-4</li><li>LR 1e-3 → best WD 0.9 → η·λ ≈ 9.0e-4</li><li>LR 3e-3 → best WD 0.3 → η·λ ≈ 9.0e-4</li><li>LR 1e-2 → best WD 0.1 → η·λ ≈ 1.0e-3</li></ul><p>This is what AdamW’s weight decay predicts. Every step, each weight is shrunk by a factor of (1 − η·λ), so the product is what the optimizer actually feels.</p><p>The practical consequence: <strong>retuning weight decay removed much of the apparent penalty for a low LR.</strong> At LR 1e-3, loss improved from 2.976 to 2.932 once weight decay was adjusted. LR still matters on its own, since 3e-3 was still best among the points with matched η·λ. But if you compare settings at different learning rates with the same weight decay, part of the difference may just come from a mistuned η·λ.</p><blockquote><strong>Rule of thumb:</strong> Once you’ve found a good learning-rate and weight-decay pair, keep η·λ fixed when you change the learning rate: multiply LR by k, divide weight decay by k. This gives you roughly the right weight decay for the new LR. It doesn’t make the new LR as good as the old one, and if you change the schedule you may need to retune η·λ.</blockquote><p>Learning rate and batch size were much more weakly coupled. For batch sizes 32, 64, and 128, the best LR stayed at 3e-3.</p><h3>Learning-rate schedules: the final decay decides the result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMJhFXt4_3PDErfdc1KekA.png" /><figcaption><em>Left: the learning-rate schedules compared. Middle: validation loss over training. Right: final loss for each schedule at LR 3e-3, WD 0.1.</em></figcaption></figure><ul><li><strong>The final decay (“annealing”) decides the final loss.</strong> Keeping the LR constant cost about 0.15. Warmup-stable-decay (WSD) schedules hold the LR flat and then decay it at the end. Those runs stayed <em>above</em> linear decay for the whole flat phase and made almost all of their gains during the decay.</li><li><strong>Cosine and linear decay are equivalent.</strong> Each at its best weight decay, they finished within noise of each other (2.921 vs. 2.919).</li><li><strong>For WSD, the length of the decay window is the key setting.</strong> Final loss improved from 2.954 with a 10% decay window to 2.926 at 30%, then levelled off around 2.92 for 40–60%.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nVXS98Fn1DY7et_nsEkRMw.png" /><figcaption><em>Final validation loss over learning rate × weight decay for three schedules. Right: the best loss over weight decay at each learning rate.</em></figcaption></figure><ul><li><strong>When you switch schedules, retune weight decay, not peak LR.</strong> Every schedule with a decay preferred a peak LR around 3e-3, but they preferred different values of η·λ. With each at its own best weight decay, linear, cosine, and long-decay WSD all tied at about 2.92.</li></ul><blockquote><strong>Takeaway:</strong> don’t compare schedules by their mid-training loss. A schedule that looks “behind” may simply not have decayed yet.</blockquote><h3>2. Scaling laws: when to trust the straight line</h3><p>I trained a ladder of models from d4 to d9 (4 to 9 layers, with width growing alongside depth) on a fixed number of tokens, so only model size changed. For each recipe I fit a power law, L = a · C^(−α) with C the training compute, to d4–d7. I wrote down predictions for d8 and d9 <em>before</em> training them, so the fit couldn’t be adjusted after seeing the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtz7PrNVtrP57VuI2WVw8w.png" /><figcaption><em>Power laws fit on d4–d7 (circles), the predictions made in advance (diamonds), and the actual d8/d9 results (stars) for four recipes: baseline, constant LR, dropout 0.2, and LR 0.03.</em></figcaption></figure><p>All four recipes looked like clean power laws on d4–d7, but only the dropout recipe predicted both d8 and d9 within noise. The baseline came in worse than predicted by 0.022 at d8 and 0.041 at d9, and the LR 0.03 recipe by up to 0.045. The curves bend because the fixed token budget increasingly limits the larger models. <strong>A fit can look perfect and still be wrong just one or two sizes beyond the data.</strong></p><h4>Three ways scaling laws break</h4><p>Changes that raise the loss by a roughly constant amount at every size kept the scaling law intact. Examples were a lower LR, dropout, and removing QK-norm at the default LR. The changes that broke it were the ones that <strong>changed how training behaves partway along the scaling axis</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHwCYI66wdnrQ2vFLrNK4g.png" /><figcaption><em>Left: model-size scaling with repeated data and with QK-norm removed. Middle: how far the actual d9 result landed from its prediction. Right: a measure of attention-logit size, and the loss penalty of removing QK-norm as LR increases.</em></figcaption></figure><ol><li><strong>Repeating data.</strong> With only 38.4M unique tokens, each seen 16 times, loss got <em>worse</em> as the model grew past d6: 3.37 at d6, 3.51 at d8, 3.59 at d9. The fitted slope pointed the wrong way. Once there were about 3 or fewer unique tokens per parameter, the larger models memorized the repeated data.</li><li><strong>Instability.</strong> Removing QK-norm cost only 0.02 at the default LR. At LR 0.01 it cost <strong>1.16</strong>, leaving the model worse than a baseline with half as many layers. At the same time, the attention-logit measure grew about 1,000×, consistent with attention collapsing onto a few tokens.</li><li><strong>Too few optimizer steps.</strong> When I scaled data instead of model size, small-data runs with a large batch (128) got too few steps to train properly, and their curve bent instead of following a line. A power law fit on 77M–307M tokens predicted a loss of 2.62 at 614M tokens; the actual loss was <strong>2.951</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3Wx7Sp_q2cpvI0I3BcZuQ.png" /><figcaption><em>Data scaling for d8 at batch sizes 64 and 128. Dashed lines are power-law fits over all four points, and the bottom panel shows how far each point lands from its fit.</em></figcaption></figure><blockquote><strong>Takeaway:</strong> The most dangerous breaks happen at the high-compute end, because a fit from small models keeps predicting improvement right up until it fails.</blockquote><h3>3. Randomness: know your noise floor before claiming a win</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZ-Nc2DuUmgd3BPxBe-EGg.png" /><figcaption><em>Right: final validation loss for three different random seeds vs. ten runs of the exact default config with seed 42, where only GPU nondeterminism varies.</em></figcaption></figure><ul><li><strong>Changing all random seeds</strong> gave a standard deviation (SD) in final loss of about <strong>0.0036</strong> across three seeds.</li><li><strong>GPU nondeterminism alone</strong> (same seeds, repeated runs) gave only about <strong>0.0008</strong>.</li></ul><p>To see which seed matters more, I varied one at a time with deterministic GPU kernels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzUQiOWIHqWR2-mR-3ly7w.png" /><figcaption><em>Final validation loss when only the data-order seed or only the initialization (model) seed varies. Three runs each.</em></figcaption></figure><ul><li><strong>The initialization seed alone</strong> gave an SD of 0.0029, about 80% of the full 0.0036. <strong>The data-order seed alone</strong> gave 0.0017, about 50%.</li><li><strong>The two add up.</strong> Their variances sum to about 87% of the total, so they act as roughly independent sources and neither dominates. Fixing one still leaves the other’s noise. With three runs per series, treat these as rough estimates.</li></ul><p>Two lessons follow:</p><ol><li><strong>A small gap between two single runs means very little.</strong> On d8, a difference under roughly 0.01 (about two seed SDs for the gap between two runs) can come from seed noise alone. Several of the hyperparameter “improvements” from section 1 were 0.008 or smaller.</li><li><strong>Rerunning a seed is not the same as changing it.</strong> All three new seeds finished worse than every repeat of seed 42, so rerunning one seed underestimates the real variance.</li></ol><p>I also repeated the seed test for a higher LR (0.009), a smaller batch (16), and smaller and larger models (d4, d9). The SD stayed between 0.003 and 0.008 in every case. The higher LR increased it the most, about 2.8×, but with only three seeds that could still be chance.</p><h3>Training is chaotic, but only at the start</h3><p>With every source of randomness fixed, I changed <strong>one token</strong> in the first training batch and tracked how far the run drifted from an unchanged reference run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjjiX00KgXHwvSVWunowmQ.png" /><figcaption><em>Absolute difference in training loss from the reference run after changing a single token at step 0. Grey lines compare runs with different initializations on the same data.</em></figcaption></figure><p>For the first ~13 steps, while warmup kept the LR tiny, the gap stayed tiny. Then it grew exponentially, about <strong>450× in roughly 20 steps</strong>. Rising LR and Adam’s per-parameter normalization turned tiny gradient differences into full-size differences in the updates. By <strong>step ≈ 26</strong> the run was as different from the reference as a run with a different initialization, and its final loss differed by about as much as two seeds do.</p><p>Next I added random noise to all the weights at a chosen step T, at sizes from 10⁻⁶ to 10⁻² relative to each weight tensor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJwF3apIWD0HunIuv7vLIQ.png" /><figcaption><em>Divergence from the reference run after adding weight noise at step T, for three noise sizes. Right: final validation-loss gap vs. the number of steps left after the noise was added.</em></figcaption></figure><ul><li><strong>At T = 0</strong>, every perturbation, even the 10⁻⁶ one, grew to seed-level differences within tens of steps.</li><li><strong>At T = 1,000</strong> (of ~9,400), with the LR still near its peak, the final gap was 10–100× smaller than seed noise.</li><li><strong>From T = 4,000 on</strong>, perturbations did not grow, and late in training they <em>shrank</em>.</li><li><strong>The size of the noise barely mattered.</strong> Across four orders of magnitude, <em>when</em> the noise was added mattered far more than how large it was.</li></ul><blockquote><strong>Takeaway:</strong> almost all run-to-run variance was created in roughly the first 1,000 steps. Later training damps small differences instead of amplifying them, so the final loss depends mostly on what happened early.</blockquote><h3>4. Reading a model’s vital signs</h3><h3>The overall shape of a loss curve is predictable</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJP9A-Vk4fBPDi5dRmQQ3A.png" /><figcaption><em>Smoothed training loss as I varied LR, β1, batch size, and schedule. Bottom right: plotted against cumulative learning rate, the schedules with a decay collapse onto one curve until their decay begins.</em></figcaption></figure><p>Every healthy run had the same shape: an initial plateau, a rapid drop, a kink followed by a steady, roughly straight descent on a log-log plot, and a final drop as the LR decays. Each setting changes a specific part of the curve:</p><ul><li><strong>Learning rate sets the timing.</strong> A low LR stretches the initial plateau and leaves the run undertrained. A very high LR, or starting at full LR with no warmup, stalls early on a second plateau (a “shoulder”).</li><li><strong>The schedule sets the ending.</strong> Plotted against <strong>cumulative learning rate</strong> (the sum of the LR over all steps so far), all the decaying schedules trace the same curve until their decay starts. To a good approximation, loss depends on how much LR you’ve accumulated, plus a bonus from the final decay.</li><li><strong>Momentum (Adam’s β1) matters only at the extremes.</strong> β1 = 0.99 caused repeated loss spikes.</li><li><strong>Batch size trades token efficiency against the number of steps.</strong> Per step, larger batches are ahead early but get fewer steps in total. Per token, smaller batches learn faster early. Very large batches (512) also changed the shape, stalling on the same shoulder as a too-high LR, and finished far behind.</li></ul><h3>Step-to-step jitter is batch noise</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwQsO4WCgbY9z45xiLUU6Q.png" /><figcaption><em>Top left: loss-curve jitter vs. batch size, falling as 1/√B. Top middle and right: jitter over training for different LRs and schedules. Bottom: the jitter itself for batch size 512, the default, and β1 = 0.99.</em></figcaption></figure><p>I measured jitter as the step-to-step scatter of the loss around its moving average. It fell as <strong>1/√(batch size)</strong> and was essentially unaffected by learning rate or schedule. It stayed the same across a 1,000× range of LR and did not shrink during the LR decay. Other hyperparameters showed up as <strong>isolated events</strong> rather than steady noise: spikes and bursts from too much momentum, from starting at full LR without warmup, or from a very high LR.</p><blockquote><strong><em>Diagnostic rule:</em></strong><em> If the whole loss curve is uniformly noisier, look at batch size. If an otherwise normal curve has sharp spikes or bursts, look at the optimizer settings, especially momentum and warmup.</em></blockquote><h3>What I’d tell any ML researcher</h3><ol><li><strong>Tune learning rate and weight decay together.</strong> For AdamW, the best weight decay scales as 1/LR, so once you’ve found a good pair, keep η·λ fixed when you change the LR.</li><li><strong>Measure your noise floor before you measure your method.</strong> Use several <em>different</em> seeds, since rerunning one seed underestimates variance.</li><li><strong>Judge schedules and interventions by the final loss</strong>, after the LR has decayed, not by how the curves look mid-run.</li><li><strong>Write down scaling predictions before running the larger models.</strong> A clean-looking fit can fail just beyond its data.</li><li><strong>Watch for changes in how training behaves along the scaling axis.</strong> Repeated data, instability, and too few optimizer steps break scaling laws.</li><li><strong>Run-to-run variance is created early.</strong> Early training is chaotic, and later training damps small differences.</li><li><strong>Learn what a healthy run looks like.</strong> The overall shape of the loss curve tells you about LR and schedule. Uniform jitter tells you about batch size. Spikes tell you about the optimizer.</li><li><strong>Scale down.</strong> A model that trains in 10–15 minutes let me test, repeat, and try to disprove my own claims. That speed is what made these findings possible.</li></ol><p><em>This post is based on my write-up for Assignment 1 of Stanford’s </em><a href="https://deep-learning-alchemy.github.io/"><em>CS 312: Deep Learning Alchemy</em></a><em> (Fall 2026). All experiments were run on the course’s d8 model and codebase. Thanks to the instructors, Tatsunori Hashimoto and Suhas Kotha, and the CAs, Kaiyue Wen and Tristan Thrush, for developing such a great course.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=216e158c7b10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modeling Earthquake Recurrence with Graph Machine Learning]]></title>
            <link>https://medium.com/@tushar.aggarwal53/modeling-earthquake-recurrence-with-graph-machine-learning-89001331e146?source=rss-95e55ae43c18------2</link>
            <guid isPermaLink="false">https://medium.com/p/89001331e146</guid>
            <dc:creator><![CDATA[Tushar Aggarwal]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 00:23:48 GMT</pubDate>
            <atom:updated>2025-12-14T10:59:42.985Z</atom:updated>
            <content:encoded><![CDATA[<p>By Tushar Aggarwal, Brandon Liu, and Mete Gumusayak<br>Stanford University (CS224W: Machine Learning with Graphs)</p><h3>Introduction</h3><p>Earthquake sequences that repeat on the same fault patches, also called characteristic earthquakes, have recurrence times that are influenced by an opaque, nonlinear combination of fault loading rate, event slip, and transient stress changes. In layman’s terms, earthquakes that repeat on the same fault have recurrence times that are dependent on a complex combination of factors, ranging from geophysical characteristics (such as rock characteristics and loading rates caused by tectonic movements) to stress changes in the rock that permeate to nearby faults. It is well studied that these factors are contributors to earthquake slip events, however, the system of interactions are not well understood. This problem lends itself well to graph-based machine learning, and this project explores a variety of approaches to modeling this system.</p><blockquote><strong>Can machine learning forecast earthquake events?</strong></blockquote><blockquote>While operational forecasting remains one of the hardest scientific challenges, recent advances in graph neural networks (GNNs) and graph transformers allow us to model the complex interactions of fault systems more naturally than before.</blockquote><p>In this blog, we walk you through our end-to-end exploration of <strong>graph-based earthquake prediction</strong>, combining:</p><ol><li>An synthetic earthquake dataset that can generate infinite events</li><li>A real-world dataset of 27,675 repeating earthquakes</li><li>Three modern ML Models: GraphSAGE, Heterogeneous GNNs, and a Graph Transformer</li></ol><p>Our goal was simple:</p><ol><li>Validate graph models on synthetic data</li><li>Apply the best-performing techniques to real seismic data</li></ol><p>This blog covers the data, architectures, experiments, results and what we learned about modeling earthquake recurrence on graphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YO1U7NfJVp7i-9PIxkQhQ.png" /><figcaption>High Level Pipeline which shows different components of our work</figcaption></figure><h3>Why Earthquakes Form Graphs</h3><p>Repeating earthquakes sequences of nearly identical events that rupture the same fault patch, naturally map into graph structures:</p><ul><li>Fault patches → nodes</li><li>Stress-transfer links → edges</li><li>Earthquake sequences → temporal dependencies</li></ul><p>Unlike conventional ML models, GNNs capture <strong>spatial relations</strong>, <strong>interaction patterns</strong>, and <strong>multi-hop fault behavior</strong>, making them a strong candidate for earthquake recurrence modeling.</p><h3>Datasets</h3><h4>1. Real-World Dataset: Northern California</h4><p>We used the authoritative dataset from Waldhauser &amp; Schaff (2021), containing:</p><ul><li><strong>27,675 earthquake events</strong></li><li><strong>7,713 repeating sequences</strong></li><li><strong>1984–2021</strong></li></ul><p>Events are grouped using waveform similarity and precise relocation, making it one of the high-quality repeating-earthquake datasets available.</p><h4>2. Synthetic Dataset: A Physics-Based Earthquake Generator</h4><p>Before experimenting on real data, we generated a <strong>synthetic catalog</strong> using geo-physically realistic parameters as shown below:</p><p><strong>Fault Patch Simulation</strong></p><ul><li>200 patches</li><li>Radii: 80–400 m</li><li>Stress drop: 4 MPa</li><li>Loading rate: 0.004–0.014 m/yr</li><li>Shear modulus: 3×10¹⁰ N/m²</li></ul><p><strong>Event Recurrence Model</strong></p><p>We modeled inter-event times using the <strong>Brownian Passage Time (Inverse Gaussian)</strong> distribution, commonly used for periodic earthquakes.</p><p>Mean recurrence interval:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/106/1*FzlQ8d35Jew-nrW-oG3Xnw.png" /></figure><p>Coefficient of variation: γ = 0.25</p><p><strong>Magnitude Modeling</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*f-CZbtM_jIuHhehAtCyDkQ.png" /></figure><p>At a high level, the most critical values we want are u (amount of slip per event), and v (the loading rate). u is calculated using a number of geophysical constants listed below, typically derived from properties of the rock, and v is typically measured or given. This provides us the mean recurrence time. Additionally, Mw was derived from analyzing seismograms themselves. However, advances in sensing technology has allowed us to calculate the seismic moment M_o based on measurements of slip, radius, and shear modulus.</p><h3>Graph Machine Learning Approaches</h3><p>For all our models, we have tried to stick with the optimal parameters which were discussed in the last lecture of the course. We evaluated three types of graph models:</p><ol><li><strong>GraphSAGE</strong> (spatial proximity graph)</li><li><strong>Heterogeneous Graph Neural Network</strong> (spatio-temporal graph)</li><li><strong>Graph Transformer</strong> (global attention)</li></ol><h4>1. GraphSAGE</h4><p>GraphSAGE learns node embeddings by aggregating neighbor features.</p><p><strong>Graph Construction:</strong><br> Nodes = fault patches<br> Edges = faults within 50 km (Haversine distance)<br> Temporal context = rolling 180-day windows</p><p><strong>Node Features:</strong></p><ul><li>Event counts</li><li>Magnitude statistics</li><li>Days since last event</li><li>0–30/30–90/90–180 day bins</li><li>Gutenberg–Richter b-value estimate</li><li>Activity rate (Events per month)</li></ul><p><strong>Architecture</strong></p><ul><li>Four GraphSAGE layers (256 hidden units)</li><li>BatchNorm + ReLU + Dropout</li><li>Multi-task output for 30/90/180-day predictions</li></ul><p><strong>Forward Pass</strong></p><pre>def forward(self, data):<br>    x, edge_index = data.x, data.edge_index<br><br>    for conv, bn in zip(self.convs, self.bns):<br>        x = conv(x, edge_index)<br>        x = bn(x)<br>        x = F.relu(x)<br>        x = self.dropout(x)<br><br>    outputs = [head(x).squeeze(-1) for head in self.heads]<br>    return torch.stack(outputs, dim=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*THUapOkyHqYfeiNW4Z-cRQ.png" /><figcaption>Embedding update step as a matrix multiplication operation</figcaption></figure><h4>2. Heterogeneous Graph Neural Network (HeteroGNN)</h4><p>To jointly model <strong>space and time </strong>in the graph structure, we constructed a heterogeneous graph with two approaches: <strong><em>temporal edge prediction</em></strong>, and <strong><em>temporal snapshot graphs</em></strong>.</p><pre>class GraphBuilder:<br>    &quot;&quot;&quot;Build and cache heterogeneous graphs for each timestamp&quot;&quot;&quot;<br>    def __init__(self, filepath, min_history_months=6):<br>        self.filepath = filepath<br>        self.spatial_scaler = StandardScaler()<br>        self.time_scaler = StandardScaler()<br>        self.min_history_months = min_history_months  # Minimum historical context<br>        self.df = None<br>        self.spatial_features = None<br>        self.spatial_nodes = None<br>        self.radius_to_idx = None<br>        self.spatial_edges = None<br>        self.spatial_edge_weights = None<br>        self.all_months = None<br>    def prepare_training_data(self, train_months, index, sample_start=True):<br>        &quot;&quot;&quot;Pre-build all the graphs&quot;&quot;&quot;<br>        print(&quot;\nPre-building training graphs...&quot;)<br>        training_samples = []<br>        <br>        for i in range(index, len(train_months)):<br>            past_cutoff = train_months[i-1]<br>            target_month = train_months[i]<br>            <br>            # Sample starting month if enabled<br>            if sample_start:<br>                # Ensure we have at least min_history_months of data<br>                earliest_start = max(0, past_cutoff - (past_cutoff - 0))  # Can start from beginning<br>                latest_start = max(0, past_cutoff - self.min_history_months)  # Must have min history<br>                <br>                if earliest_start &lt;= latest_start:<br>                    start_month = np.random.randint(earliest_start, latest_start + 1)<br>                else:<br>                    start_month = 0<br>            else:<br>                start_month = 0<br>            <br>            # Build graph from start_month to past_cutoff<br>            data = self.build_graph_with_sampled_start(start_month, past_cutoff, target_month)<br>            <br>            # Get target edges (with relative time indexing)<br>            pos_edges, neg_edges = self.get_target_edges_for_month(target_month, start_month)<br>            <br>            if pos_edges.shape[1] &gt; 0 and neg_edges.shape[1] &gt; 0:<br>                training_samples.append((data, pos_edges, neg_edges))<br>        <br>        print(f&quot;Prepared {len(training_samples)} samples&quot;)<br>        return training_samples</pre><p><strong>Temporal Edge Prediction:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*DYAq7MWXNXm3JVyivw61hA.jpeg" /><figcaption>Example for Heterogenous Graph Formulation</figcaption></figure><p>In this figure, we formulate the problem as an edge prediction problem. There are two types of nodes: spatial, and temporal nodes. Spatial nodes represent characteristic earthquake sources, and are connected amongst themselves via spatial edges. These edge weights are the distance between two spatial nodes. Temporal nodes represent individual timesteps, and are connected as a line to model the linear evolution of time. Spatial nodes are connected to temporal nodes via event edges, and the existence of an edge between spatial node X and temporal node T indicates that an earthquake event occurred at node X on time T.</p><p><strong>Node Types</strong></p><ul><li>Spatial nodes (fault locations)</li><li>Temporal nodes (months)</li></ul><p><strong>Edge Types</strong></p><ul><li>Spatial ↔ Spatial (distance)</li><li>Spatial → Time (earthquake magnitude)</li><li>Time → Time (consecutive months)</li></ul><p><strong>Prediction Task</strong></p><blockquote><em>Edge Prediction: Will spatial node experience an earthquake during month </em>t<em>?</em></blockquote><p><strong>Forward Pass for HeteroGNN</strong></p><pre>def forward(self, node_feature, edge_index, target_edges):<br>        x = node_feature.copy()<br><br>        # Pre MLPs<br>        x[&#39;spatial&#39;] = self.pre_mlp_spatial(x[&#39;spatial&#39;])<br>        x[&#39;time&#39;] = self.pre_mlp_time(x[&#39;time&#39;])<br>        <br>        # Store initial features for skip connections<br>        x_input = {key: val.clone() for key, val in x.items()}<br>      <br>        ############# Layer 1 #############<br>        x = self.convs1(edge_indices=edge_index, node_features=x)<br>        x = forward_op(x=x, module_dict=self.bns1)  # or layer norms<br>        <br>        for key in x.keys():<br>            x[key] = x[key] + x_input[key]<br><br>        x = forward_op(x=x, module_dict=self.relus1)<br>    <br>        # Store for next skip connection<br>        x_layer1 = {key: val.clone() for key, val in x.items()}<br>        <br>        ############# Layer 2, 3, 4 #############<br>        <br>        ############# Edge Prediction #############<br>        time_indices = target_edges[0]<br>        spatial_indices = target_edges[1]<br>        <br>        x_time = x[&#39;time&#39;][time_indices]<br>        x_spatial = x[&#39;spatial&#39;][spatial_indices]<br>        <br>        return (F.cosine_similarity(self.w1(x_time), self.w2(x_spatial), dim=1).view(-1, 1))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*XA7AhlcaBOLm4ZbMJOyQmw.png" /><figcaption>Embedding update step for HeteroGNN</figcaption></figure><p><strong>Temporal Snapshot Graphs:</strong></p><p>We tried a different graph formulation for the HeteroGNN as well. For instance, running the model on a temporal snapshot graph. In this formulation, each node represents some fault patch <em>v</em> at time <em>t</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*-bdkDY6-cSAFIrtuCxGuZQ.png" /><figcaption>Temporal snapshot graph example with three nodes</figcaption></figure><p>Each node at the same time step has spatial edges, that connect with other nodes at its corresponding time step (with different approaches, such as connecting nodes within some physical radius distance, or spatial attention across all nodes). Each node also has temporal edges, that connect that node to its equivalent at one future and one previous time step.</p><p>With this formulation, we can extend our context by extending the number of snapshots in each sample. We then run HeteroGNN (for this case, implented with rGCN convolution layers, which is different from the edge prediction formulation) to create node embeddings, then using the embeddings at <em>t = 0</em> to predict labels.</p><h4>3. Graph Transformer</h4><p>The HeteroGNN aggregates neighbor information using static or learnable weights treating all neighbors of the same type similarly. We hypothesized that an attention mechanism could better filter noise because it can decide which specific past earthquakes or nearby faults are more relevant or less relevant for a future prediction beyond just a distance bias.</p><p><strong>Forward Pass Code</strong></p><pre>def forward(self, node_feature, edge_index, target_edges, edge_attr_dict=None):<br>    # 1. Embed Features<br>    x = {<br>        &#39;spatial&#39;: self.spatial_enc(node_feature[&#39;spatial&#39;]),<br>        &#39;time&#39;: self.temporal_enc(node_feature[&#39;time&#39;])<br>    }<br>    <br>    # 2. Transformer Layers with Edge Attributes<br>    # The model attends to neighbors using normalized distances/magnitudes<br>    for conv in self.layers:<br>        x = conv(x, edge_index, edge_attr_dict=edge_attr_dict)<br>        x = {key: F.relu(val) for key, val in x.items()}<br><br>    # 3. Predict on Target Edges (Concatenation + MLP)<br>    time_idx = target_edges[0]<br>    space_idx = target_edges[1]<br>    <br>    feat_t = x[&#39;time&#39;][time_idx]<br>    feat_s = x[&#39;spatial&#39;][space_idx]<br>    <br>    # Concatenate features and predict<br>    combined = torch.cat([feat_t, feat_s], dim=1)<br>    return self.predict_head(combined)</pre><h3>Loss Functions</h3><p><strong><em>Classification Task:</em></strong></p><ol><li>Focal Loss → <strong>GraphSAGE</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*J7SFFofvoEXeD5o3tOTrQw.png" /><figcaption>pt is the predicted probability for the true class, αt balances positive/negative examples (α=0.75), and γ down-weights easy examples (γ = 2.0).</figcaption></figure><p>2. Binary Cross-Entropy Loss (Edge Prediction) → <strong>HeteroGNN</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*nsfbuuTI_8A_zDyfG3Lsmg.png" /><figcaption>yts ∈ {0,1} is the true label (1 for event, 0 for no event), σ(·) is the sigmoid function. E+ and E- defines positive and negative edges.</figcaption></figure><p><strong><em>Regression Task:</em></strong></p><ol><li>Mean Squared Error</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*0XzAxHh-tCFaRH9SWR-woQ.png" /><figcaption>yi is the actual time (in months) until the next earthquake, and yi_hat is the model’s predicted<br>time.</figcaption></figure><h3>Experimental Results</h3><ol><li><strong>GraphSAGE (Synthetic Data)</strong></li></ol><p>We only ran GraphSAGE on the synthetic data, before moving on to create more sophisticated graph representations. We found that the performance of the model improves with horizon:</p><ul><li><strong>30-day F1:</strong> 0.35</li><li><strong>90-day F1:</strong> 0.58</li><li><strong>180-day F1:</strong> 0.70</li></ul><p>These results demonstrate that the simple GraphSAGE architecture shows promise in capturing temporal patterns through historical feature engineering, but there is a lot of scope for improvement for the short term predictions. So, we decided to convert the graph into a heterogenous graph and use HeteroGNN model to train on the real data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*UbygMt1PFbIV7Y2Cp-PbBg.png" /><figcaption>True Recurrence time distribution for a single node</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*4T398ufeS1khY0QSLjCEBQ.png" /><figcaption>Predicted Recurrence time distribution for a single node</figcaption></figure><p>2. <strong>HeteroGNN<br></strong>We first validated this approach by training the model on synthetic data. The model got an F1-score of 72.7% on the test split of synthetic data. So, we were now more confident with this approach and trained this model on the real seismic data. Below, we present the results on the real data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*tkC2d6Jm-paUIE88a7xcRg.png" /><figcaption>Performance Metrics for the best model on the three splits [Real Seismic Data]</figcaption></figure><ul><li>High recall means the model catches a majority of earthquake months</li><li>Moderate AUC (~0.61) reflects the inherent unpredictability of earthquakes</li><li>HeteroGNN significantly outperforms GraphSAGE</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQ9dJvR85JpFDFf7O9o-ig.png" /><figcaption>Results of the best model on the test set</figcaption></figure><p>The high false positive rate suggests that the model captures some spatial-temporal patterns but struggles to distinguish between locations that will and won’t experience earthquakes. This may reflect:</p><ul><li><strong>Insufficient features:</strong> We have used geographic location and magnitude information.</li><li><strong>Inherent stochasticity:</strong> Real earthquakes may have substantial random components that fundamentally limit predictability at monthly timescales.</li><li><strong>Data scarcity:</strong> With only 239 spatial nodes and 366 temporal periods, the model may lack sufficient training examples to learn robust patterns</li></ul><p>We also tried using the temporal snapshot graph formulation with HeteroGNN. Training the model on the synthetic data, we were unable to achieve good performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hu0NYoavwcZAJkBBsPE2rQ.png" /><figcaption>HeteroGNN on the synthetic data as a temporal snapshot graph, classification task, 90-day horizon</figcaption></figure><p>We believe that this is in part related to how critical signals are spread out sparsely among a larger number of nodes that need to capture information from the time stream. At monthly granularity, there are far more nodes with 0 labels, and to coherently capture temporal patterns within a limited context window (between 6 and 12 time steps) is very difficult. More sophisticated featurization could potentially make up for this, though more exploration is needed.</p><p>However, we also used this graph formulation for the regression problem, directly predicting the recurrence time at each time step. In this, formulation, the signal at each node is more prominent, as each node’s label carries new information about the next event. On the synthetic data, with well defined generating distributions, this formulation showed more promise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_R66eBPMyuEZnMCJiOdBBA.png" /><figcaption>True recurrence time vs predicted recurrence time, node with mean 18.12 months</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPxu90bQ9VcjAwBjBLNKrw.png" /><figcaption>True recurrence time vs predicted recurrence time, node with mean 32.62 months</figcaption></figure><p>The above figures show histograms of recurrence time predictions, that are generated from inverse gaussian distributions using Brownian Passage Time. The selected nodes (30 and 180) were randomly chosen to show that the model is capable of capturing different mean recurrence times, that are dependent on the geophysical characteristics of each fault. Some nodes do not visually match as well, but more work is needed be done to analyze these results quantitatively. Note, that these figures are presented across all training splits to show the distributions more clearly.</p><p><strong>3. Graph Transformer<br></strong>The Graph Transformer had the best results for the link prediction task on real data outperforming the HeteroGNN across all key metrics. We think this could have been because the model could dynamically attend to the important neighbors based on the input information.</p><p><strong>Test F1 Score:</strong> 69.1% (vs. 62.8% for HeteroGNN)<br><strong>Test ROC-AUC:</strong> 0.73 (vs. 0.61 for HeteroGNN)</p><p>This suggests that the attention mechanism learned that not all faults matter equally, only specific interactions may effect the fault and increase the chance of a slip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GczFdePrIf9nq4lLXfURsQ.png" /><figcaption>Results of the best model on the test set</figcaption></figure><h3>Ablations</h3><ul><li><strong>Heterogeneous GNNs significantly outperform GraphSAGE</strong>, improving F1 from ~0.35 (homogeneous) to ~0.63 (heterogeneous) and boosting AUC from ~0.55 to ~0.61, showing that explicitly modeling spatial and temporal node types is essential for capturing earthquake recurrence behavior.</li><li><strong>Distance-based spatial edges are crucial</strong>. When we removed distance information and treated spatial edges as uniform, the Heterognn model collapsed to predicting the same label for nearly all spatial node highlighting that physical proximity (stress interaction strength) is a necessary structural signal for meaningful earthquake prediction.</li><li><strong>Attention mechanism is important.</strong> Adding attention mechanisms (Graph Transformer) boosted performance even more, raising the Test F1 from 62.8% to 69.1%. Weighting interactions based attributes can be better than static aggregation.</li></ul><h3>Key Takeaways</h3><ol><li>Graph ML extracts meaningful predictive structure from seismic networks</li><li>Synthetic → Real transfer validates interpretability</li><li>Heterogeneous modeling is essential for spatio-temporal forecasting</li><li>Earthquakes remain extremely hard to predict</li></ol><h3>Final Thoughts</h3><p>Earthquake forecasting lies at the intersection of geophysics, stochastic modeling, and graph machine learning. Our results show that GNNs, especially heterogeneous variants can learn meaningful structure from fault systems. While we are far from operational prediction, this work highlights a promising direction where modern graph ML meets Earth science.</p><h3>Code, Data, and Reproducibility</h3><p>All code, synthetic data generation scripts, preprocessing utilities, and experiment notebooks used in this project are publicly available on <a href="https://github.com/AggarwalTushar/CS224W_Project">GitHub</a>. We’ve structured the repository to make it easy to reproduce our results or extend the work in new directions whether by experimenting with alternative graph constructions, adding new temporal modeling approaches, or integrating physics-based interactions such as stress-transfer kernels.</p><h3>Acknowledgements</h3><p>We would like to express our sincere gratitude to the CS224W instructors, our mentor TA (Harper Hua) and all the other TAs for their guidance and support throughout the quarter. We are also deeply thankful to Prof. William Ellsworth for his valuable advice and insightful discussions, which greatly strengthened this work.</p><h3>References</h3><p>[1] Ellsworth, W. L. <em>Characteristic earthquakes and long-term earthquake forecasts: Implications of central California seismicity.</em> Urban Disaster Mitigation, 1995.</p><p>[2] Waldhauser, F., &amp; Schaff, D. P. <em>A comprehensive search for repeating earthquakes in Northern California: Implications for fault creep, slip rates, slip partitioning, and transient stress.</em> JGR: Solid Earth, 2021.</p><p>[3] Matthews, M. V., Ellsworth, W. L., &amp; Reasenberg, P. A. <em>A Brownian model for recurrent earthquakes.</em> Bulletin of the Seismological Society of America, 2002.</p><p>[4] Kipf, T. N., &amp; Welling, M. <em>Semi-Supervised Classification with Graph Convolutional Networks</em>, 2017.</p><p>[5] Leskovec, J. <em>Stanford CS224W: Machine Learning with Graphs</em>, 2025.</p><p>[6] Yun, S., Jeong, M., Kim, R., Kang, J., &amp; Kim, H. J. <em>Graph Transformer Networks</em>, 2020.</p><p>[7] Kanatsoulis, C., Choi, E., Jegelka, S., Leskovec, J., &amp; Ribeiro, A. <em>Learning Efficient Positional Encodings with Graph Neural Networks</em>, 2025.</p><p>[8] Yang, X., Yan, M., Pan, S., Ye, X., &amp; Fan, D. <em>Simple and Efficient Heterogeneous Graph Neural Network</em>, 2023.</p><p>[9] Rezania, A., &amp; Darnis, F. <em>Use of Haversine formula in finding distance between temporary shelter and waste end processing sites.</em> JPCS, 2020.</p><p>[10] Pardo-Igúzquiza, E., &amp; Dowd, P. A. <em>Inference of the Gutenberg-Richter b-value: New insights and results.</em> Tectonophysics, 2024.</p><p>[11] Hamilton, W. L., Ying, R., &amp; Leskovec, J. <em>Inductive Representation Learning on Large Graphs</em>, 2018.</p><p>[12] He, K., Zhang, X., Ren, S., &amp; Sun, J. <em>Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification</em>, 2015.</p><p>[13] Lin, T.-Y., Goyal, P., Girshick, R., He, K., &amp; Dollár, P. <em>Focal Loss for Dense Object Detection</em>, 2018.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89001331e146" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating Multimodal Models for Reasoning Tasks: Insights from My Exploration]]></title>
            <link>https://medium.com/@tushar.aggarwal53/evaluating-multimodal-models-for-reasoning-tasks-insights-from-my-exploration-d287f5947e7a?source=rss-95e55ae43c18------2</link>
            <guid isPermaLink="false">https://medium.com/p/d287f5947e7a</guid>
            <dc:creator><![CDATA[Tushar Aggarwal]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 22:28:40 GMT</pubDate>
            <atom:updated>2025-12-06T22:36:08.169Z</atom:updated>
            <content:encoded><![CDATA[<h3>Evaluating Multimodals for Reasoning Tasks: Insights from My Exploration</h3><p>The rapid advancements in multimodals, those that can process both text and images; have shown incredible promise across various domains, from image captioning to sentiment analysis. However, one area that still presents a significant challenge is <strong>reasoning tasks</strong>, where models are expected to understand and process information from multiple modalities and generate accurate, context-aware answers.</p><p>I embarked on a project last year to evaluate small, open-source multimodal models on reasoning tasks and to investigate their capabilities in extracting relevant information from images. While these models have shown impressive potential, there’s still a long way to go in terms of accurately handling complex reasoning questions.</p><h3>Setting Up the Evaluation Dataset</h3><p>I began my exploration with a small but carefully designed dataset. This collection of 25 questions paired with images, each prompting the model to reason through visual information. These tasks included circuit analysis, identifying objects, and interpreting complex graphs — all tasks that required multimodals to go beyond simple image recognition and engage in a deeper understanding of the provided visuals in the context of the text-based instructions. <br>Here’s how the dataset looked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*ufeMExm7k0R95E36CF9gtg.png" /><figcaption><strong>Picture2.png</strong></figcaption></figure><pre>{<br>    &quot;instruction&quot; : &quot;What is the value of Voltage(V) in the given circuit? You can use the formula V = IR to calculate the value of Voltage(V). Also note that the unit of Voltage is Volt(V), unit of current is Ampere(A), and unit of resistance is Ohm(Ω).&quot;,<br>    &quot;image&quot; : &quot;Picture2.png&quot;,<br>    &quot;target&quot; : &quot;350&quot;,<br>    &quot;ideal_grounding&quot; : {<br>        &quot;type&quot; : &quot;circuit&quot;,<br>        &quot;content&quot; : {<br>            &quot;Current(I)&quot; : [&quot;70&quot;],<br>            &quot;Resistance(R)&quot; : [&quot;5&quot;]<br>        }<br>    }<br>}</pre><p>In this task, the model is asked to calculate the voltage using the formula V=IR, with the current and resistance values extracted from the image. The model is expected to reason through this task by first recognizing the values for current and resistance in the image, then applying the formula to calculate the voltage.</p><p>However, this task involves much more than just identifying values — it also requires understanding the relationships between those values and applying logical reasoning to generate the correct output.</p><h3>The Prompting Techniques</h3><p>To better understand how multimodals tackle these reasoning tasks, I experimented with different prompting techniques. These included:</p><ol><li><strong>End-to-End</strong>: Directly asking the model to generate an answer based on the image and text, without any intermediary steps.</li><li><strong>Visual Grounding + Code</strong>: In this approach, the model first extracts relevant information from the image, then passes that data to a code model to generate the code that outputs the answer.</li><li><strong>Ideal Grounding + Code</strong>: Here, I provided a manually written information from the image (e.g., the correct values for current and resistance in JSON format) to the code model to generate the code, to assess the abilities of code model being used.</li><li><strong>Vision + Code</strong>: This technique involved asking the multimodal to generate the code directly from the image and the question.</li></ol><h3>Key Insights</h3><p>Through these experiments, several key insights emerged about the capabilities and limitations of multimodal models in reasoning tasks:</p><ul><li><strong>Inconsistent Performance</strong>: While multimodal models have shown strong performance in simpler tasks, they consistently underperformed in tasks that required structured reasoning. The inability to extract relevant data from images was a major bottleneck. Even with clear instructions, the models struggled to link the visual input with the logical operations required to generate the correct answer.</li><li><strong>The Potential of Structured Data</strong>: One of the most promising findings from this exploration was the realization that converting visual information into structured data — such as JSON format— subsequently providing that structured data to a code model — could lead to significant improvements in performance.</li></ul><h3>Structured Data from Images</h3><p>One key insight that emerged from my exploration is that extracting structured data from images could substantially improve performance in reasoning tasks. Imagine if multimodals could not only identify objects in images but also convert these objects and their relationships into a structured format (such as JSON). This structured data could then be provided to a code model for further reasoning.</p><p>For instance, rather than having the model attempt to learn the relationship between voltage, current and resistance, the model could output something like this:</p><pre>{<br>  &quot;Current(I)&quot;: [&quot;70&quot;],<br>  &quot;Resistance(R)&quot;: [&quot;5&quot;]<br>}</pre><p>This structured data would allow the code model to perform more accurate computations, yielding better results. By converting complex visual information into a format that’s easier for code models to interpret and process, we can significantly enhance the performance of multimodal systems on reasoning tasks.</p><h3>Conclusion</h3><p>The potential of multimodals in reasoning tasks is immense, but it’s clear that there’s still a long road ahead. While these models have made significant strides in understanding and processing both text and images, their ability to reason through complex problems remains limited.</p><p>By focusing on improving how multimodal models extract and process structured data from images, we can unlock their full potential for solving reasoning tasks. With continued research and innovation in this space, I’m excited to see how multimodal models evolve and push the boundaries of AI’s problem-solving abilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d287f5947e7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A good system prompt is all not you need: Insights from My Recent Experiments]]></title>
            <link>https://medium.com/@tushar.aggarwal53/a-good-system-prompt-is-all-not-you-need-insights-from-my-recent-experiments-707527da5755?source=rss-95e55ae43c18------2</link>
            <guid isPermaLink="false">https://medium.com/p/707527da5755</guid>
            <dc:creator><![CDATA[Tushar Aggarwal]]></dc:creator>
            <pubDate>Thu, 28 Nov 2024 20:02:06 GMT</pubDate>
            <atom:updated>2024-11-29T00:41:28.202Z</atom:updated>
            <content:encoded><![CDATA[<p>When experimenting with fine-tuning large language models (LLMs), you quickly realize that every detail matters — from the architecture and hyperparameters to the prompts you use. Recently, I found myself wrestling with two questions that I couldn’t shake: <strong>What role do system prompts really play during fine-tuning?</strong> and <strong>Should these prompts be optimized during the fine-tuning process?</strong></p><p>These questions led me down an intriguing path that not only challenged my assumptions but also revealed some surprising results. I’m excited to share my findings and the potential implications for the future of fine-tuning language models.</p><p><strong>Please note that all my current results and findings are based on the fine-tuning of the Deepseek-6.7B-Instruct model. I am yet to explore other models for comparison and further analysis.</strong></p><h3>The Role of System Prompts: Do They Need Fine-Tuning?</h3><p>System prompts are an integral part of working with language models. These prompts — often crafted with great care — set the stage for how the model should behave during inference. For example, they might instruct the model to respond in a specific tone, style, or manner. Given how important system prompts are in guiding model behavior during inference, I wondered: <strong>Should system prompts also be part of the fine-tuning process?</strong></p><p>Inspired by prior works such as <a href="https://arxiv.org/pdf/2311.10054"><em>When “A Helpful Assistant” Is Not Really Helpful</em></a>, which examined the role of system prompts during inference, I decided to investigate whether fine-tuning the model with a set of specific system prompts would yield better results compared to using arbitrary or randomly selected prompts. The hypothesis was straightforward: fine-tuning with carefully crafted prompts should lead to superior model performance.</p><h3>The Unexpected Results: Arbitrary Prompts vs. Crafted Prompts</h3><p>As I began my experiments, I expected that using well-crafted, high-quality prompts during fine-tuning would result in noticeably better performance. To my surprise, the scores achieved with arbitrary prompts were nearly identical to those obtained with carefully selected prompts.</p><p>This raised a fundamental question: <strong>Is a high-quality system prompt truly necessary during fine-tuning?</strong> The results suggested something unexpected: it seemed that the model could perform well regardless of whether the system prompt was well-crafted or arbitrary. In fact, it almost appeared as though the model was learning to disregard the system prompt during the fine-tuning process.</p><p>Here’s a comparison of the performance scores when using arbitrary versus carefully crafted system prompts during fine-tuning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TL-aHQhCqByxihHuxREdCQ.png" /></figure><h3>Rethinking the Need for System Prompts</h3><p>This led me to a rather thought-provoking proposition: <strong>Should we reconsider the need for system prompts during fine-tuning altogether?</strong> Or could we achieve better performance by utilizing a <strong>mixture of different system prompts</strong> throughout fine-tuning? By introducing a variety of prompts, we might encourage the model to learn more robust patterns and generalize better across a range of tasks.</p><p>In some cases, it might even be worth experimenting with <strong>omitting the system prompt entirely</strong>. If the model can learn to perform effectively without relying on a prompt, this could simplify the fine-tuning process, reduce unnecessary complexity, and improve efficiency.</p><h3>What This Means for Fine-Tuning Models</h3><p>So, what do these findings mean for fine-tuning language models moving forward? Here are a few takeaways:</p><ul><li><strong>System prompts may not need fine-tuning</strong>: The model’s performance may not significantly improve by using high-quality system prompts during fine-tuning, suggesting that the model can learn to perform well with a variety of prompts.</li><li><strong>Exploring a mixture of prompts</strong>: Using a mix of system prompts could potentially help the model generalize better. This could be an interesting area for further exploration, as it may lead to models that are more adaptable across different contexts.</li><li><strong>Potential to simplify the fine-tuning process</strong>: If models can disregard system prompts during fine-tuning, it might mean that we can focus on other aspects of fine-tuning, streamlining the process, and saving computational resources.</li></ul><p>These insights open up new avenues for experimentation and challenge long-held assumptions about the importance of system prompts.</p><p><strong><em>If anyone has any experiments that contradict these results and conclusion, please feel free to reach out.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=707527da5755" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>