[{"content":"","date":"24 November 2026","externalUrl":null,"permalink":"/blog/","section":"Blog","summary":"","title":"Blog","type":"blog"},{"content":" Thinking Machines recently released Inkling 2 Mini, a small open-weights mixture-of-experts (MoE) model that runs its middle twelve layers three times for every token. Every pass through the loop starts from the output of the first six layers, and passes 2 and 3 also read a gated message from the pass before. For more details on how it works and how it\u0026rsquo;s served, see the launch post, vLLM\u0026rsquo;s post and Goodfire\u0026rsquo;s write-up.\nThe loop in Inkling 2 Mini. Figure from Thinking Machines, \"Introducing Inkling 2 Mini\" (2026). Each of the twelve looped layers has a router that picks 8 of its 128 experts for every token, and the same router runs on all three passes.The router is standard, as in DeepSeek-V3. For a token with hidden state \\(x\\), it scores every expert \\(e\\) with \\(s_e=\\sigma(w_e^\\top x)\\), picks the 8 experts with the highest \\(s_e+\\beta_e\\), where \\(\\beta_e\\) is a per-expert bias, and mixes their outputs with weights proportional to \\(s_e\\). Router weights and biases are shared by all three passes. It had me wondering: when a token comes around for its second and third pass, does it go back to the same experts?\nReading Thinky\u0026rsquo;s blog, I can find two good reasons to expect some non-trivial amount of expert reuse between the passes:\nThey say they start training with the message fully blocked, so at first the three passes are exact copies of each other, including the experts. Hence, whatever separates them now got learned as the gate opened. Partway through the training, they cut each layer from 384 experts down to the 128 most used. This obviously raises the probability of reuse. To find out, I ran Inkling over 14.5M tokens of benchmark text and logged every expert it picked, on every pass. The tokens come from 23 benchmarks (the ones Thinking Machines reports on, plus some cyber sets I was curious about) and three control sets (UltraChat, The Stack and FineWeb-Edu). We only run prefill on them, with no generation. The details are in the appendix.\nMeasuring reuse # For one token at one looped layer, take two of its passes and let \\(s\\) be the number of experts it picks on both. It goes from 0 (all new) to 8 (all the same).\nAn example token at one layer (illustration). Some experts may just be popular (some act almost like shared experts). To account for that, we compare against a baseline \\(b\\), the average overlap between two different tokens from the same benchmark, one on each pass.The average can be computed directly. If expert \\(e\\) is picked by 30% of a benchmark\u0026rsquo;s tokens on pass 1 and 20% on pass 2, an unrelated pair contains it in both with probability \\(0.3\\times0.2=0.06\\). Summing over all 128 experts gives \\(b\\). We do this per benchmark and layer, so that a benchmark\u0026rsquo;s own favourite experts (code and chat favour different ones) end up in the baseline and aren\u0026rsquo;t mistaken for reuse. With all experts equally popular, \\(b\\) would be 0.5. From here on, \\(s\\) is averaged over all tokens too. In the baseline is drawn as a dashed line, and actual reuse shows up as the gap above it.One can also use the rescaled quantity \\(\\kappa=(s-b)/(8-b)\\), analogous to Cohen\u0026rsquo;s κ, which measures agreement between two raters (cf. Olson et al.).\nFor further control, we also compare against two more things. The first is the same token elsewhere in the text, on pass 1, which tells us whether a token simply has its own preferred experts.We take about 50,000 random tokens and pair each with another occurrence of the same token in a different prompt, then count the experts the two share on pass 1. 92% find a partner (about 46,000 pairs). The rest are rare tokens that appear in only one prompt, so the comparison leans towards common tokens. The second is the same pass run twice at different precision (fp32 and bf16), which shows how much rounding alone changes the routing. That one is obviously the most reuse we could hope to see.\nIn the middle of the loop, a token keeps 3.4 to 5.6 of its 8 experts between passes, against a baseline of about one ().Layers count from 1, as in Goodfire\u0026rsquo;s and Thinking Machines\u0026rsquo; posts, so the loop is L7–L18. Experts and \\(d_{2027}\\) count from 0. So it lands somewhere in the middle, way above the baseline, above the same token elsewhere in the text, and way below what rounding alone leaves in place (6.9 to 7.9 of 8). This means that roughly half of a token\u0026rsquo;s experts change from one pass to the next.\nExperts a token shares between passes, out of 8, at each looped layer, averaged over 13.0M tokens. Dashed lines are each pair's baseline, and the solid grey line is the same token elsewhere in the text, on pass 1, averaged over 46K pairs. The grey band is the same pass run twice, in fp32 and bf16 (averaged over 52 prompts), which still differs by up to one expert, since rounding can nudge an expert across the top-8 cut-off. That's about as close as two passes could get. A few things jump out. Through most of the loop, passes 2 and 3 agree with each other more than either does with pass 1. That fits the message being what pulls the passes apart (directly or through earlier layers and other tokens), since pass 1 is the only one that doesn\u0026rsquo;t get a message. Passes 1 and 3 agree least, as you\u0026rsquo;d expect if the differences pile up from one pass to the next. The very end of the loop is another story, which we break down in the next section.\nMost of the message\u0026rsquo;s effect turns out to be indirect. Each looped layer reads the message in four places (the query, key and value inputs of its attention, and the input of its experts, which is what the router sees). We can block all of these reads except a few and count how many of its 8 experts a token then reuses between passes 1 and 2. With every read blocked it reuses all 8, and with every read open it reuses 4.6. With only the attention reads open it reuses 4.5. With only the expert-input reads open it reuses 5.9. Even if the only read left open is the expert input of L7, the first looped layer, it reuses 6.5. Leaving open only the expert input of a mid-loop layer (L9, L12 or L15) gives about 7.5 at the layers after it.These runs use 78 prompts, cut at 4,096 tokens, and the numbers are averages over the looped layers. Blocking reads puts the model in a state it never trained in, so these numbers are rough. Hence the attention reads alone are enough, and the router needn\u0026rsquo;t read the message itself.\nExperts reused between passes 1 and 2 when only some of the message reads are left open. Each line runs from 8, where nothing changes, so its length is the number of experts that change. L18 switches modes on pass 3 # Goodfire\u0026rsquo;s write-up is the place to start. Each layer reads a learned mix of earlier blocks\u0026rsquo; outputs (attention residuals), which let Goodfire trace who writes to whom across blocks and loops. Among other things, they found a massive activation in coordinate 2027 (out of 2304) of the hidden state, \\(d_{2027}\\), which on average carries 46% of its squared norm. At the end of passes 1 and 2, L18 writes a big positive spike into it, which Goodfire describes as \u0026ldquo;tagging\u0026rdquo; the state for later layers, and on the next pass L13 uses it to decide to read from block 3 of the previous pass. On pass 3, L18 writes a big negative spike instead, cleaning it up before the final block.\nWe observe the same switch in the router. shows how often L18 picks each of its 128 experts, pass by pass. On passes 1 and 2, a few experts are picked for nearly every token (three on pass 1, two on pass 2), and by the end of the pass \\(d_{2027}\\) holds 47% and 41% of the hidden state\u0026rsquo;s squared norm. Let\u0026rsquo;s call these few the effective shared experts. On pass 3 the routing spreads out. No expert is picked for more than 40% of the tokens, and \\(d_{2027}\\) drops to about 1%. This also explains why the same-token line in shoots up at the end of the loop: that line is measured on pass 1, where nearly every token goes to the same few experts, so any two tokens share most of their experts.\nL18's experts on each pass. Each bar is one of the 128 experts, and its height is the share of tokens that pick it. A token picks 8 experts, so the bars add up to 800%. On the right is the share of the hidden state (squared norm) that sits on \\(d_{2027}\\) after L18. Pass 4 is one we force the model to run, which it never did in training. These runs use 78 prompts, three from each of the 26 sets, cut at 4,096 tokens (about 190K tokens in all). Passes 1–3 look the same on the full 13M-token run. Blocking the effective shared experts suggests they are not what writes the spike into \\(d_{2027}\\). Goodfire traces most of the write to L18\u0026rsquo;s experts (their Figure 7), so these are the natural place to look. We block them on passes 1 and 2, and the router has to use its next-best choices ().To block an expert, we set its score to minus infinity at L18 on that pass, just before the router takes its top 8. The router then picks the 8 best of the remaining experts and weights them as usual. Nothing else in the model is changed. A third of L18\u0026rsquo;s choices change, and \\(d_{2027}\\) stays where it was. So the other experts seem to write it just the same, which is in line with Goodfire\u0026rsquo;s finding that many neurons in the last layer of each block write for the next pass.\nBlocking them also leaves the model\u0026rsquo;s output almost untouched. We run the model on the same text with and without the block, and at every position check whether its top guess for the next token is still the same. In assistant turns (thinking, responses and tool calls), it changes at 3.3% of the positions, averaged over the 50 prompts that have such turns (52K tokens).\nL18 with its effective shared experts blocked on passes 1 and 2. Each panel compares two runs. Bars above the line show how often each expert is picked in the normal run, and bars below it show the same once the effective shared experts are blocked. The blocked experts are the dashed outlines. Other experts take over, and the share of the hidden state on \\(d_{2027}\\) hardly moves. Same 78 prompts. Goodfire suggests, broadly speaking, that the model cleans up on pass 3 because no more loops follow. That fits how the model was trained, where pass 3 was always the last one. But it made me wonder how can a pass know that it is the last (or its position, in general). Because all passes are identical when the message is blocked, it can only come from the message. I can find two observations on how the switch is triggered by what a pass receives:\nWe force a fourth pass, which the model never ran in training (last row of ). In my experiments, L18 doesn\u0026rsquo;t stay switched: on pass 4 it goes back to pass 1\u0026rsquo;s experts, with \\(d_{2027}\\) at 42% again. So a pass that receives the cleaned-up state starts tagging again. Forcing more passes repeats the pattern: running nine loops, I found that L18 cleans up again on passes 6 and 9, and tags on all the others. We block the message reads, as before, and leave open only the expert input of L18. Pass 2 then stays close to pass 1, and pass 3 doesn\u0026rsquo;t switch (at L18, passes 2 and 3 then share 7.7 of 8 experts, against 1.8 in the normal run). Hence pass 3 seems to switch only once pass 2 has itself been changed by a message.\nMy guess, building on Goodfire\u0026rsquo;s, is that the model learned a handoff. On passes 1 and 2, \\(d_{2027}\\) is a tag telling the next pass where to read. In training, the final block only ever saw the output of pass 3, so the model learned to give it a different kind of state. But a pass isn\u0026rsquo;t told its number, so it has to infer it from the message, and with three passes, a tagged message from a pass that had itself read a tagged message always means \u0026ldquo;I\u0026rsquo;m last\u0026rdquo;. A cleaned-up message carries no tag, so the pass after a clean-up starts over like pass 1. Forcing a fourth pass breaks that: pass 3 has cleared the tag, so L18 tags again on pass 4, and the final block gets an input it never saw. It also matters where we stop: against the normal three-pass run, 19% of the predictions change with four or five passes, and only 9% with six. LoopMoE reports a similar exit phase in their looped model, which they also read as a hand-off.\nA clue in how the experts are balanced # As we\u0026rsquo;ve seen in , on passes 1 and 2 L18 sends every token to the same two or three experts. MoE training usually prevents this with load-balancing. Inkling\u0026rsquo;s router has the same form as DeepSeek-V3\u0026rsquo;s: each expert has a score \\(s_e\\) and a bias \\(\\beta_e\\), and the router takes the 8 experts with the highest \\(s_e+\\beta_e\\). In DeepSeek-V3, the bias is updated after every training step by\n\\[\\beta_e \\leftarrow \\beta_e + \\gamma\\,\\operatorname{sign}(\\bar c - c_e),\\]where \\(c_e\\) is the number of tokens expert \\(e\\) got in that step, \\(\\bar c\\) is the average over the experts, and \\(\\gamma\\) is a small step size (Wang et al.). Assuming that Inkling 2 Mini was trained in the same way, we would expect that a popular expert will end up with a very low bias.\nWe find that it doesn\u0026rsquo;t happens at L18. The effective shared experts of passes 1 and 2 have biases between +0.03 and +0.07, in the upper half of the layer. The lowest bias in the layer is −0.76, and it belongs to an expert that is busy only on pass 3.\nTo see this for all 128 experts, we take the scores before the bias and count how often they would put each expert in a token\u0026rsquo;s top 8 (top panels of ). On pass 3, the busier an expert is, the lower its bias, which is what balancing should give. On passes 1 and 2 there is no such trend. This isn\u0026rsquo;t special to L18. At every looped layer, the bias follows the load of pass 3 the most and the load of pass 1 the least (bottom panel).\nThe balancing bias against load. In the top panels each dot is one of L18's 128 experts, with its bias against how often the raw scores, before the bias, would put it in a token's top 8. The bottom panel shows the correlation between bias and that load at each looped layer, one line per pass. Computed on 61K sampled tokens. My guess is that the count \\(c_e\\) only included the tokens of pass 3. The bias would then balance pass 3 and ignore the other two, so passes 1 and 2 could send every token to the same few experts without being corrected. I don\u0026rsquo;t know whether this was done on purpose or by accident.\nExpert reuse by task domain # Thinking Machines reports which benchmarks gain most from extra passes. They measure it with TML-d24-varloop-research, a research model trained to run between one and five passes. Long-context retrieval and long agentic tasks gain tens of points, while closed-book knowledge barely moves. I wanted to see whether tokens also replace more of their experts on those benchmarks, and how the cyber sets compare.\nThe sets do differ. Between passes 1 and 2, a token replaces 29% of its experts on competition math and 49% on GraphWalks. Across the 14 benchmarks with a reported gain, the ones that gain more also replace more experts (\\(r=0.64\\)).\nIt seems like a meaningful part of this is position. The further a token is into the context, the more of its experts it replaces. In a typical benchmark, a token replaces about 31% of its experts near the start, 39% by token 256 and roughly 46% by token 4K (). The benchmarks that gain the most are also the long ones. Once we account for position, and for which token it is, the link with the gain is gone (\\(r=-0.17\\)).\nExperts replaced against position, on the prompt tokens of the 14 benchmarks with loop gains, one line per benchmark. Each point is a doubling range of positions with at least 300 tokens. Each benchmark covers only part of the range, so the heavy line fits one offset per benchmark and one per position range, which gives the trend inside a typical benchmark. The band is its range when any one benchmark is left out. To take position out, we compare the sets at the same position range, tokens 256 to 511 (). They then range from 33% to 46%. GraphWalks is at the top, followed by the code-heavy sets at 42% to 44%. Math, search and tool use are at the bottom, at 33% to 34%. The cyber sets land between 39% and 42%, the same as the control sets, and vulnerable code is about the same as ordinary code.\nExperts replaced between passes 1 and 2 on prompt tokens, one row per set. The filled dot puts every set at the same position range, tokens 256 to 511, with the same kind of fit as the heavy line in , here over all the sets. The hollow dot is the plain average over all of the set's tokens. Faded dots are sets whose tokens fall in only one or two position ranges, so their value is less certain. The numbers on the right are the loop gains that Thinking Machines reports, in points. Hence, once position is taken out, what is left seems to follow the kind of text, with no sign of the loop gain. I haven\u0026rsquo;t tested why position matters.\nClosing thought # Looped models are (and will keep on) coming more often. Just this week Z.ai released GLM-5.4. There is a lot we don\u0026rsquo;t know yet about how these models work, and plenty of experiments left to run. Congrats, and a deep thank you, to Thinking Machines on this awesome release :)\nAppendix # The data # The text comes from 23 benchmarks in nine areas. 16 of them are ones Thinking Machines reported loop gains for (the three competition-math sets are pooled, so the figures show 14). I added chat, code and web text as controls. I was also curious where cyber stands, so I added seven cyber sets (CTF agent runs, cyber knowledge questions and vulnerable code).\nThe assistant turns were written by the models that produced each benchmark\u0026rsquo;s trajectories, or are the benchmark\u0026rsquo;s own answers (see the full table below ). The main run keeps up to 100 prompts per benchmark, and the first 16,384 tokens of each (making 2,261 prompts and 14.5M tokens in total). Most of the analysis leaves out chat-template tokens and any opening stretch of a prompt that matches another prompt word for word, such as a shared system prompt. That leaves around 13.0M of the 14.5M tokens. Agent trajectories dominate ().\nTokens per benchmark, split by who wrote them. Pooled numbers count every token once, so long agent runs weigh most. Where each set comes from, and who wrote its assistant turns Area Set Prompts Source Assistant text Agentic coding DeepSWE v1.1 100 kaitchup/DeepSWE1.1-trajectories-Qwen3.8-27B Qwen3.8-27B SWE-bench Pro 100 Inferact/codex_swebenchpro_traces tool calls only (see below) SWE-bench Verified 100 naderalfares/epoch_ai_swebench_verified DeepSeek-V4-Pro Agentic search BrowseComp 100 rl-rag/browsecomp-gpt-oss-120b-v2 gpt-oss-120b Tool use MCP Atlas 100 ScaleAI/MCP-Atlas Scale\u0026rsquo;s reference runs Cyber NYU CTF Bench, Cybench, InterCode-CTF 236 EnIGMA trajectories GPT-4o WMDP-Cyber 100 cais/wmdp answer key CyberMetric-500 100 tihanyin/CyberMetric answer key PrimeVul, CrossVul 150 colin/PrimeVul, hitoshura25/crossvul none (code only) Long context MRCR v2 (8 needles) 100 openai/mrcr answer key GraphWalks (BFS) 100 openai/graphwalks answer key Math HMMT Feb 2025, HMMT Feb 2026, Apex 2025 75 MathArena outputs DeepSeek-V3.2, DeepSeek-V4-Pro Science GPQA Diamond 100 lvogel123/gpqa-diamond-deepseek-v3.2-exp-high DeepSeek-V3.2-Exp Knowledge SimpleQA Verified 100 google/simpleqa-verified answer key AA-Omniscience (public) 100 ArtificialAnalysis/AA-Omniscience-Public answer key Safety FORTRESS (adversarial, benign) 200 ScaleAI/fortress_public none (prompts only) StrongREJECT 100 AlignmentResearch/StrongREJECT none (prompts only) Control Chat (UltraChat 200k) 100 HuggingFaceH4/ultrachat_200k GPT-3.5-Turbo Code (The Stack, small sample) 100 bigcode/the-stack-smol-xs none Web text (FineWeb-Edu) 100 HuggingFaceFW/fineweb-edu, sample-10BT none A few things to know about these. The public SWE-bench Pro traces replace the model\u0026rsquo;s text with filler, so its assistant turns here are just the tool calls, rebuilt from the trace, and the benchmark comparison leaves them out. MRCR and GraphWalks are cut at 16K tokens here, while Thinking Machines measured their loop gains at 256K–512K. And the math, GPQA and MCP Atlas assistant turns are long reasoning traces or reference runs.\nReferences # Inkling 2 Mini. Thinking Machines Lab (2026). \u0026ldquo;Introducing Inkling 2 Mini.\u0026rdquo; thinkingmachines.ai · model card · weights · variable-loop model Interpreting Inkling 2 Mini. Lee, A., Krishnamurthy, K., Merullo, J., Balsam, D., \u0026amp; Lubana, E. S. (2026). Goodfire Research. goodfire.com Inkling 2 Mini on vLLM. Inferact, Thinking Machines \u0026amp; NVIDIA (2026). \u0026ldquo;Inkling 2 Mini on vLLM: Day-0 Support for a Looped Model.\u0026rdquo; vllm.ai Attention Residuals. Kimi Team (2026). arXiv:2603.15031 Massive activations. Sun, M., Chen, X., Kolter, J. Z., \u0026amp; Liu, Z. (2024). \u0026ldquo;Massive Activations in Large Language Models.\u0026rdquo; COLM 2024. arXiv:2402.17762 DeepSeek-V3. DeepSeek-AI (2024). \u0026ldquo;DeepSeek-V3 Technical Report.\u0026rdquo; arXiv:2412.19437 Load balancing without an auxiliary loss. Wang, L., Gao, H., Zhao, C., Sun, X., \u0026amp; Dai, D. (2024). \u0026ldquo;Auxiliary-Loss-Free Load Balancing Strategy for Mixture-of-Experts.\u0026rdquo; arXiv:2408.15664 Cohen\u0026rsquo;s kappa. Cohen, J. (1960). \u0026ldquo;A Coefficient of Agreement for Nominal Scales.\u0026rdquo; Educational and Psychological Measurement, 20(1), 37–46. Semantic routing. Olson, M. L., Ratzlaff, N., Hinck, M., Luo, M., Yu, S., Xue, C., \u0026amp; Lal, V. (2025). \u0026ldquo;Probing Semantic Routing in Large Mixture-of-Expert Models.\u0026rdquo; arXiv:2502.10928 LoopMoE. Chen, W., Li, T., Huang, W., et al. (2026). \u0026ldquo;LoopMoE: Unifying Iterative Computation with Mixture-of-Experts for Language Modeling.\u0026rdquo; arXiv:2606.04438 GLM-5.4. Z.ai (2026). \u0026ldquo;GLM-5.4: Toward Generalized Coding with Our First Loop Transformer.\u0026rdquo; z.ai ","date":"24 November 2026","externalUrl":null,"permalink":"/blog/inkling-loop-routing/","section":"Blog","summary":"Inkling 2 Mini runs its middle layers three times per token. Do the extra passes send a token to the same experts? About half of them stay, and the last looped layer switches into a different mode on its third pass.","title":"Does Inkling 2 Mini use the same experts on every loop?","type":"blog"},{"content":"","date":"24 November 2026","externalUrl":null,"permalink":"/tags/expert-routing/","section":"Tags","summary":"","title":"Expert-Routing","type":"tags"},{"content":"","date":"24 November 2026","externalUrl":null,"permalink":"/tags/inkling-2-mini/","section":"Tags","summary":"","title":"Inkling-2-Mini","type":"tags"},{"content":"","date":"24 November 2026","externalUrl":null,"permalink":"/tags/looped-models/","section":"Tags","summary":"","title":"Looped-Models","type":"tags"},{"content":"","date":"24 November 2026","externalUrl":null,"permalink":"/tags/mixture-of-experts/","section":"Tags","summary":"","title":"Mixture-of-Experts","type":"tags"},{"content":"MSc in mathematics, now doing AI research at Novee Security. Sometimes active on Math StackExchange.\nI like math, AI, the math of AI, and AI for math.\n","date":"24 November 2026","externalUrl":null,"permalink":"/","section":"Noam Shalev","summary":"","title":"Noam Shalev","type":"page"},{"content":"","date":"24 November 2026","externalUrl":null,"permalink":"/tags/","section":"Tags","summary":"","title":"Tags","type":"tags"},{"content":" I\u0026rsquo;ve been reading about linear attention and fast-weight models lately, and one small detail caught my eye: the short convolution (aka shortconv). It shows up in many recent frontier open-weight LLMs, including Qwen (3.5 onwards), Kimi (Linear, K3), and GLM (5.3-Flash), right after the Q/K/V projections. It has even made it into Thinking Machines\u0026rsquo; Inkling, which doesn\u0026rsquo;t use linear attention at all. As Songlin Yang put it, \u0026ldquo;shortconv is scalable\u0026rdquo;. I\u0026rsquo;ve been wondering why it is there, how it got there in the first place, and why it\u0026rsquo;s almost always with kernel_size=4.\nGated DeltaNet (Qwen)\nKDA (Kimi)\nShort convolutions (\"Conv\") in Qwen3-Next and Kimi Linear. To understand shortconvs, let\u0026rsquo;s start with something all attention architectures do: use information from earlier in a conversation. We might tell an assistant what a nickname means or teach it a new shortcut, and then expect it to remember that later.\nAs an example, consider a sequence that defines a few associations:\nzeta rabbit kappa tiger omega penguin ... zeta ? We expect a well-performing model to predict the token rabbit. The pairs are deliberately arbitrary, so knowing what zeta is won\u0026rsquo;t help here - the model has to use what appeared earlier in the sequence. This is a particular instance of in-context learning, known in the linear-attention literature as associative recall. Transformers famously handle this with induction heads.\nIn softmax attention, the KV cache keeps a key and a value for each earlier position. For our task, a useful entry at the rabbit position would have a key that matches zeta and a value that carries rabbit. For that, the rabbit position needs to know that zeta came right before it. In a transformer, this is usually the job of a previous-token head in an earlier layer.\nWhen zeta appears again, its query can match that entry\u0026rsquo;s key and retrieve information about rabbit. More generally, attention combines the cached values according to how well their keys match:\n\\[ o_t=\\sum_{i\\leq t} \\operatorname{softmax}_{i}\\!\\left( \\frac{q_t^\\top k_i}{\\sqrt{d_k}}\\right)v_i. \\] Linear attention as fast weights # If we drop the softmax and use raw dot products as weights, the sum can be rearranged:\n\\[ \\begin{aligned} o_t\u0026=\\sum_{i\\leq t}(q_t^\\top k_i)\\,v_i =\\Big(\\sum_{i\\leq t}v_i k_i^\\top\\Big)q_t = S_t\\,q_t,\\\\ S_t\u0026=\\sum_{i\\leq t}v_i k_i^\\top = S_{t-1}+v_tk_t^\\top,\\qquad S_0=0. \\end{aligned} \\]Now the zeta/rabbit association is folded into one matrix, \\(S_t\\in\\mathbb R^{d_v\\times d_k}\\), together with kappa/tiger and omega/penguin. There\u0026rsquo;s no list of entries (aka KV cache) anymore, just a fixed-size matrix that the query reads from. This is the simplest (unnormalized) form of linear attention, whose computational cost grows linearly with sequence length (instead of quadratically).1\nThere\u0026rsquo;s another way to look at \\(S_t\\): as the weights of a small linear model, \\(k\\mapsto S_tk\\), that predicts a value from a key. These weights change with every token, so they\u0026rsquo;re called fast weights - an idea going back to the late 1980s2. The projections that produce \\(q\\), \\(k\\) and \\(v\\) are the usual slow weights, learned in pretraining.\nSeen this way, the layer runs a small learning loop inside every forward pass. Each token writes its key/value pair into the fast weights with a gradient step, and each query reads from them:\n\\[ \\begin{aligned} \\textbf{Write:}\\quad \u0026 W_t=W_{t-1}-\\eta_t\\nabla_W\\,\\ell\\big(f_W(k_t),\\,v_t\\big),\\\\ \\textbf{Read:}\\quad \u0026 o_t=f_{W_t}(q_t). \\end{aligned} \\]Here \\(f_W\\) is the memory, a model with fast weights \\(W\\), and the loss \\(\\ell\\) measures how well it maps keys to values. For linear attention the memory is just a linear map, \\(f_W(k)=Wk\\) with \\(W_t=S_t\\), and the loss is \\(\\ell=-\\langle Wk_t,v_t\\rangle\\). Its gradient is \\(-v_tk_t^\\top\\), so a step with \\(\\eta_t=1\\) gives back \\(S_t=S_{t-1}+v_tk_t^\\top\\). This view is often called test-time training (though I prefer fast weights, or test-time regression).\nWith the memory framed as a learning problem, most variants differ in two ways: the loss, and how the old state is decayed before each write. The dot-product loss has a gradient that doesn\u0026rsquo;t depend on \\(S\\), so the write ignores what the memory already predicts, and associations pile up. In contrast, DeltaNet (Schlag et al., 2021; Yang et al., 2024) uses \\(\\ell_2\\) loss,\n\\[ \\begin{aligned} \\ell_t(S)\u0026=\\tfrac12\\|Sk_t-v_t\\|^2,\\\\ S_t\u0026=S_{t-1}+\\beta_t(v_t-S_{t-1}k_t)k_t^\\top, \\end{aligned} \\]where now each write is a correction: it moves what the memory returns for \\(k_t\\) toward \\(v_t\\), so a new value for a familiar key replaces the old one. Gated DeltaNet (GDN) also lets old associations fade - it first decays the old state by a scalar \\(\\alpha_t\\):\n\\[ \\begin{aligned} \\widetilde S_t\u0026=\\alpha_t S_{t-1},\\\\ S_t\u0026=\\widetilde S_t+\\beta_t(v_t-\\widetilde S_tk_t)k_t^\\top. \\end{aligned} \\]Kimi Delta Attention (KDA) gives each key channel its own rate, \\(\\widetilde S_t=S_{t-1}\\operatorname{diag}(\\boldsymbol\\alpha_t)\\).\nWhy shortconv? # In practice, most of the linear-attnetion variants mentioned above pass their Q/K/V through a shortconv. In FLA\u0026rsquo;s Gated DeltaNet implementation, it even comes with a warning: \u0026ldquo;ShortConvolution is crucial to the performance. Do not turn it off unless you know what you are doing\u0026rdquo;.\nA shortconv is a small causal convolution applied to a sequence of projected vectors \\(u_1,u_2,\\dots\\in\\mathbb R^D\\). With kernel-size \\(m\\), its output is\n\\[ y_t=\\sum_{j=0}^{m-1}w_j\\odot u_{t-j},\\qquad u_s=0\\ \\text{for}\\ s\\le 0, \\]where the \\(w_j\\in\\mathbb R^D\\) are learned and \\(\\odot\\) is elementwise multiplication (each channel \\(c\\) of \\(y_t\\) sees only channel \\(c\\) of the last \\(m\\) inputs). The projection before it mixes channels at a fixed position, and the conv mixes positions within one channel. A general implementation of shortconv looks something like nn.Conv1d(D, D, kernel_size=4, groups=D, padding=3), applied to Q/K/V (sometimes concatenated).3\nTo see why this convolution might help, notice that every write to the recurrent state takes a key and a value from the same position \\(t\\). In our example, we want a key for zeta paired with a value for rabbit, but those two words sit at different positions.\nThe conv can fix this. Let\u0026rsquo;s pick its weights by hand, with \\(m=4\\). On the key path, set \\(w_1=\\mathbf 1\\) (the all-ones vector) and the other \\(w_j\\) to zero. This way \\(y_t=u_{t-1}\\), so each position\u0026rsquo;s key is precisely the previous token\u0026rsquo;s key. For simplicity, say we don\u0026rsquo;t apply shortconv to Q/V (e.g. by setting \\(w_0=\\mathbf 1\\) and the rest zero). Now, at the rabbit position, the memory writes a key that describes zeta together with a value that describes rabbit:\nShifting the key by one token pairs zeta with rabbit. When zeta shows up again, its query matches that key, and out comes rabbit. This is the previous-token head from earlier. In a transformer, an induction head takes two layers: one head copies information about the previous token forward, and a later head uses it to find what came after an earlier occurrence (Elhage et al., 2021). Here the conv does the first step inside a single layer. Trained models are messier than this, but the idea is the same.\nThe fast-weight view gives another way to see this.4 The memory is solving a small regression from keys to values. Without the conv, \\(k_t=W_kx_t\\) and \\(v_t=W_vx_t\\) are two views of the same vector, so there\u0026rsquo;s little for that regression to learn: if keys equalled values, the best memory would just be the identity. Mixing earlier tokens into the key gives it something real to fit.\nWhy four? # Keys can also span more than one token:\nalpha zeta rabbit beta zeta tiger ... alpha zeta ? Now zeta alone isn\u0026rsquo;t enough, and the key has to know about alpha too. A shift by one can\u0026rsquo;t do that, but a window of a few tokens can. For that we can just increase the kernel size of the conv. But which value works best in practice?\nIn almost every real-world implementation of shortconv (including all models mentioned earlier), the chosen kernel size is 4. What is the reason for that?\nDigging through the papers, I couldn\u0026rsquo;t find anyone arguing for 4 specifically. It seems to trace back to Albert Gu and Tri Dao\u0026rsquo;s Mamba (d_conv=4), released in December 2023, together with Dao\u0026rsquo;s causal-conv1d CUDA kernel, which only accepts kernel size \\(\\in \\{2,3,4\\}\\). Later models mostly followed. The DeltaNet paper adds its short convolution because \u0026ldquo;recent linear recurrent models typically incorporate\u0026rdquo; one (citing, among others, Hyena and xLSTM), and sets the kernel size to 4. Kimi Linear mentions \u0026ldquo;a small kernel size (e.g., 4)\u0026rdquo;, and FLA, the Qwen configs, Canon layers and Inkling all use 4 as well.\nSo does 4 actually work best? A few papers tried other kernel sizes:\nKernel size 2Mamba2Furious, ~300M (loss) Dynamic convs, 300M (PPL) Static convs, Qwen3-1.7B (PPL) no conv 3.06 19.12 13.42 1 — 18.42 — 2 2.93 18.17 12.99 3 2.91 18.08 12.79 4 2.90 18.10 13.13 In all three, most of the gain comes from adding a convolution in the first place. Beyond that the differences are small, and they don\u0026rsquo;t always favour 4. The dynamic-conv study also tried 5 and 6, but neither showed an improvement. Primer (which put depthwise conv [with kernel_size=3] after Q/K/V back in 2021) found the same: \u0026ldquo;wider depthwise convolution and standard convolution not only do not improve performance, but in several cases hurt it.\u0026rdquo;\nAblations # So how much does the conv actually help? Some papers report what happens with and without conv:\nModel Setup Without conv With conv DeltaNet 340M, 15B tokens (LAMBADA ppl) 50.87 37.37 GDN 400M (average ppl) 28.95 27.35 Kimi Linear 16-layer ablation model (validation ppl) 5.70 5.65 The conv helps in all three, but by different amounts: a lot for DeltaNet, and only a little for Kimi Linear (and that is on a small ablation model, not the released 48B one). It also isn\u0026rsquo;t strictly needed for recall (the DeltaNet paper shows high associative recall, at least on synthetic tasks, without it).\nQ, K or V? # The explanations so far give a good reason to put the conv on the keys. In practice, we see the conv appearing on Q, K and V. Why would conv help on queries and values? Two recent studies tried different placements in a transformer:\nConv on Dynamic convs, 300M Static convs, Qwen3-1.7B no conv 19.12 13.42 Q 18.69 13.38 K 18.83 13.29 V 18.56 13.21 Q + K 18.44 — Q + V 18.36 — K + V 18.35 — Q + K + V 18.10 12.85 Perplexity, lower is better. Both studies use transformers (not linear attention).\nIn both studies, V on its own helps more than Q or K on its own, and putting the conv on all three works best. The second study compared 17 different places in the block, and Q+K+V still won. The V result is the one I find most interesting, since the key-shift story from before doesn\u0026rsquo;t explain it.\nA short conv with a long history # Below is my best effort at reconstructing the chain of events that led to the emergence of shortconvs in so many frontier architectures.\nMixing a few neighbouring tokens before (or instead of) attention is an older idea than the recent linear-attention models. In 2019, Wu et al. showed that lightweight and dynamic convolutions could compete with self-attention in machine translation, and a year later Conformer combined convolutions and attention for speech recognition. The exact placement we care about here (a small depthwise convolution right after the Q/K/V projections) shows up in Primer in 2021, whose architecture search arrived at what the authors call \u0026ldquo;multi-dconv-head attention\u0026rdquo;.\nIn recurrent models, the operation started out as a shift. H3 paired a \u0026ldquo;shift-SSM\u0026rdquo;, which carries the last few tokens forward, with a longer-range SSM (designed for exactly the kind of recall this example needs). Hyena kept short convolutions next to its long ones, and Mamba made a kernel-size-4 conv a standard. Around the same time, Zoology found that most of the perplexity gap between these efficient models and attention comes down to recalling earlier tokens, and its follow-up, Based, paired linear attention with short convolutions. RWKV arrived at something similar in 2023 with its \u0026ldquo;token shift\u0026rdquo;, a learned per-channel mix of the current and previous token. By mid-2024, shortconv was common enough that in the DeltaNet paper the authors write: \u0026ldquo;Recent linear recurrent models typically incorporate a lightweight depthwise-separable convolution layer after the query/key/value projections. This \u0026lsquo;short convolution\u0026rsquo; layer generalizes the shift SSM, and is efficient in both number of parameters and computational cost.\u0026rdquo;\nMeanwhile, the shortconv also found its way back into softmax attention. The Forgetting Transformer shifts its keys and values, Canon layers add kernel-size-4 convolutions all over the block (their conv, they write, \u0026ldquo;is inspired by Mamba and GLA, which trace back to H3, where the component was introduced as \u0026lsquo;shift-SSM.\u0026rsquo;\u0026rdquo;), and Liquid AI\u0026rsquo;s LFM2 pairs short convolutions with softmax attention, with Mathias Lechner arguing that the convolutions were doing much of the work. Dynamic short convolutions bring back Wu et al.\u0026rsquo;s dynamic convolutions, whose filters are computed from the current token, and TML\u0026rsquo;s Inkling puts kernel-size-4 convolutions on K/V (but not Q).\nAt the same time, some recent models drop the shortconv. Mamba-3 removes the separate short convolution of Mamba-2 (but introduces an operation equivalent to a data-dependent convolution with kernel size 2, inside the recurrence). Most lately, DeepSeek\u0026rsquo;s Engram module was introduced in January 2026 with a kernel-size-4 causal conv, and lost it again in DeepSeek-V4.1 later that year, \u0026ldquo;because its performance gains do not justify the added complexity in our inference stack\u0026rdquo;.\nThat\u0026rsquo;s it # Thanks for reading! This post grew out of my own attempt to understand one small box in an architecture diagram, so if I got something wrong or missed a paper, please let me know :)\nReferences # Induction heads. Olsson, C., et al. (2022). \u0026ldquo;In-context Learning and Induction Heads.\u0026rdquo; Transformer Circuits Thread. transformer-circuits.pub Transformer circuits. Elhage, N., et al. (2021). \u0026ldquo;A Mathematical Framework for Transformer Circuits.\u0026rdquo; Transformer Circuits Thread. transformer-circuits.pub Linear attention. Katharopoulos, A., Vyas, A., Pappas, N., \u0026amp; Fleuret, F. (2020). \u0026ldquo;Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention.\u0026rdquo; ICML 2020. arXiv:2006.16236 Fast weights. Hinton, G. E., \u0026amp; Plaut, D. C. (1987). \u0026ldquo;Using Fast Weights to Deblur Old Memories.\u0026rdquo; Proceedings of the 9th Annual Conference of the Cognitive Science Society, 177–186. escholarship Fast weight memories. Schmidhuber, J. (1992). \u0026ldquo;Learning to Control Fast-Weight Memories: An Alternative to Dynamic Recurrent Networks.\u0026rdquo; Neural Computation, 4(1), 131–139. MIT Press · author\u0026rsquo;s blog post on the 1991 report Fast weight programmers. Schlag, I., Irie, K., \u0026amp; Schmidhuber, J. (2021). \u0026ldquo;Linear Transformers Are Secretly Fast Weight Programmers.\u0026rdquo; ICML 2021. arXiv:2102.11174 DeltaNet. Yang, S., Wang, B., Zhang, Y., Shen, Y., \u0026amp; Kim, Y. (2024). \u0026ldquo;Parallelizing Linear Transformers with the Delta Rule over Sequence Length.\u0026rdquo; NeurIPS 2024. arXiv:2406.06484 Gated DeltaNet. Yang, S., Kautz, J., \u0026amp; Hanson, A. (2025). \u0026ldquo;Gated Delta Networks: Improving Mamba2 with Delta Rule.\u0026rdquo; ICLR 2025. arXiv:2412.06464 Kimi Linear / KDA. Kimi Team (2025). \u0026ldquo;Kimi Linear: An Expressive, Efficient Attention Architecture.\u0026rdquo; arXiv:2510.26692 GLA. Yang, S., Wang, B., Shen, Y., Panda, R., \u0026amp; Kim, Y. (2024). \u0026ldquo;Gated Linear Attention Transformers with Hardware-Efficient Training.\u0026rdquo; ICML 2024. arXiv:2312.06635 Mamba-2. Dao, T., \u0026amp; Gu, A. (2024). \u0026ldquo;Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality.\u0026rdquo; ICML 2024. arXiv:2405.21060 TTT. Sun, Y., et al. (2024). \u0026ldquo;Learning to (Learn at Test Time): RNNs with Expressive Hidden States.\u0026rdquo; arXiv:2407.04620 Test-time regression. Wang, K. A., Shi, J., \u0026amp; Fox, E. B. (2025). \u0026ldquo;Test-time regression: a unifying framework for designing sequence models with associative memory.\u0026rdquo; arXiv:2501.12352 DeltaNet Explained. Yang, S. (2024). \u0026ldquo;DeltaNet Explained\u0026rdquo; (blog series, parts I–III). sustcsonglin.github.io Dynamic short convolutions. Sieberling, O., Runwal, B., Panda, R., \u0026amp; Kim, Y. (2026). \u0026ldquo;Dynamic Short Convolutions Improve Transformers.\u0026rdquo; arXiv:2606.03825 Mamba. Gu, A., \u0026amp; Dao, T. (2023). \u0026ldquo;Mamba: Linear-Time Sequence Modeling with Selective State Spaces.\u0026rdquo; arXiv:2312.00752 2Mamba2Furious. Mongaras, G., \u0026amp; Larson, E. C. (2026). \u0026ldquo;2Mamba2Furious: Linear in Complexity, Competitive in Accuracy.\u0026rdquo; arXiv:2602.17363 Hyena. Poli, M., et al. (2023). \u0026ldquo;Hyena Hierarchy: Towards Larger Convolutional Language Models.\u0026rdquo; ICML 2023. arXiv:2302.10866 xLSTM. Beck, M., et al. (2024). \u0026ldquo;xLSTM: Extended Long Short-Term Memory.\u0026rdquo; NeurIPS 2024. arXiv:2405.04517 Conformer. Gulati, A., et al. (2020). \u0026ldquo;Conformer: Convolution-augmented Transformer for Speech Recognition.\u0026rdquo; Interspeech 2020. arXiv:2005.08100 Primer. So, D. R., et al. (2021). \u0026ldquo;Primer: Searching for Efficient Transformers for Language Modeling.\u0026rdquo; NeurIPS 2021. arXiv:2109.08668 RWKV. Peng, B., et al. (2023). \u0026ldquo;RWKV: Reinventing RNNs for the Transformer Era.\u0026rdquo; Findings of EMNLP 2023. arXiv:2305.13048 H3. Fu, D. Y., et al. (2023). \u0026ldquo;Hungry Hungry Hippos: Towards Language Modeling with State Space Models.\u0026rdquo; ICLR 2023. arXiv:2212.14052 Zoology. Arora, S., et al. (2024). \u0026ldquo;Zoology: Measuring and Improving Recall in Efficient Language Models.\u0026rdquo; ICLR 2024. arXiv:2312.04927 Based. Arora, S., et al. (2024). \u0026ldquo;Simple Linear Attention Language Models Balance the Recall-Throughput Tradeoff.\u0026rdquo; ICML 2024. arXiv:2402.18668 · Hazy Research blog post Forgetting Transformer. Lin, Z., et al. (2025). \u0026ldquo;Forgetting Transformer: Softmax Attention with a Forget Gate.\u0026rdquo; ICLR 2025. arXiv:2503.02130 Canon layers. Allen-Zhu, Z. (2025). \u0026ldquo;Physics of Language Models: Part 4.1, Architecture Design and the Magic of Canon Layers.\u0026rdquo; arXiv:2512.17351 Dynamic convolutions. Wu, F., Fan, A., Baevski, A., Dauphin, Y. N., \u0026amp; Auli, M. (2019). \u0026ldquo;Pay Less Attention with Lightweight and Dynamic Convolutions.\u0026rdquo; ICLR 2019. arXiv:1901.10430 Mamba-3. Lahoti, A., Li, K. Y., Chen, B., Wang, C., Bick, A., Kolter, J. Z., Dao, T., \u0026amp; Gu, A. (2026). \u0026ldquo;Mamba-3: Improved Sequence Modeling using State Space Principles.\u0026rdquo; arXiv:2603.15569 Convolution placement and kernel size. Tian, Y., Shu, Y., He, W., Zhang, S., Zhao, T., Xu, C., Chen, X., Wang, Y., Chen, H., \u0026amp; Wang, Y. (2026). \u0026ldquo;Convolution for Large Language Models Technical Report.\u0026rdquo; arXiv:2607.18413 Short convolutions without linear attention. Lechner, M. (2025). \u0026ldquo;Flipping the Script: Why Short Convolutions Don\u0026rsquo;t Need Linear Attention\u0026rdquo; (blog post). mlechner.substack.com Why linear attention needs a short conv. Su, J. (2025). \u0026ldquo;为什么线性注意力要加Short Conv？\u0026rdquo; [Why does linear attention need Short Conv?] (blog post, in Chinese). kexue.fm Engram. Cheng, X., et al. (2026). \u0026ldquo;Conditional Memory via Scalable Lookup: A New Axis of Sparsity for Large Language Models.\u0026rdquo; ACL 2026. arXiv:2601.07372 Models and code # DeepSeek-V4.1. DeepSeek-AI (2026). \u0026ldquo;DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression.\u0026rdquo; Hugging Face Kimi K3. Kimi Team (2026). \u0026ldquo;Kimi K3: Open Frontier Intelligence.\u0026rdquo; arXiv:2607.24653 Inkling. Thinking Machines Lab (2026). \u0026ldquo;Inkling: Our Open-Weights Model.\u0026rdquo; thinkingmachines.ai · model card · weights and config Model cards. Qwen3-Next-80B-A3B-Instruct · Qwen3.5-0.8B-Base · Kimi-Linear-48B-A3B-Instruct · GLM-5.3-Flash Code. flash-linear-attention (GatedDeltaNet layer) · Hugging Face Transformers (Qwen3.5 and Qwen3-Next modeling code) · Kimi Linear modeling code · causal-conv1d (CUDA kernel for short causal convolutions) Despite the recurrence, training doesn\u0026rsquo;t have to loop token by token. Chunkwise-parallel algorithms handle the recurrence by chunks, so most of the work runs in parallel on a GPU. For a better introduction to all of this, I recommend Songlin Yang\u0026rsquo;s own blog posts, starting with DeltaNet Explained.\u0026#160;\u0026#x21a9;\u0026#xfe0e;\nThis idea goes back to Hinton \u0026amp; Plaut (1987), who used fast weights as a temporary memory, and to Schmidhuber (1992) who had one network program another network\u0026rsquo;s fast weights with outer products, which is the update rule above with keys and values under older names. This latter connection was made explicit by Schlag et al. (2021).\u0026#160;\u0026#x21a9;\u0026#xfe0e;\nIn FLA and Kimi, Q, K and V each get their own separate shortconv with \\(m=4\\). Qwen3.5 runs Q, K and V through one grouped module. Either way, each channel keeps its own filter, so there is no mathemtical difference.\u0026#160;\u0026#x21a9;\u0026#xfe0e;\nThe argument comes from a blog post by Moonshot AI\u0026rsquo;s Su Jianlin (in Chinese), which I found through Liquid AI\u0026rsquo;s Mathias Lechner\u0026rsquo;s post, along with a short English summary by Harold Benoit.\u0026#160;\u0026#x21a9;\u0026#xfe0e;\n","date":"15 September 2026","externalUrl":null,"permalink":"/blog/short-convolutions/","section":"Blog","summary":"On shortconvs and their contribution to attention: how local mixing builds key/value associations, what published ablations show, and where shortconv appears in modern models.","title":"A closer look at short convolutions","type":"blog"},{"content":"","date":"15 September 2026","externalUrl":null,"permalink":"/categories/","section":"Categories","summary":"","title":"Categories","type":"categories"},{"content":"","date":"15 September 2026","externalUrl":null,"permalink":"/tags/fast-weights/","section":"Tags","summary":"","title":"Fast-Weights","type":"tags"},{"content":"","date":"15 September 2026","externalUrl":null,"permalink":"/tags/linear-attention/","section":"Tags","summary":"","title":"Linear-Attention","type":"tags"},{"content":"","date":"15 September 2026","externalUrl":null,"permalink":"/categories/machine-learning/","section":"Categories","summary":"","title":"Machine-Learning","type":"categories"},{"content":"","date":"15 September 2026","externalUrl":null,"permalink":"/tags/short-convolution/","section":"Tags","summary":"","title":"Short-Convolution","type":"tags"},{"content":" Closed-form evaluations of log-sine integrals and Apéry-like sums in terms of polylogarithms. Integral Transforms and Special Functions, 2026.\nA symmetric extension of Zhao\u0026rsquo;s series for ζ(5). Preprint, arXiv:2610.34482, 2026.\nBorwein-Bradley-type identities for Ramanujan-type series for 1/π⁴. Preprint, arXiv:2610.04770, 2026.\nShape-Transition in Non-Euclidean Ribbons. MSc thesis, Hebrew University of Jerusalem, supervised by Prof. Cy Maor. Unpublished.\n","date":"10 September 2026","externalUrl":null,"permalink":"/publications/","section":"Noam Shalev","summary":"","title":"Publications","type":"page"},{"content":"","date":"23 October 2025","externalUrl":null,"permalink":"/tags/contrastive-learning/","section":"Tags","summary":"","title":"Contrastive-Learning","type":"tags"},{"content":"","date":"23 October 2025","externalUrl":null,"permalink":"/tags/e-graphs/","section":"Tags","summary":"","title":"E-Graphs","type":"tags"},{"content":"","date":"23 October 2025","externalUrl":null,"permalink":"/tags/embeddings/","section":"Tags","summary":"","title":"Embeddings","type":"tags"},{"content":" IntegralIndx is a search engine I built for finding integrals by what they mean rather than by how they happen to be typed. You hand it an integrand, and it hands back mathematically similar ones out of a database scraped from Math StackExchange. Try the live demo, or browse the code.\nThe live demo. This post is how it works: e-graphs and contrastive learning for the embeddings, and a rather long fight with real-world LaTeX for the data.\nWhy I Built This # In my mathematics research1 I spend a lot of time searching for integrals online, mainly on Google and on Math StackExchange. It is often very frustrating because this kind of textual search works well only on very simple integrals, and even then I might miss useful results due to syntactic differences between my query and the results I was after. This happens because mathematical expressions can be written in many different ways, due to: basic mathematical rules (commutativity, power rules, etc.), naming conventions (e^x vs. exp(x), arcsin vs. sin^{-1}), or even personal taste in TeX formatting (arbitrary choice of the variable of integration, parameter names, and TeX commands).\nFor years, I had this idea in the back of my mind: build a proper, searchable integral database. I wanted a search engine that actually \u0026lsquo;understands\u0026rsquo; mathematical expressions, providing an easy way to find other semantically similar integrals, something which simple bag-of-words approaches just can\u0026rsquo;t do.\nOnly now, when I finally found some free time, and after delving deeper into machine learning theory at university, I realized how ridiculously complex this problem actually is. The key thing needed for such a search engine is good embeddings of mathematical expressions, ones that capture the actual semantic meaning of the symbols involved. So I started reading some literature. I found MathBERT (Peng et al., 2021), which showed impressive results on mathematical reasoning tasks. The thing is, it\u0026rsquo;s fundamentally a language model. It\u0026rsquo;s trained on mathematical text with surrounding natural language, learning to predict masked tokens based on textual context. Even though it works reasonably well, I wanted something that understands pure mathematical equivalence without any surrounding text.\nThen I found SemEmb (Gangwar \u0026amp; Kani, 2023), which creates embeddings over symbolic expressions directly. This seemed like exactly what I was looking for! It had decent results and was heading in the right direction. But then I stumbled upon the recent E-Gen (Zheng et al., 2025) paper, and I was genuinely thrilled. E-Gen took everything SemEmb was doing and pushed it much further. The greatest obstacle thus far was the very limited amount of meaningful training data available. The authors of E-Gen proposed a beautiful solution for this problem (using e-graphs), and showed how to generate massive synthetic datasets of equivalent expressions starting with only a small initial set of clean mathematical expressions. I immediately knew that I must try it out.\nThis demo is my attempt at putting my idea into practice, and build a search engine that actually understands mathematical expressions.\nE-Graphs \u0026amp; E-Gen Overview # How Do We Get Good Embeddings of Mathematical Expressions? # The key insight is that embeddings need to capture semantic equivalence, not just syntactic similarity. If two expressions are mathematically identical, like \\(\\sin^2(x) + \\cos^2(x)\\) and \\(1\\), their embeddings should be close together in vector space. But how do you teach a neural network what \u0026ldquo;mathematically equivalent\u0026rdquo; means? The answer is to train it on pairs (or clusters) of equivalent expressions. By showing the model many (!) examples of expressions that mean the same thing but look different, it learns to recognize the underlying mathematical structure rather than just memorizing symbol patterns. As I mentioned, the main challenge is in the creation of a large enough corpus of such equivalence clusters, so that a model can actually read some signal off of the data.\nSemEmb took this approach by generating equivalent expression pairs using SymPy\u0026rsquo;s simplification functions. The problem is that SymPy is designed to find the most simplified form directly, without generating intermediate steps. This meant SemEmb was limited to cluster sizes of just 2 (pairs of expressions), missing out on the rich diversity of equivalent expressions that exist between the original and simplified forms.\nE-Gen\u0026rsquo;s Innovation: E-Graphs # E-Gen solves this limitation using e-graphs (equality graphs), a data structure originally invented in 1980 by Nelson \u0026amp; Oppen for automated theorem proving. The idea of equality saturation (applying all possible equalities within an e-graph until saturation) was later leveraged for program optimization by Tate et al. (2009), and more recently, Willsey et al. (2021) developed the egg library, which made equality saturation fast and practical (via new techniques like efficient rebuilding and e-class analyses). Instead of producing just a pair of expressions, equality saturation starts with a seed expression and systematically applies mathematical rewrite rules to explore the entire space of equivalent forms. The e-graph compactly represents all these equivalences in \u0026ldquo;e-classes\u0026rdquo;, where each e-class contains expressions that are mathematically identical (see this blogpost for a really nice introduction to e-graphs).\nThis enables E-Gen to generate dozens or even hundreds of equivalent forms per seed expression, creating rich training datasets where each expression becomes a large cluster of mathematically equivalent variants. A transformer trained on these massive clusters using contrastive learning (pulling equivalent expressions together, pushing unrelated ones apart) learns to capture deep semantic relationships rather than surface-level syntactic patterns.\nFigure 1: Overview of E-Gen and the cluster-based training framework. Equivalent expressions of each initial expression are generated using an e-graph-based approach, forming clusters of equivalent expressions. The original E-Gen paper implemented both a seq2seq model (trained on equivalent expression pairs) and a contrastive learning model (trained on triplets). For IntegralIndx, I chose to focus on the contrastive learning approach because it\u0026rsquo;s more efficient for similarity search tasks, learning embeddings directly without requiring a decoder. Source: Zheng et al. (2025), \u0026ldquo;E-Gen: Leveraging E-Graphs to Improve Continuous Representations of Symbolic Expressions.\u0026rdquo; Figure 2. The key insight is that expressions like \\(x^2 + 2x + 1\\) and \\((x + 1)^2\\) are mathematically identical, and their embeddings should reflect this equivalence. E-graphs provide the machinery to systematically generate and exploit these equivalences during training, going far beyond what simple rewrite rules can achieve.\nData Collection \u0026amp; Processing Pipeline # Of course, good embeddings mean little without actual data to embed. I turned to Math StackExchange for the data, knowing that it contains thousands of high-quality integrals from real problems, that people asked about and cared to solve. Better yet, each integral can be linked to its source discussion, which often includes the context in which this integral arises, possible closed-forms, and a variety of solution attempts.\nWhen I started this project, I thought the data part would be straightforward. Scrape the integrals from MSE, throw them in a database, and move on to the interesting ML work. Naive me.\nData processing is easily the hardest part of this entire project. Real-world LaTeX from MSE is messy, inconsistent, and filled with edge cases I never imagined. People write integrals in dozens of different ways, use custom macros, nest them in complex equation environments, and mix them with narrative text. I needed to convert all of this dirty, real-world LaTeX into a clean, normalized form that could be reliably parsed.\nWhy can\u0026rsquo;t we just use the LaTeX as is? # LaTeX is designed for typesetting, not semantic analysis. The expression \\(x^2\\) can be written as x^2, x^{2}, {x}^{ 2 }, and many other variations which result in the same visuals. These different strings would be treated as unrelated expressions if we were to tokenize LaTeX directly. SymPy provides semantic parsing: a canonical tree representation that stays the same regardless of how the expression was typeset. This semantic representation is useful here for two reasons: first, it gives an easy way to convert the expression to prefix notation (pow x 2), which is a good format to apply tokenization to, and second, it allows us to use SymPy\u0026rsquo;s simplification functions to deduplicate integrals by their canonical integrand.\nBut getting to that point required building custom parsing logic to clean the raw MSE data. After applying a plethora of hand-tailored normalization and filtering rules (which I\u0026rsquo;ll describe below), we still need to convert the cleaned LaTeX into SymPy format. While there are some good LaTeX-to-SymPy parsers out there, nothing exactly fit my requirements. I ended up forking the latex2sympy2_extended package (which is itself a fork of previous latex2sympy versions) and adding custom parsing capabilities for some special functions. Even then, I had to be pretty restrictive: blacklisting certain LaTeX commands that caused parsing issues, setting timeouts on the parser (20 seconds per expression), and rejecting anything that looked remotely ambiguous. I\u0026rsquo;m sure I lost thousands of potentially valid integrals in the process, but reliability was more important than coverage.\nWhat started as \u0026ldquo;just scrape and parse\u0026rdquo; became a multi-stage pipeline with normalization, validation, deduplication, and variable canonicalization. Let me walk you through it.\nPipeline Overview # Four stages take the corpus from 206k raw strings down to 12,337 distinct integrands.\nScraping. I queried the Math StackExchange API across 20 integral-related tags (closed-form, integration, definite-integrals, special-functions, polylogarithm, and so on), taking 80 pages per tag at 100 questions per page, sorted by votes. Questions and answers together gave 206,328 raw LaTeX strings.\nLaTeX normalization. MSE posts wrap their mathematics in align and equation environments, chain several forms of the same quantity together, and tack conditions onto the end. So the raw strings are parsed into structure first: environments unwrapped, relation chains split into their members (so \\(A = B = C\\) becomes \\(\\{A, B, C\\}\\), which conveniently hands us equivalent forms for free), and parametric conditions like \u0026ldquo;for \\(x \u003e 0\\)\u0026rdquo; separated from the expression they constrain.\nExtraction and validation. Definite and indefinite integrals are pulled out of the normalized strings and handed to SymPy, which acts as the arbiter: anything it refuses to parse, or that reaches for a function outside the vocabulary, is dropped. After quality filtering and deduplication, 26,730 integrals survived.\nCanonicalization and grouping. Two integrals that differ only in their choice of letters are the same integral. So every integration variable becomes \\(x\\), free parameters are renamed in alphabetical order as \\(a, b, c\\) (at most three), and what remains is grouped by the hash of the simplified integrand. That collapsed 23,638 instances into 12,337 distinct groups.\nStage Expressions surviving Raw MSE strings 206,328 Parsed and validated integrals 26,730 After canonicalization 23,638 Unique integrand groups 12,337 I do hope to find the time in the future to scale up this database, and create similar databases for sums, products, and special functions.\nModel Architecture \u0026amp; Training # Transformer Architecture # IntegralIndx uses an encoder-only transformer architecture for generating mathematical expression embeddings. The model processes tokenized expressions in prefix notation and produces vector representations via mean pooling. Unlike seq2seq, this architecture directly optimizes for embedding quality through contrastive learning, making it ideal for similarity search tasks.\nComponent Specification Encoder Layers 6 Hidden Dimension 512 Attention Heads 8 Feed-Forward Dimension 2048 Dropout 0.1 Positional Encoding Sinusoidal Pooling Strategy Mean Output Embedding Dimension 512 Vocabulary Size 62 tokens Total Parameters 18,946,048 (~19M) Figure 2: The encoder. Tokens pass through 6 transformer layers, then mean-pooling collapses them to a single 512-dimensional embedding. (Made with draw.io.) Contrastive Learning # The model is trained using contrastive learning with the InfoNCE loss (temperature = 0.1). This is a self-supervised approach: rather than requiring manual labels, the model learns from equivalence clusters generated via E-Gen. Given a query expression and its positive equivalent, the loss maximizes their cosine similarity while minimizing similarity to negative samples (randomly sampled from other clusters). This forces the encoder to learn representations where mathematically equivalent expressions cluster together in the 512-dimensional embedding space.\nTraining Data Generation # Training data was generated through a three-stage pipeline:\nSeed Selection: 1,793 seed expressions were frozen for training: 337 hand-crafted synthetic seeds covering common patterns (polynomials, trig identities, logarithms, etc.) 1,456 expressions extracted from the IntegralIndx database with max token length = 8 Token limit ensures E-Gen can generate diverse equivalents without timing out E-Gen Equivalence Generation: Apply E-Gen to each seed. Of the 1,793 seeds, 1,243 seeds successfully generated equivalents (69.3% success rate), producing an average of 154 equivalents per seed (median: 74). This resulted in 191,394 total equivalent expressions across all clusters. The variability in cluster sizes reflects the mathematical complexity of different expressions: simple expressions often yield larger clusters, while complex expressions may have fewer equivalent forms within the token limit. TSV Construction: Split seeds 80/10/10 (train/val/test). For each seed, generate all pairwise combinations (query, positive) and sample 3 negatives from other clusters within the same split (clusters with more than 200 equivalents are restricted to 70 positives per query via random sampling to prevent over-representation). The dataset is stored in TSV (tab-separated values) format for efficient loading. Train: 12.68M lines (994 seeds) Validation: 1.59M lines (124 seeds) Test: 1.46M lines (125 seeds) Total: 15.73M training quintuples (query, positive, neg1, neg2, neg3) Training Procedure # The model was trained for 4 epochs over 49 hours on a rented L40S GPU via Vast.ai (totaling $35). The production model uses checkpoint 175,000 (3.5 epochs, 43 hours), as the final checkpoint was accidentally deleted (sigh). Training used the AdamW optimizer with cosine annealing and a 1-epoch warmup schedule. The warmup phase linearly increases the learning rate from 1e-5 to 1e-4, after which the learning rate decays via cosine annealing to a minimum of 1e-6.\nHyperparameter Value Optimizer AdamW (\\(\\beta_1 = 0.9\\), \\(\\beta_2 = 0.999\\), \\(\\varepsilon = 10^{-8}\\)) Learning Rate (max) 1e-4 Weight Decay 0.01 LR Schedule Cosine Annealing + Linear Warmup Warmup Epochs 1 Min Learning Rate 1e-6 Batch Size 256 Gradient Clipping max_norm = 1.0 Loss Function InfoNCE Temperature 0.1 Epochs 4 Training Results # The model converges steadily across 3.5 epochs, with training loss decreasing from 1.18 (initial) to ~0.0015 and validation loss from 0.0131 (end of epoch 1) to ~0.009. Validation loss tracks training loss closely with minimal overfitting, indicating good generalization to unseen equivalence clusters.\nFigure 3: Training and validation loss curves over ~198k iterations (3.5 epochs). The bump at iteration ~49k corresponds to the warmup schedule transitioning from 1e-5 to 1e-4. Both losses decrease steadily, indicating successful contrastive learning of mathematical equivalence. Validation is evaluated every 10k iterations (marked with orange dots). FAISS Similarity Search # Once the transformer model has generated 512-dimensional embeddings for all integrand groups in the database, the next challenge is efficient similarity search: given a query embedding, how do we quickly find the most similar integrands among thousands of candidates? This is where FAISS (Facebook AI Similarity Search) comes in. FAISS is a library developed by Facebook AI Research for efficient similarity search and clustering of dense vectors. It\u0026rsquo;s optimized for large-scale vector search operations and is widely used in recommendation systems, image retrieval, and natural language processing. FAISS provides both exact and approximate nearest neighbor search algorithms, with support for CPU and GPU acceleration.\nIntegralIndx uses IndexFlatIP (Flat Inner Product), which performs exact search using dot product similarity. Note that mathematically, via L2-normalization, dot product similarity is the same as cosine similarity. The flat index guarantees exact nearest neighbors (no false negatives), which naturally requires more compute (a flat index requires \\(O(n)\\) comparisons), but with our \\(n = 12\\text{k}\\) database this is less than 10ms on a modern CPU. For larger datasets, approximate indexes like IVFFlat or HNSW would be faster.\nSearch Pipeline # One thing to get out of the way first: all that LaTeX machinery was for building the database, not for serving it. A query is entered as a SymPy expression and handed straight to sympify, so the search side never touches LaTeX at all. What it does share with the corpus is everything downstream of that, and that is the part that matters: the same variable normalization, the same prefix notation, the same tokenizer, the same encoder. That is what puts a query and the database in one space.\n\\[ \\begin{aligned} \\text{query} \u0026\\xrightarrow{\\ \\texttt{sympify} + \\text{validate}\\ } e \\xrightarrow{\\ \\text{normalize}\\ } \\tilde{e} \\xrightarrow{\\ \\text{prefix}\\ } (t_1, \\ldots, t_n) \\\\ \u0026\\xrightarrow{\\ \\text{tokenize}\\ } (i_1, \\ldots, i_n) \\xrightarrow{\\ E_\\theta,\\ \\text{mean-pool}\\ } v \\in \\mathbb{R}^{512} \\xrightarrow{\\ v \\,/\\, \\lVert v \\rVert\\ } \\hat{v} \\end{aligned} \\]The first arrow parses and rejects: anything SymPy cannot read, anything reaching for a symbol outside the vocabulary, and anything with multi-letter variable names gets turned away with a message rather than silently mangled. The second is the canonicalization from earlier, integration variable renamed to \\(x\\) and free parameters to \\(a, b, c\\), so a query written in \\(t\\) still finds integrands stored in \\(x\\). The third and fourth flatten the expression tree into prefix notation and look those tokens up in the 62-token vocabulary. The fifth is the encoder \\(E_\\theta\\), mean-pooling its hidden states into a single 512-dimensional vector. The last puts that vector on the unit sphere, which is what makes the inner product FAISS computes a cosine similarity.\nFAISS then returns the top-\\(k\\) nearest integrand groups by inner product against \\(\\hat{v}\\), and those come back with their similarity scores attached.\nClosing Thoughts # So that\u0026rsquo;s IntegralIndx. From an idea I had years ago, to a working semantic search engine built on e-graphs and contrastive learning. It\u0026rsquo;s far from perfect. The database is still small, the normalization pipeline could be more efficient, training could be longer, and I\u0026rsquo;m certain there are parsing errors lurking in edge cases I haven\u0026rsquo;t encountered yet. But it does what I wanted: you can type in an integral, and it actually understands what you\u0026rsquo;re looking for, not just what characters you typed. Whether you\u0026rsquo;re a student stuck on a homework problem or a researcher hunting for closed forms, I hope this makes finding relevant integrals a little less frustrating than it was for me.\nReferences # E-Gen. Zheng, H., Wang, S., Gangwar, N., \u0026amp; Kani, N. (2025). \u0026ldquo;E-Gen: Leveraging E-Graphs to Improve Continuous Representations of Symbolic Expressions.\u0026rdquo; NAACL 2025. arXiv:2501.14951 · code (CC BY-NC-SA 4.0) · patent US20240135148A1 (University of Illinois System). This project is built upon the foundational research and implementation provided by the E-Gen team. MathBERT. Peng, S., Yuan, K., Gao, L., \u0026amp; Tang, Z. (2021). \u0026ldquo;MathBERT: A Pre-trained Language Model for General NLP Tasks in Mathematics Education.\u0026rdquo; arXiv:2105.00377 SemEmb. Gangwar, N., \u0026amp; Kani, N. (2023). \u0026ldquo;Semantic Representations of Mathematical Expressions in a Continuous Vector Space.\u0026rdquo; TMLR. arXiv:2211.08142 E-graphs (original). Nelson, G., \u0026amp; Oppen, D. C. (1980). \u0026ldquo;Fast Decision Procedures Based on Congruence Closure.\u0026rdquo; Journal of the ACM, 27(2), 356–364. doi:10.1145/322186.322198 Equality saturation. Tate, R., Stepp, M., Tatlock, Z., \u0026amp; Lerner, S. (2009). \u0026ldquo;Equality Saturation: A New Approach to Optimization.\u0026rdquo; POPL 2009, 264–276. doi:10.1145/1480881.1480915 · PDF. An extended journal version appeared as Logical Methods in Computer Science 7(1) (2011), arXiv:1012.1802. egg (fast equality saturation). Willsey, M., Nandi, C., Wang, Y. R., Flatt, O., Tatlock, Z., \u0026amp; Panchekha, P. (2021). \u0026ldquo;egg: Fast and Extensible Equality Saturation.\u0026rdquo; PACMPL, 5(POPL), 1–29. (Distinguished Paper Award, POPL 2021.) doi:10.1145/3434304 · arXiv:2004.03082 · egraphs-good.github.io Data source # All integral expressions in the dataset are sourced from Math StackExchange. User-contributed content there is licensed under CC BY-SA 4.0. I gratefully acknowledge the MSE community for creating and curating this valuable mathematical content.\nLicense \u0026amp; disclaimer # IntegralIndx is licensed under CC BY-NC-SA 4.0. Repository: github.com/noamshh/IntegralIndx.\nNon-commercial use only. This is a personal research project for educational purposes. No warranty is provided. Users should independently verify all mathematical expressions and results. The dataset may contain parsing errors or inaccuracies from the source data. Always verify results before relying on them for academic or professional work.\nMostly closed forms for integrals and series. See publications.\u0026#160;\u0026#x21a9;\u0026#xfe0e;\n","date":"23 October 2025","externalUrl":null,"permalink":"/blog/integralindx-theory/","section":"Blog","summary":"A search engine I built that finds integrals by semantic similarity, using e-graphs and contrastive learning.","title":"IntegralIndx: semantic search for integrals","type":"blog"},{"content":"","date":"23 October 2025","externalUrl":null,"permalink":"/tags/integrals/","section":"Tags","summary":"","title":"Integrals","type":"tags"},{"content":"","date":"23 October 2025","externalUrl":null,"permalink":"/categories/projects/","section":"Categories","summary":"","title":"Projects","type":"categories"},{"content":"","date":"23 October 2025","externalUrl":null,"permalink":"/tags/symbolic-math/","section":"Tags","summary":"","title":"Symbolic-Math","type":"tags"},{"content":"","externalUrl":null,"permalink":"/authors/","section":"Authors","summary":"","title":"Authors","type":"authors"},{"content":"","externalUrl":null,"permalink":"/series/","section":"Series","summary":"","title":"Series","type":"series"}]