DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • RAG Architecture Patterns: Proxy, Caching, and Routing
  • How Cache Invalidation Caused Memory Pressure and API Failures at Scale
  • How I Built a Storage System for My Agent’s Memory
  • Prompt Caching: Overriding Tokenization for Faster and More Cost-Effective AI

Trending

  • Function Calling: Responses API vs Chat Completions
  • Treat AI Agents Like Long-Running Background Jobs: A Production Reference Architecture
  • Google Cloud Pub/Sub vs. AWS SNS and SQS: One Java API for Both With MultiCloudJ
  • Bolting an LLM Onto a System That Can't Afford to Be Wrong

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Why GPUs Run at 40% in LLM Inference and How To Fix It

Why GPUs Run at 40% in LLM Inference and How To Fix It

Low GPU utilization in LLM serving is a memory problem, not a compute one, and paged KV cache memory plus continuous batching is the fix.

By 
Susmita Singh
·
Dec. 01, 26 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
16 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

If you deploy an open-weights model like Llama 3 on your own infrastructure, one of your first surprises will likely be the output of nvidia-smi:

GPU Name Memory-Usage GPU-Util Operational State
0 NVIDIA H100 80GB 76,420 MiB / 81,559 MiB (93.7%) 38% Memory-Bound

Table 1: Initial GPU telemetry during generative inference (Llama 3 70B). Memory-Usage and GPU-Util are as reported by nvidia-smi; the operational state is inferred. Memory is nearly fully committed while compute cores remain largely underutilized.


What you may find is that VRAM is almost full, but GPU utilization hovers between 35% and 45%.

Even that 40% figure is deceptive. That column only reports the fraction of time that any GPU kernel was active, not whether compute cores were saturated — a memory-bound loop copying bytes back and forth can register high utilization while doing negligible mathematical work. The hardware isn't waiting on math; it's waiting on memory, spending most of its clock cycles moving weights and cached tokens across the bus while compute cores sit idle.

To see why this happens, and how engines like vLLM, SGLang, and TensorRT-LLM fix it, we have to look at what is actually happening during generation.

1. Prefill, Decode, and the Batching Economy

Every generative LLM request runs in two distinct phases:

  1. Prefill (Prompt Processing): The model ingests the entire prompt in a single forward pass. Because all input tokens are known upfront, this phase executes as large matrix multiplications. The GPU's Tensor Cores are fully saturated, arithmetic intensity is high, and processing is compute-bound.
  2. Decode (Token Generation): The model generates one token at a time. For each new token, the GPU must read every parameter in the model and all historical context from VRAM into its local on-chip SRAM cache. Because this step produces only a single token per stream, arithmetic intensity is low. The hardware is bottlenecked entirely by memory bandwidth.

Because output generation requires hundreds of sequential steps while prompt ingestion takes only one, the vast majority of execution time is spent in the memory-bound decode phase.

This brings us to the core reason batching matters: amortizing weight transfers.

When serving a single request, the GPU must transfer roughly 140 GB of weights (for a 70-billion-parameter model in 16-bit precision, distributed across multiple GPUs) across its memory bus, just to generate one token.

If you batch 32 concurrent requests together, the GPU reads the 140 GB of weights across the bus once, and reuses them to calculate output tokens for all 32 users in the same forward pass. Scaling from a batch size of 1 to 32 is sub-linear, because attention operations and KV cache access scale with batch size. But amortizing the static weight read typically yields roughly an order of magnitude increase in aggregate throughput over single-stream generation on modern hardware (which follows from the roofline scaling analysis in Pope et al., 2023).

The bottleneck to higher throughput is keeping that batch size as large as possible. Traditional serving architectures, however, make this almost impossible.

2. The Limits of Static Batching and Contiguous Memory

In computer vision or embedding models, static batching works reliably. You collect N inputs, group them into a single tensor, run the forward pass, and every sample finishes simultaneously.

Generative text does not behave this way. Request lengths are fundamentally unpredictable.

Consider four requests submitted in the same batch:

  • Request 1 (classification): generates 2 tokens
  • Request 2 (short summary): generates 45 tokens
  • Request 3 (code explanation): generates 210 tokens
  • Request 4 (essay): generates 850 tokens

