Loopy Inference in Code LLMs: Depth, KV Caching, and Cost

    Recurrent inference in code large language models reuses a shared block of layers across multiple passes, adding computational depth without extra weights or more generated tokens. This article explains how weight-shared recurrence works, how per-round gating controls what each pass writes back, how tiered KV caching balances per-round near-context with shared far-context, and how sparse-index reuse trades recall for speed. It closes with a practical framework for measuring whether the added compute actually delivers accepted code changes.

    1. Recurrence Adds Computational Depth, Not More Generation Rounds

    The hard problems code assistants face are rarely about producing a syntactically correct function. They are about making a set of edits that simultaneously satisfy interface constraints, call relationships, and existing tests. A larger context window lets the model see more relevant files, but that does not mean it can use that information well. Recurrent inference addresses a different question: within a single forward pass, can the model apply several transformations to the same intermediate representations, without provisioning an independent set of weights for each transformation?

    In a conventional deep network, data flows through each layer once per forward pass. A recurrent architecture instead designates a segment of layers as a shared computational block: the first pass takes the upstream representation, and the second pass uses the previous pass’s output as its starting point, executing the same block again. Because the two passes receive different inputs, the updates need not be identical even though the weights are. The reused layers gain executions, but no separate copy of the weights is stored for the second pass. This also does not make a recurrent model equivalent to a model with the same effective depth whose layers are independently trained: weight sharing saves parameters, but it also constrains how much each pass can learn independently.

    The “recurrence” here happens inside the model. It is not generating a patch first and then feeding that patch back as a prompt for another rewrite. It does not increase the number of output tokens, nor does it amount to running tests or verifying the edit. For autoregressive generation, the change is that the forward computation needed to produce the next token requires the shared block to execute more times.

    Recurrent structures can be trained from scratch, or built on top of an existing pretrained model and then further trained. The latter reuses existing weights, but you cannot simply run the original network layers a second time and expect stable gains. Layers that originally executed once now receive, on their second pass, representations transformed by themselves in the previous pass—an input distribution that may differ from the original training regime. The core problem of continued training is to help the shared layers adapt to inputs from different passes and learn how to use the extra computation.

    2. Per-Round Gating: Controlling How Much Each Pass Writes Back

    A recurrent block does not have to write every pass’s computation results back into the backbone unchanged. Per-round, per-token gating can control how strongly each pass’s candidate update is written into the residual stream. In simplified terms: the updated hidden state equals the original hidden state plus “gate coefficient times the candidate update.” With a small coefficient, more of the backbone representation is preserved; with a large coefficient, the current pass’s results exert a stronger influence on subsequent processing.

    The value of this design is that different positions in a sequence do not have to accept updates of the same strength. Separators, local variable references, and cross-file interface references in code depend on different kinds of information. During training, the model can learn to preserve existing representations at some positions while writing new contextual information into others earlier, reducing the distribution shift caused by repeatedly stacking updates.

    It is tempting to interpret the two passes as “first build a contextual representation, then refine it based on what exists,” but the architecture does not guarantee this division of labor. The first pass is not a fixed code parser, and the second is not a fixed error checker; gate values should not be read as model confidence. Whether gating actually works must ultimately be judged by whether it improves pass rates on the target task—not by changes in internal coefficients alone.

    3. Tiered KV Caching: Reusing Weights Does Not Mean Reusing Intermediate States

    Autoregressive generation caches the keys and values that historical tokens use in attention computation, avoiding a full recomputation of the context for every new token. This is the KV cache. Although recurrent structures share layer weights, the input representations differ across passes, so the resulting keys and values may differ too. If every pass retains a complete historical cache, the cache space required by the shared block still grows with the number of rounds; the longer the window and the more concurrent requests, the more this overhead needs to be accounted for separately.

    One compromise is to split history into a near window and far context: the near portion is cached per pass so each round can read its own local representations, while the far portion is shared across passes to avoid duplicating the entire history. For code tasks, the near window typically contains the function or patch fragment currently being generated, and preserving per-pass differences helps the model handle local dependencies. Sharing the far context is a capacity trade-off, not a statement that older information is unimportant. Type definitions, permission constraints, or compatibility requirements that appeared earlier may still determine whether the current edit is correct.

    A simplified model estimates the space involved. Let the current sequence length be N, the near window contain W tokens, and the block run R passes. If every pass retains the full history, the shared block must hold caches corresponding to roughly R×N token positions; if the far context is stored once and the near window per pass, the figure is roughly N−W+R×W. This relationship only describes cache positions for the shared block under the given assumptions—it does not represent total GPU memory, nor does it account for non-recurrent layers, cache precision, index metadata, or runtime buffers. When sequences are short and fall almost entirely inside the near window, the savings from tiering shrink accordingly.

    4. Sparse Index Reuse: Eliminating Repeated Selection, Not Repeated Computation

    Sparse attention over long contexts typically reads only a subset of historical positions. The system must first select candidate positions, then compute attention using the information at those positions. If every recurrent pass re-runs the selection, both the candidate search and the index construction are duplicated. One approach is to let the first pass build the index, and let subsequent passes reuse the same position list. Later passes still perform attention with their current query representations and still read the corresponding caches; what is saved is only the re-selection of positions.

    Whether this trade-off pays off depends on how similar the information needs are across passes. If the first pass already selected the relevant definitions, callers, and tests, later passes can redistribute attention over the same positions without searching again. Conversely, if the model only recognizes a new cross-file dependency in the second pass and the corresponding position never entered the first-pass candidate set, continued computation cannot directly read what was missed. Therefore, when validating index reuse, do not look only at average speed—deliberately test samples where key information sits far away, has similar names, or involves indirect dependencies. Passing local code completion does not prove that long-range dependencies are handled equally well.

    5. Measuring Cost Against Real Repositories, in Terms of “Acceptable Edits”

    Recurrence changes the cost structure, but it does not mean cost simply shifts from memory to token count. Weight reuse reduces storage requirements relative to independently expanded layers; more passes typically increase per-token compute and may add some cache overhead. Whether output gets longer depends on what is generated, and request cost depends on how usage is metered. For engineering teams, the more useful metrics are: to obtain one change that passes acceptance, how long do you wait in total, how many retries are needed, and how many resources are consumed?

    When evaluating, break the process into three steps:

    1. Group tasks by nature. At minimum, distinguish local completion, single-file fixes, cross-file refactoring, and long-context constraint following. Each group should use a fixed repository snapshot, task description, and visible file scope, so retrieval or prompting differences are not mistaken for gains from the recurrent structure.
    2. Judge quality by verifiable outcomes. Beyond checking whether the output parses, check whether builds succeed, whether relevant tests and regression tests pass, and whether interfaces not slated for change remain intact. For an interface migration, check whether the model updated callers and tests in sync—not just the interface definition.
    3. Record interaction latency and resource cost separately. Log time to first output token, full-response latency, peak GPU memory, and throughput under different concurrency levels, keeping long- and short-context cases separate. If you can control the architecture configuration, compare single-pass vs. multi-pass and index reuse vs. recomputation; if you cannot, report only overall differences and do not attribute results to any single internal design choice.

    Ultimately, whether recurrent inference is worth adopting depends on which classes of errors the extra compute eliminates. High-frequency completion usually prioritizes response speed; changes that span multiple modules and carry high rework costs may justify spending more compute for a more reliable result in one shot. Only by putting pass rates, rework counts, and end-to-end latency in the same evaluation table can you tell whether shared computational depth delivers real gains—or just a more expensive generation.