Why Large-Model Inference Produces Garbled Output: Investigating Cache Races

    Garbled characters and repeated text in large-model inference are not always encoding or sampling problems. In high-concurrency, long-context workloads—especially coding-agent requests—incorrect or premature KV-cache reads can silently corrupt attention results. This article explains how to use speculative-decoding metrics to narrow the search, identify cache-reclamation and asynchronous-loading races, design timing-sensitive regression tests, and optimize layer-wise cache partitioning only after correctness is secured.

    In large-model inference services, garbled output is often initially treated as a character-encoding issue, while repeated output is commonly attributed to sampling. During one large-scale deployment, however, both anomalies appeared mainly in high-concurrency, long-context requests from coding agents and were difficult to reproduce with conventional tests.

    The eventual investigation showed that the problem was not in the output text itself. The attention computation was reading incorrect or not-yet-ready cache data.

    The incident exposed two constraints that throughput optimizations can easily obscure:

    • A request ending does not mean that device-side writes have finished.
    • Submitting a load operation does not mean that its data is already readable.

    1. Use Speculative-Decoding Metrics to Narrow the Investigation

    Speculative decoding first generates a sequence of candidate tokens and then asks the target model to verify them, allowing one verification step to advance multiple tokens when possible. The candidate acceptance rate measures the proportion of candidates that are accepted. The per-round accepted length measures how many consecutive candidates are accepted in one verification round.

    The exact definitions may vary between implementations. During an investigation, first confirm the denominator and determine whether accepted length includes an additional token generated by the target model.

    In this deployment, requests that produced garbled or unusual characters often had a lower accepted length. Some requests with repeated output, however, showed a relatively high acceptance rate.

    The latter pattern is particularly easy to misinterpret. If both the target model and the candidate-generation process continue along the same repeated text, they can frequently agree even when the output is useless to the user.

    An accepted candidate indicates prediction agreement, not content correctness.

    These metrics should therefore be treated only as investigation signals. Code fragments, rare identifiers, sampling settings, and changes in candidate length can also affect them. A more effective approach is to group requests by context length, concurrency, cache-hit path, and cancellation state. Compare each group against a baseline for similar requests, then correlate anomalous requests with the timeline of cache allocation, writes, loads, and release events.

    If problems are concentrated in long-context requests that were cancelled, prioritize cache-lifetime checks. If anomalies are concentrated on requests using asynchronous loading, inspect data-readiness conditions. Do not classify the failure based solely on a global average.

    2. Cache-Reclamation Race: Old Writes Can Land After Cancellation

    Generative models store the keys and values required for attention in a KV cache. This avoids recomputing the entire historical context for every generated token.

    In a disaggregated prefill-and-decode architecture, the prefill side processes the input and builds the cache, while the decode side reads the cache and generates tokens incrementally. The two stages can be scheduled independently, but that separation requires explicit rules defining who may write to a cache block and when the block can be reclaimed.

    A typical failure sequence looks like this:

    1. The decode side determines that a request has timed out and releases its cache block.
    2. The cache pool quickly assigns that block to a new request.
    3. A write submitted earlier by the old request on the prefill side is still executing.
    4. The old write later lands in the memory now assigned to the new request.
    5. The new request reads a mixture of new and old data.

    The cache address, shape, and data type may all remain valid, so the computation does not necessarily fail immediately. Instead, generation silently diverges from the expected result.

    Adding a lock around cache-pool allocation and release is not sufficient. A lock can protect host-side metadata, but it cannot immediately stop a device write that has already been submitted.

    A more reliable design separates request termination from cache reusability. After cancellation, mark the cache block as pending reclamation. Return it to the cache pool only after the prefill side confirms that all related writes have completed—or confirms that no further write can land in that block.

    If allocation generations are used to identify delayed completion notifications, there is another limitation to consider. Generation checks can prevent an old notification from modifying metadata belonging to a new request, but they cannot prevent an already in-flight device write from overwriting memory.

    This fix also has a capacity cost. A pending-reclamation block cannot be immediately assigned to another request, so its count and waiting time should be monitored. If completion confirmations continue to accumulate, inspect the execution path first. When necessary, limit new requests from entering the system rather than releasing cache blocks prematurely to reduce apparent cache usage.

    3. Asynchronous-Loading Race: Computation Starts Before the Data Arrives

    Another class of failures occurs on the asynchronous loading path for tiered caches. When a cache is not currently on the device, the runtime can start loading it while overlapping the transfer with computation from other requests.

    The problem is that streams are ordered independently. A transfer stream and a compute stream each execute their own operations in order, but that does not create an implicit ordering relationship between the two streams. If an indexing operation on the forward-computation stream starts first, it may read a cache that has only been partially populated.

    An explicit dependency should be established between the operation that produces the data and the first operator that consumes it. For example, after the relevant transfer completes, record an event and make the compute stream containing the indexing operation wait for that event.

    If a load involves multiple shards or several transfers, the event must cover every piece of data required by the computation. It must not merely indicate that one transfer has completed.

    A failed or cancelled load must not cause the cache to be marked ready. Depending on the path, the system should recompute the required cache or terminate the request and report an error.

    During diagnosis, global synchronization can help determine whether the anomaly is related to execution order. However, using global synchronization as the permanent fix usually prevents unrelated requests from running concurrently.

    The production fix should place the wait immediately before the first actual consumer of the data, allowing tasks that do not depend on that cache to continue running. This preserves the required read-after-write ordering while retaining the performance benefits of asynchronous loading.

    4. Load Tests Must Reproduce Failure Timing, Not Just Higher Concurrency

    Short requests, low cancellation rates, and an abundant cache pool are unlikely to cover either of these races. Multi-turn coding-agent requests may continuously accumulate code, logs, and tool results. This increases prefill cost and extends the time that some operations remain in flight.

    A sudden rise in concurrency combined with active cancellation makes it even more likely that a cache will be reused before an old write has completed, or that computation will begin before an asynchronous load is ready.

    Regression testing can focus on three areas.

    Verify the Reclamation Boundary

    In a controlled test, delay prefill writes, trigger request cancellation, and make other requests compete for a limited cache pool. The test should directly assert that a cache block cannot be reallocated while an old write could still land in it.

    Checking only whether the output appears normal can miss errors that do not produce an obvious text change.

    Verify the Readiness Boundary

    Introduce controlled delays into asynchronous loading and cover complete loads, partial loads, failures, and cancellations. Confirm that indexing and subsequent computation never read data that is not ready. Also verify that the wait affects only tasks dependent on that batch of data.

    Establish an Output Reference

    Use fixed inputs and controlled decoding settings to compare the asynchronous path with a synchronous reference path under the same configuration.

    If the execution environment cannot guarantee token-by-token equality, focus on cache ownership, read/write ordering, and the rate of abnormal output. Do not automatically classify normal numerical or sampling differences as cache corruption.

    After deployment, expand the rollout gradually while monitoring abnormal-output rate, accepted length, the number of pending-reclamation blocks, and tail latency.

    These metrics must be interpreted together. A lower accepted length with normal output may simply reflect a change in request composition. A lower anomaly rate combined with a continuing buildup of pending-reclamation blocks may indicate that the correctness fix has exposed a new capacity bottleneck.

    5. Optimize Prefill with Layer-Wise Partitioning Only After Correctness Is Stable

    Long contexts increase cache consumption and the data-movement pressure during prefill. Layer-wise cache partitioning assigns different layers’ cache storage to different accelerator devices. When dependencies allow, some data transfers can overlap with computation in other layers.

    This can reduce per-device cache pressure. If transfer time is fully hidden by computation, it can also reduce prefill waiting caused by data movement.

    However, finer partitioning is not always better. If the device interconnect becomes a bottleneck, or if overly small shards increase scheduling and synchronization overhead, communication can re-enter the critical path.

    Under the same model, hardware, and request distribution, compare prefill throughput, time to first token, tail latency, and peak per-device cache usage—not throughput alone.

    Cancellation, reclamation, and asynchronous-loading regression tests must also cover the partitioned path. Moving from centralized cache management to distributed management does not change the two fundamental constraints:

    • Old writes must finish before memory is reused.
    • Data must be ready before it is read.

    The most practical investigation sequence is:

    1. Use output anomalies and decoding metrics to locate problematic requests.
    2. Use event timelines to verify read and write ordering.
    3. Reproduce the race with controlled timing.
    4. Evaluate throughput optimizations only after correctness is protected.

    When intermittent garbled output cannot be reproduced by conventional tests, repeatedly increasing the test count is often less effective than deliberately targeting the two critical windows: an old write is still in flight, or new data is not yet ready.