Under static batching, Request 1 finishes after step 2. But because the batch tensor has fixed dimensions, Request 1 cannot leave GPU memory. Its slot remains locked. For the remaining 848 iterations, the GPU performs matrix operations on padded zeros for Request 1, 2, and 3 while waiting for Request 4 to conclude.

Timeline for four requests in a static batch.

Figure 1: The straggler problem in static batching. When requests vary in completion length, early-terminating requests lock GPU memory and waste compute on padding tokens until the slowest sequence completes.


Why couldn't traditional systems release finished sequences and admit new ones? Because of how they allocated the Key-Value (KV) cache.

The KV Cache Footprint

To avoid recalculating attention for previous tokens at every step, transformers store intermediate Key and Value tensors in GPU memory. The formula for the KV cache size per token is:

Plain Text
 
bytes_per_token = 2 (K and V) × layers × kv_heads × head_dim × bytes_per_value


For a model like Llama 3 70B running in 16-bit precision (80 layers, 8 Key-Value heads using Grouped-Query Attention, head dimension 128, 2 bytes per float):

Plain Text
 
2 × 80 × 8 × 128 × 2 = 327,680 bytes ≈ 320 KB per token


A single conversation reaching an 8,192-token context consumes 2.56 GB of VRAM for its KV cache alone. Serving 40 concurrent requests at that length demands over 100 GB of memory just for context, on top of the model weights.

The Contiguous Allocation Problem

Standard CUDA memory allocators require a tensor's underlying storage buffer to be contiguous in physical memory. Because an engine cannot predict whether an incoming request will generate 10 tokens or 4,000 tokens, naive frameworks allocated space for the sequence's maximum possible length upfront.

Diagram of a 4,096-token contiguous KV cache reservation.

Figure 2: Traditional contiguous pre-allocation waste. Because the runtime cannot predict completion length, it allocates contiguous VRAM for the maximum possible context, stranding the majority of memory in unused reservations.


A 2023 paper (Efficient Memory Management for Large Language Model Serving with PagedAttention, SOSP 2023) by Kwon et al. showed that in production systems, 60% to 80% of the memory set aside for the KV cache was wasted. This waste resulted from three sources:

  • Over-reservation: Space held for future tokens that the user never generated.
  • Internal fragmentation: Fixed-size pre-allocated slots exceeding actual sequence lengths.
  • External fragmentation: Free memory scattered in disjointed blocks too small to fit a new maximum-length request.

Because memory was exhausted by empty reservations, engines were forced to severely restrict concurrent batch sizes. The GPU cores sat starved for work.

3. PagedAttention and Continuous Batching

Modern serving systems solve these constraints by borrowing virtual memory concepts that operating systems developed decades ago.

Diagram mapping three logical KV cache blocks.

Figure 3: PagedAttention memory architecture. The logical KV cache is partitioned into fixed 16-token pages. A centralized block table maps logical indices to non-contiguous physical memory in VRAM, eliminating internal fragmentation and memory reservations.


PagedAttention

Instead of forcing a sequence's KV cache into a single continuous buffer, PagedAttention breaks it into fixed-size physical blocks (pages), typically sized to hold 16 or 32 tokens.

A central Block Table tracks which physical blocks belong to which sequence. Physical blocks do not need to be adjacent in VRAM. When a request begins, the engine allocates only the blocks needed for the prompt. As the model generates new tokens, it assigns an additional block only when the active one fills up.

This achieves what Kwon et al. describe as "near-zero waste in KV cache memory." With a 16-token block size, the only memory a sequence can waste is the unfilled slots in its final block — at most 15 tokens. Whether a generation finishes after 50 tokens or 5,000 tokens, the maximum possible waste per sequence is bounded by those few unused slots, driving memory waste toward zero as context grows.

By eliminating fragmentation, the available VRAM can suddenly accommodate significantly more concurrent sequences.

Prefix Sharing and Copy-on-Write

Paged memory management unlocks a second major advantage: zero-overhead prompt sharing.

In applications like multi-turn chatbots, few-shot evaluations, or multi-agent frameworks, dozens of requests often share an identical system prompt. In older systems, that shared prompt had to be evaluated and stored in memory for every single user.

