Effective Depth Design for Looped Transformers: Gating, KV Cache Reuse, and Serving Trade-offs

    Looped computation is not simply running a network again. This article explains how shared intermediate blocks increase effective depth without increasing parameter count, how two loop passes can serve different roles, and how token-level gating enables progressive refinement. It also covers cross-loop KV cache reuse, training and inference stability, evaluation criteria for programming and long-context tasks, and a practical decision process for deciding when looped depth is worth the compute and memory trade-offs.

    Looped computation is not simply running the network “one more time.” In an ordinary multilayer network, each layer uses its own parameters, and the hidden state is transformed once per layer. A looped structure lets several intermediate layers share one set of weights and executes them a fixed number of times. The parameter count is still mainly determined by the vocabulary, embeddings, the unique front and back layers, and this shared block. What increases is the computational depth of each forward pass. For programming, math, and long-document tasks, this depth can sometimes be more useful than adding parameters alone, because it moves part of the multi-step organization inside the network instead of relying entirely on the model to write out a long intermediate process in its output.

    Effective Depth and Parameter Scale Are Not the Same Thing

    Parameter scale determines how much static knowledge the model can store and affects the width of a single matrix multiplication. Effective depth determines how many times information can be rewritten before the final answer is fixed. Both consume compute, but the cost structure is different. Widening or adding layers pushes up parameters, optimizer states, and checkpoint size linearly or even faster. Sharing an intermediate block and running it for two passes mainly increases activation computation and a small amount of extra caching, while parameters and optimizer states barely grow with the number of loops.

    For evaluation, therefore, at least four dimensions should be tracked together: task quality, generation length, compute per forward pass, and KV cache usage during serving. Looking only at quality underestimates latency. Looking only at generated token count can also mislead, because the loop itself has already performed an extra internal pass. If the second pass makes the final answer shorter, the savings in per-token decoding cost may not offset the added full-sequence computation in the forward pass. End-to-end cost must be accounted for separately as prefill, looped forward, and decode.

    What the Two Loop Passes Do

    Running the shared intermediate block twice is a minimal and easy-to-analyze setting. The first pass is better suited to establishing global context: who is speaking, what the constraints are, which symbols in the codebase are relevant, and how sections of a long document relate to one another. At this stage, the hidden state can change substantially, roughly building a coarse-grained working memory. The second pass is better suited to refinement: checking for contradictions, filling in boundary conditions, and turning vague intent into executable steps. Because both passes use the same weights, the network must learn to “play different roles at different loop steps” rather than relying on two separate sets of parameters for division of labor.

    More loops are not always better. With each additional pass, activations have another chance to be amplified by the same transformation. In later training, this can lead to norm drift, attention entropy collapse, or oversensitivity to noisy tokens. In engineering practice, the number of loops should be treated as a hyperparameter as important as depth and learning rate. Run same-parameter ablations at medium scale first, then decide whether to carry the setting to a larger model. Same-parameter comparison is especially important: if the control model merely performs one fewer pass, the result reflects computational depth; if the control model also has fewer parameters, it is impossible to separate the contributions of width and looping.

    Gated Progressive Updates

    Simply repeating the same block means each pass overwrites the previous state with a new result, which can wash out global information already established in the first pass. A safer approach is to add gating at the token dimension so that each pass updates the hidden state only by a proportion. In conceptual form:

    new_state = old_state + gate × (candidate_update − old_state)

    When the gate is close to 0, the original state is preserved; when it is close to 1, the rewrite from the current pass is accepted. The gate can be produced from the current token’s hidden state, a loop-step embedding, and a small linear layer, with a bounded activation limiting its magnitude. In this way, simple tokens such as punctuation and known keywords can remain almost unchanged, while complex tokens such as unclosed logic, cross-file symbols, and ambiguous requirements receive a larger rewrite budget. The gate distribution is usually broader in the first pass and sparser in the second, changing only positions that remain uncertain.

    Three implementation points matter. First, the gate must be differentiable, and its initial value should not be too small, or the second pass will effectively do nothing and waste budget; it should also not be initialized fully open, or early training will be unstable. Second, residual scaling should be tied to the loop step to avoid variance doubling when two residual passes are simply added. Third, monitor hidden norms and gate means per layer and per loop. If the second-pass gate stays close to 0 or 1 for a long time, the gate has degenerated into “skip” or “overwrite,” and the loop is not producing progressive refinement.

    Reusing KV Cache Across Loops

    Attention KV cache usually grows with layer count and sequence length. If every pass stores a full cache, two loop passes nearly double this part of memory usage, and long contexts will hit memory limits before they hit compute limits. A practical compromise is to let the second pass reuse the sparse KV already computed in the first pass, keep additional recent KV only for a local sliding window, and reuse the sparse attention indices from the first pass.

    The implication is that long-range information has already been compressed into a sparse index in the first pass. The second pass trusts this index by default and only re-examines the recent window at fine granularity. This fits tasks where the global structure is stable and local refinement is needed, such as changing one interface implementation inside a long specification or reusing an already located file in a large code repository while rewriting only the current function. It does not fit tasks where global relevance must be rewritten on every pass; if the requirement fundamentally changes in the second pass, a stale index can lock attention onto the wrong region.

    On the serving side, account for the cache in three parts: first-pass sparse KV, second-pass local window, and reusable index structures. The index can share storage across passes, but it must be isolated between concurrent requests. Window length should be tuned together with batch size: if the window is too large, the savings from reuse are eaten up; if it is too small, the second pass cannot see newly generated constraints. For long-context scenarios, prioritize reducing the memory peak during prefill rather than looking only at per-token latency during decoding.

    Training, Inference, and Stability

    Training compute will be higher than for a same-parameter model without looping, because the shared block’s forward and backward passes both run multiple times. During backpropagation, gradients from different loop steps accumulate into the same set of parameters, so learning rate, gradient clipping, and loss scaling need to be more conservative than in an ordinary deep network. Activation checkpointing should be scheduled by “pass” rather than only by “layer”; otherwise, activations from both passes remain resident at the same time, and the memory advantage disappears.

    There are two inference strategies. One is to always run the full fixed number of passes, which makes latency predictable and simplifies batching. The other is to exit early based on gates or intermediate confidence, so simple requests use fewer passes. Early exit saves compute, but it makes request paths diverge within the same batch and complicates scheduling. If the serving goal is stable tail latency, fixed passes are usually more appropriate; if request length and difficulty vary widely, dynamic passes can be considered.

    Numerically, prevent the loop from amplifying outliers. In practice, apply mild normalization to each pass’s output, record the proportion of overflowing tokens, and segment ultra-long prompts for prefill before entering the looped block. Do not interpret “one more internal pass” as a reason to remove external chain-of-thought or tool calls. The internal loop improves the organization capability of a single forward pass; external steps still handle repository access, test execution, and reading errors. The two are complementary.

    From Completion to General Programming

    The value of programming models is shifting from single-line completion to multi-step tasks: reading requirements, editing multiple files, calling tools, and revising based on execution results. For these tasks, the meaning of a looped structure is to align constraints more fully within one generation, reducing meaningless repeated rewrites. If visual understanding is added as an additional capability, it should serve the same goal: inspect design mockups, UI screenshots, or structure diagrams and then generate executable modifications, rather than optimizing a standalone “can see images” metric.

    For deployment, accept tasks by closed-loop outcomes rather than static fill-in-the-blank performance. At minimum, cover whether a defect fix can be reproduced and caught by tests; whether a cross-file rename keeps references consistent; whether interface constraints in long documents are respected; and whether a tool failure leads to a narrower modification scope based on the error. For generation of video, interactive prototypes, 3D or mechanical structures, the evaluation criterion should be whether downstream tools can consume the result—valid format, satisfied constraints, and editability—not whether the text looks complete.

    How to Decide Whether to Adopt It

    Use the following sequence to avoid being led by the parameter-scale narrative.

    1. Fix the parameter count and compare “shared block runs one pass” with “shared block runs two passes” to confirm that quality gains come from looping rather than extra parameters.
    2. Record training time, prefill memory, decoding length, and tail latency at the same time. If quality gains come with doubled cache, long-context serving may not be worth it.
    3. Check whether the gate actually varies with difficulty. If all tokens receive almost the same update magnitude, progressive updating is not working.
    4. Retest on real repositories and long prompts, not only short problems. Loop benefits often appear on samples with many constraints and long context.
    5. Separate the budget for internal loops from the budget for external tool steps. The former saves erratic generation; the latter saves missing execution feedback.

    A minimal illustrative single-step update can stay very small, just enough to make the data flow clear, rather than matching any framework API:

    1. state = state + gate * (block(state, reused_kv, local_window) - state)

    Here, block is the shared-weight block, reused_kv comes from the previous pass’s sparse cache, local_window covers only recent tokens, and gate is computed per token and limited to the range 0 to 1. A production implementation also needs normalization, index lifecycle management, and batch-dimension masks. These details determine whether the system can serve stably, not whether the concept is valid.

    Summary

    The core trade of a looped Transformer is this: exchange repeated computation for effective depth, use gating to limit the rewrite magnitude per pass, and use cross-loop reuse to pull KV memory back from “doubling per pass.” It does not automatically become a cheaper model, nor does it replace tests, retrieval, or tool execution. For a team, the useful approach is to measure the real trade-off between quality, memory, and latency under the same parameter count, then decide the number of loops, window size, and whether to fix the pass count. Once these accounts are clear, looped depth becomes an operable capability rather than a story that exists only in a parameter comparison table.