Loop Inference: Multi-Pass Computation and Shared GPU Memory

    Loop inference uses repeated computation over shared model weights to refine intermediate states without multiplying parameter count. This article explains gated updates, shared global KV caches with local sliding windows, difficulty-aware routing, and production safeguards, along with an evaluation framework for balancing quality, latency, and GPU memory usage.

    Why Add Another Pass at Inference Time?

    A large language model’s parameter count determines its capacity to store knowledge, but the computational depth of a single forward pass is fixed. In tasks involving multi-step planning, long-document constraints, or internally consistent generation, a model may process the entire input without resolving it into a coherent result. It can overemphasize individual tokens, lose track of global constraints later in the response, and produce output that is grammatically complete but logically unresolved.

    Loop inference, or recurrent-style inference, is not simply running the same code twice. It schedules multiple computational passes over the same weights so that a later pass can refine the global representation established by an earlier one. The central question is whether additional computation can produce more stable intermediate states without increasing the parameter count severalfold.

    Think of this as inference-time compute scheduling rather than a new training paradigm. Training can remain based on standard next-token prediction, while the serving system decides which requests receive additional computation, at which layers, and for how many passes.

    The Computation Graph: Global Reading, Local Refinement

    An additional pass that merely repeats the same attention pattern can compound numerical noise in activations—and in gradients where applicable—particularly over long sequences. A more useful approach gives the passes distinct responsibilities.

    The first pass performs a broad global reading. Its attention distribution is less concentrated, prioritizing document structure, task constraints, and entity relationships. Information-dense or ambiguous passages should still receive more attention during this pass rather than treating every position equally.

    The second pass performs local refinement. Building on the existing global state, it updates only the current generation window, unresolved constraints, and error-prone passages.

    This can be expressed as a gated progressive update. Let (h_t) denote the hidden state at a given layer in pass (t). The gate (g_t \in (0,1)) depends on the current hidden state and an estimate of task difficulty:

    [
    h{t} = (1-g_t)\, h{t-1} + gt\, f(h{t-1}, x)
    ]

    Here, (f) consists of the usual attention and feed-forward sublayers. A gate close to 0 preserves the previous state; a gate close to 1 permits substantial rewriting.

    Difficult terms, long-range references, and instructions with multiple constraints should receive larger first-pass gates, spending the compute budget on understanding the problem. Second-pass gates should be smaller and more localized to avoid overwriting global semantics that have already stabilized.

    The following illustrative implementation describes scheduling logic without depending on a vendor-specific interface:

    1. def loop_step(h_prev, x, difficulty):
    2. # difficulty: 0–1, estimated from entropy, constraint count, or retrieval conflicts
    3. g = torch.sigmoid(w_g(h_prev) + alpha * difficulty)
    4. delta = block(h_prev, x) # Standard attention + FFN
    5. h = (1 - g) * h_prev + g * delta # Progressive update to limit repeated-compute distortion
    6. return h

    Three engineering safeguards matter:

    1. Bound the gate to preserve state. The retained-state coefficient must not approach zero unintentionally, or a pass may effectively erase its history.
    2. Keep normalization numerically aligned. Both passes should share the same layer-normalization configuration, or at least maintain numerical alignment, so that a second-pass distribution shift is not mistaken for deeper reasoning.
    3. Set a hard pass limit. Tie the limit to request timeouts and token budgets so difficult inputs cannot trigger unlimited additional computation.

    KV Caching: More Computation Without Proportional Memory Growth

    Multi-pass computation is often assumed to multiply GPU memory usage by the number of passes. That happens if every pass retains a complete key-value cache. For contexts containing millions of characters, this can make deployment prohibitively expensive.

    A more practical design combines shared global memory with a separate sliding-window cache.

    The global cache retains the KV entries from the first pass, or the most recently committed pass, covering the full document. The second pass reuses that cache in read-only mode rather than copying it. It provides the context of having already processed the entire input.

    A smaller incremental KV cache is allocated separately for the local window currently being generated or rewritten. Entries can be reclaimed when they leave the window.

    A rough memory estimate is:

    [
    M \approx M{\text{weights}} + M{\text{global KV}} + M{\text{window}} + M{\text{activations}}
    ]

    Here, (M_{\text{window}}) scales with the window length rather than the full document length. The full context still determines the size of the global KV cache, but that cache does not grow linearly with the number of passes. Under this design, the main cost of an extra pass is computation and latency rather than a duplicate full-context cache.

    Implementation guidelines include:

    • Keep global KV read-only. Do not allow the second pass to modify it in place, which could create inconsistent cache versions across passes.
    • Resize the local window dynamically. Include the current sentence and referenced passages associated with unmet constraints instead of using a large fixed window.
    • Use chunked prefill for very long inputs. Populate global KV first, then perform lightweight alignment at chunk boundaries to reduce attention discontinuities between chunks.
    • Monitor peak memory, not just average memory. When loop computation overlaps with prefill, temporary activation buffers can pose a greater risk than the KV cache itself.

    Long-context deployment still depends on controlling global KV precision and cache management through quantization, paged caching, and prefix reuse. The loop need not multiply that storage cost.

    If general-purpose object storage is used for prefix caching and a container platform hosts multiple replicas, rolling deployments must keep each request’s global KV cache and local window on the same inference instance.

    Difficulty-Aware Routing: Spend Compute Where It Matters

    Applying an extra pass uniformly to every token can quickly lose its value to added latency. Difficulty-aware routing is a more selective approach.

    Useful difficulty signals can come from the model itself or the request structure, without an external scoring service:

    • Predictive entropy or the gap between leading token probabilities in the first pass. High entropy indicates uncertainty.
    • The number of instruction constraints, negated conditions, or required output fields.
    • Entities referenced repeatedly in a long document but not yet reconciled in working memory.
    • Fields that fail validation in tool calls or structured output.

    The routing policy can be simple: always perform one global prefill pass, then activate a second pass over a local window only when difficulty exceeds a threshold.

    Calibrate that threshold on an offline evaluation set. The goal is to select cases where a single pass fails and a second pass can correct the answer, rather than spending more compute on straightforward questions already answered correctly.

    This also explains why difficult terms deserve more attention in the first pass. Uncertain positions should be represented in global KV when the global memory is established, not encountered meaningfully for the first time during refinement. The second pass should correct an existing understanding, not compensate for missing the input.

    Evaluation: Test Transfer, Not Just a Single Score

    Compared with a single-pass baseline using the same weights, loop inference may show its clearest gains in multi-step mathematics, difficult scientific questions, long-document reasoning, and strict instruction following. These tasks depend heavily on consistent intermediate states.

    However, relative improvements observed in smaller models should not be assumed to transfer proportionally to larger ones. As model size increases, the single-pass baseline becomes stronger, potentially reducing the marginal benefit of looping. Added latency and queueing effects can also become more significant.

    Evaluate four dimensions using internal task definitions or general public benchmarks rather than tying the analysis to a particular model leaderboard:

    1. Correctness: Measure the pass-rate difference between loop and single-pass inference on identical prompts, grouped by difficulty.
    2. Stability: Measure answer consistency across repeated samples of the same prompt and the rate of successful format validation.
    3. Cost: Track the additional passes’ impact on P95 latency, GPU time, and peak GPU memory.
    4. Failure modes: Distinguish between cases where the model still missed relevant context and cases where it understood the context but refinement damaged the answer. The latter suggests overly aggressive gating and a need to reduce second-pass update strength.

    When comparing against a much larger single-pass model, report both quality and per-request cost. The value proposition is that a medium-sized model may approach a larger model’s performance on difficult subsets within an acceptable latency budget—not that it will outperform it on every simple task.

    Production Practices and Risks

    In an online system, loop inference should be an optional strategy rather than a default doubling of computation.

    • Classify requests. Use a single pass by default for interactive conversation. Enable refinement for complex generation, long-document review, and structured output with multiple constraints.
    • Degrade gracefully on timeout. If the second pass cannot finish within budget, return the already decoded first-pass result and mark it as unrefined rather than leaving the user waiting.
    • Instrument the process. Record per-request pass counts, average gate values, window lengths, and cache hits. Use standard monitoring and alerts for P95 latency and out-of-memory failures, not just average throughput.
    • Track cache consistency. Make global KV versions traceable within each session. Invalidate old caches when a rolling deployment changes model weights.
    • Maintain safety and compliance controls. An extra pass does not automatically make a model safer. System instructions, output validation, and permission controls remain necessary; looping itself should not be treated as a risk-content filter.

    For inference services running on cloud container platforms, logging services can retain gate and pass information, while monitoring and alerting support capacity planning. These are general infrastructure capabilities, not dependencies on a model vendor’s proprietary interface.

    Where Loop Inference Fits—and Where It Does Not

    Loop inference is best suited to tasks whose internal state needs to converge: writing under extensive constraints, multi-hop question answering, and structured output that must remain consistent throughout.

    It is a poor fit for short questions that are already answered quickly and reliably. It also cannot repair an incorrect objective simply by applying more computation. More precise updates may only make the result more consistently wrong.

    Parameter scale, data quality, and evaluation coverage still set the limits. Loop inference extends computational depth at inference time; it is not a free multiplier of intelligence.

    Successful deployment has concrete signs: quality improves on difficult subsets, latency remains nearly unchanged on simple ones, memory usage stays broadly flat as the pass count increases, and failures can be explained through gating and routing behavior.