Under PagedAttention, multiple logical block tables can point to the same physical memory blocks. The engine evaluates the system prompt once. All subsequent requests reference those read-only physical blocks. If a request branches or appends unique tokens, the engine allocates a new private block on write (Copy-on-Write). In production setups with heavy system prompts, this substantially reduces memory usage across concurrent sessions.

Continuous Batching

With dynamic block allocation in place, the need for static batching disappears. Modern engines implement Continuous Batching (iteration-level scheduling, originally proposed in the Orca paper by Yu et al., OSDI 2022). In their original evaluation, the Orca authors demonstrated up to a 36.9x throughput improvement over FasterTransformer on a 175-billion-parameter model at matched latency by replacing request-level batching with iteration-level scheduling.

Instead of scheduling at the request level, the engine makes scheduling decisions after every single token iteration:

  1. At each step, all active sequences execute one forward pass.
  2. If Request 1 emits an end-of-sequence token, it is evicted immediately.
  3. Its physical blocks are freed back to the memory pool.
  4. An incoming request waiting in the queue is pulled into the batch for the next step.

Timeline of four batch slots.

Figure 4: Continuous batching (iteration-level scheduling). Sequences are evaluated and scheduled at every token step. As soon as a request emits an end-of-sequence token, its VRAM blocks are reclaimed, and a waiting query is immediately admitted into the forward pass.


The batch stays saturated. Fast requests exit without delay; long requests continue without holding other users hostage.

4. What the Empirical Data Shows: The SOSP Evaluation

