Loop Computation and Shared Memory: Designing Architectures for Long Contexts

    This article examines how loop-based computation affects parameter count, compute cost, and historical state storage in long-context language models. It explains why recurrently executing the same modules does not automatically reduce KV-cache usage, how sparse memory and sliding windows trade complexity for efficiency, and why shared-memory designs can decouple context capacity from the number of processing rounds. It also outlines the latency, training, quality, evaluation, and implementation considerations required to assess these architectures reliably.

    1. Evaluate Parameters, Computation, and Caching Separately

    When evaluating loop-based architectures for language models, it is not enough to ask how many times the same network layers are executed. The more important questions are:

    • How much additional computation does looping introduce?
    • How is historical state stored?
    • Does the available long-context capacity change?
    • Can the extra computation improve task quality?

    Loop-based computation applies a network module to an intermediate representation multiple times. Compared with simply stacking more independent layers, this approach reuses parameters and can increase effective computational depth without increasing parameter count at the same rate.

    However, parameter sharing is not the same as computation sharing, and neither is equivalent to cache sharing. Executing the same weights twice generally still requires the corresponding computation twice. If the two executions produce different historical key-value states, the inference system may also need to store those states separately.

    Therefore, at least three dimensions should be evaluated independently:

    • Parameter size: How many model weights must be stored.
    • Compute cost: How much computation is required for input processing and output generation.
    • State cost: How much historical information must be retained for subsequent generation.

    The potential value of loop-based designs lies in reallocating these resources, not in making all three decrease at no cost.

    2. Why Conventional Autoregressive Architectures Produce Growing Caches

    In standard autoregressive attention, each position produces a query, key, and value. When generating subsequent tokens, the model uses the current query to access previously stored keys and values, avoiding the need to recompute the entire historical sequence.

    This historical state is commonly called the key-value cache, or KV cache. Ignoring memory alignment, management metadata, and other overhead, its size can be approximated as:

    1. M ≈ 2 × B × T × L × Hkv × Dh × S

    Where:

    • B is the number of sequences processed concurrently;
    • T is the historical sequence length;
    • L is the number of effective layers requiring independent caches;
    • Hkv is the number of key-value heads;
    • Dh is the dimension of each head;
    • S is the number of bytes used by each cached element;
    • The factor 2 accounts for keys and values.

    This relationship shows that cache capacity grows not only with context length, but also with the number of layers whose historical states must be stored independently.

    When a module is executed repeatedly, its intermediate inputs are usually different in each round, even if the same parameters are used. The resulting keys and values may therefore also be different. If later generation needs to access the historical states from each round independently, separate caches are required.

    Under otherwise identical conditions, if a looped region stores a complete historical state for every round, its cache usage may grow approximately linearly with the number of rounds. This does not mean that the cache for the entire model will necessarily double. The actual increase depends on the scope of the loop, the sharing strategy, and the design of local attention.

    Identical weights alone do not justify overwriting the cache from a previous round. Shared parameters indicate that the same transformation rule is being used; they do not mean that the inputs or outputs of that transformation are identical.

    3. Sparse History and Local Windows: Trading Complexity for Efficiency

    One possible approach is to avoid storing the complete history after every round. Instead, historical access can be divided into long-range access and local access.

    3.1 Use Sparse Memory for Long-Range Access

    For distant historical positions, the model can access only selected tokens or segments. It may preserve structural positions, important content, or history selected through a learned mechanism.

    This can reduce the amount of data involved in attention computation, but two cases must be distinguished:

    • If the complete key-value state is still retained and only a subset is selected during computation, the primary savings are in compute and memory bandwidth.
    • If the system stores only the selected key-value states, cache capacity may also decrease, but this introduces information loss and the risk of selecting the wrong history.

    For this reason, sparse attention should not automatically be equated with a smaller cache. The implementation must be examined to determine what is stored, what is read, and what is discarded.

    3.2 Use a Sliding Window for Recent History

    For the most recent history, the system can maintain an independent local KV cache generated by a particular round. If the window length is W, the size of this state is mainly determined by W rather than continuing to grow with the full context length.

    Local windows are useful for recent dialogue, consecutive code segments, and short-range semantic dependencies. Information outside the window still requires another path for access. If a critical constraint is located far away, the model cannot rely on local state alone.

    3.3 Reuse Retrieval Results with a Correction Mechanism

    Different loop rounds can reuse parts of the historical selection results, reducing repeated indexing and retrieval overhead. However, loop computation can change the current representation and the information required by the model. A segment considered unimportant in one round may become important in a later round.

    A safer design is to reuse a candidate set while allowing rescoring, local supplementation, or fallback retrieval. The system should avoid permanently locking in the first selection.

    The main cost of this hybrid approach is engineering complexity. Cache lifecycles, position mapping, cross-round state boundaries, and multi-request scheduling all become more difficult. Whether the resource savings justify this complexity must be validated under realistic workloads.

    4. Why Shared-Memory Architectures Fit Loop-Based Computation

    Another approach is to separate the construction of historical memory from the repeated processing of current representations.

    The network can be abstracted into two parts:

    1. Memory construction module: Processes historical inputs and creates context representations that can be accessed later.
    2. Looped processing module: Applies multiple transformations to the current representation while reading the shared memory through mechanisms such as attention.

    The key is not simply to divide the network into an earlier half and a later half. Instead, the architecture must explicitly define which modules own long-lived state and which modules only read that state.

    Let the shared historical memory be M, and let the current representation be h₀. The loop can be written as:

    1. hᵣ₊₁ = F(hᵣ, M)

    Here, F is the reused processing module and r is the loop round. If every round reads the same M and does not create a separate full-history cache, increasing the number of rounds does not have to increase global cache capacity proportionally.

    This design partially decouples the amount of history the model can remember from the number of times it processes the current state.

    However, the design depends on several important assumptions:

    • The shared memory remains consistent throughout the loop.
    • All rounds can in fact use the same historical representation.
    • The memory projection does not create and retain a complete independent key-value copy for every round.
    • The costs of local state, temporary tensors, and auxiliary indexes are controlled.

    If different layers or rounds require complete independently projected key-value copies, sharing the source representation does not automatically mean that the final cache is shared. Actual capacity must be measured according to the physical tensors retained during deployment.

    5. A Constant Global Cache Does Not Mean Constant Total Cost

    The most common misunderstanding about shared memory is to interpret “global cache size does not grow with the number of loop rounds” as “additional loops are free.”

    In practice, looping still introduces several types of overhead.

    5.1 Attention Reads May Be Repeated

    Every round may need to read the shared history again. Even without creating additional global cache entries, long-context reads continue to put pressure on memory bandwidth.

    When the historical sequence is very long, the inference bottleneck may shift from cache capacity to the speed at which the cache can be accessed.

    5.2 Compute and Generation Latency Usually Increase

    More loop rounds mean more representation transformations and attention operations. A stable parameter count does not guarantee stable per-token generation latency.

    For interactive applications, it is important to measure whether additional loops significantly slow each output and whether the quality improvement is sufficient to justify the latency cost.

    5.3 Training Still Requires Activation and Gradient Memory

    During inference, some temporary states can be released. During training, however, intermediate activations typically need to be retained or recomputed for backpropagation. Therefore, lower inference cache usage cannot be directly interpreted as a proportional reduction in training memory.

    5.4 Greater Capacity Does Not Guarantee Better Effective Use

    The ability to accept a longer input only shows that the system can operate at that capacity. It does not prove that the model can accurately retrieve distant facts, preserve constraints, or integrate information across separated segments.

    “Fits in memory” and “is used effectively” must be evaluated separately.

    6. Why These Designs Are Worth Studying for AI Agents

    Long-running agents continuously accumulate dialogue, tool outputs, execution traces, and intermediate conclusions. As a task progresses, the history becomes larger, while each individual decision usually depends on only part of it.

    The combination of shared memory and looped processing is well suited to workloads with large historical state and current decisions that require multiple rounds of processing:

    • Historical inputs can serve as a continuously maintained memory source.
    • The current step can be processed repeatedly around plans, constraints, and evidence.
    • Under the appropriate architectural constraints, increasing the number of processing rounds does not have to increase global historical cache size by the same amount.

    However, internal loops should not automatically be interpreted as observable reflection, nor should they be assumed to improve tool-use reliability. Whether the model learns effective information integration depends on the training objective, data distribution, and module design.

    Agent systems should also avoid appending every raw log entry to the context indefinitely. A more practical approach is to manage state in layers:

    • Preserve recent interactions in relatively complete form.
    • Store long-term facts and critical constraints as structured records.
    • Place large tool outputs in external storage and retrieve them when needed.
    • Record execution state separately from model inferences.
    • Preserve the sources of summaries and retrieved content for verification.

    Architectural optimization and system-level memory management complement each other; one does not replace the other.

    7. How to Build a Reliable Evaluation Framework

    These architectures should be compared under consistent conditions rather than evaluated only by maximum context length or a theoretical cache formula.

    7.1 Resource Metrics

    Measure model weights, global cache, local cache, index structures, temporary workspaces, and additional runtime usage separately. Tests should cover different input lengths, output lengths, and concurrency levels. A single-request result is not sufficient to estimate production capacity.

    7.2 Performance Metrics

    Distinguish between input processing time, time to first output, subsequent generation speed, and overall throughput. Shared memory may improve capacity without improving every performance metric.

    Tail latency under high concurrency should also be measured, along with whether loop computation makes request scheduling more difficult.

    7.3 Quality Metrics

    Evaluation should go beyond single-location information retrieval. It should include:

    • Integrating facts distributed across multiple segments;
    • Distinguishing similar pieces of content accurately;
    • Preserving long-range constraints;
    • Selecting useful evidence from tool outputs;
    • Measuring error accumulation and recovery in multi-step tasks.

    7.4 Ablation Studies

    With training and inference conditions kept as consistent as possible, vary the number of loop rounds, local window size, sparse-access strategy, and memory-sharing method separately.

    This makes it possible to determine where the improvement comes from: additional computation, better memory representations, or simply a larger accessible range. If parameter size, data, and compute budget all change at the same time, clear conclusions become difficult.

    8. In Production, State Correctness Comes First

    Cache optimization is a system-level change that can introduce subtle and difficult-to-detect errors. The implementation should first define the ownership, update timing, and invalidation conditions of every state object.

    In particular, verify that:

    • Shared memory is updated in the correct order when new tokens are added;
    • Different rounds do not read states belonging to another round;
    • Position relationships remain correct as a local window moves;
    • Sparse indexes do not access released or replaced data;
    • Caches remain strictly isolated when processing multiple requests in a batch;
    • No historical representation accidentally contains information from the future.

    Before optimizing throughput, use an implementation that is easy to inspect as a reference. Compare full-sequence computation with incremental decoding to verify output consistency.

    After introducing sparse selection, low-precision caching, or other approximation methods, measure the resulting numerical error and task-quality changes separately.

    9. Conclusion: The Main Value Is Decoupling, Not Simply Adding More Loops

    Loop-based computation provides a path for parameter reuse, but its benefits depend heavily on how historical state is managed. If every round maintains a separate complete cache, long-context costs may grow rapidly. If local windows and sparse history are used to control that growth, the system must accept more complex information selection and engineering management. If shared historical memory is further separated from looped processing, global cache capacity may no longer need to increase in proportion to the number of rounds.

    The central question is not whether one architecture is inherently more advanced. It is whether the design achieves a better balance among explicit quality targets, latency limits, and resource budgets.

    Only by evaluating memory capacity, memory-access cost, effective computational depth, and task reliability together can we determine whether loop-based architectures are genuinely suitable for long-context applications.