Large Language ModelsInference & Performance Optimization

How do you use a workload-specific roofline model to identify whether LLM inference is compute-, memory-, or communication-bound before choosing optimizations?

Question 294 of 309 · Updated

On this page

The short answer#

Use a roofline model to compare the work a workload performs with the hardware resources it must consume. For each important operator or execution phase, estimate arithmetic intensity (operations per byte transferred), compare it with the accelerator's compute-to-bandwidth ratio, and then validate the estimate with profiling. Extend the analysis to communication when tensor or pipeline parallelism introduces collectives and transfers.

Do not label an entire LLM serving system “memory-bound” simply because attention reads a large KV cache. Prefill, decode, batched dense layers, attention, KV movement, and tensor-parallel collectives can have different bottlenecks. Even the same model can move between regimes as batch size, prompt length, output length, concurrency, context length, precision, and parallelism change.

The practical rule is: measure the bottleneck at the level where the optimization acts, then optimize the resource that actually limits the target SLO or throughput.

1. What the roofline model tells you#

A GPU has finite compute throughput and finite memory bandwidth. A kernel cannot run faster than the tighter of those two ceilings.

Let:

  • = floating-point operations performed (FLOPs)
  • = bytes transferred from the relevant memory level
  • = peak compute throughput, in FLOP/s
  • = peak memory bandwidth, in byte/s
  • = arithmetic intensity, in FLOP/byte

The idealized roofline is:

LaTeX

The ridge point is:

LaTeX

If , the memory-bandwidth ceiling is lower: the operation is potentially memory-bound. If , the compute ceiling is lower: it is potentially compute-bound.

This is a ceiling model, not a promise of achieved performance. Real kernels can fall below both ceilings because of launch overhead, synchronization, poor occupancy, uncoalesced access, cache misses, register pressure, inefficient layouts, dependency chains, or insufficient parallelism.

A simple numerical example#

Assume a hypothetical accelerator sustains at most 1,000 TFLOP/s of the chosen arithmetic and 4 TB/s of HBM bandwidth.

LaTeX

A kernel with intensity 20 FLOP/byte has a bandwidth roof of:

LaTeX

It cannot reach 1,000 TFLOP/s because data movement is the tighter idealized limit. A kernel at 500 FLOP/byte has a bandwidth roof of 2,000 TFLOP/s, so the compute roof of 1,000 TFLOP/s becomes the tighter limit.

The hardware numbers above are illustrative. Use the exact accelerator, precision mode, and sustained—not merely advertised—bandwidth and compute rates for a real deployment.

2. Why LLM inference needs more than one roofline point#

An LLM request passes through multiple operations with different data reuse patterns.

Prefill#

Prefill processes the prompt tokens together. Large matrix multiplications can reuse model weights across many token rows, increasing arithmetic intensity. For sufficiently large prompt batches, dense layers often become compute-heavy.

But “prefill is compute-bound” is not universally true. Long-context attention can become a major part of prefill latency; a short prompt with a large cached prefix can have a very different profile from a fresh long prompt. Kernel choice and batch shape matter.

Decode#

Decode generates tokens autoregressively. At low concurrency, each step has relatively little matrix work per weight read, and attention reads the accumulated KV cache. This often makes decode sensitive to memory bandwidth and context length.

However, batched decode reuses model weights across requests. As active batch size grows, dense-layer arithmetic intensity rises. The overall serving workload can therefore become compute-bound even when an individual attention component remains memory-bound.

Communication#

Tensor parallelism splits work across devices and requires collectives such as all-reduce or all-gather. These operations consume interconnect bandwidth and incur latency and synchronization. A workload can be limited by NVLink, PCIe, InfiniBand, or cross-node communication even when neither GPU compute nor local HBM is saturated.

Other costs#

CPU scheduling, tokenization, sampling, queueing, kernel launch overhead, data transfers, and synchronization can dominate small batches or short requests. These are not captured by a simple compute-versus-HBM roofline. Measure them separately rather than forcing every delay into a GPU-bound category.

3. Build a workload description before calculating anything#

A roofline analysis without a workload definition can produce misleading conclusions. Record at least:

  1. Model architecture and parameter count, including attention type (MHA, GQA, or MQA), expert structure, and layer dimensions.
  2. Weight and activation precision, KV-cache precision, and any quantization or dequantization path.
  3. Prompt-length distribution, including cached-prefix length and cache-hit rate.
  4. Output-length distribution and whether generation is speculative.
  5. Concurrent active sequences and scheduler batch-size distribution—not just incoming request rate.
  6. Arrival pattern, queue depth, and whether traffic is interactive, offline, or mixed.
  7. Parallelism topology: tensor, pipeline, expert, and data parallel degrees; devices per node; interconnect type.
  8. Target metric: TTFT, time-between-tokens (TBT/ITL), end-to-end latency, tokens/s, goodput, or cost per successful request.
  9. SLO percentile and workload mix. An average can conceal a long-context or low-batch tail.

Use representative production traces or a carefully designed workload matrix. A single synthetic batch size is not a sufficient description of a multi-tenant service.

4. Estimate arithmetic intensity for the operations that matter#

For each significant operator, estimate FLOPs and bytes moved. Be explicit about what the byte count includes: HBM traffic, cache traffic, or network transfer. Do not mix these levels in one denominator.

A first-order estimate for a dense matrix multiplication is:

LaTeX

Ignoring lower-order operations:

LaTeX

For element size bytes, a simple lower-bound data estimate is:

LaTeX

Then:

LaTeX

This estimate assumes each input is read once and the output written once. Real HBM traffic depends on tiling, cache reuse, spills, fusion, and whether weights or activations are reloaded.

The key insight is that , the number of token rows processed together, changes the reuse of the weight matrix. Prefill may have a large ; decode at batch one has near one. Increasing active decode batch can amortize weight reads and move dense projections toward compute saturation—but may increase queueing and per-token latency.

Worked dense-layer example#

Take a simplified square projection with , BF16 values (2 bytes), and .

LaTeX
LaTeX

So intensity is approximately 1 FLOP/byte. If , the same weight matrix is reused across 256 token rows; the FLOP count grows approximately 256 times while the weight bytes do not. The resulting intensity rises substantially, although activation and output traffic also grow.

This is why a kernel's bottleneck cannot be inferred from the model name alone. The actual matrix shape matters.

5. Account for KV-cache traffic separately#

During decode, attention reads keys and values accumulated for each active sequence. A rough lower-bound estimate for reading a full KV cache for one decode step is:

LaTeX

where:

  • = number of transformer layers
  • = cached context length in tokens
  • = number of key/value heads
  • = head dimension
  • = bytes per element
  • the leading 2 accounts for keys and values

For a batch of independent sequences, multiply by as a first approximation. Actual traffic depends on attention kernel tiling, cache residency, GQA/MQA sharing, block layout, and reuse.

Numerical KV example#

Assume 32 layers, 8 KV heads, head dimension 128, BF16 (2 bytes), and a 16,384-token context.

LaTeX

That is approximately 2.0 GiB of KV data read for one decode step for one sequence under this simplified full-read assumption. It is not a universal measured traffic value: kernel implementation, caching, and head sharing can change actual HBM traffic.

If context length doubles, the raw KV state and the corresponding full-read estimate approximately double. This helps explain why long-context decode can become bandwidth-sensitive even when short-context decode does not show the same behavior.

6. Model communication instead of mistaking it for memory traffic#

For tensor-parallel execution, estimate the bytes exchanged by collectives and the number of synchronization rounds. A simplified communication time model is:

LaTeX

where is per-round latency and is effective interconnect bandwidth. This is a simplification: real collectives depend on topology, message size, algorithm, contention, and overlap with compute.

A small collective repeated many times can be latency-bound; a large collective can be bandwidth-bound. Cross-node tensor parallelism may behave very differently from intra-node NVLink communication.

Do not add HBM bytes and network bytes and call the sum “memory traffic.” They are distinct resource ceilings. Track them separately and consider whether transfer overlaps useful computation.

7. Use measured ceilings, not marketing peaks#

Peak FLOPs and theoretical HBM bandwidth are useful upper bounds, but real systems rarely sustain both simultaneously for a particular kernel.

Build empirical ceilings for the exact hardware and software stack:

  • Measure sustained matrix-multiplication throughput for relevant shapes and precision.
  • Measure memory bandwidth with access patterns similar to the kernel.
  • Benchmark collectives at the actual message sizes and topology.
  • Measure kernel launch and synchronization costs for small operations.
  • Profile representative model kernels under realistic concurrency.
  • Record clocks, power limits, thermal state, GPU partitioning, and competing workloads.

Use roofline analysis to identify a plausible bottleneck, then confirm it using counters and traces. High HBM utilization with low achieved FLOPs supports a bandwidth-limited hypothesis; high compute utilization with headroom in bandwidth supports a compute-limited hypothesis. High interconnect activity and collective stalls point toward communication. Low utilization across all three may indicate launch, scheduling, occupancy, synchronization, or dependency limits.

8. Translate the diagnosis into the right optimization#

If compute-bound#

Potential levers:

  • Improve matrix-multiplication shapes and batch formation.
  • Use efficient fused kernels and supported low-precision arithmetic.
  • Reduce unnecessary FLOPs or model width where quality permits.
  • Improve Tensor Core utilization and kernel occupancy.
  • Increase useful batching when the latency budget allows it.

Do not blindly increase batch size: it can raise queueing delay, TTFT, and memory pressure.

If HBM-bandwidth-bound#

Potential levers:

  • Reduce bytes moved through quantization or more compact KV representations, after quality validation.
  • Use GQA/MQA where the model architecture supports it.
  • Improve memory coalescing, tiling, and data reuse.
  • Avoid redundant KV reads and unnecessary materialization.
  • Keep frequently reused data in faster memory where practical.
  • Use speculative decoding only when its additional work improves accepted tokens per unit of memory traffic and latency.

Quantization can reduce memory traffic but may add dequantization work or change numerical quality. Benchmark the full path, not just the compressed tensor size.

If communication-bound#

Potential levers:

  • Keep frequent collectives within high-bandwidth nodes when possible.
  • Revisit tensor-parallel degree and partitioning.
  • Reduce collective frequency or message volume when algorithmically safe.
  • Overlap communication with independent compute.
  • Improve topology-aware placement and collective implementation.
  • Consider pipeline parallelism or a different model partition if it reduces synchronization.

More GPUs do not automatically mean faster inference. Communication overhead can erase the benefit of extra compute.

If launch-, scheduling-, or synchronization-bound#

Potential levers:

  • Fuse small operations where fusion reduces launch and intermediate-memory overhead.
  • Reduce host-device synchronization.
  • Batch small work without violating latency SLOs.
  • Improve asynchronous dispatch and queue management.
  • Investigate CPU bottlenecks, Python overhead, and allocator behavior.

A roofline point alone will not diagnose these cases; use timeline profiling.

9. Avoid the common inference-analysis traps#

Trap 1: “Decode is always memory-bound.” Low-batch decode often is, especially for attention and weight reads. Batched dense operations can become compute-heavy; end-to-end serving can have a different bottleneck from one attention kernel.

Trap 2: “Prefill is always compute-bound.” Long-context attention, small batches, cached-prefix patterns, and implementation details can shift the dominant cost.

Trap 3: “The GPU is only 30% utilized, so it needs more GPUs.” Low utilization may mean the workload is waiting on memory, communication, CPU dispatch, synchronization, or dependencies. Adding devices can worsen communication.

Trap 4: “Peak FLOPs divided by peak bandwidth is the answer.” The ridge point is only as useful as the measured ceilings, precision mode, and memory level used in the calculation.

Trap 5: “A single average hides no important detail.” Short and long contexts, low and high concurrency, and different model shapes can occupy different regions of the roofline.

Trap 6: “The slowest component must be the optimization target.” Optimize the component that limits the user-facing objective. Reducing prefill time may not improve TBT if decode is the bottleneck; increasing throughput may be irrelevant if TTFT p99 is already failing.

Trap 7: “The roofline proves causality.” It gives a performance bound and a hypothesis. Profiling, controlled experiments, and production measurements establish whether the proposed optimization actually helps.

10. A practical diagnostic workflow#

  1. Freeze the workload definition. Capture model, precision, prompt/output distributions, concurrency, cache behavior, parallelism, and target SLO.
  2. Separate phases and operators. At minimum distinguish queueing, prefill dense layers, prefill attention, decode dense layers, decode attention/KV, collectives, and CPU/runtime work.
  3. Estimate FLOPs and bytes. Calculate arithmetic intensity for dominant kernels; separately estimate KV reads and network transfers.
  4. Calculate hardware ridge points. Use measured sustained compute and bandwidth for the deployed device and precision.
  5. Profile a representative run. Capture kernel time, achieved FLOPs, HBM throughput, interconnect traffic, occupancy, stalls, and synchronization.
  6. Compare estimate with evidence. Investigate mismatches; the simple model may omit cache reuse, repeated loads, or a hidden bottleneck.
  7. Choose one intervention. State the predicted resource change and expected SLO effect before tuning.
  8. Run paired experiments. Compare identical traffic and hardware conditions; report confidence intervals and tail percentiles.
  9. Validate the whole service. Check TTFT, TBT/ITL, end-to-end latency, goodput, throughput, GPU-hours, and cost per successful request.
  10. Re-profile after every major change. Removing one bottleneck often exposes another.

Example: why the first optimization can be wrong#

Suppose a service has low batch concurrency and long contexts. Profiling shows decode attention saturates HBM while compute units remain underused. The first hypothesis is KV traffic. The team reduces KV precision and validates quality, then measures lower HBM bytes and improved TBT.

Later, traffic increases and continuous batching raises active sequences. Dense projections now dominate and compute utilization approaches its ceiling. Further KV compression yields little additional throughput. The next useful lever is improving matrix throughput or batching efficiency—not repeating the previous memory optimization.

The bottleneck changed because the workload changed. The correct roofline analysis must be repeated.

11. Production metrics to keep#

Track these by model, hardware class, phase, context-length bucket, batch-size bucket, and parallelism configuration:

  • Achieved FLOP/s and percentage of a measured compute ceiling.
  • HBM read/write bandwidth and percentage of a measured bandwidth ceiling.
  • KV bytes read per generated token, where measurable.
  • Interconnect bytes, collective time, and communication overlap.
  • Kernel time distribution and launch/synchronization overhead.
  • SM occupancy and relevant stall reasons.
  • TTFT, TBT/ITL, end-to-end p50/p95/p99.
  • Input/output tokens per second and SLO-compliant goodput.
  • GPU utilization, memory headroom, and cost per successful request.

Avoid relying on a single “GPU utilization” percentage. It is not a direct measure of useful work or a diagnosis of the limiting resource.

12. Rollout checklist#

  • [ ] Workload mix and SLOs are documented and reproducible.
  • [ ] Prefill and decode are analyzed separately.
  • [ ] Dense, attention/KV, communication, and runtime overheads are distinguished.
  • [ ] FLOPs, bytes, arithmetic intensity, and ridge points use consistent units.
  • [ ] Sustained hardware ceilings are measured for the target precision and topology.
  • [ ] Roofline predictions are checked against profiler evidence.
  • [ ] The optimization targets the measured bottleneck.
  • [ ] Quality, TTFT, TBT, goodput, and cost are evaluated together.
  • [ ] Tests include low/high concurrency and short/long context.
  • [ ] The system is re-profiled after the change and during rollout.

13. Interview-ready answer#

“I would not call an entire LLM serving system compute-bound or memory-bound from the model architecture alone. I would define the workload—prompt and output lengths, active batch, precision, cache reuse, parallelism, and SLO—then split execution into prefill, decode, attention/KV, dense projections, collectives, and runtime overhead. For each dominant operator I estimate FLOPs and bytes, calculate arithmetic intensity, and compare it with the measured compute-to-bandwidth ridge point of the actual GPU. I separately model network collectives and validate everything with profiler counters and traces. Then I optimize the constrained resource and rerun the same workload, measuring TTFT, inter-token latency, goodput, quality, and cost. The key is that a memory-bound attention kernel does not imply end-to-end serving is memory-bound; batching and overlap can change the system-level bottleneck.”

Related questions

Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents