Conditional Storage for LLM Inference: Applicability, Bandwidth Estimation, Layer-wise Prefetching, and Deployment Troubleshooting

    This article examines conditional storage—layer-wise weight offloading—for LLM inference when GPU memory is the bottleneck. It explains when the approach is appropriate, provides a bandwidth-based feasibility estimate, compares it with quantization and MoE, offers a runnable layer-wise prefetch example, and outlines pre-deployment checks such as PCIe bandwidth measurement, capacity planning, and NVMe read performance.

    Introduction: GPU Memory Often Runs Out Before Compute

    During LLM inference, GPU memory often reaches its limit before compute does. The FP16 weights of a 7B-parameter model take about 14 GB (using GB = 10^9, i.e., 7×10^9 parameters times 2 bytes per parameter), not including KV cache and activations. Quantization can compress weights, but it introduces accuracy loss. Conditional storage is another approach: keep parameters not needed for the current step in CPU memory or on local NVMe, and move them into GPU memory when needed.

    In this article, conditional storage refers to layer-wise weight offloading. It is different from operating system swap. Swap evicts memory pages passively, and the inference program cannot control when eviction happens, making latency hard to predict. Conditional storage is actively scheduled by the inference program layer by layer, so transfers and computation can be ordered in advance.

    This approach does not reduce the amount of computation, nor does it automatically make inference faster. Every forward pass still executes all layers, and parameters still travel over the PCIe bus, whose transfer speed is usually much lower than GPU memory read speed. The sections below first cover applicability boundaries, then provide an estimation method, an example, deployment checks, troubleshooting steps, and evaluation metrics.

    1. Decide First Whether Conditional Storage Is Appropriate

    Suitable cases:

    • Model weights are read-only and do not need to be written back during inference.
    • A single GPU cannot hold the full weights, but host memory or local NVMe has enough capacity.
    • The application can tolerate increased time to first token (TTFT) latency, or it is an offline batch processing task.
    • PCIe bandwidth between the host and GPU is sufficient, and prefetching can overlap with computation.

    Unsuitable cases:

    • High-concurrency online services with strict latency requirements.
    • Quantization alone can fit the model fully in GPU memory, and the quantized accuracy meets requirements.
    • Input distribution varies widely, making parameter access order hard to predict.

    A rough estimate can help decide. Let the weight size of a single layer be W bytes, the actual available PCIe bandwidth be B bytes per second, and the compute time for one layer be t_c. The transfer time for one layer is t_m = W / B. If t_m is not greater than t_c, prefetching can be fully covered by computation, and the extra overhead is small. If t_m is much greater than t_c, every layer has to wait for data, and throughput will drop significantly.

    Take the 64 MiB layer used in the example below (about 67.1 MB). Assuming an actual PCIe bandwidth of 20 GB/s, t_m is about 3.4 ms. If computation for this layer takes only 0.3 ms, transfer is the bottleneck. In this case, increasing the batch size can spread the transferred data across more computation.

    The 20 GB/s figure is only an assumption; actual bandwidth must be measured. The measurement method is covered in the checks in Section 4.

    2. Differences Between Conditional Storage, Quantization, and MoE

    Method Mainly reduces Skips computation per token? Impact on output Main cost Predictability of access order Implementation complexity
    Quantization Parameter bytes No Precision loss, depending on bit width and calibration Accuracy drop; depends on kernel support Not applicable; all weights resident Low to medium
    MoE Computation per token Yes; only some experts are activated Determined by model architecture, not an extra inference-time loss All experts still need storage; expert load may be imbalanced Determined by routing results; depends on input Medium; requires model support
    Conditional storage Amount of parameters resident in GPU memory No; all layers still execute Mathematical results identical to the resident version, but transfers affect latency Transfer latency; throughput drop Fixed layer order; relatively high Medium to high

    The three methods can be combined, but two risks need attention.

    Quantization plus conditional storage is a common combination. Quantized weights use half the bytes, so transfer volume is also halved. However, dequantization kernels increase per-layer compute time, and this overhead must be confirmed separately in testing. The accuracy loss from quantization itself also needs to be validated with the application’s evaluation set; do not look only at transfer savings.

    MoE plus conditional storage requires the inference framework to know in advance which experts will be needed for the next step. Routing results are usually available only after the current layer is computed, so prefetching can rely only on prediction. If the prediction is wrong, the required experts still have to be transferred on demand, causing a sudden latency increase. Alternatives worth considering include multi-GPU expert parallelism, or an LRU cache for experts that keeps only recently frequent experts in GPU memory.

    To choose, follow three steps: first look at the GPU memory gap—how many bytes the model cannot fit; then look at the latency budget—how much extra latency the application can accept; finally, check whether access order is predictable. Offline tasks with a small gap and fixed order are the best fit for conditional storage. Tasks with a large gap but unpredictable access should prioritize quantization, multiple GPUs, or a smaller model.

    3. How to Implement Layer-wise Prefetching and Caching

    The following example uses a simplified Transformer layer structure to demonstrate the prefetch mechanism. It does not depend on a specific LLM, so it can run directly on a single GPU and be used to verify results. The example demonstrates only overlap between weight transfer and computation; it does not include KV cache.

    Environment requirements:

    • Python 3.10 or later.
    • PyTorch 2.1 or later, with a CUDA build.
    • A CUDA-capable NVIDIA GPU whose driver version meets the CUDA runtime requirements of the installed PyTorch.

    Installation and check commands:

    1. python -m pip install --upgrade torch --index-url https://download.pytorch.org/whl/cu121
    2. nvidia-smi
    3. python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.is_available())"

    The cu121 index URL must match your local driver and required CUDA version; see the official PyTorch installation instructions for details.

    The complete code below is saved as offload_demo.py:

    1. import copy
    2. import time
    3. import torch
    4. import torch.nn as nn
    5. from torch.func import functional_call
    6. DEVICE = "cuda"
    7. DTYPE = torch.float16
    8. class ToyBlock(nn.Module):
    9. """A simplified Transformer layer: two linear layers plus a residual connection."""
    10. def __init__(self, hidden):
    11. super().__init__()
    12. self.fc1 = nn.Linear(hidden, hidden * 4)
    13. self.fc2 = nn.Linear(hidden * 4, hidden)
    14. def forward(self, x):
    15. return x + self.fc2(torch.relu(self.fc1(x)))
    16. class OffloadedStack:
    17. """Weights stay in CPU pinned memory and are asynchronously moved to GPU memory layer by layer during the forward pass."""
    18. def __init__(self, blocks, prefetch_depth=2):
    19. self.depth = prefetch_depth
    20. self.cpu_states = [
    21. {k: v.detach().to(dtype=DTYPE).cpu().pin_memory()
    22. for k, v in b.state_dict().items()}
    23. for b in blocks
    24. ]
    25. # The skeleton only provides the module structure; parameters are replaced from the buffers by functional_call
    26. self.skeleton = copy.deepcopy(blocks[0]).to(DEVICE, dtype=DTYPE)
    27. self.copy_stream = torch.cuda.Stream()
    28. self.gpu_buffers = [None] * len(blocks)
    29. self.events = [None] * len(blocks)
    30. def _prefetch(self, i):
    31. if i >= len(self.cpu_states) or self.gpu_buffers[i] is not None:
    32. return
    33. with torch.cuda.stream(self.copy_stream):
    34. buf = {k: v.to(DEVICE, non_blocking=True)
    35. for k, v in self.cpu_states[i].items()}
    36. ev = torch.cuda.Event()
    37. ev.record(self.copy_stream)
    38. self.gpu_buffers[i] = buf
    39. self.events[i] = ev
    40. @torch.no_grad()
    41. def forward(self, x):
    42. compute = torch.cuda.current_stream()
    43. n = len(self.cpu_states)
    44. for i in range(n):
    45. # Initiate transfers for layers i through i+depth ahead of time, overlapping with current-layer compute
    46. for j in range(i, min(i + self.depth + 1, n)):
    47. self._prefetch(j)
    48. compute.wait_event(self.events[i])
    49. buf = self.gpu_buffers[i]
    50. # Tell the allocator that these tensors are still used by the compute stream and cannot be reused early
    51. for t in buf.values():
    52. t.record_stream(compute)
    53. x = functional_call(self.skeleton, buf, (x,))
    54. self.gpu_buffers[i] = None
    55. self.events[i] = None
    56. return x
    57. def timed(fn, iters=20):
    58. for _ in range(3):
    59. fn()
    60. torch.cuda.synchronize()
    61. t0 = time.perf_counter()
    62. for _ in range(iters):
    63. fn()
    64. torch.cuda.synchronize()
    65. return (time.perf_counter() - t0) / iters * 1000
    66. @torch.no_grad()
    67. def main():
    68. hidden, n_layers, batch, depth = 2048, 32, 8, 2
    69. blocks = [ToyBlock(hidden) for _ in range(n_layers)]
    70. x = torch.randn(batch, hidden, device=DEVICE, dtype=DTYPE)
    71. resident = [copy.deepcopy(b).to(DEVICE, dtype=DTYPE).eval() for b in blocks]
    72. def run_resident():
    73. h = x
    74. for b in resident:
    75. h = b(h)
    76. return h
    77. stack = OffloadedStack(blocks, prefetch_depth=depth)
    78. ref = run_resident()
    79. out = stack.forward(x)
    80. torch.cuda.synchronize()
    81. print("max_abs_diff:", (out - ref).abs().max().item())
    82. print("allclose:", torch.allclose(out, ref, atol=1e-3, rtol=1e-3))
    83. print(f"resident: {timed(run_resident):.2f} ms/forward")
    84. print(f"offloaded: {timed(lambda: stack.forward(x)):.2f} ms/forward")
    85. print(f"peak_mem: {torch.cuda.max_memory_allocated() / 2**20:.1f} MiB")
    86. if __name__ == "__main__":
    87. main()

    Run command:

    1. python offload_demo.py

    Expected output format, where values depend on hardware and are shown as placeholders here:

    1. max_abs_diff: <value>
    2. allclose: True
    3. resident: <value> ms/forward
    4. offloaded: <value> ms/forward
    5. peak_mem: <value> MiB

    Output explanation:

    • max_abs_diff should be 0.0 or a small value at the level of floating-point error. Both paths use the same weights and the same operations, so results should be identical. If the difference is significantly larger, first check whether all weights were converted to the same dtype.
    • allclose being True means the output from the offloaded path matches the resident path.
    • The offloaded time is usually higher than resident. In this example, the batch size is small and compute time is short, so transfers are hard to fully cover; this is normal. It verifies the mechanism and does not represent real application performance.
    • peak_mem includes GPU memory used by the resident path. To measure the peak of the offloaded path alone, run the two parts separately, or call torch.cuda.reset_peak_memory_stats() before and after the run.

    Key parameters:

    • prefetch_depth: the number of layers to transfer ahead of time. A larger value makes it easier for transfers to be covered by computation, but more layers remain resident in GPU memory. The peak buffer size is about the weight size of (prefetch_depth + 1) layers.
    • hidden and batch: determine single-layer size and compute time. Both change the ratio of t_m to t_c and are the main tuning levers.
    • pin_memory: weights must be in pinned memory so asynchronous copies can overlap with computation. Pinned memory is not swapped out to disk.

    To use this with a real model, replace ToyBlock with the target model’s layer, and manage KV cache separately in GPU memory.

    4. What to Check Before Deployment

    First, measure actual PCIe bandwidth. Theoretical bandwidth and actual values often differ significantly, so rely on measurements. The script below measures host-to-GPU copy speed. Use pinned memory during measurement and take the median of multiple results.

    1. import torch
    2. size = 256 * 2**20
    3. host = torch.empty(size, dtype=torch.uint8, pin_memory=True)
    4. dev = torch.empty(size, dtype=torch.uint8, device="cuda")
    5. for _ in range(5):
    6. dev.copy_(host, non_blocking=True)
    7. torch.cuda.synchronize()
    8. times = []
    9. for _ in range(20):
    10. s = torch.cuda.Event(enable_timing=True)
    11. e = torch.cuda.Event(enable_timing=True)
    12. s.record()
    13. dev.copy_(host, non_blocking=True)
    14. e.record()
    15. torch.cuda.synchronize()
    16. times.append(s.elapsed_time(e) / 1000)
    17. times.sort()
    18. print(f"H2D median: {size / times[len(times) // 2] / 1e9:.2f} GB/s")

    Also check the GPU’s PCIe link status to confirm that the rate and link width meet expectations:

    1. nvidia-smi -q | grep -i -A 3 "link"

    If measured bandwidth is far below expectations, common causes include a degraded link, shared lanes with other devices, or data not using pinned memory.

    Second, do capacity planning. Host memory must hold all offloaded weights with headroom. It is recommended to reserve at least 20% free memory for the operating system, other data in the inference process, and burst requests. NVMe capacity must cover the weight files and leave space for writing temporary files.

    Third, check NVMe read performance. If weights are stored on NVMe, measure random-read latency and bandwidth.