Text Generation
Transformers
English
recurrent-depth
looped-transformer
weight-tying
test-time-compute
latent-reasoning
mixture-of-experts
reproducible-research
negative-result
Instructions to use transilienceai/loop-surgery with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use transilienceai/loop-surgery with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="transilienceai/loop-surgery")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("transilienceai/loop-surgery", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use transilienceai/loop-surgery with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "transilienceai/loop-surgery" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "transilienceai/loop-surgery", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/transilienceai/loop-surgery
- SGLang
How to use transilienceai/loop-surgery with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "transilienceai/loop-surgery" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "transilienceai/loop-surgery", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "transilienceai/loop-surgery" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "transilienceai/loop-surgery", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use transilienceai/loop-surgery with Docker Model Runner:
docker model run hf.co/transilienceai/loop-surgery
File size: 15,866 Bytes
a87deb6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | # Loop Surgery: can you bolt a thinking-loop onto a model you already have?
*A deep-dive into recurrent-depth transformers, a bit-exact way to add one to a pretrained model, and five experiments that told us β honestly β when it pays off and when it doesn't.*
---
## Why we went looking for a loop
Most transformers you have ever run are **fixed-depth**: a token's hidden state passes through layer 1, then 2, then 3, β¦ through N, once each, and out comes a prediction. The amount of computation per token is bolted to the layer count at training time. If a token needs "more thinking," the usual lever is to make the model emit more *tokens* β a longer chain of thought β and pay for every one of them in latency and context.
**Recurrent-depth** models break that coupling. Instead of N distinct layers run once, they take a block of layers and run it **K times with the same weights** β a weight-tied loop in the middle of the network. The model can spend more compute per token *without emitting a single extra visible token*. The "thinking" happens in the latent space of the loop, not in the text.
Thinking Machines' **Inkling-2-Mini** is the model that put this on our radar. It's an open (Apache-2.0) **looped mixture-of-experts**: ~26B total parameters, only a few billion active per token, and a middle block that it runs **K=3** times per forward pass. That loop is why a ~3.4B-active model behaves like a ~5.4B-active one, and why its chain-of-thought at 5 passes was less than half the length of its 1-pass CoT β same reasoning, fewer emitted tokens.
Three design choices from Inkling stuck with us:
1. **Loop the *middle*, not the end.** In their ablations a middle-block loop beat a last-layer loop on 27 of 28 evals. Middle layers carry the more abstract, compositional representations β exactly what you want to iterate on.
2. **The loop opens from a *closed* gate.** The looped block's contribution is multiplied by a learned gate that starts at ~0 ("initially blocks the entire message⦠increases the gain over training"). At init the network is identical to a plain stack; the loop is *learned* into existence.
3. **Latent reasoning is real reasoning.** The model computes inside the loop, so a strong answer can appear with little or no externalized chain-of-thought.
That raised an irresistible question for a team that already ships a capable in-house model: **do we have to train a looped model from scratch, or can we take a base we already own, surgically add a middle-loop, and cheaply heal it into a better reasoner?**
This post is the honest answer. The short version: the **mechanism works perfectly and is fully de-risked** β and the **payoff, for our use case at this scale, is a careful null**. Both halves are useful, and we think the null is the more interesting result.
---
## The operation: "loop surgery"
The goal is a transformation with one non-negotiable property:
> **At initialization, the loopified model must be bit-for-bit identical to the base.**
If adding the loop perturbs a good model's outputs at all, you've paid a tax before training buys you anything, and you can no longer cleanly attribute any later change to the loop. So we build the loop around a **zero-initialized interpolation gate**.
Take a contiguous middle block of decoder layers and collapse it into a single pseudo-layer that runs the block `K` times, tied:
```python
class LoopedMiddle(nn.Module):
# y1 = block(h) # one application == base behaviour
# yK = block^K(h) # deep, weight-tied recurrence
# out = y1 + gate * (yK - y1) # gate == 0 -> out == y1 (exact)
def __init__(self, layers, n_passes=3, gate_init=0.0):
super().__init__()
self.layers = nn.ModuleList(layers) # reused => weight-tied
self.n_passes = n_passes
self.gate = nn.Parameter(torch.tensor(gate_init)) # a single scalar
def forward(self, h, **kw):
y1 = self._run_once(h, **kw) # == base (single pass)
yk = y1
for _ in range(self.n_passes - 1):
yk = self._run_once(yk, **kw) # extra tied passes
return y1 + self.gate * (yk - y1) # gate=0 -> y1 bit-for-bit
```
The whole loop adds **exactly one new parameter** β the gate scalar. The layer objects are *reused*, not copied, so the weight-tie is literal and the parameter count is otherwise unchanged. `out = y1 + gateΒ·(yK β y1)` is an interpolation between "one pass" and "K passes": at `gate = 0` it returns `y1`, which is precisely what the base network computes for that block. The extra passes contribute nothing until the optimizer pushes the gate off zero.
To make a stock Hugging Face stack drive this unchanged, two gotchas matter β both are the kind of thing that silently corrupts your invariant if you miss them:
- **Expose `attention_type`.** Modern decoder `forward` loops pick each layer's causal mask by reading `layer.attention_type`. A pseudo-layer that doesn't expose one gets the wrong mask. We assert the block's layers share a single type and surface it.
- **The zero-gate fast path must be *eval-only*.** It's tempting to short-circuit `return y1` whenever the gate is 0 (skipping the discarded passes keeps the KV-cache clean under `generate`). But if you do that in *training*, the gate never enters the autograd graph, gets no gradient, and **can never open from zero**. In training you always run the full gated path; the no-op shortcut is strictly an inference optimization.
### Proving it's correct for $0
Before touching a GPU, we proved the surgery on **Qwen3-0.6B** (28 layers, middle third `[9:18)`), on CPU, in fp32 β four checks:
| check | what it asserts | result |
|---|---|---|
| **Invariant** | `gate=0, K=3` β `maxβloop β baseβ` logits = 0 | `0.000e+00` β bit-identical |
| **Wired** | `gate=0.5` β logits move | changed (the passes actually flow) |
| **Depth dial** | `K: 3β5` β output changes | a real, live test-time-compute dial |
| **Generation** | greedy decode at `gate=0` == base | identical token-for-token |
The invariant is exact, not approximate. That's the foundation the whole plan rests on, and it cost nothing to establish. *(Reproduce: `PYTHONPATH=. python3 prove_invariant.py`.)*
---
## The heal: a closed gate does nothing until you train it
Here's the catch that makes this honest work rather than a free lunch: because the gate starts at zero, **the loop initially does nothing**. The model works β it's the base β but the extra passes are inert. "Healing" is continued training that teaches the shared middle block to actually *use* the extra passes, and nudges the gate open.
Our setup:
- **Base:** our no-refusal security worker (`Qwen3.6-35B-A3B`, the in-house `coder` tag β a MoE that does *authorized* security testing without over-refusing). De-risked first on 1.7B and 8B stand-ins, exactly as we'd do the real thing, at ~1% of the cost.
- **Data:** 538 in-house security reasoning pairs; held-out set of 125 security questions.
- **Design:** a **matched control** β the identical model, identical data, trained identically but run at **one pass** β versus the **looped** model. The *only* structural difference is the single gate scalar. That isolation is the point: any held-out difference is attributable to the loop and nothing else.
On the **mechanism**, every run agreed and every run passed:
- **Bit-exact at init**, trains end-to-end, **gate opens** under training, and a **clean monotone pass-dial** emerges (more passes β lower held-out NLL, up to the trained depth).
- **Behavior preserved:** 0/16 refusals on authorized security prompts, and visible `<think>` reasoning in essentially every sample (~800β1180 chars). The loop model stayed a non-refusing, thinking security assistant. No catastrophic breakage, and β once trained with variable passes β no generation collapse.
So: the surgery is correct, trainable, stable, and behavior-preserving. The recurrent-depth *mechanism* is fully de-risked. That result stands on its own.
Then we asked the only question that actually justifies custom-serving a new architecture: **does the trained loop reason measurably better than the matched one-pass control?**
---
## Five levers, one ceiling
We measured the **margin** = (control held-out NLL) β (best-depth looped NLL). Positive means the loop helped; lower NLL is better. We moved five independent levers β each one a different theory of *why* an earlier run might have left value on the table:
| # | lever moved | margin (nats) | gate opened |
|---|---|---|---|
| 1 | answer-only light SFT | ~0.0019 | +0.039 |
| 2 | **training strength** β variable 1β5 passes, 50Γ gate learning-rate, 8 epochs | ~0.0024 | +0.029 |
| 3 | **data richness** β Qwen3-8B teacher `<think>` traces + soft-KL distillation | ~0.0022 | +0.0235 |
| 4 | **structural capacity** β loop the middle *half* (14 layers), Kβ€8 | ~0.0004 | +0.0079 |
| 5 | **training objective** β deep supervision: LM loss at *every* depth {1,2,4,8} | ~0.0010 | +0.011 |
The margin **never exceeds ~0.0024 nats β about 0.1%** β and it is essentially **insensitive to every lever**. More data, harder training, and distillation all left it flat at ~0.002. That alone would be a weak, inconclusive result.
What makes it *decisive* is the two levers we aimed **directly at the loop mechanism** β and both came in **lower**, not higher:
- **Bigger block hurt (margin collapsed ~5Γ to 0.0004).** Looping half the network sounds like more room to think. It's the opposite: a 14-layer block is expressive enough that *one* pass can already do the job, so the control trains it to do exactly that. The baseline gets stronger and the loop's delta `(yK β y1)` shrinks toward nothing. More capacity per pass β more reasoning headroom.
- **Deep supervision couldn't rescue it (margin ~0.0010).** We explicitly rewarded *every* depth to decode the target, so each pass has to earn its keep. It nudged the middle depths β but it could not make the 8th pass useful. The loop **saturates around 4 passes** no matter how we train it; passes beyond that fall back toward the one-pass answer.
When the two interventions designed to make the loop matter both make it matter *less*, that's not undertraining and it's not a recipe bug. That's the regime telling you something.
---
## The verdict (and why a null is worth publishing)
For **~$7.5 of GPU across five runs**, five independent cheap proxies agree:
> **Loopifying a pretrained base and lightly healing it does not buy a reasoning win large enough to justify custom-serving a new architecture** β at this scale, for this task.
So we did the boring, correct thing: **we banked the recipe and shipped base + skills.** The 35B light-heal loopify β which would have cost low-thousands of dollars and weeks β is **not founded** by this evidence, and we didn't spend it. A $7.5 experiment that prevents a $low-thousands bet on a null is one of the best trades a research budget can make.
The deeper lesson is about *where recurrent-depth wins come from*. Inkling didn't get its loop by bolting one onto a finished model β it **trained the loop in as a first-class part of the computation** (it was pruned and healed with on the order of a trillion distilled tokens). Our result is the natural consequence of the opposite approach: if a strong base already solves the block's job in one pass, a lightly-trained gate has almost no gap to exploit. **Surgery + light heal and from-scratch recurrent training are not two budgets for the same outcome β they're two different outcomes.** The loop has to be load-bearing during the training that *makes* the model, not annealed in afterward.
What we keep:
- A **proven, bit-exact loop-surgery recipe** on the shelf β correct, stable, reproducible, ready if we ever pursue first-class recurrent depth for its own sake (behind a hard early kill-gate).
- A clean, matched **measurement methodology** for "did the loop actually help," which is reusable for any future architecture bet.
- The discipline of **de-risking on a 1.7B stand-in before committing to the 35B.** That ordering is the single biggest risk-reducer we have.
---
## Supporting act: running the *real* Inkling on commodity NVIDIA
Since we couldn't justify growing our own looped model, we run Thinking Machines' Inkling where it earns its place β as a reasoning worker in our autonomous pentest harness. Getting there involved debunking one assumption and fixing one real integration bug, both worth a note.
- **It is not Mac-only, and it is not B200-only.** Inkling's packaged Ollama build ships **MLX** weights (Apple-Silicon only) β a dead end on our NVIDIA cloud. The original Hugging Face checkpoint, however, serves fine under **vLLM**. Our first attempt used a prebuilt image whose custom kernels were compiled Blackwell-only, which is where the "needs a B200" folklore came from. The **stock vLLM nightly image carries the full Hopper kernels**, so Inkling serves on an **H100 β about 37% cheaper than a B200** β with cold starts around a couple of minutes (and GPU memory-snapshot/scale-to-zero plumbing to cut that for bursty use).
- **Latent reasoning, confirmed.** On a real cross-tenant authorization finding posed as a triage task, Inkling nailed it β correct vulnerability class (BOLA/IDOR, CWE-639, OWASP API1:2023), symptom-vs-root-cause separation, a safe non-destructive verification plan, correct severity and fix β while emitting **zero** externalized chain-of-thought at both medium and high effort. The reasoning happened in the loop; higher effort produced a *longer answer*, not a longer think-span. Judge these models by their answers, not their visible CoT.
- **A concurrency gotcha worth knowing.** Running many harness workers in parallel against a live target raced the auth/token path and produced spurious `401`s. Serializing to one worker cleared it completely (200s vs 401s flipped from a trickle to the overwhelming majority). The model and the harness were both fine; the failure was request concurrency, not reasoning.
The division of labor we settled on: **the latent-reasoning worker runs on the GPU; the planner, decider, and verifier stay local and free.** You pay for depth exactly where depth helps.
---
## Takeaways
1. **Recurrent depth decouples compute-per-token from token count.** That's a genuinely useful axis, and Inkling is a strong existence proof of it at ~26B.
2. **You can add a weight-tied loop to a pretrained model bit-exactly**, via a zero-initialized interpolation gate, for essentially no parameter cost and $0 to prove. The mechanism is not the hard part.
3. **Light surgery is not a shortcut to a first-class loop.** Across five levers β including the two aimed straight at the mechanism β a loopified-and-healed base beat its matched one-pass control by at most ~0.1%, and the mechanistically-targeted interventions made it *worse*. The win comes from training the loop in, not annealing it on.
4. **Cheap, honest de-risking pays for itself.** $7.5 and a 1.7B stand-in turned a $low-thousands architecture bet into a measured "no."
5. **Use the right tool where it wins.** We don't ship a home-grown looped model; we serve the real one on an H100 as a reasoning worker and keep the surgery recipe on the shelf.
*Reproducibility: the loop surgery (`loopify.py`), the invariant proof (`prove_invariant.py`), and all five heal/distill/gate/deep-supervision runs with raw metrics are in this repository; the decision memo is [`reports/LOOP_INVESTIGATION_MEMO.md`](reports/LOOP_INVESTIGATION_MEMO.md). The interactive demo is the [Loop Surgery Space](https://huggingface.co/spaces/rkreddyp/loop-surgery).*
|