Running 28 Layers Twice: Practical Depth Scaling with Recurrent Transformers

    Recurrent Transformers decouple model depth from parameter count by repeatedly applying a shared attention-and-FFN block. This article explains the architecture, KV-cache design, adaptive early exit, training stability, quantization risks, cost trade-offs, long-context and multimodal interactions, and why code is an effective intermediate representation for verifiable generation tasks. It also provides an evaluation framework and deployment recommendations for balancing reasoning depth, latency, and cost.

    1. The Starting Point: Why Depth Is the Most Expensive Capability

    In a standard Transformer, parameter count and computational depth are tightly coupled. Adding the Lth layer means roughly another O(12·d²) parameters—the four attention projections plus the two feed-forward layers—and requires every token to pass through another complete attention and feed-forward computation.

    Increasing depth therefore consumes two scarce resources at the same time: memory capacity and inference compute.

    In deployment, the main bottleneck is often not raw compute but memory capacity and bandwidth. Model weights must remain resident, KV cache size grows with context length, and batch concurrency is reduced. Increasing width increases bandwidth pressure, while increasing depth extends the serial dependency chain and raises time-to-first-token latency. This has traditionally forced a choice between models that are wide and shallow and those that are narrow and deep.

    Recurrent architectures attempt to break this connection by decoupling depth from the parameter count.

    2. Core Mechanism: Weight Sharing Turns Depth into a Time Dimension

    Assume a recurrent block contains one attention module and one feed-forward module. Its parameter count is comparable to that of a single layer. During the forward pass, the block is executed for T iterations while the hidden state continues to evolve:

    • Parameter count: remains O(d²), independent of T;
    • Effective depth: becomes L × T;
    • Compute per token: increases approximately linearly with T.

    In other words, recurrence converts depth from a static capacity cost into a dynamic time cost. The capacity budget stays fixed while the compute budget becomes adjustable. This makes the design suitable for spending more iterations on difficult problems and fewer on easy ones.

    The idea itself is not new. Differentiable halting mechanisms for general-purpose Transformers and cross-layer weight sharing in parameter-efficient pretraining have both supported the same broader observation: before representation capacity is saturated, repeated computation can deliver more benefit than widening under an equivalent parameter budget.

    3. Implementation Sketch: A Minimal Recurrent Block

    1. # Language-agnostic pseudocode illustrating the control flow
    2. def loop_block(x, T_max, exit_fn=None):
    3. h = x
    4. for t in range(T_max):
    5. h = h + attn(ln_1(h), step=t) # Attention sublayer
    6. h = h + ffn(ln_2(h)) # Feed-forward sublayer
    7. if exit_fn is not None and exit_fn(h, t):
    8. break # Adaptive early exit
    9. return h

    A production system must address at least four additional concerns before this simple loop can be trained reliably and served efficiently.

    4. Four Engineering Problems That Must Be Redesigned

    1. The Interaction Between KV Cache and Recurrence

    This is one of the easiest issues to overlook.

    If every iteration writes new entries to the cache, cache size grows by a factor of T, making the design impractical for long-context workloads. If all iterations share exactly the same cache, later iterations cannot introduce new positional information, and the recurrence degenerates into little more than repeated feed-forward processing.

    A common compromise is to allow only selected iterations to write to the cache, or to introduce an independent positional bias for the iteration index. This keeps cache growth under control while preserving distinctions between iterations.

    The cache semantics must be defined before the number of recurrent steps is chosen.

    2. Adaptive Exit and Latency Distribution

    With a fixed T, every request pays the same compute cost. Early exit based on confidence or a residual-change threshold can reduce average cost, but it also increases latency variance. Under the same model, an easy request and a difficult request may have response times that differ by several times.

    Serving infrastructure therefore needs separate queues and timeout policies for long-tail requests. Otherwise, a small number of deep-reasoning requests can dominate P99 latency.

    3. Training Stability

    Sharing weights across iterations amplifies two risks.

    First, gradients must pass through T serial stages, so effective learning signals may weaken for later iterations. Second, representations across iterations may converge toward one another, resulting in repeated computation without additional information.

    Typical mitigation strategies include:

    • Maintaining an identity residual path between iterations;
    • Normalizing the output of each iteration;
    • Applying a mild regularization term that encourages representation differences across iterations;
    • Using iteration-level stochastic depth so the model learns to produce useful outputs at different iteration counts.

    4. Numerical Precision and Quantization

    Because the same weights are read and applied repeatedly, quantization errors can accumulate across iterations. In low-bit inference, attention projections and normalization layers should receive priority for precision, and the residual stream between iterations should be monitored for error growth.

    5. Cost Structure: Trading Depth for Parameters Is Not Free

    The cost can be expressed through a rough multiplication:

    1. Total cost ≈ input tokens × prefill compute per token
    2. + output tokens × (decode compute per token + per-iteration overhead)

    Keeping the parameter count constant mainly reduces the weight-reading component of the first term. Doubling effective depth, however, approximately doubles compute per token. If the model also tends to generate longer reasoning traces, the increase in output token count multiplies the effect, producing several times the total cost.

    This explains a common observation in practical testing: stronger reasoning modes can take several times longer than lightweight modes, while consuming an order of magnitude more reasoning tokens.

    The conclusion is not that recurrent architectures are uneconomical. Their value depends heavily on the task distribution. Batch-oriented, structured, and verifiable coding workloads can amortize fixed overhead. Short question answering and high-concurrency online services are more heavily penalized by serial depth.

    6. Long Context and Multimodal Input: Orthogonal Capabilities with Combined Costs

    Million-token contexts and visual input are separate capability dimensions from recurrence, but they can amplify one another’s costs:

    • Long-context processing depends on position-encoding extrapolation, chunked or sparse attention, and cache compression;
    • Visual input adds encoding overhead and increases the number of tokens;
    • Recurrent depth requires the system to reread these longer sequences at every iteration.

    As a result, the practical operating range of such a model is the intersection of long inputs and deep reasoning, not every possible combination of the two. During model selection, teams should use their own workloads to identify the three-dimensional turning point across context length, iteration count, and latency.

    7. The Technical Basis of “General-Purpose Code Generation”: Code as a Universal Intermediate Representation

    Extending generation beyond natural language to video, games, 3D scenes, and mechanical structures depends on a common premise: these outputs can be represented as executable, composable, and verifiable code or declarative descriptions.

    • Video: scripted descriptions of timelines and keyframe parameters;
    • Games: declarative definitions of scene graphs, rules, and state machines;
    • 3D and mechanical design: parametric geometry and constraint-solving expressions.

    Code is effective as an intermediate representation because it provides three built-in advantages:

    1. Executability: it can produce an actual result;
    2. Verifiability: constraints and regressions can be checked automatically;
    3. Composability: components can be reused and compared through diffs.

    These properties compensate for the limited interpretability of deep reasoning. A solution produced after multiple internal iterations can ultimately be evaluated by a compiler, renderer, or simulator, which provides objective feedback.

    This is why recurrent architectures can be especially valuable for verifiable tasks.

    8. How to Evaluate These Models: Do Not Rely on a Single Leaderboard

    A single benchmark ranking is not enough to support a deployment decision. Evaluation should cover at least four dimensions:

    1. Capability: pass rates broken down by task type rather than only an aggregate score;
    2. Cost: normalized metrics such as useful output per unit cost and the average token count for requests that meet the target quality;
    3. Stability: P50, P95, and P99 latency, degradation curves under long contexts, and early-exit rates;
    4. Engineering readiness: structured-output compliance, tool-call success rate, and cache hit rate.

    A small but demanding private evaluation set of 50–200 real business samples is often more informative for deployment than chasing public leaderboard positions.

    9. Access Strategy: General Considerations for Weights, Interfaces, and Safety Evaluation

    Availability also determines the path to adoption. In practice, model access often develops along three separate tracks:

    • Availability inside subscription-based programming tools;
    • API access after safety evaluation;
    • Weight release after additional hardening and responsible-release processes.

    These tracks do not necessarily progress at the same pace. Engineering teams should therefore build an abstraction layer and avoid binding business logic to a single access path.

    10. Deployment Checklist

    • Wrap model calls in a replaceable adapter layer, with iteration count, reasoning mode, and context length exposed as configuration;
    • Enable deeper reasoning for verifiable tasks, while using shallow modes for high-concurrency short requests;
    • Assign independent timeouts and fallback paths to long-tail deep-reasoning requests;
    • Load-test the two-dimensional matrix of context length and output length before launch to identify cost turning points;
    • Use normalized cost metrics rather than absolute benchmark scores when making technology-selection decisions.

    The value of recurrence is not simply that the parameter table looks smaller. Its real value is turning the reasoning budget into an adjustable control. Teams capture the benefit of trading depth for parameters only when they align that control with task difficulty, verification methods, and cost limits.