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: 11,092 Bytes
a7b9459 265abc8 c91cc5b 265abc8 a7b9459 | 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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | ---
license: apache-2.0
library_name: transformers
pipeline_tag: text-generation
language:
- en
base_model:
- Qwen/Qwen3-0.6B
- Qwen/Qwen3-1.7B
- Qwen/Qwen3-8B
tags:
- recurrent-depth
- looped-transformer
- weight-tying
- test-time-compute
- latent-reasoning
- mixture-of-experts
- reproducible-research
- negative-result
---
# Loop Surgery β zero-init-gate recurrent-depth surgery, and when it pays off
**A reproducible recipe for turning a pretrained transformer into a weight-tied, recurrent-depth ("looped") model *bit-exactly*, plus a rigorous five-experiment investigation into whether that buys better reasoning. The headline result is an honest null: the mechanism works perfectly; light surgery + heal does not, at this scale, beat a matched baseline.**
> β οΈ **This repository ships a method, a proof, and metrics β not large model weights.** The experiments were run on small open base models (Qwen3-0.6B / 1.7B, with a Qwen3-8B teacher) and are fully reproducible from the scripts here. See [Reproduction](#reproduction).
### Links
- π **Interactive demo (Space):** [rkreddyp/loop-surgery](https://huggingface.co/spaces/rkreddyp/loop-surgery) β run the bit-exact invariant proof live on Qwen3-0.6B and browse the five-experiment results.
- βοΈ **Deep-dive write-up:** [the Loop Surgery blog post](https://huggingface.co/blog/rkreddyp/loop-surgery) β why we went looking for a loop, how the surgery works, the five experiments, and the honest null. *(Also in-repo as [`BLOG.md`](BLOG.md).)*
---
## TL;DR
Recurrent-depth models run a weight-tied block of layers `K` times per token, spending more compute *without emitting more tokens* ("latent test-time compute"). Thinking Machines' [Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) is a looped mixture-of-experts built this way.
We asked: **can you add such a loop to a model you already have, cheaply, and heal it into a better reasoner?** We split that into a *mechanism* question and a *payoff* question and answered both:
- **Mechanism β proven.** A zero-initialized interpolation gate makes the loopified model **bit-for-bit identical to the base at init**, then opens stably under training, yielding a clean monotone depth-dial. Behavior (here, non-refusing authorized-security reasoning with visible `<think>`) is preserved.
- **Payoff β a careful null.** Across **five independent experiments** on a 1.7B stand-in, the looped model's advantage over a matched one-pass control never exceeded **~0.0024 nats (~0.1%)** of held-out NLL, and was insensitive to every lever β including the two aimed directly at the loop, which made it *worse*. Light surgery + heal is **not** a shortcut to a first-class recurrent-depth win.
**Decision:** bank the (proven) recipe; do **not** commit to a large light-heal loopify. A ~$7.5 study that de-risks a $low-thousands bet into a measured "no."
---
## What's in this repo
| File | What it is |
|---|---|
| `loopify.py` | The surgery: collapse a middle block of decoder layers into a weight-tied `LoopedMiddle` with a zero-init interpolation gate. |
| `prove_invariant.py` | Four-check CPU proof on Qwen3-0.6B: bit-exact at `gate=0`, wired at `gateβ 0`, live depth-dial, identical greedy generation. |
| `modal_heal.py` | The heal runs (`main`, `strong`, `gate`, `deepsup`): matched control-vs-looped training on security reasoning data. |
| `modal_distill.py` | Trace-distillation heal (Qwen3-8B teacher `<think>` traces + soft-KL). |
| `heal_demo.py` | Minimal local heal illustration. |
| `*_results*.json` | Raw metrics (held-out NLL by depth, gate value, generation samples) for every run. |
| `reports/` | Per-experiment write-ups and the decision memo (`LOOP_INVESTIGATION_MEMO.md`). |
## Model / release details
- **Type:** research code + reproduction scripts + metrics (a *method* release; no large weights).
- **Base models exercised:** `Qwen/Qwen3-0.6B` (invariant proof), `Qwen/Qwen3-1.7B` (heals), `Qwen/Qwen3-8B` (distillation teacher). All Apache-2.0.
- **Framework:** PyTorch + π€ Transformers **4.56.2** (the `LoopedMiddle` pseudo-layer is driven by the stock `Qwen3Model.forward` loop; tested against that version).
- **License:** Apache-2.0.
- **Inspiration:** Inkling-2-Mini (Thinking Machines) and the recurrent-depth literature. Inkling is **not** part of this release and is not redistributed here.
---
## The method: loop surgery
The non-negotiable property is that adding the loop must not perturb a good base at initialization:
> **At `gate = 0`, the loopified model is bit-for-bit identical to the base.**
A contiguous middle block of layers is run `K` times with tied weights and combined with the one-pass result through a single learned scalar gate initialized to zero:
```python
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)
```
The only new parameter is the gate scalar; the layer objects are *reused*, not copied, so the weight-tie is literal. Two integration gotchas (both silent-corruption traps):
1. **Expose `attention_type`** on the pseudo-layer β the stock forward loop selects each layer's causal mask by it. Assert the block's layers share one type.
2. **The zero-gate no-op fast path must be eval-only.** Short-circuiting `return y1` in *training* keeps the gate out of the autograd graph, so it never receives gradient and can never open. Train on the full gated path; the shortcut is an inference-only optimization that also keeps the KV-cache clean under `generate`.
## How to get started
```bash
pip install "transformers==4.56.2" torch
python prove_invariant.py # ~1 min on CPU, downloads Qwen3-0.6B
```
Expected output: `max|loop-base| = 0.000e+00` at `gate=0` (bit-identical), logits move once the gate opens, a working `3β5` pass dial, and greedy generation identical to the base at `gate=0`.
Use `loopify()` on any π€ Qwen3 model:
```python
from transformers import AutoModelForCausalLM
from loopify import loopify
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B")
n = len(model.model.layers)
model, loop = loopify(model, start=n//3, end=2*n//3, n_passes=3) # loop the middle third
# loop.gate starts at 0.0 -> model == base; train to open it, or set loop.gate.data.fill_(x)
```
---
## The investigation: five levers, one ceiling
We trained a **matched control** (the identical model/data, run at **one pass**) against the **looped** model, and measured the **margin** = (control held-out NLL) β (best-depth looped NLL), in nats. Positive = the loop helped. The only structural difference between the two is the single gate scalar, so any difference is attributable to the loop.
| # | lever moved | margin (nats) | gate opened |
|---|---|---:|---:|
| 1 | answer-only light SFT | ~0.0019 | +0.039 |
| 2 | training strength (variable 1β5 passes, 50Γ gate-LR, 8 epochs) | ~0.0024 | +0.029 |
| 3 | data richness (Qwen3-8B teacher `<think>` traces + soft-KL distill) | ~0.0022 | +0.0235 |
| 4 | structural capacity (loop the middle *half*, 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 (~0.1%)** and is insensitive to every lever. Decisively, the two interventions aimed *directly* at the loop came in **lower**:
- **Bigger block hurt** β a 14-layer block is expressive enough that one pass already does the job, so the control's baseline strengthens and the loop's `(yK β y1)` delta shrinks. More capacity per pass β more reasoning headroom.
- **Deep supervision couldn't rescue it** β rewarding every depth to decode the target nudged middle depths but could not make the 8th pass earn its keep; the loop **saturates around 4 passes**.
Behavior held throughout: **0/16 refusals** on authorized-security prompts and visible `<think>` reasoning (~800β1180 chars) in every run; no generation collapse once trained with variable passes.
### Verdict
**Loopifying a pretrained base and lightly healing it does not buy a reasoning win worth custom-serving a new architecture β at this scale, for this task.** Where Inkling-style wins come from is training the loop in as a *first-class* part of the computation (from-scratch / heavy continued-pretrain), not surgery + light heal. The recipe is correct and on the shelf; we ship base + skills.
---
## Intended uses & limitations
**Intended uses**
- A **reference implementation** of zero-init-gate recurrent-depth surgery for π€ Transformers decoders.
- A **reproducible negative result** and a **matched-control methodology** for evaluating whether an added loop actually helps.
- A teaching artifact for latent test-time compute / weight-tied recurrence.
**Out of scope / limitations**
- **Not a ready-to-use model.** No large weights ship here; the shipped checkpoints of record are small (1.7B) de-risking stand-ins, and even those are reproduced from the scripts rather than redistributed.
- The null-result bound was measured at **0.6Bβ1.7B** with light heals; it argues against a *light* loopify win and explicitly does **not** evaluate first-class recurrent-depth training at scale.
- The security-reasoning behavior studied is scoped to **authorized** testing; the base retains its safety floor for genuinely out-of-scope requests. Nothing here is a jailbreak or an "uncensored" model.
- `loopify.py` is validated against **Transformers 4.56.2 / Qwen3**; other versions or architectures may need the `attention_type` / mask handling revisited.
## Reproduction
```bash
# invariant proof (CPU, free)
python prove_invariant.py
# the heal / distill runs (GPU; originally on Modal A100)
modal run modal_heal.py::main # answer-only SFT
modal run modal_heal.py::strong # training-strength lever
modal run modal_heal.py::gate # bigger-block lever
modal run modal_heal.py::deepsup # deep-supervision lever
modal run modal_distill.py::main # 8B-teacher trace distillation
```
Raw metrics and generation samples are in the matching `*_results*.json`; per-run analysis and the decision memo are in `reports/`.
## Base models, attribution & licensing
- Built on **Qwen3** (`Qwen/Qwen3-0.6B/1.7B/8B`), Apache-2.0 Β© Alibaba Cloud / the Qwen team.
- **Inspired by** Inkling-2-Mini (Thinking Machines) β middle-loop over last-loop, learned-gate-starts-blocked, K=3 / variable passes β which is **not** redistributed here.
- Recurrent-depth lineage: Universal Transformers (Dehghani et al., 2018); latent recurrent-depth reasoning (Geiping et al., 2025); open looped LMs (Ouro, ByteDance).
This release is Apache-2.0. See `LICENSE`.
## Citation
```bibtex
@misc{loop-surgery-2026,
title = {Loop Surgery: zero-init-gate recurrent-depth surgery, and when it pays off},
year = {2026},
note = {Reproducible recipe + a five-experiment investigation with a negative result},
howpublished = {Hugging Face repository}
}
```
|