<?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 Jun Nishimura on Medium]]></title>
        <description><![CDATA[Stories by Jun Nishimura on Medium]]></description>
        <link>https://medium.com/@j.tech.reveil?source=rss-ac21d639db9d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Kyl_3bo_7uJepawO</url>
            <title>Stories by Jun Nishimura on Medium</title>
            <link>https://medium.com/@j.tech.reveil?source=rss-ac21d639db9d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:21:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@j.tech.reveil/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[When Matching Hidden States Isn’t Enough: Debugging a PHOTON Conversion — and Releasing OpenPHOTON]]></title>
            <link>https://medium.com/@j.tech.reveil/when-matching-hidden-states-isnt-enough-debugging-a-photon-conversion-and-releasing-openphoton-fed28d689c50?source=rss-ac21d639db9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fed28d689c50</guid>
            <category><![CDATA[qwen]]></category>
            <category><![CDATA[kv-cache]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Jun Nishimura]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 19:23:27 GMT</pubDate>
            <atom:updated>2026-08-07T19:23:56.947Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/nj-1015/OpenPHOTON">View the code on GitHub — OpenPHOTON</a></p><p><em>Part 3 — the wall, the fix, the inference path, an honest negative result, and the code.</em></p><blockquote><em>This is </em><strong><em>Part 3 of 3</em></strong><em>. </em><a href="https://medium.com/towards-artificial-intelligence/reading-vertically-photon-and-the-kv-cache-bottleneck-3e25b470bdcd"><em>Part 1</em></a><em> explained PHOTON; </em><a href="https://medium.com/towards-artificial-intelligence/what-is-perplexity-a-gentle-guide-with-qwen3-and-gemma4-7ce1ea30d66b"><em>Part 2</em></a><em> converted a pretrained Qwen3–0.6B into it by distillation — and got stuck at </em><strong><em>20× the teacher’s perplexity</em></strong><em> despite near-perfect reconstruction. This is where we figure out why, break through it, build the efficient inference path, run one experiment that </em>fails<em> informatively, and open-source the whole thing.</em></blockquote><h3>The puzzle</h3><p>We left Part 2 with a contradiction. After stage S2, the model <strong>reconstructs the teacher’s final hidden state almost perfectly</strong> — cosine 0.99 — and yet the composed model is <strong>still 20× worse at predicting the next word.</strong></p><p>Reconstruction: solved. Prediction: stuck. Both true at once. That shouldn’t be possible… unless we were measuring the wrong thing.</p><h3>The probe: even a perfect briefing doesn’t help</h3><p>To find the bottleneck, we ran a clean experiment. The decoder generates each token from a “briefing” it reconstructs internally. So: what if we cheat and hand it a <strong>perfect</strong> briefing — the <em>true</em> encoder latent instead of the reconstructed one?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rf7l6mXAbFqw-G58ca45oA.png" /><figcaption>Three-way probe: baseline, magnitude-fixed, and oracle all land at the same perplexity</figcaption></figure><p>Nothing. Baseline, a magnitude-corrected version, and the <strong>oracle</strong> with a literally perfect briefing all land in the same ballpark — <strong>25–31× the teacher</strong> — and if anything the <em>oracle is the worst of the three.</em> A perfect briefing doesn’t just fail to help; it makes no difference at all. On top of that, the error was <strong>uniform across positions</strong>, not concentrated where compression should hurt most.</p><p>So the wall was <strong>not</strong> reconstruction quality, and <strong>not</strong> the chunker’s compression. Perfect inputs, same bad output. The problem had to be somewhere we hadn’t looked.</p><h3>The realization: it was never trained to predict</h3><p>Here’s what we’d missed. S1 and S2 both trained the model to match the teacher’s <strong>hidden states</strong> — its internal activations. <strong>Neither ever trained it to predict the next token.</strong> The perplexity we kept measuring was an <em>untrained byproduct</em> — a number nobody had ever optimized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5CidXcpU6a5wAW8t1ntvpg.png" /><figcaption>S1/S2 copy hidden states; S3 matches the output distribution</figcaption></figure><p>The fix writes itself: stop copying activations, and start matching the teacher’s <strong>output distribution</strong> — plain knowledge distillation.</p><h3>S3: logit distillation breaks the floor</h3><p>So S3 trains the model to match the teacher’s next-token probabilities (forward KL divergence), warm-started from S2. We ran a small 0.5B-token trial and watched the gap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHAwVtTzOQRQcrFONPfR8Q.png" /><figcaption>S3 trajectory: 20.5× drops to ~7.5× and saturates</figcaption></figure><p>The 20× floor <strong>broke immediately</strong> — down to ~9× in the first 14% of training, then settling around <strong>7×</strong>. Switching the objective to prediction did in a fraction of a run what hidden-matching couldn’t do at all. (It also saturates: at 0.5B tokens it converges near 7×, and pushing lower is a <em>data-scale</em> question — more on that at the end.)</p><h3>Does it actually speak?</h3><p>Numbers are abstract; here’s what the ~7× model generates (sampled, mid-distillation):</p><blockquote><strong><em>“In a small village by the sea, there lived”</em></strong><em> → </em>until the early 1950, when it was the first place in Africa. He was the father of the mother and the mother of the mother…</blockquote><blockquote><strong><em>“She opened the letter and began to read:”</em></strong><em> → </em>“What is the importance of the text of the message… We are the message that can be used to address the problem.”</blockquote><p>Fluent, grammatical, and <strong>wandering</strong> — unmistakably a working language model, not yet a good one. Which is exactly the honest claim: this demonstrates the conversion <em>works</em>, not that it’s <em>finished</em>.</p><h3>Building the efficient inference: RecGen</h3><p>A converted model is only interesting if you can run it the efficient way. So we implemented <strong>RecGen</strong> — the recursive generation from Part 1, where the decoder’s reconstruction refreshes the summary and the encoder never re-reads generated tokens.</p><p>Two things we verified:</p><ul><li><strong>The mechanics are exact.</strong> A “plumbing” test reproduces the model’s own forward pass to a difference of <strong>2.9e-5</strong> — so the indexing, the local windows, and the position handling are all provably right (5/5 tests pass).</li><li><strong>The KV win is real.</strong> At 2048 tokens the resident growing cache drops from <strong>57,344 → 3,584 entries — the 16× reduction, realized in code</strong>, not just a diagram.</li></ul><h3>Testing the paper’s exactness theorem — for real</h3><p>PHOTON’s paper proves something neat: RecGen gives <em>identical</em> output to an exact decode <strong>whenever the decoder’s reconstruction equals the encoder’s state.</strong> But nobody had measured how close that is in a <em>real, imperfect</em> model. So we did.</p><p>The answer: <strong>~22% token agreement.</strong> RecGen’s output diverges from the exact decode after about six tokens — because the reconstruction it relies on is only ~<strong>0.80</strong> similar (cosine) to the encoder’s latent, not 1.0.</p><p><em>(Didn’t we just say reconstruction was 0.99? Different tensor. The </em><strong><em>0.99</em></strong><em> was the model’s </em><strong><em>final-hidden</em></strong><em> reconstruction — which the training directly optimized. The </em><strong><em>0.80</em></strong><em> is an </em><strong><em>internal, mid-level latent</em></strong><em> that RecGen quietly depends on, but that nothing ever pinned down. That gap is the whole story of the next section.)</em></p><p>The theorem holds; our model just isn’t consistent <em>enough</em> yet to cash it in.</p><p>Which raised an obvious question — could we <em>train</em> it to be consistent enough? That led to the one experiment that failed, and taught us the most.</p><h3>The sweep: we tuned the wrong knob</h3><p>S3 has a small “consistency” term (rec_weight) meant to keep the reconstruction faithful. So we swept it — 0.1, 0.3, 1.0, 3.0 — expecting RecGen fidelity to climb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfZwTMN1Zr-3uW20OcKNjw.png" /><figcaption>The sweep: the consistency term’s own target rises, but RecGen fidelity stays flat</figcaption></figure><p>It didn’t. Cranking rec_weight cleanly improved <em>its own</em> target (cos(chunk2·, h₂), blue, 0.91 → 0.97) — but the quantity RecGen fidelity actually depends on (cos(ĥ₁, h₁), red) <strong>stayed flat at 0.79</strong>, and RecGen agreement <strong>never budged from ~18%.</strong></p><p>The reason, once we saw it, was obvious: we’d strengthened the <em>wrong consistency term</em>. RecGen exactness needs ĥ₁ ≈ h₁ (call it rec_A) — but S3&#39;s knob controls a <em>different</em>, weaker consistency (rec_B). A clean <strong>negative result</strong>: rec_A is the lever, not rec_B. Sometimes the most useful experiment is the one that rules a knob <em>out</em>.</p><h3>The full journey</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMusE3v9ClwOwnMVIAMD1g.png" /><figcaption>The full journey: 33× → 20× → 7× across S1, S2, S3</figcaption></figure><p>From a surgically-assembled model that was 33× the teacher, to 20× with composition, to <strong>~7× with logit distillation</strong> — plus a verified, 16×-lighter inference path. Not a finished model, but a genuine proof of concept.</p><h3>OpenPHOTON — the code</h3><p>Everything here is open. <a href="https://github.com/nj-1015/OpenPHOTON"><strong>OpenPHOTON on GitHub</strong></a> ships:</p><ul><li>photon/ — the architecture (surgery, chunkers, converters).</li><li>train/ — the full S0→S3 distillation pipeline.</li><li>inference/recgen.py — RecGen generation + the KV-footprint accounting.</li><li>tests/ — the correctness gates (including the exact-plumbing test).</li></ul><p>The final S3 checkpoint is on <strong>[HuggingFace](to be released)</strong>. Loading it and generating — the efficient way — is a few lines:</p><pre>from openphoton import load_openphoton, generate, kv_footprint<br><br># downloads the S3 checkpoint from HuggingFace and assembles the ~7x model<br>model = load_openphoton(&quot;OpenPHOTON/Qwen3-0.6B&quot;)<br># generate the efficient way (RecGen); handles tokenization + chunk padding for you<br>print(generate(model, &quot;In a small village by the sea,&quot;,<br>               max_new_tokens=40, temperature=0.7))<br># and see the KV reduction yourself<br>print(kv_footprint(model, seq_len=2048))   # -&gt; (57344, 3584, 16.0)</pre><h3>Honest close</h3><p>Let’s be precise about what this is and isn’t.</p><p><strong>It’s not a product.</strong> ~7× the teacher’s perplexity is a model that speaks fluently but wanders; you wouldn’t ship it. The path to <em>usable</em> is clear but unglamorous: <strong>more data</strong> (logit distillation scales with tokens, and we ran only a 0.5B trial), plus fixing RecGen fidelity via the rec_A lever the sweep pointed us to.</p><p><strong>But it is a real result.</strong> It’s the first evidence that PHOTON is reachable by <strong>distillation from a pretrained model</strong>, not only by pretraining from scratch — with the ~16× KV reduction realized in working code, and the paper’s exactness theorem measured empirically for the first time (including a negative result that pins down exactly which knob controls it).</p><p>If any of that is useful to you, it’s all in <a href="https://github.com/nj-1015/OpenPHOTON"><strong>OpenPHOTON</strong></a>. Go break it.</p><p><em>PHOTON is the work of Ichikawa et al. (arXiv:2512.20687); the staged distillation approach follows MOHAWK (Bick et al., arXiv:2408.10189). This series is an independent reproduction and study — every result here (the probe, 33×→20×→7×, the 16× KV reduction, the ~22% RecGen fidelity and the rec_weight sweep) is our own measured output on this Qwen3–0.6B conversion. All diagrams are my own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fed28d689c50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Perplexity? A Gentle Guide (with Qwen3 and Gemma4)]]></title>
            <link>https://pub.towardsai.net/what-is-perplexity-a-gentle-guide-with-qwen3-and-gemma4-7ce1ea30d66b?source=rss-ac21d639db9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ce1ea30d66b</guid>
            <category><![CDATA[perplexity]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[qwen]]></category>
            <category><![CDATA[gemma]]></category>
            <category><![CDATA[japanese]]></category>
            <dc:creator><![CDATA[Jun Nishimura]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 15:35:21 GMT</pubDate>
            <atom:updated>2026-08-10T03:15:47.828Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>The one number everyone uses to measure a language model — explained simply, then measured for real in a few lines of code.</em></h4><figure><a href="https://colab.research.google.com/github/nj-1015/OpenPHOTON/blob/main/notebooks/perplexity_tutorial.ipynb"><img alt="https://colab.research.google.com/github/nj-1015/OpenPHOTON/blob/main/notebooks/perplexity_tutorial.ipynb" src="https://cdn-images-1.medium.com/max/281/1*G7Kxu7QEcbEWGyF0_MB7LQ.png" /></a></figure><h3>The one-sentence version</h3><p><strong>Perplexity measures how <em>surprised</em> a language model is by a piece of text.</strong> Low perplexity means the model found the text predictable (good); high perplexity means it was confused. That’s the whole idea — everything below is just making it precise.</p><h3>The die analogy</h3><p>The cleanest way to feel what perplexity means: <strong>a perplexity of N is like being as unsure as rolling a fair N-sided die</strong> — every single word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05ADYnrMyoTux1Jojs4gXA.png" /><figcaption>Perplexity N is like a fair N-sided die: coin=2, die=6, Qwen3 on English ≈ 30</figcaption></figure><p>A coin has perplexity 2 (two equally-likely outcomes). A die, 6. When Qwen3–0.6B reads ordinary English, its perplexity is about <strong>30</strong> — as if, at each word, it were choosing among ~30 equally-likely options. A <em>perfect</em> model that always knew exactly the next word would have perplexity <strong>1</strong> (no uncertainty at all).</p><p>So: <strong>lower perplexity = the model is less surprised = it understands the text better.</strong></p><h3>Watch it happen, word by word</h3><p>Perplexity isn’t one guess — it’s the model’s surprise <em>averaged over every word</em>. Here’s Qwen3 reading “The cat sat on the mat,” showing its probability for each actual next word:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hn1aEQ8dqcw7AC-E_NoPxQ.gif" /><figcaption>Reading a sentence word by word: the model is surprised by content words, confident on function words</figcaption></figure><p>Notice the pattern: the model is <strong>confident</strong> on predictable words (“on” 70%, “the” 73%) and <strong>surprised</strong> by content words it couldn’t have guessed (“cat”, “mat”). Perplexity rolls all of that — the confident moments <em>and</em> the surprises — into a single number.</p><h3>How it’s actually computed</h3><p>Four small steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4bfH_BiL50yxMCog0qrO8g.png" /><figcaption>The perplexity pipeline: text, model probabilities, negative log, average, exp</figcaption></figure><ol><li>For each position, the model gives a <strong>probability to the <em>true</em> next word</strong>.</li><li>Take <strong>−log</strong> of that probability — call it the “surprise” (a probability of 1 → surprise 0; a tiny probability → big surprise).</li><li><strong>Average</strong> the surprise over all the words.</li><li><strong>Exponentiate</strong> — and that’s perplexity.</li></ol><p>In one line of math: <strong>perplexity = exp( average of −log p(true next word) )</strong>.</p><h3>A worked example (real numbers)</h3><p>Here’s every step for “The cat sat on the mat,” measured with Qwen3–0.6B:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc56f6d9beb082a27073b909e9f96fba/href">https://medium.com/media/bc56f6d9beb082a27073b909e9f96fba/href</a></iframe><p>Average surprise = <strong>4.38</strong>, and exp(4.38) ≈ <strong>79.5</strong> — the perplexity of that little phrase. Notice it’s dominated by the <em>surprising</em> words; the two confident predictions barely move it. (Short, out-of-context phrases like this run high; give the model a real sentence with context and it drops.)</p><h3>Measure it yourself</h3><p>The whole thing is a few lines. This function computes real perplexity with Qwen3:</p><pre>import torch, torch.nn.functional as F<br>from transformers import AutoTokenizer, AutoModelForCausalLM<br><br>tok = AutoTokenizer.from_pretrained(&quot;Qwen/Qwen3-0.6B&quot;)<br>model = AutoModelForCausalLM.from_pretrained(&quot;Qwen/Qwen3-0.6B&quot;).eval()<br>def perplexity(text):<br>    ids = tok(text, return_tensors=&quot;pt&quot;).input_ids<br>    with torch.no_grad():<br>        logits = model(ids).logits<br>    logp = F.log_softmax(logits[0, :-1], dim=-1)     # a distribution at each position<br>    true_next = ids[0, 1:]                            # the words that actually came next<br>    surprise = -logp[range(len(true_next)), true_next]  # -log p of each true next word<br>    return torch.exp(surprise.mean()).item()          # average, then exp<br>print(perplexity(&quot;The cat sat on the warm windowsill in the afternoon sun.&quot;))<br># ≈ 30</pre><p>That’s it — grab a probability for each true next token, average the negative logs, exponentiate.</p><h3>Predictable vs gibberish — and bigger vs smaller</h3><p>Two lessons in one chart. Start with the <em>same</em> model (Qwen3–0.6B, blue) on four kinds of text: the more expected the text, the lower the perplexity — from <strong>9</strong> (predictable) to <strong>11,200</strong> (random), three orders of magnitude. Then add two more models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHe5dW1CAqRaMOF-OnIMiQ.png" /><figcaption>Perplexity across three models and four text types, with Qwen3.5 flagged as a different tokenizer</figcaption></figure><p><strong>A bigger, same-family model is less perplexed.</strong> Qwen3<strong>–1.7B</strong> (green) beats Qwen3–0.6B on every sentence — 5.5 vs 9 on predictable text, 23 vs 30 on ordinary English. Same tokenizer, same tokens, just a bigger and better model: a fair, apples-to-apples comparison.</p><p><strong>Now look at Qwen3.5–0.8B (purple, hatched).</strong> It’s a strong, more recent model — yet its perplexity looks <em>worse</em> than even the smaller Qwen3–0.6B (37 vs 30 on ordinary English; 17.5 vs 9 on predictable text). That’s <strong>not</strong> because it’s a weaker model. It uses a <strong>different, larger tokenizer</strong> (248k tokens vs Qwen3’s 152k), which chops the same text into different pieces and changes the arithmetic. Its number simply <strong>isn’t comparable</strong> — the caveat, caught live. Which brings us to the rule.</p><h3>A twist: a third family, and a second language</h3><p>We can push the tokenizer lesson further — with a <strong>third</strong> model family and a <strong>second language</strong>. Drop in <strong>Gemma 4</strong> (Google’s models) at two sizes, E2B and E4B, and measure both an ordinary English sentence and a meaning-matched ordinary Japanese one across everybody:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKemvSU9o4q_GkZb2wQdQg.png" /><figcaption>Perplexity for five models across two families on English and Japanese; Gemma sits on a different scale, and Japanese costs more everywhere</figcaption></figure><p>Two things repeat, and one is new:</p><ul><li><strong>Bigger still helps — inside a family.</strong> Gemma-4-E4B beats E2B on English (37 vs 134) <em>and</em> Japanese (102 vs 213), exactly the way Qwen3–1.7B beats Qwen3–0.6B. Same tokenizer, bigger model, lower perplexity — a fair comparison.</li><li><strong>Across families, the numbers live on different scales.</strong> Gemma’s ordinary-English perplexity (37–134) sits well above Qwen3’s (22–37) — <strong>not</strong> because Gemma is a worse model, but because it’s a <em>third</em> tokenizer (262k tokens). Same caveat as before, now with three families instead of two.</li><li><strong>Japanese costs more than English — for every model</strong> (each hatched bar is taller than its solid twin).</li></ul><p>But <em>why</em> is Japanese pricier, and why can’t we compare Japanese perplexity across families either? Look at how each tokenizer chops up the very same sentence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqSDW2InLCs1Q1GV3lYPmA.png" /><figcaption>The same Japanese sentence split into 18 tokens by Qwen3 (including 4 raw byte-fragments for one word) versus 14 tokens by Gemma-4</figcaption></figure><p>Gemma’s larger, more multilingual vocabulary swallows 「差し」「暖かい」「窓辺」 as whole units — <strong>14 tokens</strong>. Qwen3–0.6B’s smaller vocabulary splits the same sentence into <strong>18</strong> — and for 「窓辺」 (<em>windowsill</em>) it has no whole-kanji token at all, so it falls back to <strong>four raw UTF-8 bytes</strong>. Different number of prediction steps, over different chunks of text: the two perplexities are averaging <em>different things</em>. Not comparable, full stop — and the gap is even starker than it was in English.</p><h3>Reading the number: what counts as “good”?</h3><p>Lower is better — but with the caveat we just watched happen: <strong>perplexity is only comparable when the tokenizer is the same.</strong> That’s exactly why Qwen3.5–0.8B “lost” to a smaller Qwen3 above — its different tokenizer, not its ability. You can’t directly compare across tokenizers (GPT-2 vs Qwen3, or Qwen3 vs Qwen3.5); each splits text differently, which changes the math. Think of perplexity as a <strong>within-family yardstick</strong>: perfect for tracking a model as it trains (perplexity dropping = it’s learning), or comparing versions of the <em>same</em> model with the <em>same</em> tokenizer — not as an absolute quality score across different models.</p><h3>Why it matters</h3><p>Perplexity is the <strong>standard dashboard number</strong> for language models: it’s how researchers watch a model learn (the curve falling during training) and how they compare one version to the next. If you’ve seen a training run, you’ve watched perplexity drop.</p><p>It’s also exactly the number I leaned on throughout a recent series on converting Qwen3 into a new architecture — every “how close are we to the teacher?” check was a perplexity ratio. If you’d like to see perplexity used in anger, that’s where to look next.</p><p><em>All numbers here are real, measured on CPU in fp32 — Qwen3–0.6B/1.7B, Qwen3.5–0.8B, and Gemma-4-E2B/E4B, on English and Japanese.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ce1ea30d66b" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/what-is-perplexity-a-gentle-guide-with-qwen3-and-gemma4-7ce1ea30d66b">What Is Perplexity? A Gentle Guide (with Qwen3 and Gemma4)</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrofitting a New Architecture onto a Pretrained LLM: Converting Qwen3 into PHOTON by Distillation]]></title>
            <link>https://medium.com/@j.tech.reveil/retrofitting-a-new-architecture-onto-a-pretrained-llm-converting-qwen3-into-photon-by-distillation-7efdd208b7b4?source=rss-ac21d639db9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7efdd208b7b4</guid>
            <category><![CDATA[kv-cache]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[knowledge-distillation]]></category>
            <dc:creator><![CDATA[Jun Nishimura]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 18:53:34 GMT</pubDate>
            <atom:updated>2026-08-02T18:53:34.109Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 — reusing a trained model’s weights and teaching it a new shape, without pretraining.</em></p><blockquote><em>This is </em><strong><em>Part 2 of 3</em></strong><em>. [Part 1](</em><a href="https://medium.com/towards-artificial-intelligence/reading-vertically-photon-and-the-kv-cache-bottleneck-3e25b470bdcd">https://medium.com/towards-artificial-intelligence/reading-vertically-photon-and-the-kv-cache-bottleneck-3e25b470bdcd</a><em>) explained the PHOTON architecture — hierarchical, and far lighter on the growing KV cache (about </em><strong><em>16×</em></strong><em> in the (2,2) conversion we build here; the paper’s own from-scratch models report up to 10.8×). The catch was that PHOTON is </em>pretrained from scratch<em>. Here we try to skip that. Part 3 is the technical deep-dive, a demo, and an open-source release.</em></blockquote><h3>The bet</h3><p>PHOTON is an appealing way to generate text, but the paper’s every result comes from <strong>training a model from zero</strong> — which is exactly what most of us can’t afford. Meanwhile, we already have <strong>Qwen3–0.6B</strong>: 28 transformer layers full of hard-won knowledge, free to download.</p><p>So here’s the bet: <strong>keep those trained weights, rearrange them into PHOTON’s shape, and teach the new behavior by <em>distillation</em> instead of pretraining.</strong> If it works, you get PHOTON’s efficiency without PHOTON’s training bill.</p><p>This isn’t a wild idea — it’s the playbook of <strong>MOHAWK</strong> (Bick et al., 2024), which distilled Transformers into a completely different (SSM) architecture in stages. We adapt its staged approach — the hidden-state-matching and end-to-end stages — to convert a Transformer into PHOTON instead.</p><h3>Step 1 — the surgery</h3><p>Qwen3–0.6B is 28 layers in a flat stack. PHOTON needs four roles — two encoder stacks and two decoder stacks. So we <strong>split the 28 layers 7/7/7/7</strong> and drop each group into a role: enc¹, enc², dec², dec¹. The layers themselves are <strong>reused verbatim</strong> — not re-initialized, not re-authored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t68086F0jzDZ7ALM0LdY6A.png" /><figcaption>The surgery: reuse all 28 Qwen3 layers, weave in 4 small new modules</figcaption></figure><p>The only genuinely <em>new</em> parts are the pieces that make the hierarchy work — <strong>2 chunkers and 2 converters</strong> (from Part 1). Together they add just <strong>8.39M parameters, about 1.4%</strong> on top of the 0.6B we started with. Almost everything is inherited; very little is new.</p><h3>Starting sane — identity-mean init</h3><p>There’s a trap here. Those new chunkers and converters start out untrained. If you initialize them randomly, they feed the decoders <strong>noise</strong> for the first few thousand steps — and while they flail, the transferred Qwen3 attention weights drift badly, un-learning what they knew before any useful signal arrives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUED-a-tTZxnmnKAeQqVTQ.png" /><figcaption>Random init feeds garbage; identity-mean init is sane from step 0</figcaption></figure><p>The fix is to make the new modules start as something <em>sane</em>: initialize the chunker to <strong>average-pool</strong> and the converter to <strong>broadcast</strong>. At step 0 the network computes a lossy-but-reasonable “average, then copy back out” — so distillation becomes <strong>refinement</strong>, not a cold start from scratch.</p><h3>Prove the surgery first (S0)</h3><p>Before spending a cent on training, one sanity check. Run the freshly-assembled model in <strong>“bypass mode”</strong> — compression turned off (merge factor 1) — and confirm it reproduces <strong>stock Qwen3, bit-for-bit</strong>.</p><p>It does: maximum difference <strong>0.0</strong>. That golden test proves the wiring is exactly right — the reshapes, the layer order, the attention masks — <em>before</em> any of it can silently poison a training run. (Catching a wiring bug here costs minutes; catching it after a training run costs days.)</p><h3>Then distill — in stages</h3><p>You can’t just fine-tune your way across this gap; the architecture changed too much. So we teach the model in <strong>stages</strong>, each one harder than the last, each starting from where the previous left off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APNVShnPrVHYvQNOPxYWkg.png" /><figcaption>Distillation in stages — S0 surgery, S1 hidden matching, S2 compose + reconstruct</figcaption></figure><h3>Two ways to train: S1, then S2</h3><p>The interesting part is <em>how</em> the two training stages differ — and it’s the whole reason the conversion is tractable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzifN2NCOjeX1gZcfUhdyQ.png" /><figcaption>S1 is teacher-forced and decoupled; S2 runs composed end-to-end with a reconstruction loss</figcaption></figure><p><strong>S1 — match the hidden states (left).</strong> Freeze the hard problem. Train each block to reproduce the teacher’s activations at its depth — matched to a <em>pooled</em> version, since the student’s stream is compressed. Crucially, it’s <strong>decoupled and teacher-forced</strong>: every block is handed the teacher’s <em>real</em> inputs, so a mistake in one block can’t compound into the next. Each block learns its job in isolation.</p><p><strong>S2 — compose and reconstruct (right).</strong> Now take the training wheels off. Run the whole model <strong>end-to-end on its own outputs</strong> (no more teacher-forcing) — still matching the teacher’s final hidden state, but now <em>composed</em> rather than block-by-block — and add PHOTON’s <strong>recursive-consistency loss</strong> on top: the RecGen fixed point from Part 1, which pushes the decoder’s reconstruction to match the encoder’s latent.</p><h3>The scoreboard</h3><p>How far is the <em>composed</em> model — everything chained together, generating on its own — from the teacher it’s copying? We measure perplexity (lower = better; the teacher sits at 35).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVJA4EiPrXCwKAdZ0xT7Lg.png" /><figcaption>Teacher-gap after each stage: S1 33.3×, S2 20.5×</figcaption></figure><p>Real progress: <strong>33.3× after S1, down to 20.5× after S2.</strong> The composed model went from “hopelessly far” to “half as far.” And S2’s reconstruction got <em>excellent</em> — cosine similarity <strong>0.99</strong> between the decoder’s output and the encoder’s latent. The recursive loss did its job.</p><h3>The cliffhanger</h3><p>Which sets up the puzzle that took the rest of the project to crack.</p><p>After S2, the model <strong>reconstructs the teacher’s hidden states almost perfectly (0.99)</strong> — and yet it’s <strong>still ~20× worse than the teacher at actually predicting the next word.</strong> Reconstruction: solved. Prediction: stuck.</p><p>How can both of those be true at once? The answer surprised us, and it’s where Part 3 begins.</p><p><em>PHOTON is the work of Ichikawa et al. (arXiv:2512.20687). The staged distillation-to-convert approach follows </em><strong><em>MOHAWK</em></strong><em> (Bick et al., “Transformers to SSMs,” arXiv:2408.10189). This is an independent reproduction; the numbers here (33.3×, 20.5×, +8.39M, bit-exact, cos 0.99) are our own measured results on this Qwen3–0.6B conversion. All diagrams are my own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7efdd208b7b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading Vertically: PHOTON and the KV-Cache Bottleneck]]></title>
            <link>https://pub.towardsai.net/reading-vertically-photon-and-the-kv-cache-bottleneck-3e25b470bdcd?source=rss-ac21d639db9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e25b470bdcd</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[photon]]></category>
            <category><![CDATA[kv-cache]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Jun Nishimura]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 04:51:08 GMT</pubDate>
            <atom:updated>2026-08-02T16:04:42.201Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How a hierarchical architecture shrinks the growing KV cache — explained mostly in pictures.</em></h4><blockquote><em>This is </em><strong><em>Part 1 of 3</em></strong><em>. Here we explain the PHOTON architecture (Ichikawa et al., 2025). Part 2 retrofits it onto a pretrained Qwen3 by distillation; Part 3 is the technical deep-dive, a live demo, and an open-source release.</em></blockquote><h3>The bottleneck nobody optimizes away</h3><p>When a language model generates text, it produces one token at a time — and for every new token, it re-reads its entire memory of the conversation so far. That memory is the <strong>KV cache</strong>, and it has two nasty properties:</p><ol><li>It <strong>grows by one entry every single token</strong>, across <em>every</em> layer. 2. The work of <em>reading</em> it grows too — step 1 reads 1 entry, step 100 reads 100.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ufmZEZC9gIgHeJMVTnJEwA.gif" /><figcaption>The KV cache — and the reads — keep growing</figcaption></figure><p>Add those reads up and you get <strong>~t²/2</strong> total memory traffic to generate t tokens. On a modern GPU the arithmetic isn&#39;t the problem — <em>fetching that cache from memory</em> is. This is what people mean when they say &quot;decoding is memory-bound,&quot; and for long contexts or on-device models it&#39;s the wall that matters most.</p><p>Plenty of tricks chip at this — grouped-query attention, KV quantization, paged caches. They help, but they all keep the same basic shape: <strong>one flat sequence, re-read in full, forever.</strong> PHOTON asks a different question — <em>what if the sequence you re-read barely grew at all?</em></p><h3>The idea: stop reading horizontally</h3><p>A Transformer reads <strong>horizontally</strong> — left to right along one flat row of tokens. PHOTON reads <strong>vertically</strong>: it compresses tokens into a handful of coarse summaries and generates from <em>those</em>, keeping the full-resolution detail only in tiny local windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Az4vINFPqtsea-MDEfMneQ.png" /><figcaption>A Transformer reads horizontally; PHOTON reads vertically</figcaption></figure><p>The intuition: most of what you need from far-back context is a <em>summary</em>, not every word verbatim. So keep a running summary at the top of a pyramid, and only that top level has to persist as you generate.</p><h3>Three simple pieces</h3><p>The whole architecture is built from three small parts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmtcSTBasUfvfKuu63wdDA.png" /><figcaption>Chunker, converter, local decoder</figcaption></figure><ul><li><strong>Chunker</strong> — merges C neighboring tokens into a single coarse latent (compression).</li><li><strong>Converter</strong> — unpacks one parent latent into R short &quot;briefing&quot; vectors for the level below.</li><li><strong>Local decoder</strong> — reconstructs tokens inside a <strong>fixed window</strong> of R + C positions. Crucially, this window <em>never grows with context length</em> — it&#39;s always the same tiny size.</li></ul><p>That fixed window is the key. A normal decoder attends over everything it has ever seen; PHOTON’s local decoders attend over ~4 positions, no matter how long the document is.</p><h3>The shape: compress up, reconstruct down</h3><p>Stack those pieces and you get an hourglass. A <strong>bottom-up encoder</strong> compresses tokens into ever-coarser latents; a <strong>top-down decoder</strong> takes the coarsest summary and reconstructs the tokens back out, one local window at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaL5AKCNsRubnSTDHZoJPQ.png" /><figcaption>Bottom-up encoder compresses; top-down decoder reconstructs</figcaption></figure><p>Here’s the payoff hiding in that diagram: <strong>only the coarse stream at the top keeps a growing cache.</strong> The encoder’s fine levels are summarized upward and then dropped; the two decoder stacks never look back more than a handful of positions, so their caches have nothing to remember between chunks.</p><h3>One quick label: (C₁, C₂)</h3><p>You’ll see PHOTON described by two numbers — its <strong>compression schedule</strong> — and it’s worth pinning down, because everything else scales with it. The two numbers are simply the merge factors at each level: <strong>C₁</strong> is how many tokens the first chunker merges into one latent; <strong>C₂</strong> is how many of <em>those</em> it merges again into one summary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHjJupfyL7NfcDItJFbgTw.png" /><figcaption>What (C₁, C₂) means: our (2,2) vs the paper’s (4,4)</figcaption></figure><p>So <strong>(2,2)</strong> — the gentle setting we use to convert Qwen3 — merges 2, then 2 again: <strong>4 tokens under each summary.</strong> The paper’s headline <strong>(4,4)</strong> merges 4, then 4: <strong>16 tokens per summary</strong>, with correspondingly larger savings. Bigger numbers → more compression → more speedup → but a harder model to train. Keep the little (2,2) picture in mind; the next section is just it, in motion.</p><h3>Generating: 4 tokens, 1 cache entry</h3><p>Now watch what happens during generation. In a vanilla model, every token adds one entry to the growing cache. In PHOTON, one pass down the hierarchy produces a whole <strong>chunk of tokens</strong> but adds only <strong>one</strong> entry to the single growing stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*NF5CyBLaWu-D2j-ajlk3Ww.gif" /><figcaption>Same 16 tokens — who caches what</figcaption></figure><p>Two things compound here. PHOTON caches <strong>fewer moments</strong> (one entry per C₁×C₂ tokens — 4, at the (2,2) setting shown) <strong>and</strong> on <strong>fewer layers</strong> (only the top encoder stack). At the specific setup this series builds toward — Qwen3-0.6B split into 4 stages of 7 layers — that&#39;s 4× fewer moments × 4× fewer layers ≈ <strong>16× less growing cache.</strong> (That 16× is <em>our</em> conversion&#39;s arithmetic, not the paper&#39;s headline — the real paper numbers are below.)</p><h3>RecGen: refreshing the summary without re-reading</h3><p>There’s one subtlety left — and it’s the clever part. After you generate a chunk of tokens, the summary at the top is <strong>stale</strong>: it doesn’t yet know about the words you just wrote. Before you can generate the <em>next</em> chunk, you have to update it.</p><p>The obvious way is to take the new tokens and push them <strong>back up through the encoder</strong>. But that means re-reading them — exactly the cost we set out to avoid. PHOTON’s trick, called <strong>RecGen</strong> (recursive generation), sidesteps it in four small moves. Let’s take them one at a time.</p><p><strong>Step 1 — Decode down.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fp3EkZV2OCTB8_VOdMY2Gw.png" /><figcaption>Step 1 — the summary drives the decoders to write the next tokens</figcaption></figure><p>The current summary flows down through the decoders, which write the next few tokens. Nothing surprising yet — this is just normal generation.</p><p><strong>Step 2 — A free byproduct.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFqbvsKmWeUEGPnwq09KNg.png" /><figcaption>Step 2 — the decoders also produced a reconstruction along the way</figcaption></figure><p>Here’s the key observation. To produce those tokens, the top-down decoder had to compute a <strong>reconstruction</strong> of them along the way. That reconstruction is just <em>sitting there</em> — a free byproduct of decoding, no extra work.</p><p><strong>Step 3 — Refresh the summary (the trick).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Du5AGGgh2f6U-m6oTvveVw.png" /><figcaption>Step 3 — re-chunk the reconstruction to update the summary; the encoder is skipped</figcaption></figure><p>Instead of sending the new tokens all the way back up through the encoder (the dashed, crossed-out path), PHOTON applies just the cheap <strong>chunker</strong> to that reconstruction and uses the result as the updated summary. <strong>The encoder never runs on the new tokens at all</strong> — that’s the whole savings.</p><p><strong>Step 4 — Cache +1, then repeat.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpB5vI1hL5QydAACBJ7u5w.png" /><figcaption>Step 4 — the summary is current again and the growing cache grew by one</figcaption></figure><p>The summary is current again, the growing cache has gained <strong>exactly one</strong> entry, and we’re ready to generate the next chunk. Loop back to Step 1.</p><p><strong>So when is this exact?</strong> RecGen gives the same answer as <em>actually</em> re-encoding <strong>whenever the decoder’s reconstruction equals what the encoder would have produced.</strong> PHOTON trains a dedicated <em>recursive loss</em> to make that true. When it’s only <em>approximately</em> true, RecGen becomes an approximation — and measuring exactly how good that approximation is turns out to be a fun rabbit hole we’ll fall into in Part 3.</p><h3>The payoff: a much smaller growing cache</h3><p>Put it all together and the growing cache — the thing that dominates decode memory traffic — shrinks dramatically. Here’s the arithmetic for the specific setup this series builds toward: converting <strong>Qwen3–0.6B</strong> at the gentle <strong>(2,2)</strong> compression (that’s Part 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9zkzHHTjN6Qeiztfv087g.png" /><figcaption>Growing KV per token — our (2,2) Qwen3–0.6B conversion, ~16× (analytic)</figcaption></figure><p><strong>That ~16× is <em>our</em> conversion’s analytic number — not the paper’s.</strong> PHOTON’s own results come from models <strong>trained from scratch</strong> at a more aggressive <strong>(4,4)</strong> compression (600M / 900M / 1.2B parameters, on the Pile). What the paper actually <em>measures</em> is bigger and real, not idealized arithmetic: on a 1.2B model, <strong>KV memory 0.390 → 0.036 GiB (10.8×)</strong>, decode throughput <strong>43.8×</strong>, and up to <strong>~1⁰³× higher throughput per unit memory</strong> — their headline “tokens-per-memory” metric.</p><p><strong>Two honest caveats:</strong></p><ul><li><strong>The step-count speedup is config-dependent.</strong> At the gentle <strong>(2,2)</strong> setting <em>we</em> use, there’s <em>no sequential-step speedup at all</em> — every gain is <strong>memory traffic</strong> (still the dominant lever, since decode is memory-bound). At the paper’s <strong>(4,4)</strong>, PHOTON <em>does</em> post real wall-clock throughput gains (e.g. 2.3× for a from-scratch 600M model under RecGen). More compression, more speedup.</li><li><strong>Analytic ≠ realized.</strong> Our 16× is idealized arithmetic for one (2,2) conversion; the paper’s numbers are <em>measured</em> on different, from-scratch (4,4) models. Different systems, different settings — but the honest pattern is the same in both: real-world reductions land somewhat below the clean analytic figure once local caches, activations, and kernel overhead are counted. The reduction is real; it just isn’t free.</li></ul><h3>The catch — and what’s next</h3><p>PHOTON is a genuinely different way to generate text: read vertically, cache only the summary, reconstruct locally. But there’s a practical catch — <strong>it’s pretrained from scratch.</strong> Every result in the paper comes from training a PHOTON model from zero, which is exactly what most of us can’t afford.</p><p>So the question that kicked off this series: <strong>could you take an existing pretrained model — say Qwen3–0.6B — and <em>convert</em> it into the PHOTON architecture, cheaply, without pretraining?</strong></p><p>That’s Part 2.</p><p><em>PHOTON is the work of Ichikawa et al. — “PHOTON: Parallel Hierarchical Operation for TOp-down Networks” (arXiv:2512.20687). This series is an independent, distillation-based reproduction and study; all diagrams here are my own illustrations of their architecture.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e25b470bdcd" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/reading-vertically-photon-and-the-kv-cache-bottleneck-3e25b470bdcd">Reading Vertically: PHOTON and the KV-Cache Bottleneck</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Swap Is a Reflection: The Delta Rule Behind Qwen’s Efficient VLMs]]></title>
            <link>https://pub.towardsai.net/a-swap-is-a-reflection-the-delta-rule-behind-qwens-efficient-vlms-0634540426d6?source=rss-ac21d639db9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0634540426d6</guid>
            <category><![CDATA[gated-deltanet]]></category>
            <category><![CDATA[qwen]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nvidia]]></category>
            <dc:creator><![CDATA[Jun Nishimura]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 01:21:51 GMT</pubDate>
            <atom:updated>2026-07-02T11:30:02.092Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A linear-time recurrence has one fixed-size matrix for memory — no growing KV-cache. That sounds like a hard limit on what it can remember, yet a good write rule makes it the efficiency engine inside modern systems like Qwen — including their vision-language models, where images and video blow the token count into the thousands and cheap sequence mixing becomes essential. That write rule is Gated DeltaNet. Here it is, opened all the way up, on the one task where it cleanly beats Mamba-3: keeping track of a shuffle.</em></p><h3>The setup: one matrix, forever</h3><p>A Transformer answers “what did I see earlier?” by keeping every past token in a KV-cache and attending back over all of it. That cache grows with the sequence — quadratic attention, linear memory. Linear-attention models make a different bet: compress the entire past into a <strong>single fixed-size state matrix</strong> S and update it token by token. Constant memory, linear time.</p><p>The bet only pays off if S can actually hold what you need. And that comes down to two design choices — <strong>how you write</strong> into S, and <strong>how you forget</strong>. Gated DeltaNet (<a href="https://arxiv.org/abs/2412.06464">Yang et al., MIT · NVIDIA, ICLR 2025</a>) picks a particularly good pair, and the result is a recurrence with a surprising superpower: it can track a <em>permutation</em> — a running shuffle of items — perfectly, using a memory the size of a postage stamp. Mamba-3, the stronger model overall, cannot track it at all.</p><p>That dissociation is the whole story, and it’s visible cell by cell. Let’s build up to it.</p><h3>Fast weights: memory as a sum of outer products</h3><p>The starting point is the oldest idea in associative memory. Store a key→value association by adding an <strong>outer product</strong> to a matrix:</p><pre>S  ←  S + k ⊗ v          (write &quot;k means v&quot;)<br>o  =  Sᵀq                (read: what&#39;s stored for q?)</pre><p>If your keys are orthonormal, this is exact: reading with q = kᵢ returns vᵢ and nothing else. This is <em>linear attention</em> — the &quot;fast weights&quot; of a fast-weight programmer — and it&#39;s what makes the recurrence linear-time.</p><p>But it has two failure modes. First, <strong>interference</strong>: real keys aren’t orthonormal, so every write bleeds a little into every other association. Second, and worse, the write is <strong>blind and additive</strong> — write the same key twice with different values and you get their <em>sum</em>, not the new value. There’s no overwrite, and no forgetting. The memory just accumulates crosstalk until it’s mush.</p><p>Gated DeltaNet fixes exactly these two problems, with one idea each.</p><h3>Fix #1 — the delta rule: read before you write</h3><p>Instead of blindly adding, <strong>check what’s already there and write the correction</strong>:</p><pre>pred = Sᵀk                 read what k currently returns<br>corr = β (v − pred)        the ERROR, scaled by a write strength β<br>S    ← S + k ⊗ corr        write only the correction</pre><p>This is the <strong>delta rule</strong> (Widrow–Hoff, 1960), and it’s an error-correcting write. If k already returns the right value, pred = v, the error is zero, and nothing changes. If k returns a stale value, corr <em>subtracts the stale part and adds the new one</em> in a single step. Algebraically the update is S ← (I − βkkᵀ)S + βk vᵀ — that (I − βkkᵀ) factor is a <strong>projection</strong> (at β=1) or <strong>reflection</strong> (at β=2) that removes the old association before the new one lands. Overwrite, solved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fg3huUAcPX3EEJv_oKS9eA.gif" /><figcaption><em>The delta rule overwriting a stale association — </em>corr<em> subtracts the old value before writing the new one.</em></figcaption></figure><h3>Fix #2 — the gate: a learned forget</h3><p>The second fix is a scalar <strong>forget gate</strong> α = sigmoid(g) applied to the whole state each step:</p><pre>S  ←  α · S + k ⊗ β(v − Sᵀk)</pre><p>With α slightly below 1, old associations decay geometrically — the model can <em>let go</em> of information it no longer needs and reallocate that finite capacity. This is what &quot;Gated&quot; adds to plain DeltaNet, and it&#39;s the same trick that makes Mamba-2 work. β (the write strength) and α (the forget) are both learned per token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKFJdNX2RvkEF989dp3keQ.gif" /><figcaption><em>The forget gate decaying old memory so the fixed-size state doesn’t saturate.</em></figcaption></figure><p>That’s the entire model:</p><pre>S  ←  α · S  +  k ⊗ β( v − Sᵀk )        (write, with forget + delta correction)<br>o  =  Sᵀq                                (read)</pre><p>Two lines. The rest of this article is about <em>what those two lines can do that a diagonal SSM can’t.</em></p><h3>The task where the write rule matters: tracking a shuffle</h3><p>Here is a task designed to separate models: <strong>permutation tracking</strong>. Six items start in positions 0–5. A stream of <strong>swaps</strong> shuffles them — each swap exchanges the items in two positions. After the whole stream, we ask: <em>which item is now in position p?</em></p><p>This is the symmetric-group (Sₙ) word problem, and it’s a canonical <strong>state-tracking</strong> task. It’s hard for a specific reason: swaps <strong>don’t commute</strong>. Swap(0,1) then swap(1,2) lands somewhere different from swap(1,2) then swap(0,1). A model that can only <em>accumulate</em> or <em>rotate</em> information can’t track it — it has to actually <em>compose non-commuting operations</em> in its state.</p><p>Watch two real trained models run the same shuffle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71IDn-rrDDrYYW7xGRQY0Q.gif" /><figcaption><em>Top rows: the true permutation, Gated DeltaNet’s, and Mamba-3’s, updated swap by swap. Bottom: each model’s internal read-out </em>P(item | position)<em>. GDN&#39;s is a crisp permutation matrix that stays locked to the truth; Mamba-3&#39;s is diffuse and drifts off almost immediately.</em></figcaption></figure><p>The scoreboard, on held-out shuffles:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f992c3ce0a4a619566cad66cb190a9a/href">https://medium.com/media/5f992c3ce0a4a619566cad66cb190a9a/href</a></iframe><p>Mamba-3 does no better than guessing. Because <strong>a swap is a reflection</strong> — and the delta rule’s write is built out of reflections.</p><h3>The mechanism, one step at a time</h3><p>Here’s the key fact: the swap of positions <em>a</em> and <em>b</em> is a Householder reflection</p><pre>S  ←  (I − β k kᵀ) S ,   with   k = (eₐ − e_b)/√2 ,  β = 2</pre><p>That’s <em>exactly</em> the delta rule’s write factor. So a swap isn’t something Gated DeltaNet approximates — it’s the native operation of its recurrence. Let’s walk through it with the internals fully exposed. (These are the idealized values — k = (eₐ−e_b)/√2, v = 0, β = 2 — so the mechanism is legible; more on the trained model&#39;s messier reality below.)</p><p><strong>Step 1 — swap positions 0 and 1.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCSAwsrrm5Ip8B2FYorfjg.png" /></figure><p>The key k = (e₀−e₁)/√2 has <strong>exactly two nonzeros</strong>. That&#39;s not incidental: a swap couples <em>two</em> coordinates, so its key must span two dimensions — the difference direction between them (the reflection&#39;s mirror-plane normal). The written value v = 0, so the correction corr = β(0 − Sᵀk) = −β·pred is <em>pure reflection</em>: it reads what sits on the swap axis and subtracts twice it. The state S — a 6×6 matrix where row = position, column = item — goes from the identity to the identity with rows 0 and 1 exchanged.</p><p><strong>Step 2 — swap positions 0 and 2.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_2dUEME8s361HbMU68SIg.png" /></figure><p>Notice the subtlety: k is lit at positions 0 and 2, but pred = Sᵀk is lit at positions 1 and 2 — because pred reads the <em>current</em> contents on the axis, which already reflect step 1&#39;s swap. The reflection composes correctly regardless. The permutation is now [2,0,1,3,4,5].</p><p><strong>Step 3 — swap positions 1 and 3.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KcNSU5eYFlTX7VAeC6YuYQ.png" /></figure><p>A third reflection. The crucial thing: after three composed swaps, S is <em>still an exact permutation matrix</em> — one lit cell per row, no residue. Reflections compose into permutations, cleanly. State: [2,3,1,0,4,5].</p><p><strong>Step 4 — query position 0.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GcdjpQhK8EtbMataCPVHg.png" /></figure><p>Now the read. The query q = e₀ (a position), and o = Sᵀq pulls out <strong>row 0 of the permutation matrix</strong> — a one-hot vector pointing at item 2. Softmax turns it into a confident answer: <strong>position 0 holds item 2. ✓</strong> The state carried the entire shuffle in six-by-six numbers, and the read-out decodes any position in one dot product.</p><h3>Why Mamba-3 can’t</h3><p>Mamba-3’s state transition is <strong>diagonal</strong> — a per-channel complex eigenvalue, implemented as a rotation on <em>fixed</em> pairs of dimensions. Such a transition can <em>scale</em> each coordinate and <em>rotate</em> within a preset pair, but it can <strong>never reconfigure which coordinates couple</strong>: it cannot move mass between two coordinates that aren’t already in the same fixed rotation pair. And an arbitrary swap demands exactly that — coupling an arbitrary pair of positions, and a <em>different</em> pair at every step.</p><p>Put differently: the two-nonzero key is an <strong>off-diagonal coupling</strong>. It’s the thing a diagonal matrix structurally lacks. So Mamba-3 has no way to compose non-commuting swaps — it stays frozen near the identity and reads out noise (17.6% ≈ chance). This is a <em>representational</em> limit, not a training failure: no amount of data fixes a diagonal transition on a task that requires off-diagonal structure.</p><h3>Caveat: idealized vs. trained</h3><p>The step-by-step figures above use the <strong>idealized</strong> reflection — hand-set k = (eₐ−e_b)/√2, v = 0, β = 2 — so the state stays a pristine permutation matrix. The <strong>trained</strong> Gated DeltaNet that scores 100% behaves the <em>same way functionally</em>, but its internals are messier: its learned keys drift slightly off the exact (eₐ−e_b) direction, it learns a small nonzero v, and its write strength β settles at ≈ 1.5 rather than 2. Those partial, approximate reflections leave a little residue each step, which accumulates — so the trained model&#39;s real state looks like a <em>dense, noisy</em> matrix rather than a clean table. The read-out head learns to decode that messy state into a sharp answer anyway. The idealization shows the mechanism; the trained model shows it still works when the mechanism is only approximate.</p><h3>Why this matters: the block inside efficient VLMs like Qwen</h3><p>Permutation tracking is a stand-in for a whole class of problems that require composing operations that don’t commute — following a chain of pointer reassignments, tracking entity state through a narrative, executing a sequence of edits. The delta rule’s reflection structure is what lets a <em>linear-time</em> model do this at all.</p><p>That’s why the gated delta rule has become a real production building block, not just a research curiosity. <strong>Qwen’s</strong> efficient hybrid backbone, <strong>Qwen3-Next</strong>, stacks Gated DeltaNet and full-attention layers at a <strong>3:1 ratio</strong> — three linear-recurrence layers for cheap long-context memory, one attention layer to cover the exact recall that linear recurrence is weak at. That same backbone is what powers Qwen’s efficient <strong>vision-language models</strong>: a vision tower feeds thousands of image and video tokens into the Gated-DeltaNet language model. And it’s precisely because vision and video explode the sequence length that the linear-time block earns its keep — full attention over that many tokens is quadratic and quickly unaffordable, while Gated DeltaNet carries the entire context in one fixed-size state.</p><h3>Notes &amp; sources</h3><ul><li><strong>Paper:</strong> Songlin Yang et al., <em>Gated Delta Networks: Improving Mamba2 with Delta Rule</em> (MIT · NVIDIA), ICLR 2025 — <a href="https://arxiv.org/abs/2412.06464">arXiv:2412.06464</a>. Builds on DeltaNet and Mamba-2; the delta rule itself is Widrow–Hoff (1960), revived by the fast-weight-programmer line (Schmidhuber 1992; Schlag et al. 2021).</li><li><strong>State-tracking theory:</strong> <em>The Illusion of State in State-Space Models</em> (<a href="https://arxiv.org/abs/2404.08819">arXiv:2404.08819</a>); <em>Unlocking State-Tracking in Linear RNNs through Negative Eigenvalues</em> (<a href="https://arxiv.org/abs/2411.12537">arXiv:2411.12537</a>); <em>DeltaProduct</em> (<a href="https://arxiv.org/abs/2502.10297">arXiv:2502.10297</a>).</li><li><strong>Production usage:</strong> Qwen3-Next uses Gated DeltaNet for 3 of every 4 layers (3:1 hybrid with gated attention), and this efficient backbone underpins Qwen’s vision-language models — <a href="https://blog.vllm.ai/2025/09/11/qwen3-next.html">vLLM: Qwen3-Next hybrid architecture</a>, <a href="https://qwen.ai/blog?id=4074cca80393150c248e508aa62983f9cb7d27cd&amp;from=research.latest-advancements-list">Qwen3-Next blog</a>.</li><li><strong>Reproducibility:</strong> all figures are from small models (d = 6) trained from scratch on the tasks shown; the permutation model reaches 100% on held-out shuffles, Mamba-3 17.6%. The step-by-step internals use the idealized reflection for legibility, as disclosed above.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0634540426d6" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/a-swap-is-a-reflection-the-delta-rule-behind-qwens-efficient-vlms-0634540426d6">A Swap Is a Reflection: The Delta Rule Behind Qwen’s Efficient VLMs</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mamba3 in Three Animations]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://pub.towardsai.net/mamba3-in-three-animations-f1573608b169?source=rss-ac21d639db9d------2"><img src="https://cdn-images-1.medium.com/max/1000/1*i_QYObG-HvI2DIMtwqgK4g.gif" width="1000"></a></p><p class="medium-feed-snippet">The three changes that turn Mamba-2 into Mamba-3 &#x2014; each one watched, not just described. Two of the three animations are driven by real&#x2026;</p><p class="medium-feed-link"><a href="https://pub.towardsai.net/mamba3-in-three-animations-f1573608b169?source=rss-ac21d639db9d------2">Continue reading on Towards AI »</a></p></div>]]></description>
            <link>https://pub.towardsai.net/mamba3-in-three-animations-f1573608b169?source=rss-ac21d639db9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1573608b169</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mamba3]]></category>
            <dc:creator><![CDATA[Jun Nishimura]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 00:15:19 GMT</pubDate>
            <atom:updated>2026-07-01T07:11:24.896Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Mamba2 is literally attention. Here’s how.]]></title>
            <link>https://pub.towardsai.net/mamba-is-literally-attention-heres-how-62d16716087f?source=rss-ac21d639db9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/62d16716087f</guid>
            <category><![CDATA[mamba]]></category>
            <category><![CDATA[nemotron]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Jun Nishimura]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 09:17:33 GMT</pubDate>
            <atom:updated>2026-06-21T05:48:25.709Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mamba2 is Literally Attention. Here’s How.</h3><p><em>Part 2 of 3 — Mamba-2 and the State Space Duality. How the recurrence becomes a matmul, why Nemotron-H ships this one, for ML engineers who already speak fluent Transformer.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmAAMtVSy0gohtZffQlLsg.png" /></figure><h3>1. Why this one, why now</h3><p><a href="https://medium.com/medium_article_draft.md">Part 1 of this series</a> showed that any trained Mamba-1 layer can be rewritten as an attention matrix — the recurrence’s output decomposes into a content-weighted sum of past inputs, exactly the shape attention has. But that was an <strong>equivalence of functions</strong>, proved on paper after the fact. Mamba-1’s forward pass is a recurrence: carry a state, update it token by token, read it out. No L×L matrix is ever allocated. The attention matrix is something <em>you</em> write down to interpret the model — not a tensor the GPU ever holds.</p><p><strong>In Mamba-2 that rewrite isn’t a description. It’s the forward computation.</strong> The training kernel literally builds the matrices — CBᵀ (the scores), Λ (the decay mask), M = Λ ⊙ CBᵀ — as real tensors in memory, then multiplies y = M·x. That&#39;s an <strong>equivalence of computation</strong>, not just of functions: the model scores every pair of positions, masks, and takes a weighted sum of values because that is the sequence of ops it runs, not because of how we chose to read it.</p><p>Put differently, the arrow of derivation flips. In M1 the recurrence is primary and the matrix is <em>derived</em>; in M2 the matrix is primary — it’s how training computes — and the recurrence becomes the <em>derived</em> fast path for inference. (Two caveats keep this honest, both cashed out later: it’s structured <strong>masked</strong> attention, not softmax — there’s no exp-normalization, §7; and the literal construction is the training/dual form, while the inference recurrence computes the <em>identical</em> function by the SSD theorem, §6.)</p><p>That single shift is what made selective SSMs production-ready. Nemotron-H, IBM Granite-4, AI21 Jamba — the recent hybrids ship Mamba-2 layers, not Mamba-1. The reason is unfussy: M2 trains <strong>2–8× faster</strong> at matched parameter count, supports a much larger state dimension (d_state 64–256 vs M1’s 16), and the kernel is plain tensor-core matmul rather than a custom CUDA selective-scan.</p><p>This article is about <em>how</em> one design choice — restricting the state matrix A from a diagonal of N distinct rates down to a single scalar — unlocks all of that, and how the “Mamba is attention” reading sharpens from rhyme into identity. Same TinyStories setup as Part 1: a small 6-layer M2 trained alongside the same parameter-matched Transformer, the same prompt for the comparison figure, so you can put the two articles’ heatmaps next to each other.</p><p>No code in the post — just the math and the pictures. The notebooks and a fully-worked code tutorial are linked at the bottom.</p><h3>2. The three moves (Mamba-2 in one paragraph)</h3><p>Dao &amp; Gu’s 2024 paper (<em>Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality</em>) makes three changes to Mamba-1:</p><ol><li><strong>A becomes scalar.</strong> Where M1’s A was a diagonal matrix with N distinct decay rates per channel (the HiPPO spectrum we plotted in Part 1’s section 4), M2 sets A_t = a_t · I — one decay rate per head per token. All N state slots inside a head share that decay at each step.</li><li><strong>The recurrence becomes a structured matrix multiply.</strong> Unrolling the SSM with scalar A gives y = M · x where M = Λ ⊙ (CBᵀ). Λ is a lower-triangular <em>scalar decay mask</em> with Λ[t,j] = ∏ ā_k for j+1 ≤ k ≤ t, and CBᵀ is an L×L content-similarity matrix — exactly the shape of attention scores. This is the <strong>State Space Duality</strong>: the same SSD computation can be evaluated as a recurrence (linear cost, fixed state memory) or as a matmul (quadratic cost, all dense matrix ops), and the two views agree by construction.</li><li><strong>The block reshapes into multi-head.</strong> Channels regroup into H heads of width P (so d_inner = H·P). Δ promotes from per-channel to per-head. B and C are shared across head groups, GQA-style. Per-channel timescale diversity is gone, but you get capacity back by having more heads at a larger d_state.</li></ol><p>The payoff is hardware. Forming Λ, forming CBᵀ, taking their Hadamard product, and computing M · x are all dense matrix operations — exactly what GPUs and TPUs want. The linear recurrence still exists (and is what inference uses), but training rides the quadratic dual.</p><p>The rest of this post earns those three claims one at a time: §3 shows where the recurrence comes from and why “scalar A” is the load-bearing choice, §6 unrolls it into M, and §5/§7/§8 look at what the resulting matrix actually does.</p><h3>3. From an ODE to a recurrence: the one scalar that changes everything</h3><p>Before we can say “the recurrence becomes a matrix,” it’s worth being honest about where the recurrence itself comes from — because that’s where the scalar-A choice does its work.</p><p>A selective SSM begins life as a <strong>continuous</strong> system. For a single state channel, with state h(s) ∈ ℝ^N:</p><pre>dh/ds = a · h(s) + B · x(s),      y = C · h</pre><p>To run it on a sequence of tokens you have to <strong>discretize</strong> — turn the continuous derivative into a per-step update. The standard move (zero-order hold) is to integrate the ODE across one step of size Δ, holding the input fixed across that step. The exact solution of a linear ODE over one step has two pieces: the old state, shrunk by an exponential of the elapsed &quot;time,&quot; plus the new input, written in:</p><pre>h_t = exp(Δ_t · a) · h_{t-1}  +  (input gain) · B_t · x_t<br>        └──── decay ā_t ────┘</pre><p>The decay factor ā_t = exp(Δ_t · a) is the entire story. Three observations:</p><ul><li><strong>Δ_t is the selective timestep.</strong> It&#39;s a positive number the model emits per token (Δ_t = softplus(W_Δ x_t)). Large Δ_t → ā_t near 0 → forget the past aggressively; small Δ_t → ā_t near 1 → hold the state. This is the &quot;selective&quot; in selective SSM, and it survives untouched into M2.</li><li><strong>a is where M1 and M2 part ways.</strong> In Mamba-1, a is the n-th diagonal entry of A — a <em>different rate for each of the N state slots</em>. In Mamba-2, a is <strong>one scalar per head</strong>: every slot in a head decays at the same rate at each step. That is the whole of &quot;A = a·I.&quot;</li><li><strong>The input gain quietly disappears.</strong> The exact discretization puts a gain on the input term too (it tends to Δ_t in the small-step limit — that&#39;s M1&#39;s familiar Δ_t B_t x_t). M2&#39;s clean presentation folds that gain into the already-learned B projection, so Δ ends up living <em>only</em> in the decay. It&#39;s a mild simplification, not an identity — but it&#39;s why every Δ you&#39;ll see from here on sits inside ā, never on the write. (The full zero-order-hold derivation, including why dropping the gain is safe, is in the code tutorial linked at the end.)</li></ul><p>Why does making a a scalar matter so much? Because of what it does to the <em>next</em> step. When a is a single number, ā_t is a single number — a plain scalar multiplier on the whole state. And a scalar multiplier is something you can pull out of a sum. That one algebraic fact is what lets the recurrence collapse into a clean matrix in §6. With M1&#39;s per-slot diagonal A, the decay is trapped inside the state and no such collapse exists. The scalar isn&#39;t a minor simplification of the recurrence; it&#39;s the hinge the entire matrix view swings on.</p><h3>4. Selectivity survives</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lzx13LnxCW4sh9BDDTEqg.png" /></figure><p>The thing that made Mamba <em>Mamba</em> — Δ as a content-aware write gate — is still there. This is a Δ heatmap from the same selective-copy task as Part 1’s fig 1, but the rows are now <strong>heads</strong> (M2 has H=8 here, sharing Δ within each head) instead of channels. The pattern is the same: most of the sequence sits at Δ ≈ 0, and at the few positions holding a real content token, certain heads light up.</p><p>What changed visually: only a couple of heads (4 and 7 in this run) carry the selective firing. The rest stay dark. M1 spread the same job across hundreds of channels; M2 concentrates it into a handful of heads, each operating on a much larger N-dimensional state. The mean-Δ panel at the bottom shows the per-head spikes still cleanly track real-token positions even after averaging — the same content-aware write gating, just coarser-grained and louder per head.</p><p>The selectivity that gave the family its name isn’t what M2 traded away.</p><h3>5. What A = a·I actually costs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X28-MYSSeIABBAcVdOZVKw.png" /><figcaption>In Part 1, section 4 showed M1’s memory-horizon spectrum: each of the N=16 state slots inside a channel had its own A^(n) initialized to −n, giving an almost-linear staircase of half-lives from ~100 tokens at n=0 down to ~6 at n=15. That ladder <em>inside</em> a single head was M1&#39;s headline structural fact — one layer, many timescales, baked into A&#39;s diagonal.</figcaption></figure><p>In M2, that ladder vanishes. With A_t = a_t · I, every slot inside one head decays at the <em>same</em> rate at every step. There is no longer a &quot;long-horizon slot&quot; and a &quot;short-horizon slot&quot; within a head; there is just one number, picked per token by the model.</p><p>The figure shows the half-life picture from the trained 6-layer M2 at layer 3. The ladder isn’t gone — it has <em>moved across heads</em>. Head 1 holds ~1⁰⁵ tokens of memory (the bright yellow stripe in the heatmap); head 3 forgets in a fraction of a token; heads 0 and 2 sit between at a few hundred to a few thousand tokens. Each head settles on a characteristic timescale and varies modestly around it per token — head 3 varies the most, its ā collapsing on specific tokens to overwrite the state. The diversity M1 baked into A&#39;s diagonal initialization, M2 distributes across heads.</p><p>That tradeoff is real. On paper, M2’s per-layer expressive class is strictly smaller than M1’s — you’ve lost the ability to hold multiple horizons in the same head simultaneously. In practice, two compensations close the gap: heads multiply the number of decay rates available at any given timestep, and d_state grows from 16 to 64–256, so each head carries much more capacity. Whether the cross-head ladder beats the per-slot ladder is an empirical question; the paper’s answer is “comfortably, once you scale heads × d_state past this toy regime.”</p><h3>6. The unroll: how a loop becomes a matrix</h3><p>Here’s the move the whole paper is built on, and with §3 in hand it’s three lines of algebra. Take the discretized recurrence — decay the state, write the new input, read it out:</p><pre>h_t = ā_t · h_{t-1} + B_t · x_t,      y_t = C_t · h_t</pre><p><strong>Unroll it by back-substitution.</strong> Feed in an input at step j and follow it forward. It&#39;s written in fresh at j, then shrunk by ā_{j+1} at the next step, by ā_{j+2} after that, and so on, until you read out at step t. So the contribution of x_j to the state at time t is x_j multiplied by <em>every decay in between</em>:</p><pre>h_t = Σ_{j ≤ t}  (∏_{k=j+1}^{t} ā_k) · B_j · x_j</pre><p>Now read it out with C_t. The decay factor is a scalar and C_t · is linear, so both slide inside the sum:</p><pre>y_t = Σ_{j ≤ t}  (∏_{k=j+1}^{t} ā_k) · (C_t · B_j) · x_j</pre><p>That is an input→output map y_t = Σ_j M[t,j] · x_j. Read off the coefficient of x_j:</p><pre>M[t,j] = (∏_{k=j+1}^{t} ā_k) · (C_t · B_j),    for j ≤ t   (and 0 for j &gt; t)<br>         └──── scalar decay ────┘   └── dot product ──┘</pre><p><strong>This is exactly where the scalar A pays off.</strong> Inside M1, the decay lives <em>inside</em> the sum over state slots — each slot n decays at its own rate A^(n), so you cannot separate &quot;how much does t care about j&quot; from &quot;how aged is that signal.&quot; With scalar a, the decay is the same for every slot, so it factors straight out of the sum, and what&#39;s left, Σ_n C_t^(n) B_j^(n), collapses into a single inner product C_t · B_j — the literal analogue of a Q·K score. The scalar didn&#39;t simplify the recurrence so much as it <em>untangled</em> score from decay.</p><p>Stack M[t,j] over all pairs (t,j) and the two factors separate into two matrices:</p><pre>M = Λ ⊙ (CBᵀ),     Λ[t,j] = ∏_{k=j+1}^{t} ā_k</pre><p>One more practical point, because it’s why this is fast and not just elegant. You never compute that product directly. Since ā_k = exp(Δ_k a), a product of decays is the exponential of a <em>sum</em> of log-decays — and a sum over a range [j+1, t] is just a difference of running totals. One cumulative sum over the sequence, one outer-difference, one exp, and the entire L×L mask Λ falls out — no loops, no underflow from multiplying hundreds of sub-1 numbers. That cumulative-product-as-prefix-sum structure is also exactly what makes Λ a <strong>1-semiseparable matrix</strong> (every off-diagonal block is rank-1), the property that lets the same matrix multiply be re-evaluated as a linear-time recurrence. Duality, made of one cumsum.</p><h3>7. The structured matrix view</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lJojLLKZVM7rZnlWz75GA.png" /><figcaption>§6 was the algebra; this is the picture. The left panel is <strong>Λ</strong> alone — the soft causal decay mask we just built, Λ[t,j] = ∏ ā_k. Lower-triangular by construction (causality), diagonal equal to 1 (the current token enters un-decayed), and each subdiagonal extends the one above it by one more ā factor. The middle panel is <strong>CBᵀ</strong> — the content-similarity matrix, same shape as a Transformer&#39;s QKᵀ, and notably <em>not</em> causal on its own and shared across heads. The right panel is the Hadamard product M = Λ ⊙ (CBᵀ) — the full structured &quot;attention&quot; matrix Mamba-2 multiplies against the input.</figcaption></figure><p>Read the three panels as a division of labor: <strong>CBᵀ decides what’s relevant, Λ decides what’s still in reach, and M is their product.</strong> The causal triangle comes entirely from Λ; the texture comes entirely from CBᵀ.</p><p>If you set every ā_k = 1 (no decay), Λ becomes the standard causal 0/1 mask and M reduces to plain linear attention. So Mamba-2 is literally <strong>&quot;causal linear attention with a learned multiplicative decay mask&quot;</strong> — and the mask is what gives it expressive power that plain linear attention does not have. Look at Λ on its own: that&#39;s the only piece without a Transformer analogue, and it&#39;s the entire structural prior that separates the two families.</p><h3>8. The reveal: same prompt, three matrices</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Nm_swa3fX28FHONnsnp-g.png" /><figcaption>The same prompt from Part 1 — <em>“Lily had a red ball. Tom had a blue ball. Lily wanted to play, so she gave her”</em> — through three layer-3 representations: Mamba-1’s implicit |M| (the post-hoc decomposition from Part 1), Mamba-2’s M (computed <em>directly</em> as Λ ⊙ (CBᵀ), no unrolling), and the Transformer&#39;s softmax attention.</figcaption></figure><p>Three things to notice.</p><p><strong>M2 is actually softer than M1 here — and §5 says why.</strong> M1’s diagonal trace is crisper; M2’s pattern spreads more uniformly across the lower triangle. That’s the opposite of what the averaging math alone would suggest: M1 averages |M| over 512 channels, M2 over only 4 heads, so fewer terms in the mean should give a sharper picture. The explanation is in §5: head 1 holds memory across the entire prompt (Λ ≈ I... rather, Λ ≈ 1 on the whole lower triangle), so its contribution to the head-mean M is essentially |C·Bᵀ| — a dense matrix with no causal falloff. That one long-memory head dominates the head-average and washes out the others. At production scale (M2 routinely runs 24–32 heads, not 4), no single head dominates the mean this way.</p><p><strong>Both M1 and M2 are softer than the Transformer.</strong> Softmax produces hard, nearly one-hot weighting at peaks; M2’s mask is monotone-decaying but not normalised, so it spreads. The pattern rhymes with attention, but the <em>type</em> of weighting still differs — there is no exp-of-scores normalization anywhere in M2.</p><p><strong>The bright leftmost column persists in all three.</strong> In M1 and M2 it’s partly structural (early positions accumulate the most decay-survival inside Λ); in the Transformer it’s the well-studied attention-sink phenomenon. Three different mechanisms, one converging visual.</p><p>The honest read is the same as Part 1: at this toy scale, on this prompt, the routing patterns rhyme. What Part 2 adds is the <em>computational</em> identification — M2 and the Transformer now agree not just in interpretation but in <em>form</em>. Both compute (structured mask) ⊙ (content score) · values. M2&#39;s mask is learned, soft, multiplicative; the Transformer&#39;s is a hard causal 0/1 followed by softmax normalization. Whether the rhyme survives long-context retrieval at production scale is the open question hybrid stacks are implicitly betting on.</p><h3>9. Why production stacks ship Mamba-2</h3><p>Three reasons, in order of how loudly they show up in benchmarks.</p><p><strong>Wall-clock training.</strong> M1’s selective-scan kernel is fast but does sequential scalar updates that don’t use tensor cores well. M2’s training reduces to a sequence of dense matmuls — CBᵀ, the cumulative log-sums forming Λ, the Hadamard, and M·x, all of which sit in tensor-core sweet spots. <a href="https://arxiv.org/abs/2405.21060">The paper</a> reports the SSD core layer is <strong>2–8× faster</strong> than Mamba-1’s optimized selective scan — a layer-level speedup, and one that comes precisely because the work is now dense matmul on tensor cores. That’s the line that turns a research architecture into something you can train at scale on a fixed budget.</p><p><strong>Larger d_state.</strong> Dropping A from diagonal to scalar also drops the cost of growing N. M1 carried d_state = 16; M2 routinely runs at 64, 128, or 256. That’s the same trade Transformers made when going from MHA’s small d_head to GQA’s larger d_head per remaining head — more capacity per head, fewer total heads, simpler kernel.</p><p><strong>Shared kernel surface with attention.</strong> Because the M2 forward is (Λ ⊙ CBᵀ) · x, a lot of the same chunking, recompute, and FlashAttention-style tiling tricks apply directly. In practice the real kernel never materializes the full L×L matrix at all: it cuts the sequence into chunks, does the dense dual form <em>within</em> each chunk, and passes a single rank-1 state across chunk boundaries (that 1-semiseparable property from §6). The chunked block algorithm is essentially &quot;FlashAttention with a multiplicative decay mask.&quot; The same engineers writing fast attention kernels can write fast SSD kernels.</p><h3>What’s next in the series</h3><ul><li><strong>Part 3 — Mamba-3.</strong> What the line does after SSD: the next iteration on the selective-SSM family. Covered when there’s enough public detail to say something visual about it.</li></ul><h3>References</h3><ul><li>Dao, T. &amp; Gu, A. (2024). <em>Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Mamba-2).</em> <a href="https://arxiv.org/abs/2405.21060">arXiv:2405.21060</a>.</li><li>Gu, A. &amp; Dao, T. (2023). <em>Mamba: Linear-Time Sequence Modeling with Selective State Spaces.</em> <a href="https://arxiv.org/abs/2312.00752">arXiv:2312.00752</a>.</li><li>Ali, A., Zimerman, I. &amp; Wolf, L. (2024). <em>The Hidden Attention of Mamba Models.</em> <a href="https://arxiv.org/abs/2403.01590">arXiv:2403.01590</a>.</li><li>Lieber, O. et al. (2024). <em>Jamba: A Hybrid Transformer-Mamba Language Model.</em> <a href="https://arxiv.org/abs/2403.19887">arXiv:2403.19887</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62d16716087f" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/mamba-is-literally-attention-heres-how-62d16716087f">Mamba2 is literally attention. Here’s how.</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mamba is attention. Here’s what it looks like.]]></title>
            <link>https://medium.com/@j.tech.reveil/mamba-is-attention-heres-what-it-looks-like-58a5e0acf814?source=rss-ac21d639db9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/58a5e0acf814</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mamba]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[nemotron]]></category>
            <category><![CDATA[state-space-model]]></category>
            <dc:creator><![CDATA[Jun Nishimura]]></dc:creator>
            <pubDate>Wed, 27 May 2026 04:57:32 GMT</pubDate>
            <atom:updated>2026-05-27T04:57:32.593Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 1 of 3 — the original selective SSM (Mamba-1). A visual tour of the layer that grew into Nemotron-H, Jamba, and Granite-4, for ML engineers who already speak fluent Transformer.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nszh71tTONBkCXF1Imc2pA.png" /></figure><h3>1. Why bother now</h3><p>Mamba is no longer a paper. NVIDIA’s Nemotron-H, AI21’s Jamba, TII’s Falcon-Mamba, IBM’s Granite-4 — every recent “frontier-adjacent” release ships some flavour of state-space layer in the stack. The headline feature (“linear cost in sequence length”) is well-known. Less well-known: <strong>a trained Mamba layer can be rewritten exactly as an attention matrix, and you can plot it next to a real Transformer’s.</strong></p><p>That’s what this article is about. We’ll skim the SSM math just enough to make the visuals legible, then spend most of our budget staring at four figures pulled from a small Mamba I trained on TinyStories alongside a parameter-matched Transformer. By the end you’ll know what “selective” means visually, why one Mamba layer holds many memory horizons at once, and what’s actually different — and what’s surprisingly similar — about how the two architectures route information.</p><p>A scope note: this article covers <strong>Mamba-1</strong> — the original selective SSM from Gu &amp; Dao (2023). Production hybrids like Nemotron-H actually ship <strong>Mamba-2</strong>, which reframes the same recurrence as a structured matrix multiply (the “SSD” form) to get attention-style hardware efficiency. Part 2 of this series picks the story up there; Part 3 will cover Mamba-3. Everything below is the foundation those variants build on.</p><p>No code in the post. The notebooks are linked at the bottom if you want to reproduce.</p><h3>2. SSM in 30 seconds</h3><p>A continuous-time linear SSM is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*2zV7oVoc86UYyK19f6JN2w.png" /></figure><p>Discretise with step size Δ and you get the recurrence every Mamba post writes down:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*oGmvi9dbNO92HbDnfHWF7Q.png" /></figure><p>with Ā = exp(ΔA) and B̄ ≈ ΔB. So far this is just a linear RNN with a particular parametrization.</p><p>The Mamba (S6) twist is one line: <strong>Δ, B, and C are produced from x_t by linear projections</strong>, instead of being fixed parameters. Only A stays input-independent. That single change — making the recurrence’s coefficients functions of the current input — is what “selective” means in “selective state-space model.” It’s also why S6 dramatically outperforms S4 on tasks where the model needs to <em>decide</em> whether a given token is worth remembering.</p><p>Mechanically, a Mamba layer is D independent scalar SSMs running in parallel — one per channel — sharing only the B and C vectors that read and write the N-dimensional state. In our trained model D = 512, N = 16. So the hidden state h_t has shape (D, N) = (512, 16): think of it as 512 little memory cells, each carrying a 16-dimensional summary of the past at its own timescale. The next three figures are different views of that buffer.</p><h3>3. What “selective” looks like</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPxXzUVq8wK6SSa8uoWp5g.png" /></figure><p>This is Δ_t for layer 0 of the trained Mamba, on a 64-token sequence. Rows are channels (d = 0, …, 63 shown), columns are token positions, brightness is the value of Δ. The bottom panel is the mean over channels; the red verticals mark positions where a real, content-bearing token was seen (vs. padding/filler).</p><p>The striking thing is how spiky it is. Most of the sequence is dark — Δ ≈ 0.025, near the floor. At a handful of positions the whole stripe lights up, sometimes saturating around Δ ≈ 1.6. Those spikes line up with the red verticals: the model has learned to fire Δ on real tokens and stay quiet on filler.</p><p>Why does that matter? Because Δ does double duty in the recurrence. The discrete decay is Ā = exp(ΔA) with A &lt; 0, so a small Δ keeps Ā ≈ 1 — the state coasts, barely changing. A large Δ drives Ā → 0 and overwrites the state with the current input. Simultaneously, the discrete write gain B̄ ≈ ΔB scales linearly with Δ, so a small Δ also means “barely write anything new.” A single learned quantity decides <em>both</em> what to keep and what to write. The heatmap is showing that learned policy in action: most tokens, do nothing; on the tokens that matter, take a big step.</p><p>This is the difference between Mamba and its predecessor S4. S4’s Δ was per-channel but <strong>fixed</strong> — every token got the same gate. S6 made Δ a function of x_t, and the model promptly learned to use it as a content-aware write gate. The bottom panel makes the result vivid: filler tokens get Δ ≈ 0.025; content tokens get Δ thirty to seventy times larger. That is the entire selectivity mechanism, in one picture.</p><h3>4. One layer holds many memory horizons</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N061Gb1TR7o0YvslVewrwQ.png" /></figure><p>For each (channel, state) cell (d, n), the per-step decay is Ā^(d,n) = exp(Δ · A^(d,n)), and the <em>memory half-life</em> — how many tokens until a past input’s contribution decays to half — is just log(0.5) / log(Ā). The figure plots the half-life of all D·N = 1024 cells in layer 0, using the typical Δ ≈ 0.007 the model actually applies at runtime.</p><p><strong>Left panel: the spectrum is broad and right-skewed.</strong> The x-axis is half-life in tokens, log-scaled. Most cells cluster between 3 and 15 tokens — the bulk of layer 0’s memory is short-range. A thin tail extends past 100 tokens; a small subset of cells holds genuinely long context. There is no single horizon; there is a distribution of horizons.</p><p><strong>Right panel: the spectrum is structured.</strong> For each of the N=16 state components, take the median half-life across the channels. The y-axis is log-scaled, and you get an almost-linear staircase: n=0 lives ~100 tokens, n=15 lives ~6, with each step roughly geometric in between.</p><p>That ladder is not an accident. Mamba initialises A_n = -1, -2, …, -N (a HiPPO-style spectrum), so before training, n=0 already decays slowest and n=15 fastest. What’s interesting is that training <strong>mostly preserves</strong> that ordering rather than learning it away. The model accepts the inductive bias and tunes the channels within it, instead of rebuilding the structure from scratch.</p><p>For a Transformer reader, the analogy is multi-head attention with a <em>fixed</em> per-head receptive field. Each n is like a head with a baked-in time scale; the per-channel Δ is what lets the model still tune behaviour within each “head.” One layer, many heads, many timescales — already, before we get to attention.</p><h3>5. What is “the state,” actually</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJpj1SR_bZvIf9l8vXJ47g.png" /></figure><p>“Hidden state” gets thrown around as if it were a vector. In Mamba it’s a matrix: h_t ∈ ℝ^(D×N), where rows are channels and columns are state components. Each row d runs an independent scalar SSM; each column n holds that channel’s contribution at one of the timescales we just saw in section 4.</p><p>The figure shows snapshots of h_t at nine positions through the sequence. Red is positive, blue negative, white near zero. The highlighted panel (t=40, marked ★) is a position where a real, content-bearing token landed — note the sharper, more structured mass than the neighbours. That’s a Δ spike doing what section 3 told us to expect: writing strongly into the state.</p><p>Two things to take away. The state is not a summary vector; it’s a structured 2D buffer, and you can read off <em>which channels</em> have woken up. And the build-and-decay rhythm is the recurrence working in plain sight: new content flows in at gate openings, then leaks out across positions at the per-channel timescale. This figure is what fig 1 (when to write) and fig 2 (how long it persists) actually look like once you let them play out.</p><h3>6. Mamba is attention</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DPEfXISQ5E5hLCn0uFlVg.png" /></figure><p>The recurrence is linear in x. Substituting h_t into itself t times and rearranging, the output cleanly factors as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*vjrwXUGNzCEMDDbWxtOffA.png" /></figure><p>Stare at the three factors of M[t, j]. The dot product Σₙ Cₜ⁽ⁿ⁾·Bⱼ⁽ⁿ⁾ is structurally identical to a Transformer’s Qₜ·Kⱼᵀ — a content-based affinity between the readout at t and the write at j. The Δⱼ in front is a write-gate. The exponential decay is the only piece without a Transformer analogue: a soft, learned recency bias. So the SSM output is a content-weighted sum of past inputs, exactly like attention, with one structural prior baked in.</p><p>The figure puts these matrices side by side. Two representative layers from each architecture — layer 0 (top row) and layer 3 (bottom row) — Mamba’s |M| on the left, the parameter-matched Transformer’s softmax attention on the right, both on the same prompt (<em>“Lily had a red ball. Tom had a blue ball. Lily wanted to play, so she gave her”</em>).</p><p><strong>Layer 0 (top row).</strong> This is where the two architectures look most different. Mamba’s M concentrates almost entirely on the first column — a strong recency-and-sink pattern with a barely visible diagonal. The Transformer shows the same leftmost-column dominance, but with much more diffuse off-diagonal glow and a slightly sharper local-context diagonal.</p><p><strong>Layer 3 (bottom row).</strong> Mid-stack, the two converge visually. Both heatmaps now show bright leftmost columns, a clear diagonal trace, and scattered off-diagonal mass — Mamba via Δ-gated decay accumulating along the recurrence, the Transformer via softmax attention to sink positions.</p><p>The honest read is <em>“the patterns rhyme at this scale,”</em> not <em>“the mechanisms converged.”</em> Two caveats keep that distinction sharp. First, Mamba’s brightness on early columns is partly a mathematical tilt: those positions accumulate the most decay-survival in the formula above, so some of the stripe is structural rather than a learned routing decision. The Transformer’s leftmost-column brightness is the well-studied attention-sink phenomenon and is more clearly a learned behaviour. Second, both models here are small, trained briefly on TinyStories, and the heatmaps are computed on a single 22-token prompt — neither has been pushed to a regime where long-range coreference or retrieval would force the patterns to specialise. Whether the visual similarity holds at Nemotron scale on long, content-dense inputs is an open question; this figure is one data point.</p><p><strong>The interpretive gotcha.</strong> A bright cell at M[i, j] does <em>not</em> mean Mamba retrieved x_j when computing y_i. Mamba never stores past inputs — only the running h_t. The matrix exists only as a mathematical decomposition of what the recurrence computed. Ali, Zimerman, and Wolf’s <a href="https://arxiv.org/abs/2403.01590"><em>Hidden Attention of Mamba Models</em></a> made this rigorous: an SSM’s output can always be written as a content-weighted sum, and the resulting weights have the same interpretive value as attention scores — even though no retrieval ever happened.</p><p>One caveat on the figure: it averages |M⁽ᶜ⁾| over all 512 channels and row-normalises. Sharp single-channel signals — a coreference spike at one specific (i, j) — get diluted by the 500+ uninteresting channels. Per-channel matrices are much sparser; the average is what you see when you can’t pick the channel.</p><h3>7. Why industry is adopting it</h3><p>Linear cost in sequence length is the headline reason to ship Mamba in 2026. The practical reason is more specific: <strong>KV-cache memory at long context.</strong> A Transformer at 1M-token context needs gigabytes of KV cache per request and pays for it on every generated token. A Mamba layer only needs the constant-size hidden state plus a 4-token conv window — total cache regardless of context length is a few hundred kilobytes. For inference-bound deployments, that’s the line that matters.</p><p>So why aren’t production stacks pure Mamba? The figure in section 6 shows the answer. Mamba’s content routing is real, but <em>softer</em> than attention’s — its |M| is dominated by smooth decay rather than sharp spikes. For tasks that need precise content lookup (coreference, retrieval-style copying, in-context citation), attention’s hard, peaked weighting wins. Pure-Mamba models trained at scale (Mamba-2, Falcon-Mamba) work well, but on long-context recall benchmarks they consistently trail hybrids.</p><p>Hence the modern recipe, visible in Nemotron-H, Jamba, and Granite-4: <strong>mostly Mamba, with a few attention layers sprinkled in.</strong> The Mamba layers carry bulk sequence mixing at linear cost; the attention layers — typically every 4th to 8th block — handle the sharp content-lookup work that the heatmap of section 6 shows Mamba doing softly. You get Mamba’s cost profile and attention’s precision in the same model.</p><p>The headline isn’t “attention is dead.” It’s that attention is becoming a specialty layer rather than the default. Mamba is the boring, cheap layer that handles most of what attention used to. Section 6 is one data point for why that handoff <em>might</em> be reasonable: even on a tiny TinyStories model, the routing patterns rhyme. Whether the alignment holds at Nemotron scale on long, content-dense inputs — or breaks down precisely there — is the question current hybrids are implicitly betting on.</p><h3>What’s next in the series</h3><ul><li><strong>Part 2 — Mamba-2: when the recurrence becomes a matmul.</strong> Dao &amp; Gu’s State Space Duality rewrites the Mamba-1 recurrence as a structured matrix multiply, which is how Nemotron-H and friends actually run it on a GPU. Same selectivity, very different hardware story — and the “Mamba is attention” reading becomes literal rather than analogical.</li><li><strong>Part 3 — Mamba-3.</strong> The next iteration on the selective-SSM line. Covered when the dust settles enough to say something visual about it.</li></ul><h3>References</h3><ul><li>Gu, A. &amp; Dao, T. (2023). <em>Mamba: Linear-Time Sequence Modeling with Selective State Spaces.</em> <a href="https://arxiv.org/abs/2312.00752">arXiv:2312.00752</a>.</li><li>Gu, A., Goel, K. &amp; Ré, C. (2022). <em>Efficiently Modeling Long Sequences with Structured State Spaces (S4).</em> <a href="https://arxiv.org/abs/2111.00396">arXiv:2111.00396</a>.</li><li>Dao, T. &amp; Gu, A. (2024). <em>Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Mamba-2).</em> <a href="https://arxiv.org/abs/2405.21060">arXiv:2405.21060</a>.</li><li>Ali, A., Zimerman, I. &amp; Wolf, L. (2024). <em>The Hidden Attention of Mamba Models.</em> <a href="https://arxiv.org/abs/2403.01590">arXiv:2403.01590</a>.</li><li>Lieber, O. et al. (2024). <em>Jamba: A Hybrid Transformer-Mamba Language Model.</em> <a href="https://arxiv.org/abs/2403.19887">arXiv:2403.19887</a>.</li><li>NVIDIA (2025). <em>Nemotron-H technical report.</em></li><li>TII (2024). <em>Falcon-Mamba.</em></li><li>IBM (2025). <em>Granite 4.0.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58a5e0acf814" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On-Device AI Camera using Gemma 4 to Frame My Photos]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@j.tech.reveil/on-device-ai-camera-using-gemma-4-to-frame-my-photos-323906731fbc?source=rss-ac21d639db9d------2"><img src="https://cdn-images-1.medium.com/max/600/1*MUpFbN5OKNXyA-bsjZ3Z_Q.png" width="600"></a></p><p class="medium-feed-snippet">A walkthrough of wiring Gemini Nano 4 (the Gemma 4 family) to CameraX so a E2B model decides when to zoom.</p><p class="medium-feed-link"><a href="https://medium.com/@j.tech.reveil/on-device-ai-camera-using-gemma-4-to-frame-my-photos-323906731fbc?source=rss-ac21d639db9d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@j.tech.reveil/on-device-ai-camera-using-gemma-4-to-frame-my-photos-323906731fbc?source=rss-ac21d639db9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/323906731fbc</guid>
            <category><![CDATA[gemma-4]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai-core]]></category>
            <category><![CDATA[gemma]]></category>
            <category><![CDATA[gemini-nano]]></category>
            <dc:creator><![CDATA[Jun Nishimura]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 21:56:47 GMT</pubDate>
            <atom:updated>2026-04-19T21:56:47.989Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Your Phone Is an MCP Server: A Hands-On Tutorial with mcp-camera]]></title>
            <link>https://medium.com/@j.tech.reveil/your-phone-is-an-mcp-server-a-hands-on-tutorial-with-mcp-camera-7e4421b5d763?source=rss-ac21d639db9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e4421b5d763</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[cameras]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Jun Nishimura]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 21:46:35 GMT</pubDate>
            <atom:updated>2026-04-21T05:13:23.768Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Learn the Model Context Protocol by turning an Android phone’s camera into a tool any AI agent can call.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SA_xFUp6LXlZNFqHsN2LMQ.png" /><figcaption><em>Phone in airplane mode, USB-tethered to the laptop. Gemini CLI asks the phone to take a photo and describes what it sees — no LLM on the phone.</em></figcaption></figure><p>If you’ve been watching the AI agent space for the last year, you’ve probably tripped over the acronym <strong>MCP</strong> — the Model Context Protocol. The pitch is simple: one standard way for agents to discover and use tools, data, and services. No more bespoke plugin APIs for every model, every IDE, every chat client.</p><p>The pitch is easy to understand. The protocol is less easy to understand until you’ve built something with it.</p><p>This tutorial fixes that. We’ll use a real, runnable project called <strong>mcp-camera</strong> — a native Android app that exposes your phone’s camera as an MCP server — and use it as a lens to understand the three primitives at the heart of MCP:</p><ul><li><strong>Tools</strong> — functions the agent can invoke</li><li><strong>Resources</strong> — data the agent can read</li><li><strong>Sampling</strong> — when the server asks the agent’s LLM for help</li></ul><p>By the end, you’ll have a phone-in-your-hand demo where Claude Desktop (or any MCP client) can say <em>“take a photo and tell me what you see,”</em> and the camera on your actual phone will fire.</p><p>This is aimed at readers who are new to MCP. You don’t need to know Kotlin or Android — we’ll read the code together, not write it from scratch.</p><h3>What We’re Building</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*BbgxOs5sAnLcK8Wx8dNuXg.png" /></figure><p>The phone runs a real MCP server over HTTP on port 3001. The client connects over WiFi, lists the available tools, and calls them. When you ask the client to take a photo, the phone’s camera fires — and then the phone turns around and asks the <em>client’s</em> LLM to describe the photo that just got taken.</p><p>That last step is the interesting one. Hold onto it.</p><h3>Prerequisites</h3><ul><li>An Android phone (API 26 / Android 8.0 or newer) and a USB cable</li><li><a href="https://developer.android.com/studio">Android Studio</a> Ladybug (2024.2) or newer</li><li>Node.js 18+ (for the MCP Inspector and the optional stdio bridge)</li><li>An MCP client — we’ll use <strong>Claude Desktop</strong> and <strong>MCP Inspector</strong></li><li>Your phone and computer on the same WiFi network</li></ul><p>Nothing else. No API keys, no cloud account.</p><h3>MCP in 60 Seconds</h3><p>Before the code, the shortest possible mental model.</p><p>MCP is a protocol that sits between two things:</p><ul><li>An <strong>MCP client</strong> — usually running inside an AI app (Claude Desktop, Cursor, your own agent). The client owns the LLM.</li><li>An <strong>MCP server</strong> — a program that exposes capabilities. Could be a filesystem, a database, a Jira account, or — as we’re about to see — a phone camera.</li></ul><p>They talk over JSON-RPC. Either stdio (for local servers spawned as subprocesses) or HTTP (for servers that live on a network, like ours).</p><p>A server advertises three kinds of capability:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1930be1431c739f95f3724693b1b9b56/href">https://medium.com/media/1930be1431c739f95f3724693b1b9b56/href</a></iframe><p>That last row is the one most tutorials gloss over. We won’t.</p><h3>Sidebar: What Is JSON-RPC?</h3><p>MCP messages are all <strong>JSON-RPC 2.0</strong>, so it’s worth a one-minute detour.</p><p>JSON-RPC is a tiny remote-procedure-call protocol: you invoke a function on another process by sending it a JSON object. A request looks like this:</p><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 1,<br>  &quot;method&quot;: &quot;tools/call&quot;,<br>  &quot;params&quot;: {<br>    &quot;name&quot;: &quot;camera_takePhoto&quot;,<br>    &quot;arguments&quot;: { &quot;filename&quot;: &quot;cat.jpg&quot; }<br>  }<br>}</pre><p>The server replies with a matching id, plus either a result or an error:</p><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 1,<br>  &quot;result&quot;: { &quot;content&quot;: [ /* ... */ ] }<br>}</pre><p>That’s the whole protocol. Four fields matter: jsonrpc (always &quot;2.0&quot;), method (what to call), params (arguments), and id (so the reply can be matched to the request). Requests without an id are <strong>notifications</strong> — fire-and-forget, no response expected.</p><p>Two properties of JSON-RPC are why MCP picked it:</p><ul><li><strong>Transport-agnostic.</strong> The same JSON object travels unchanged over stdio, HTTP, WebSockets, whatever. MCP uses stdio (for local servers spawned as subprocesses) and HTTP (for networked servers like ours).</li><li><strong>Bidirectional.</strong> Either end can send a request at any time. Which is exactly how Sampling works: the server sends sampling/createMessage back to the client over the same connection. Without bidirectionality, this pattern wouldn&#39;t exist.</li></ul><p>When an MCP client calls camera_takePhoto, it sends an HTTP POST whose body is a JSON-RPC request just like the one above; the phone&#39;s embedded server parses it, dispatches to the matching handler, and returns a JSON-RPC result. No mystery — just JSON over a socket.</p><h3>Another Sidebar: MCP Is Language-Agnostic</h3><p>Worth saying explicitly before the code starts: <strong>the language of an MCP server doesn’t matter.</strong> MCP is a protocol, not a framework. If a process can read and write JSON-RPC over stdio or HTTP, it can be an MCP server.</p><p>mcp-camera is written in Kotlin because that’s the sensible language for a native Android app — not because MCP requires it. The same server, if it were running somewhere else, could just as reasonably be:</p><ul><li><strong>TypeScript</strong>, with @modelcontextprotocol/sdk — the most common choice for local tools spawned as subprocesses</li><li><strong>Python</strong>, with the mcp SDK (or its FastMCP helper) — popular for data-science and scraping tools</li><li><strong>Go</strong>, with mcp-go — popular for networking tools and system integrations</li><li><strong>C#</strong>, <strong>Rust</strong>, <strong>Swift</strong>, <strong>Java</strong> — all have official or community SDKs</li></ul><p>You don’t even strictly need an SDK — you could hand-roll JSON-RPC by writing to stdout and reading from stdin. Nothing in the MCP spec forces a particular language, runtime, or framework.</p><p>The rule of thumb: <strong>let the server’s job shape the language.</strong> An Android subsystem → Kotlin. A filesystem or git tool → TypeScript or Python. A Postgres adapter → whatever your team already writes Postgres in. The client and the LLM don’t know or care.</p><h3>Part 1: Tools — Functions the Agent Can Call</h3><p>Now we read the code. Open app/src/main/java/com/mcpmobile/camera/mcp/Tools.kt. Here&#39;s the shape of a tool definition (trimmed):</p><pre>server.addTool(<br>    name = &quot;camera_takePhoto&quot;,<br>    description = &quot;Take a photo with the device camera. Returns the file path, &quot; +<br>                  &quot;size, and an AI-generated description of the photo content.&quot;,<br>    inputSchema = Tool.Input(<br>        properties = buildJsonObject {<br>            putJsonObject(&quot;filename&quot;) {<br>                put(&quot;type&quot;, &quot;string&quot;)<br>                put(&quot;description&quot;, &quot;Output filename. Auto-generated if omitted.&quot;)<br>            }<br>            putJsonObject(&quot;camera&quot;) {<br>                put(&quot;type&quot;, &quot;string&quot;)<br>                putJsonArray(&quot;enum&quot;) { add(&quot;rear&quot;); add(&quot;front&quot;) }<br>                put(&quot;default&quot;, &quot;rear&quot;)<br>            }<br>        }<br>    ),<br>    toolAnnotations = ToolAnnotations(<br>        title = &quot;Take Photo&quot;,<br>        readOnlyHint = false,<br>        destructiveHint = false,<br>        idempotentHint = false,<br>        openWorldHint = false<br>    )<br>) { request -&gt;<br>    val filename = request.arguments?.get(&quot;filename&quot;)?.jsonPrimitive?.content<br>        ?: &quot;photo_${System.currentTimeMillis()}.jpg&quot;<br><br>    val result = cameraManager.takePhoto(filename)       // Fires Camera2 API<br>    // ... (we&#39;ll come back to this)<br>}</pre><p>Three things are worth pausing on.</p><p><strong>1. The input schema is JSON Schema.</strong> That’s the entire contract. The client reads this schema, shows a form to the LLM, and lets it fill in arguments. No shared type system between client and server — just JSON.</p><p><strong>2. The tool annotations are hints to the client.</strong> readOnlyHint = false tells Claude Desktop &quot;this tool has side effects, maybe prompt the user.&quot; destructiveHint = false says &quot;but it doesn&#39;t delete anything.&quot; The client uses these hints to decide whether to auto-approve, ask first, or warn. A good MCP client honors them; a bad one ignores them and the security model collapses. This matters.</p><p><strong>3. The handler is a coroutine.</strong> It calls cameraManager.takePhoto(...), which wraps CameraX&#39;s ImageCapture.takePicture() in a suspendCancellableCoroutine. The MCP SDK doesn&#39;t care — it just awaits a result.</p><p>The other two tools (camera_listPhotos, camera_getPhoto) follow the same shape. Read through them.</p><h3>Interlude: How the LLM Sees Your Tools</h3><p>A fair question at this point: if the tool is defined on the phone, how does the LLM — running somewhere in Anthropic’s or Google’s datacenter — know it exists?</p><p>The short answer: <strong>the LLM doesn’t discover tools. The client does, and then it tells the LLM</strong> by injecting the tool list into every API call. Let’s untangle that across two phases.</p><h3>Phase 1 — Discovery (once, at connect time)</h3><p>When the client (Claude Desktop, Gemini CLI, MCP Inspector) first attaches to the MCP server, it runs the JSON-RPC handshake:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*FFmmkm0HZMQbJ-HwdyBfHA.png" /></figure><p>initialize negotiates protocol version and capabilities. tools/list returns the full catalog of tool names, descriptions, and JSON Schemas (everything you defined in Tools.kt). resources/list returns the URI catalog. The client caches all of it in memory.</p><p>At this point the server’s job is mostly done — the catalog is on the client side.</p><h3>Phase 2 — Per turn (every user message)</h3><p>Now the user types <em>“take a selfie.”</em> Here’s the full loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgtVG15OnWvuA44r0yse8Q.png" /></figure><p>The critical moment is step 2. The client is about to call the LLM provider’s API — Anthropic’s POST /v1/messages, Google&#39;s generateContent, whatever. That API call includes a tools field, and the client populates it from the cached MCP catalog, translated into the provider&#39;s expected shape (Anthropic&#39;s tools, Gemini&#39;s function_declarations, OpenAI&#39;s functions).</p><p>So <strong>the LLM sees the tools the same way it sees the system prompt</strong>: they’re part of its input context, sent fresh on every request. That’s it. No magic, no training-time knowledge — just a field on an HTTP POST.</p><p>When the LLM decides to use a tool, it emits a structured tool_use response (step 3). The client intercepts this, checks the tool&#39;s annotations (destructiveHint, readOnlyHint), possibly prompts the user (step 4–5), and then — only then — translates it into an MCP tools/call and dispatches it to the server (step 6).</p><h3>Who does what</h3><p>ActorResponsibility<strong>LLM</strong>Reasons about the prompt; chooses <em>which</em> tool and <em>what</em> arguments. Nothing else.<strong>MCP client</strong>Discovers tools, injects them into LLM calls, enforces approval UX, executes tools/call, feeds results back to the LLM.<strong>User</strong>Approves or denies individual calls (for non-read-only tools).<strong>MCP server</strong>Advertises the catalog; runs the handler when called.</p><h3>The key insight</h3><p><strong>MCP and LLM tool-calling are two separate protocols. The client bridges them.</strong></p><ul><li>MCP is JSON-RPC between client ↔ server.</li><li>LLM tool-calling is whatever format Anthropic, Google, or OpenAI defined between their API ↔ the model.</li></ul><p>The MCP client is a translator. It reshapes MCP’s tools/list response into the provider&#39;s tool-definition format, and reshapes the LLM&#39;s tool_use response into an MCP tools/call request. Strip that translation layer out and nothing works.</p><p>This is also why MCP is model-agnostic. Our phone doesn’t know or care what LLM will eventually call it. It just publishes tools in the MCP shape. Whether Claude, Gemini, or a local Llama is doing the reasoning is somebody else’s problem.</p><h3>Part 2: Resources — Data the Agent Can Browse</h3><p>Open mcp/Resources.kt:</p><pre>server.addResource(<br>    uri = &quot;camera://capabilities&quot;,<br>    name = &quot;Camera Capabilities&quot;,<br>    description = &quot;Hardware capabilities of the device camera(s). &quot; +<br>                  &quot;Includes available cameras (rear/front), supported resolutions, &quot; +<br>                  &quot;flash availability, and night mode support.&quot;,<br>    mimeType = &quot;application/json&quot;<br>) {<br>    val caps = cameraManager.getCapabilities()<br>    ReadResourceResult(<br>        contents = listOf(<br>            TextResourceContents(<br>                uri = &quot;camera://capabilities&quot;,<br>                mimeType = &quot;application/json&quot;,<br>                text = Json.encodeToString(caps)<br>            )<br>        )<br>    )<br>}</pre><p>This is where beginners usually ask: <em>“Wait — isn’t this just a tool that returns data? Why is it a different primitive?”</em></p><p>Two reasons.</p><p><strong>One</strong>, resources have URIs. camera://capabilities is a stable, addressable identifier. A conversation can reference it, pin it, subscribe to changes on it. Tools don&#39;t have that — they&#39;re verbs, not nouns.</p><p><strong>Two</strong>, resources are for <em>browsing</em>, not <em>doing</em>. Before any tool gets called, the client (or the user) may want to load context: <em>“what cameras does this phone have?”</em> Resources are the door for that — URI-addressable, side-effect-free, safe to read without an approval prompt. In most clients today, the <em>user</em> or the <em>client</em> decides which resources to attach to the conversation (Claude Desktop via @-mention, Gemini CLI via slash-commands); the LLM doesn&#39;t autonomously crawl them. The spec allows richer discovery, but practice has lagged.</p><p>In mcp-camera, camera://capabilities tells the client the phone has a rear + front camera, supports 4K, has a flash. Attach that to the conversation and the LLM can pick arguments for camera_takePhoto intelligently. Without it, it has to guess.</p><h3>Part 3: Sampling — The Server Calls the Client’s LLM</h3><p>This is the part that makes MCP feel different from “yet another function-calling API.”</p><p>Look at the full camera_takePhoto handler. After the photo is captured, <em>before</em> it returns, the server does this:</p><pre>val description = try {<br>    requestPhotoDescription(server, cameraManager, result.path)<br>} catch (e: Exception) {<br>    &quot;Photo captured (description unavailable: ${e.message})&quot;<br>}</pre><p>And requestPhotoDescription — in mcp/Sampling.kt — looks like this:</p><pre>val result = withTimeoutOrNull(10_000L) {<br>    server.createMessage(<br>        CreateMessageRequest(<br>            messages = listOf(<br>                SamplingMessage(<br>                    role = Role.user,<br>                    content = ImageContent(<br>                        data = imageBase64,<br>                        mimeType = &quot;image/jpeg&quot;<br>                    )<br>                )<br>            ),<br>            systemPrompt = &quot;&quot;&quot;<br>                Describe the photo in ONE concise sentence (max 15 words).<br>                Then suggest a descriptive filename using lowercase and underscores.<br>                Format your response EXACTLY as: DESCRIPTION|FILENAME<br>            &quot;&quot;&quot;.trimIndent(),<br>            maxTokens = 100<br>        )<br>    )<br>}</pre><p>Read that again. The <strong>server</strong> is calling createMessage. The server is asking <em>for an LLM response</em>. The server is the one holding a photo, not the client. It has the data; the client has the model.</p><p>Here’s what happens on the wire:</p><ol><li>Client calls camera_takePhoto on the phone.</li><li>Phone captures the JPEG.</li><li>Phone sends a sampling/createMessage request <strong>back</strong> through the same MCP connection.</li><li>Client (Claude Desktop) asks the user: <em>“The mcp-camera server wants to describe a photo with your LLM. Allow?”</em></li><li>On approval, client runs the image through Claude, gets “A coffee cup on a wooden desk | coffee_cup_desk,” and sends it back.</li><li>Phone embeds that description in the tool result.</li></ol><p>This is the bit most agent frameworks can’t do. The server doesn’t ship its own model. It doesn’t need an OpenAI key. It borrows whatever model the client has configured. If you use Claude Desktop, it’s Claude. If you pointed a local-Ollama agent at the same server, it’d be Gemma. <strong>Model-agnostic by protocol, not by abstraction layer.</strong></p><p>The flip side: sampling is dangerous if misused. A malicious MCP server could ask the client’s LLM to leak the conversation, run arbitrary reasoning, etc. That’s why every serious client prompts for approval per-request. When you write servers, use sampling sparingly and explain why you’re asking.</p><h3>Part 4: Wiring a Real Client</h3><p>You’ve already driven the server with MCP Inspector. Now let’s wire it into a real agent. We’ll cover two: Claude Desktop and Gemini CLI. The shape is the same; only the config file path and one field name differ.</p><p>Find your phone’s IP address first (Android WiFi settings → your network → details). For the examples below, assume it’s 192.168.1.42.</p><h3>Option A: Claude Desktop</h3><p>Edit Claude Desktop’s config:</p><p><strong>macOS:</strong> ~/Library/Application Support/Claude/claude_desktop_config.json <strong>Windows:</strong> %APPDATA%\Claude\claude_desktop_config.json</p><p>Claude Desktop’s remote MCP support is stdio-only in current releases, so we bridge through the small Node script included in the repo (mcp-camera-stdio-bridge/index.js — see the aside at the end of this section for what it does):</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;mcp-camera&quot;: {<br>      &quot;command&quot;: &quot;node&quot;,<br>      &quot;args&quot;: [&quot;/absolute/path/to/mcp-camera-stdio-bridge/index.js&quot;],<br>      &quot;env&quot;: { &quot;MCP_CAMERA_URL&quot;: &quot;http://192.168.1.42:3001&quot; }<br>    }<br>  }<br>}</pre><p>Restart Claude Desktop. In a new conversation you should see a hammer icon showing mcp-camera is connected.</p><h3>Option B: Gemini CLI</h3><p>If you’d rather drive the camera from a terminal, <a href="https://github.com/google-gemini/gemini-cli">Gemini CLI</a> works too. Install it (npm install -g @google/gemini-cli).</p><p>The easiest way to register the server is to let the CLI write the config for you:</p><pre>gemini mcp add --scope user --transport sse --timeout 30000 \<br>  mcp-camera http://192.168.1.42:3001/sse</pre><p>That writes the following into ~/.gemini/settings.json:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;mcp-camera&quot;: {<br>      &quot;url&quot;: &quot;http://192.168.1.42:3001/sse&quot;,<br>      &quot;type&quot;: &quot;sse&quot;,<br>      &quot;timeout&quot;: 30000<br>    }<br>  }<br>}</pre><p>Two gotchas, both of which bit me the first time:</p><ul><li><strong>The </strong><strong>type field matters.</strong> If you hand-write the config with just url and omit type, Gemini CLI defaults to the streamable HTTP transport and can&#39;t connect. You&#39;ll see (http) - Disconnected in gemini mcp list --debug. The fix is the explicit &quot;type&quot;: &quot;sse&quot; above.</li><li><strong>The path is </strong><strong>/sse, not </strong><strong>/mcp.</strong> The MCP Kotlin SDK (0.6.0) used in mcp-camera mounts the server at /sse using the legacy SSE transport. Hitting /mcp returns a 404.</li></ul><p>Verify with gemini mcp list --debug — you want to see ✓ mcp-camera: http://.../sse (sse) - Connected.</p><h3>Take it for a spin</h3><p><a href="https://youtube.com/shorts/EPZI55iNF7I?feature=share">https://youtube.com/shorts/EPZI55iNF7I?feature=share</a></p><p>In either client, try:</p><blockquote><em>Take a photo with my phone and describe what you see.</em></blockquote><p>The agent will:</p><ol><li>Call camera_takePhoto.</li><li>Your phone’s shutter fires.</li><li>The phone’s sampling request pops up — the client asks permission to use its LLM.</li><li>You approve. The photo is described by the agent’s model (Claude or Gemini — the server doesn’t know or care).</li><li>The tool returns. The agent writes you a sentence about what’s in front of your camera.</li></ol><p>That’s the full loop, on real hardware, with two different vendors’ models describing the same pixels. Same server, same code, zero changes. That interchangeability is the whole point of MCP.</p><h3>Aside: what if my client is stdio-only?</h3><p>Some clients (older OpenClaw builds, certain CLI agents) only speak stdio MCP, not HTTP. The repo has a small Node bridge for exactly this case: mcp-camera-stdio-bridge/index.js. It reads JSON-RPC from stdin, POSTs it to the phone, and streams SSE events back to stdout. A 100-line file — worth reading if you ever need to translate transports.</p><h3>Part 5: Add Your Own Tool</h3><p>The best way to learn MCP is to add a tool. Let’s add camera_deletePhoto.</p><p>In Tools.kt, after the existing addTool blocks:</p><pre>server.addTool(<br>    name = &quot;camera_deletePhoto&quot;,<br>    description = &quot;Delete a photo by filename.&quot;,<br>    inputSchema = Tool.Input(<br>        properties = buildJsonObject {<br>            putJsonObject(&quot;filename&quot;) {<br>                put(&quot;type&quot;, &quot;string&quot;)<br>                put(&quot;description&quot;, &quot;Filename of the photo to delete.&quot;)<br>            }<br>        },<br>        required = listOf(&quot;filename&quot;)<br>    ),<br>    toolAnnotations = ToolAnnotations(<br>        title = &quot;Delete Photo&quot;,<br>        readOnlyHint = false,<br>        destructiveHint = true,     // This one IS destructive<br>        idempotentHint = true,<br>        openWorldHint = false<br>    )<br>) { request -&gt;<br>    val filename = request.arguments?.get(&quot;filename&quot;)?.jsonPrimitive?.content<br>        ?: return@addTool CallToolResult(<br>            content = listOf(TextContent(text = &quot;filename is required&quot;)),<br>            isError = true<br>        )</pre><pre>    val file = File(cameraManager.photoDir, filename)<br>    if (file.exists() &amp;&amp; file.delete()) {<br>        CallToolResult(content = listOf(TextContent(text = &quot;Deleted $filename&quot;)))<br>    } else {<br>        CallToolResult(<br>            content = listOf(TextContent(text = &quot;File not found: $filename&quot;)),<br>            isError = true<br>        )<br>    }<br>}</pre><p>Note destructiveHint = true. A well-behaved client will now pause and ask <em>you</em> before it lets the LLM delete anything. The protocol gives you the knob; the client enforces the policy.</p><p>Rebuild, re-run, re-connect the inspector — the new tool shows up. You just extended an MCP server.</p><h3>What You Actually Learned</h3><p>Strip away Android, CameraX, and Kotlin, and the MCP shape is three boxes:</p><ul><li>A <strong>server</strong> declares tools, resources, and optionally sampling support.</li><li>A <strong>client</strong> discovers them, lets an LLM use them, and mediates permission.</li><li>A <strong>transport</strong> (stdio or HTTP) carries JSON-RPC between them.</li></ul><p>Everything else is implementation detail. A Postgres MCP server exposes query as a tool and schema://public.users as a resource — same primitives. A filesystem server exposes read_file as a tool and file:///path as a resource — same primitives. A camera server exposes camera_takePhoto and camera://capabilities — same primitives.</p><h3>Where to Go Next</h3><ul><li><strong>The spec</strong>: <a href="https://modelcontextprotocol.io/">modelcontextprotocol.io</a> — dense but readable.</li><li><strong>Kotlin SDK</strong>: <a href="https://github.com/modelcontextprotocol/kotlin-sdk">github.com/modelcontextprotocol/kotlin-sdk</a> — what mcp-camera is built on.</li><li><strong>Other SDKs</strong>: TypeScript, Python, Go, Rust — same primitives, different language.</li><li><strong>Write your own server</strong>: start with a tool that wraps one API call you already have. Ship it. Then add a resource. Then, if you need it, add sampling.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e4421b5d763" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>