To see how these architectural changes translate into real-world performance, we can look at the empirical evaluation published by Kwon et al. in the original vLLM paper (SOSP '23).

The researchers evaluated inference performance on NVIDIA A100-80GB GPUs across 1, 4, and 8 GPU configurations using OPT (13B, 66B, and 175B) and LLaMA-13B. They tested against two real-world trace datasets: ShareGPT (transcripts of actual ChatGPT interactions with wide variations in prompt and completion lengths) and Alpaca.

Their evaluation compared vLLM against NVIDIA's FasterTransformer and three reimplemented variants of Orca (Yu et al., 2022).

The Memory Findings

The paper's central discovery was the scale of KV cache memory waste in existing systems. As the authors noted:

"only 20.4% – 38.2% of the KV cache memory is used to store the actual token states in the existing systems."


The remaining 61.8% to 79.6% was lost to internal fragmentation, over-reservation, and external memory gaps between sequences. By contrast, PagedAttention eliminates internal and external fragmentation by allocating blocks dynamically, bringing KV cache waste down to near-zero.

Throughput and Request Rates

By eliminating memory waste and packing significantly more sequences into available VRAM, vLLM achieved substantial throughput gains:

  • 2–4× higher throughput: The paper's headline finding shows vLLM improves throughput across popular models by 2–4× at the same level of latency compared to state-of-the-art baselines like FasterTransformer and Orca.
  • Up to 22× higher request capacity: In heavy-load scenarios (§6.2), vLLM sustained up to 22× higher request arrival rates than FasterTransformer before violating target latency thresholds.

Note on project launch claims: The often-cited "up to 24x" throughput number originates from the vLLM project's initial release blog, which benchmarked against unoptimized Hugging Face Transformers pipelines on A10G and 40GB A100 GPUs, rather than the peer-reviewed FasterTransformer and Orca baselines evaluated at SOSP.

Why Orca Wasn't Enough: The "Oracle" Comparison

The most revealing comparison in the paper is not against FasterTransformer, but against Orca.

Orca was never open-sourced. To establish a rigorous comparison, the vLLM authors reimplemented Orca in three variants, differing strictly in how memory was allocated:

  1. Orca-Max: Pre-allocates memory for the model's maximum sequence length upfront (2,048 tokens in the evaluation)
  2. Orca-Pow2: A bounded reservation policy that over-reserves space for outputs by up to 2×, rounding the required reservation up to the nearest power of two (for example, reserving 32 positions for a 25-token response).
  3. Orca-Oracle: An idealized, theoretical upper bound that magically knows the exact output length of every request in advance and reserves only that amount.

The critical takeaway: vLLM sustained 1.7× – 2.7× higher request rates compared to Orca (Oracle).

Even when Orca was given an impossible advantage — a magic crystal ball that predicted the exact output length of every request — vLLM still outperformed it by roughly 2x. Because Orca still required each sequence's KV cache to reside in contiguous physical memory. Contiguous allocation inevitably leaves small, unusable gaps between sequences as requests start and finish.

Orca proved that iteration-level scheduling fixes the compute scheduling bottleneck. But PagedAttention proved that non-contiguous paging is necessary to fix the physical memory bottleneck. Without both, an engine runs out of physical memory long before it can saturate the GPU cores.

Testing on Your Own Hardware

If you have access to an NVIDIA GPU and want to evaluate these dynamics on your own traffic distribution, vLLM includes built-in benchmarking utilities:

Shell
 
# 1. Start the vLLM server
vllm serve meta-llama/Meta-Llama-3-8B-Instruct \
    --gpu-memory-utilization 0.90 \
    --port 8000 &

# 2. Wait until the server is live
until curl -s http://localhost:8000/health > /dev/null; do
    sleep 2
done

# 3. Run a saturating benchmark using the ShareGPT dataset
python3 benchmarks/benchmark_serving.py \
    --backend vllm \
    --model meta-llama/Meta-Llama-3-8B-Instruct \
    --dataset-name sharegpt \
    --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json \
    --num-prompts 200 \
    --request-rate inf


5. Sizing the KV Cache: How Production Memory Actually Works

A common source of confusion when configuring engines like vLLM is the relationship between max context length, concurrency ceilings, and physical memory.

Consider this production command:

Shell
 
vllm serve meta-llama/Meta-Llama-3-70B-Instruct \
    --tensor-parallel-size 4 \
    --gpu-memory-utilization 0.90 \
    --max-model-len 8192 \
    --max-num-seqs 128


At first glance, the numbers might appear contradictory. Earlier calculations showed that for Llama 3 70B, an 8,192-token sequence requires roughly 2.56 GB of KV cache. If --max-num-seqs is set to 128, wouldn't that require 128 × 2.56 GB = 327.68 GB of KV cache?

Across 4x H100 GPUs (320 GB total), after loading ~140 GB of model weights, there would not be enough memory left.

The explanation is that in modern engines, --max-num-seqs is an admission ceiling, not a memory reservation.

Here is how the memory is actually budgeted:

  1. Total Hardware Memory: 4 × 80 GB = 320 GB.
  2. Allocation Cap: With --gpu-memory-utilization 0.90, vLLM reserves 320 × 0.90 = 288 GB. (The remaining 32 GB is left for transient CUDA activation memory and PyTorch runtime overhead).
  3. Weight Footprint: A 70B model in 16-bit precision occupies approximately 140 GB.
  4. Usable KV Cache Pool: 288 GB minus 140 GB leaves 148 GB for the KV cache pool.

At 320 KB per token, 148 GB (roughly 148 billion bytes divided by 327,680 bytes per token) accommodates approximately 452,000 active tokens.

If every single user generated text out to the absolute limit of 8,192 tokens simultaneously, the pool would saturate at:

Plain Text
 
452,000 tokens ÷ 8,192 tokens/request ≈ 55 concurrent requests


In reality, most production traffic skews short. Most queries generate between 150 and 600 tokens. If the average active sequence length is 600 tokens, that same 148 GB pool can comfortably sustain over 700 concurrent requests before running out of blocks.

The --max-num-seqs 128 parameter merely tells the scheduler: "Never pack more than 128 active requests into a single forward pass, even if there is free memory available." This prevents individual iteration passes from becoming excessively compute-heavy.

6. The Trade-offs and the Operational Reality

Continuous batching optimizes aggregate system throughput (tokens/sec across all users). It does not improve single-request latency. If your system receives exactly one request at 2:00 AM, continuous batching provides zero speedup compared to standard Hugging Face code. Under heavy concurrent load, Inter-Token Latency will even degrade slightly because the GPU's memory bus is saturated across dozens of requests.

The Prefill Bubble and Chunked Prefill

When a user submits a large prompt (e.g., a 6,000-token PDF in a RAG pipeline), processing that prompt requires a compute-heavy prefill.

In early continuous batching setups, a massive incoming prefill would monopolize the GPU for 200MS or more. Every active decode stream paused while the prefill finished, causing visible stutter in users' streaming text.

Modern engines resolve this using Chunked Prefill (introduced by Agrawal et al. in Sarathi-Serve, 2024). The engine divides large prompts into smaller chunks (typically 512 tokens) and co-schedules them alongside active decode iterations. Chunked prefill is enabled by default in recent versions of vLLM (v0.6+). You can verify this in your server startup logs (look for the engine initialization line confirming chunked prefill is enabled).

Memory Exhaustion and Preemption

When traffic spikes and the KV block pool runs out of memory, the engine must resolve the shortage.

Because vLLM does not pre-allocate per-request memory, it can overcommit. If the block pool is 100% full and an active request demands another block to generate its next token, the engine triggers preemption:

  • The engine pauses an active sequence.
  • It either swaps the sequence's KV blocks to host CPU memory, or frees them entirely.
  • When GPU memory clears, the preempted sequence is recomputed from its prompt.

Preemptions show up in monitoring as sudden, severe tail-latency spikes.

7. A Production Diagnostic Checklist

When debugging inference performance on your own clusters, avoid relying on surface-level GPU utilization metrics. Instead, monitor vLLM's exposed Prometheus metrics (/metrics).

Metric Observation Root Cause Actionable Remedy
vllm:num_requests_waiting > 0 and vllm:gpu_cache_usage_perc < 0.60 Requests are queueing even though memory is free. Your --max-num-seqs ceiling is set too low. Increase it to allow higher batch concurrency.
vllm:gpu_cache_usage_perc ≈ 1.0 and vllm:num_preemptions_total > 0 The KV pool is completely exhausted. Incoming requests cause active queries to abort and recompute. Lower your concurrency ceiling, reduce --max-model-len, or add tensor-parallel GPU capacity.
Mean ITL is steady, but p99 ITL shows periodic spikes Long incoming prompts are stalling active decodes. Confirm that chunked prefill is active in your startup logs.


The Broader Ecosystem

While vLLM popularized PagedAttention, these techniques are standard across modern inference systems:

  • SGLang: Integrates RadixAttention, which maintains an explicit radix tree for automatic KV cache reuse across complex multi-turn and structured decoding workflows.
  • TensorRT-LLM: NVIDIA's optimized serving framework, offering native in-flight batching and paged memory integrated directly with custom Tensor Core kernels.
  • Hugging Face TGI: Uses continuous batching (via FlashAttention and Paged Attention kernels) tailored for Kubernetes deployments.

If your generative AI workloads run on unbatched pipelines or static batching servers, moving to an engine with paged memory and iteration-level scheduling is the most reliable way to lower your cost per token and get your GPUs doing useful work.

References

  • Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu, C. H., ... & Stoica, I. (2023). Efficient memory management for large language model serving with PagedAttention. Proceedings of the 29th ACM Symposium on Operating Systems Principles (SOSP '23), 611-626.
  • Yu, G. I., Jeong, J. S., Kim, G. W., Kim, S., & Chun, B. G. (2022). Orca: A distributed serving system for Transformer-Based generative models. 16th USENIX Symposium on Operating Systems Design and Implementation (OSDI '22), 521-538.
  • Agrawal, A., Kedia, N., Panwar, A., Mohan, J., Kwatra, N., Gulavani, B. S., ... & Ramjee, R. (2024). Taming throughput-latency tradeoff in LLM inference with Sarathi-Serve. arXiv preprint arXiv:2403.02310.
  • Pope, R., Douglas, S., Chowdhery, A., Devlin, J., Bradbury, J., Heek, J., ... & Dean, J. (2023). Efficiently scaling transformer inference. Proceedings of Machine Learning and Systems (MLSys '23), 5.
Cache (computing) Memory (storage engine) large language model

Opinions expressed by DZone contributors are their own.

Related

  • RAG Architecture Patterns: Proxy, Caching, and Routing
  • How Cache Invalidation Caused Memory Pressure and API Failures at Scale
  • How I Built a Storage System for My Agent’s Memory
  • Prompt Caching: Overriding Tokenization for Faster and More Cost-Effective AI

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook