State Caching for Hybrid Architecture Agents: Unified Pool and Reuse Design

    In multi-turn Agents, the context grows continuously with tool calls, code read/write operations, and test outputs. As an intelligent coding Agent executes each step, new content is appended to the history, requiring the model to perform prefill on the entire long prefix in every turn. Prefix caching can reuse the previously computed parts to eliminate redundant computation, but hybrid architecture models complicate this process. This article first explains the caching challenges introduced by hybrid architectures, then discusses the design, benefits, and boundaries of a unified state pool, CPU tiered offloading, and cross-node reuse. Finally, it provides a checklist and citation rules for performance metrics.

    In multi-turn Agents, the context grows continuously with tool calls, code read/write operations, and test outputs. As an intelligent coding Agent executes each step, new content is appended to the history, requiring the model to perform prefill on the entire long prefix in every turn. Prefix caching can reuse the previously computed parts to eliminate redundant computation, but hybrid architecture models complicate this process.

    This article first explains the caching challenges introduced by hybrid architectures, then discusses the design, benefits, and boundaries of a unified state pool, CPU tiered offloading, and cross-node reuse, and finally provides a checklist and citation rules for performance metrics.

    1. Why Hybrid Architectures Make Prefix Caching Difficult

    Hybrid architecture models place both full attention layers and linear layers within the same network. Full attention layers save the KV Cache, which grows with sequence length. Linear layers (such as state space models or linear attention variants) save recursive hidden states, the size of which is basically independent of sequence length. The memory structure, lifecycle, and reuse methods of these two types of states are different, meaning the paged management originally designed only for the KV Cache cannot be directly applied.

    There are three specific pain points:

    1. State Heterogeneity: The management methods for the two types of states differ, and unified scheduling requires additional abstraction.
    2. Restoration Overhead: Before prefilling the new input, the system must first load the historical linear state, then recursively update it according to the new token sequence, or complete the update using a parallel scan. Linear states cannot be directly concatenated with new inputs. If the deserialization and VRAM copying of the state are not handled well, the Time To First Token (TTFT) will increase significantly.
    3. VRAM Fragmentation: The size of linear states is fixed, while the KV Cache grows with length. When mixed together, the block sizes are inconsistent, and free VRAM will be split into small chunks that are difficult to reuse.

    Another easily overlooked difference is the reuse position. KV blocks are truncated by prefix and can be shared as long as the prefix tokens match. A linear state is the recursive result at a certain position and can only be reused as a whole at the exact position where it was saved. Therefore, the caching system needs to proactively create checkpoints at appropriate boundaries (e.g., at the end of each turn, or upon each tool call return).

    Dimension Full Attention Layer KV Cache Linear Layer Recursive State
    Size Grows with sequence length Basically independent of sequence length
    Lifecycle Each token appends a record, can be truncated by block Overwritten and updated at each step, only the latest value is kept
    Reuse Granularity Shared by block, any matching prefix can hit Can only be reused as a whole at the exact saved position
    Migration Method Can be transferred in batches by block Transferred as a whole, fixed volume

    When not to use a unified state pool: Pure full attention models already have mature paged KV solutions; introducing a unified pool only adds complexity. In highly real-time scenarios with extremely tight latency budgets, any additional copy on the restoration path may exceed limits. When VRAM margin is very small, the metadata and size-classified free lists themselves will also occupy space.

    2. How to Design a Unified State Pool

    The core idea is to map both types of states into standardized memory blocks, managed by a single pool and a single set of reference counts. The inference engine therefore does not need to write a separate scheduling logic for the linear layer. The following code is a reference implementation, where the allocation function is injected externally, and a regular byte array can be used instead of VRAM allocation during unit testing.

    1. import threading
    2. from dataclasses import dataclass
    3. VALID_TYPES = ("kv_cache", "linear_state")
    4. @dataclass
    5. class StateBlock:
    6. block_id: int
    7. state_type: str
    8. size_bytes: int # Rounded up according to alignment
    9. data: object = None # Returned by allocate_fn; must be completely overwritten when reused
    10. ref_count: int = 0
    11. class HybridStatePool:
    12. def __init__(self, capacity_bytes, allocate_fn, free_fn, alignment=256):
    13. if not isinstance(capacity_bytes, int) or capacity_bytes <= 0:
    14. raise ValueError("capacity_bytes must be a positive integer")
    15. if not isinstance(alignment, int) or alignment <= 0 or alignment & (alignment - 1):
    16. raise ValueError("alignment must be a power of 2")
    17. if not callable(allocate_fn) or not callable(free_fn):
    18. raise TypeError("allocate_fn and free_fn must be callable")
    19. self._lock = threading.Lock()
    20. self._allocate = allocate_fn
    21. self._free_fn = free_fn
    22. self._capacity = capacity_bytes
    23. self._alignment = alignment
    24. self._used = 0 # Bytes allocated to blocks, including blocks in the free list
    25. self._next_id = 0
    26. self._active = {} # req_id -> {(layer_idx, state_type): block}
    27. self._free = {} # (state_type, aligned_size) -> [block, ...]
    28. def _align(self, size_bytes):
    29. return (size_bytes + self._alignment - 1) // self._alignment * self._alignment
    30. def _take_block(self, state_type, size_bytes):
    31. if state_type not in VALID_TYPES:
    32. raise ValueError(f"unknown state_type: {state_type}")
    33. if not isinstance(size_bytes, int) or size_bytes <= 0:
    34. raise ValueError("size_bytes must be a positive integer")
    35. aligned = self._align(size_bytes)
    36. bucket = self._free.get((state_type, aligned))
    37. if bucket:
    38. return bucket.pop()
    39. if self._used + aligned > self._capacity:
    40. raise MemoryError("State pool capacity insufficient")
    41. data = self._allocate(aligned) # Allocate first, update count only on success
    42. block = StateBlock(self._next_id, state_type, aligned, data)
    43. self._next_id += 1
    44. self._used += aligned
    45. return block
    46. def get_state(self, req_id, layer_idx, state_type, size_bytes):
    47. with self._lock:
    48. layers = self._active.setdefault(req_id, {})
    49. key = (layer_idx, state_type)
    50. block = layers.get(key)
    51. if block is None:
    52. block = self._take_block(state_type, size_bytes)
    53. block.ref_count = 1
    54. layers[key] = block
    55. return block
    56. def share(self, req_id, layer_idx, block):
    57. with self._lock:
    58. if block.ref_count < 1:
    59. raise RuntimeError("Can only share blocks that are still held")
    60. layers = self._active.setdefault(req_id, {})
    61. key = (layer_idx, block.state_type)
    62. if key in layers:
    63. return
    64. block.ref_count += 1
    65. layers[key] = block
    66. def release(self, req_id):
    67. with self._lock:
    68. layers = self._active.pop(req_id, None)
    69. if layers is None:
    70. return 0 # Idempotent: repeated releases do not change any counts
    71. freed = 0
    72. for block in layers.values():
    73. block.ref_count -= 1
    74. if block.ref_count == 0:
    75. self._free.setdefault((block.state_type, block.size_bytes), []).append(block)
    76. freed += 1
    77. return freed
    78. def shrink(self):
    79. with self._lock:
    80. for bucket in self._free.values():
    81. while bucket:
    82. block = bucket.pop()
    83. self._free_fn(block.data)
    84. self._used -= block.size_bytes
    85. block.data = None
    86. self._free.clear()

    The responsibilities of each method are as follows:

    • _take_block first checks the free list and reuses it directly if hit; otherwise, it checks the capacity and then calls the allocation function. The used byte count is updated only after successful allocation, so an allocation failure will not mess up the count.
    • get_state holds only one reference for the same request, same layer, and same type. Repeated calls return the existing block without incrementing the count.
    • share allows another request to share an existing block, which is the basis for cross-request prefix reuse. It requires that the block is still held by at least one request, otherwise it raises an error directly.
    • release returns directly for unknown requests, making repeated releases safe. Blocks whose reference count reaches zero enter the free list instead of being immediately returned to the system.
    • shrink actually returns free blocks to the allocator and deducts the used byte count.

    There are three types of failure modes to note in the implementation. The first is missing decrements in reference counting, where blocks are never recycled and the pool gradually depletes. The second is repeated releases causing negative counts, which this implementation avoids through idempotent releases. The third is that code still reads a block’s data after it has been released, forming a dangling reference.

    This reference implementation also has clear boundaries. It uses a single global lock, which may become a bottleneck under high concurrency, and can be changed to a request-sharded lock. It does not handle GPU stream synchronization, nor does it have an eviction policy. Reused linear state blocks retain old data; the restoration path must write completely and cannot assume the block content is clean.

    3. How to Weigh CPU Tiered Offloading

    The benefit of offloading is freeing up VRAM. Long-term idle sessions can move their states to CPU memory, leaving VRAM for active requests, allowing the same card to host more sessions.

    The cost of offloading lies in the restoration path. States returning to VRAM must pass through PCIe or other interconnects and undergo deserialization. Whether it is worthwhile can be judged by a simple condition:

    T_restore = state bytes / effective bandwidth + deserialization time

    Offloading only makes sense if T_restore is significantly less than the Prefill time for recalculating that prefix. Both numbers must be measured on your own hardware and target sequence lengths; you cannot directly apply numbers from others.

    There are mainly four failure modes:

    1. The copy stream and compute stream are not synchronized, and inference reads data that has not been fully written.
    2. When CPU memory is insufficient, the operating system starts paging, making recovery time unpredictable.
    3. The eviction policy mistakenly evicts blocks that are still referenced.
    4. The copy uses non-pinned memory, resulting in actual bandwidth far lower than expected.

    Checkpoints include three items. Compare the TTFT of the “restore” and “recompute” paths within the target sequence length range. Record the actual effective bandwidth rather than the nominal value. Artificially trigger idle eviction and then restore to confirm the output is consistent with the non-offloaded baseline.

    4. How to Ensure Consistency in Cross-Node Reuse

    The benefit of cross-node reuse is that when the scheduler migrates the same session to another machine, it does not need to prefill from scratch. For multi-turn Agents, session migration is very common, making the benefits of reuse more pronounced.

    The boundary is that the state is tightly bound to the model. Linear states depend on the specific weight version, quantization configuration, tokenizer version, and prefix token sequence. When versions are inconsistent, the system may silently reuse incorrect states, producing erroneous outputs without any error reports. This type of problem is harder to troubleshoot than VRAM exhaustion.

    Consistency design can be approached from three aspects:

    • Content-Addressed Key: The key of the state consists of hash(model_id, weight_version, quantization_config, tokenizer_version, layer_index, prefix_token_hash). If any item changes, a new key is generated, and the old state will naturally not be hit.
    • Immutable After Write: The state is not modified after being written. When an update is needed, a new key is written instead of overwriting the old one, so concurrent writes to the same key only need to keep one copy.
    • Read-Time Verification: Verify the checksum upon reading. If it does not match, discard the state and fall back to recomputation. Session ownership is managed by leases; only after the lease expires can other nodes take over the writing.

    Failure modes include the following three categories. First, transmission interruption leaves a half-written block at the receiving end. Second, network partition causes two nodes to simultaneously believe they hold the lease. Third, after a version upgrade, old states remain and continuously occupy capacity.

    Checkpoints include three items. After modifying the weight version number, the hit rate should drop to zero, and the output should be consistent with the baseline. If the transmission is interrupted midway, it should be able to fall back to recomputation. For concurrent writes to the same key, only one copy should be kept.

    5. Performance Metric Citation Boundaries

    Performance metrics in the text cannot be directly taken as conclusions if detached from their context. Citable numbers should at least be accompanied by the following information:

    • Model scale and precision.
    • Sequence length, batch size, and concurrency.
    • Hardware model and interconnect method.
    • Whether the cached state is cold or hot.
    • Measurement starting point, whether it is request arrival or Prefill start.
    • Statistical methods, including sample size, median, and P95.

    There are four usage patterns to avoid. First, horizontal comparisons without context. Second, numbers that have only been run once. Third, comparing TTFT under a hot cache with throughput under a cold start. Fourth, directly interpreting VRAM savings as throughput improvement. This article does not cite specific performance metrics because the existing materials do not provide reproducible measurement conditions.

    6. Common Mistakes

    • Reference counts are not decreed on exception paths, preventing block recycling.
    • The same session is released repeatedly, or its state is still being read after release.
    • Applying the linear state reuse to requests after the saved position, which will yield incorrect recursive results.
    • Comparing TTFT where one side uses a hot cache and the other is a cold start.

    7. Reproducible Test Checklist

    1. Concurrent Reference Counting: Multi-threaded simultaneous execution on the same request