Forward Deployed EngineeringAI InfrastructureGPU Performance
How do you determine whether a kernel is memory-bound or compute-bound?
Question 39 of 73 · Updated
On this page
- Interview-ready answer
- 1. Establish the Roofline model
- 2. Count the correct operations and bytes
- 3. Example A: vector addition
- 4. Example B: matrix multiplication
- 5. Tested Python Roofline calculator
- 6. Profile the real workload with Nsight
- Establish the measurement boundary
- Collect targeted kernel evidence
- 7. Distinguish actual bottlenecks
- 8. Optimize the bottleneck and validate the change
- 9. FDE production example: LLM inference
- Likely interviewer follow-ups
- Interview takeaway
Interview-ready answer#
I would use the Roofline model to form an initial hypothesis and a GPU profiler to test it. A memory-bandwidth-bound kernel spends most of its limiting execution time moving data through a memory interface; a compute-throughput-bound kernel is limited by the rate at which the relevant execution pipelines can perform its arithmetic.
First, calculate the kernel's arithmetic intensity: floating-point operations divided by bytes transferred at the memory interface being analyzed. Compare that intensity with the GPU's ridge point, which is its applicable peak compute throughput divided by its memory bandwidth. Below the ridge point, the idealized Roofline ceiling is set by bandwidth; above it, the ceiling is set by compute throughput.
Then measure actual execution time, operations, memory traffic and utilization using CUDA profiling tools such as Nsight Compute. If a kernel is near its attainable DRAM bandwidth but far below its applicable compute ceiling, bandwidth is likely the limiting resource. If it approaches the relevant compute ceiling without saturating memory bandwidth, it is likely compute-throughput limited. If it is far below both ceilings, investigate latency, insufficient parallelism, instruction dependencies, synchronization, divergence, launch overhead or another resource bottleneck rather than forcing a binary classification.
I would optimize the identified bottleneck and remeasure both the kernel and the customer-facing workload. A kernel can change from memory-side to compute-side as its shape, precision, caching or batching changes.
1. Establish the Roofline model#
Let:
- F = floating-point operations performed by the kernel (FLOPs).
- D = bytes transferred through the chosen memory interface.
- T = elapsed kernel time in seconds.
- P = applicable peak arithmetic throughput in FLOPs/s.
- B = applicable peak memory bandwidth in bytes/s.
The arithmetic or operational intensity at that interface is I = F / D, in FLOPs/byte. Achieved arithmetic throughput is F / T, and achieved bandwidth is D / T.
The basic Roofline performance ceiling is:
The ridge point is I* = P / B. When I is below I*, the bandwidth roof is lower. When I is above I*, the compute roof is lower. At the ridge, the two idealized ceilings coincide.
The corresponding lower bound on elapsed time is:
T ≥ max(F / P, D / B).
This is a lower bound, not a prediction of actual runtime or a claim of perfect overlap. Dependencies, pipeline scheduling, startup, serialization and contention may increase time. Counting a fused multiply-add as two FLOPs is the usual convention; use the same convention in the operation count and compute ceiling.
On the conventional log-log Roofline chart, bandwidth × intensity is a rising diagonal line with slope one, while the compute ceiling is horizontal. The ridge is their intersection. The measured kernel point is plotted at its intensity and achieved throughput. A point far below the applicable roof needs further investigation.
The numerical examples below use hypothetical decimal hardware rates: 60 TFLOPs/s for the relevant arithmetic pipeline and 2 TB/s of DRAM bandwidth. These are not specifications for a particular GPU. The ridge point is 60 × 10^12 / (2 × 10^12) = 30 FLOPs/byte.
2. Count the correct operations and bytes#
A useful initial estimate can come from the algorithm. A reliable diagnosis needs the actual executed workload and memory level.
| Quantity | What to count or measure |
|---|---|
| FLOPs | Floating-point operations using a documented counting convention, precision and execution path |
| DRAM traffic | Actual bytes read from and written to device memory |
| L2 traffic | Transfers at the L2 interface relevant to the selected hierarchical roof |
| L1/shared-memory traffic | Transfers through the relevant on-chip interface, using a matching ceiling |
| Kernel time | Device execution duration, with consistent warmup and measurement boundaries |
Algorithmic bytes are not always physical traffic. Caching, alignment, memory transactions, write behavior, spills, compression, tiling, repeated loads and communication can make actual traffic different. A DRAM Roofline needs DRAM traffic, not merely the sum of source-code loads. If the working set fits in L2, an L2-bandwidth roof may be more informative.
Do not divide FP32 operation counts by a peak quoted for a different precision or specialized Tensor Core pipeline. Use a ceiling applicable to the instructions, precision, sparsity conditions and device configuration. For integer, transcendental, conversion or mixed-instruction kernels, a single FLOP-based roof may not describe the relevant execution bottleneck.
3. Example A: vector addition#
Consider C[i] = A[i] + B[i] with FP32 arrays. One element requires one floating-point addition, reads two four-byte values and writes one four-byte result.
Idealized streaming traffic per element is 12 bytes; arithmetic intensity is 1/12 ≈ 0.0833 FLOPs/byte. This assumes each input is fetched once and each result is written once at the selected memory interface, with no additional traffic.
For 100 million elements:
| Quantity | Illustrative calculation |
|---|---|
| Floating-point operations | 100 million |
| Minimum modeled bytes | 1.2 billion |
| Intensity | 0.0833 FLOPs/byte |
| Bandwidth-side throughput ceiling | 0.1667 TFLOPs/s |
| Compute-only time lower bound | 1.67 microseconds |
| Memory-transfer time lower bound | 600 microseconds |
The idealized bandwidth ceiling is much lower than the applicable 60 TFLOPs/s compute ceiling. It is therefore a strong candidate for a streaming memory-bandwidth-bound workload when the arrays are large and sufficient warps can sustain traffic. A small array or inefficient launch may instead be overhead- or latency-limited.
CUDA__global__ void add(const float* a, const float* b, float* c, size_t n) { size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; if (i < n) { c[i] = a[i] + b[i]; } }
Use nonoverlapping valid buffers, suitable launch dimensions and a bounds check. Adjacent threads access adjacent FP32 elements, which generally supports coalescing when alignment and layout are appropriate. For this kernel, improving memory efficiency or avoiding unnecessary loads and stores is generally a better first hypothesis than increasing peak floating-point throughput.
A common optimization is to fuse adjacent pointwise operations so an intermediate value remains in registers rather than being materialized and read again. Fusion can reduce DRAM traffic and launch overhead, but may increase register pressure and reduce scheduling flexibility.
4. Example B: matrix multiplication#
For square dense matrices of dimension N, a conventional multiplication C = A × B performs approximately 2N³ FLOPs under the convention that multiply-add contributes two operations. The exact count depends on initialization and implementation.
An optimistic minimum FP32 traffic estimate assumes each input matrix is fetched once and the output is written once:
For N = 1,024:
- FLOPs ≈ 2,147,483,648.
- Modeled bytes = 12,582,912.
- Idealized intensity ≈ 170.67 FLOPs/byte.
- With the hypothetical hardware, compute-side ceiling = 60 TFLOPs/s.
- Compute-only time lower bound ≈ 35.79 microseconds.
- Memory-transfer time lower bound ≈ 6.29 microseconds.
Under the optimistic traffic model, the point lies above the 30 FLOPs/byte ridge. However, a naive implementation can repeatedly load the same elements from global memory. Its measured traffic can be much greater, so the mathematical lower bound on bytes does not prove that an actual GEMM is compute-bound.
CUDA__global__ void matmul_naive(const float* a, const float* b, float* c, int n) { int col = blockIdx.x * blockDim.x + threadIdx.x; int row = blockIdx.y * blockDim.y + threadIdx.y; if (row >= n || col >= n) return; float acc = 0.0f; for (int j = 0; j < n; ++j) { acc += a[size_t(row) * n + j] * b[size_t(j) * n + col]; } c[size_t(row) * n + col] = acc; }
This is a simple square row-major matrix multiplication for valid positive n and grid dimensions that cover the output. It is an educational baseline, not a tuned kernel. The exact executed arithmetic can depend on compiler FMA transformations and optimization options.
Tiling can improve reuse by loading blocks of inputs into shared memory and performing several multiply-accumulate operations before loading the next tile. Register blocking, vectorized memory access, supported Tensor Core operations and optimized library kernels can further improve arithmetic efficiency. These techniques change resource consumption and sometimes numerical behavior; verify correctness and performance under the actual precision and shape.
Both CUDA snippets are illustrative, manually reviewed, and were neither compiled nor executed: nvcc and an exposed NVIDIA GPU were unavailable. No GPU performance result is claimed.
5. Tested Python Roofline calculator#
This small exact-arithmetic implementation calculates the idealized roof and lower time bound. All inputs use integer SI units: operation count, bytes, FLOPs per second and bytes per second. It assumes positive traffic and hardware ceilings and permits zero operations.
PYTHONfrom fractions import Fraction def roofline(flops, bytes_moved, peak_flops, bandwidth): if flops < 0 or bytes_moved <= 0 or peak_flops <= 0 or bandwidth <= 0: raise ValueError('invalid work or hardware limits') intensity = Fraction(flops, bytes_moved) ridge = Fraction(peak_flops, bandwidth) ceiling = min(Fraction(peak_flops), bandwidth * intensity) compute_s = Fraction(flops, peak_flops) memory_s = Fraction(bytes_moved, bandwidth) bound = ('memory-side' if memory_s > compute_s else 'compute-side' if compute_s > memory_s else 'ridge') return intensity, ridge, ceiling, max(compute_s, memory_s), bound
Example:
PYTHONp = 60 * 10**12 b = 2 * 10**12 vector = roofline(10**8, 12 * 10**8, p, b) matrix = roofline(2 * 1024**3, 3 * 1024**2 * 4, p, b) assert vector == ( Fraction(1, 12), Fraction(30), Fraction(500000000000, 3), Fraction(3, 5000), 'memory-side' ) assert matrix[-1] == 'compute-side' assert roofline(30, 1, p, b)[-1] == 'ridge'
The helper describes the side of an idealized roof, not a profiler-based bottleneck diagnosis. For zero FLOPs, the arithmetic throughput ceiling is zero while the memory transfer time lower bound can be positive. Pure integer workloads require a different throughput model.
Local verification: Python 3.13.5 executed the exact helper across 15,840 parameter combinations: operation counts 0–32, positive byte counts 1–16, six compute limits and five bandwidth limits. Independent checks verified both ceiling inequalities, the active constraint, both elapsed-time lower bounds, exact intensity and ridge identities, and classification using integer cross-products. Five invalid-input cases and three worked-example/ridge cases also passed, totaling 15,848 checks. This validates the arithmetic only; it does not validate actual hardware counters, CUDA execution or performance.
6. Profile the real workload with Nsight#
Establish the measurement boundary#
Use a representative device, model precision, input shape, batch size, driver and runtime configuration. Warm up the workload, account for clock variation and thermal/power limits, and repeat measurements. Determine whether buffers are already resident on the GPU. Keep host-to-device transfer time, kernel execution time and end-to-end latency separate unless deliberately measuring the full pipeline.
CUDA events recorded in the appropriate stream can measure device elapsed time after synchronization. A CPU wall-clock measurement of an asynchronous kernel launch may measure only launch submission. Use a system timeline such as Nsight Systems first when the true bottleneck may be host gaps, transfers, synchronization or many tiny launches.
Collect targeted kernel evidence#
An illustrative Nsight Compute invocation on an authorized CUDA development machine is:
BASHncu --section SpeedOfLight --section MemoryWorkloadAnalysis \ --section SchedulerStats --section WarpStateStats ./your_benchmark
The section names, available metrics, permissions and replay behavior depend on the installed tool version and GPU. Inspect ncu --list-sections and ncu --query-metrics and choose the appropriate kernel and metrics. The command has not been run in this environment. Do not collect broad production traces or sensitive data without authorization. Profiling overhead and kernel replay may alter timing, cache state or side-effect behavior; use a safe benchmark environment.
Representative metrics or metric families to inspect include:
| Evidence | Example counter or report | Interpretation |
|---|---|---|
| Kernel duration | gpu__time_duration.sum | Device duration in the reported units |
| DRAM traffic | dram__bytes_read.sum and dram__bytes_write.sum | Actual measured reads and writes; use a compatible reporting boundary |
| DRAM throughput | dram__throughput.avg.pct_of_peak_sustained_elapsed | Activity relative to the profiler's defined sustained peak |
| SM throughput | sm__throughput.avg.pct_of_peak_sustained_elapsed | Broad SM throughput indicator; not proof of arithmetic saturation |
| Relevant arithmetic pipelines | FP32, tensor or other instruction/pipeline counters | Match the actual instruction mix and numerical precision |
| Warp scheduling | Eligible/issued warps and active warps | Distinguish residency from useful instruction issue |
| Stall reasons | Long scoreboard, barriers, execution dependencies | Locate waiting mechanisms; interpret in context |
| Memory efficiency | L1/L2/DRAM traffic and memory sectors per request | Identify poor coalescing, redundant traffic and cache behavior |
These are representative metric names and families, not guaranteed supported metric identifiers. The relevant arithmetic counts and sustained-peak denominators vary by chip and tool release. Check the profiler's actual units, metric definitions and available Roofline sections. In particular, high SM throughput does not alone prove compute saturation, and a long-scoreboard stall does not alone prove saturated DRAM bandwidth.
Compute achieved FLOPs/s and bandwidth using matched measurements. Compare them with attainable throughput from appropriate calibration benchmarks, not blindly with the GPU marketing specification. A sustained streaming bandwidth benchmark and a compute benchmark using the relevant instruction type are useful calibration tools. For hierarchical Roofline analysis, use separate roofs for the measured memory interfaces.
7. Distinguish actual bottlenecks#
| Observation | Hypothesis to test |
|---|---|
| Near sustained DRAM bandwidth; low arithmetic throughput | DRAM bandwidth-bound |
| Near a relevant arithmetic pipeline's ceiling; memory throughput has headroom | Compute-throughput-bound |
| Low bandwidth, many memory dependency stalls and little eligible work | Memory-latency limited, insufficient concurrency, poor access pattern or locality |
| Low compute and bandwidth utilization with small grids | Insufficient parallelism or overhead |
| High synchronization or divergent execution cost | Control-flow or coordination bottleneck |
| High occupancy but few eligible warps | Dependencies, resource bottlenecks or stalls; occupancy alone is insufficient |
| High cache traffic but relatively little DRAM traffic | Possible cache-level bandwidth/latency bottleneck |
Near the ridge point, both resources may matter. Different phases of one kernel may have different bottlenecks, so aggregate metrics can conceal phase behavior. An algorithmic intensity below the ridge is not sufficient evidence that the actual kernel saturates bandwidth.
8. Optimize the bottleneck and validate the change#
For memory-throughput limitations, improve coalescing and alignment, eliminate unnecessary transfers, fuse suitable kernels, increase data reuse with tiling, and consider lower-precision storage where quality permits. Reduce spills and avoid excessive intermediate allocation. If memory latency rather than bandwidth is limiting, consider exposing independent work, improving locality and memory-level parallelism. More traffic is not inherently a useful way to raise bandwidth utilization.
For compute-throughput limitations, reduce unnecessary arithmetic, use well-supported optimized math libraries and instruction types, consider appropriate mixed precision, improve batching and tiling, and reduce divergence or redundant recomputation. Faster instructions or lower precision can change numerical error, output quality and reproducibility; establish acceptance criteria before optimizing.
For kernels far below both roofs, investigate launch overhead, small problem shapes, pipeline dependencies, occupancy constraints, register pressure, shared-memory conflicts, synchronization, load imbalance and host/device interaction. A high theoretical occupancy target can be counterproductive if it increases spills or removes useful data reuse.
Use a controlled comparison: preserve input, output contract, precision or approved tolerance, and representative load. Measure the original and modified kernel and report actual changes in duration, traffic, arithmetic work and end-to-end performance. Do not infer that the optimization succeeded merely because a utilization percentage increased.
9. FDE production example: LLM inference#
In many transformer serving workloads, prefill on sufficiently large token batches can expose substantial matrix-multiplication parallelism and reuse. Small-batch autoregressive decode may spend a substantial fraction of time moving model weights and KV-cache data relative to the arithmetic performed. These are common workload tendencies, not universal classifications.
Batch size, sequence length, attention algorithm, KV-cache representation, quantization, model architecture, tensor parallelism, hardware and scheduling all change the intensity and attainable throughput. KV-cache paging and inter-device communication can introduce constraints that a DRAM-only single-GPU roof does not describe.
For a customer deployment:
- Measure time to first token, inter-token latency, output throughput, queueing and customer-facing success under representative traffic.
- Locate the expensive kernels and transfers on a system timeline.
- Profile the relevant kernel shapes separately for prefill and decode.
- Compare measured work and traffic with applicable compute, memory and communication limits.
- Evaluate a targeted change such as improved batching, a different attention implementation or approved quantization.
- Validate task quality, memory capacity, latency SLOs, throughput and cost per successful request.
Increasing batch size can improve reuse while increasing queueing delay and memory demand. A faster single kernel may have little customer-visible effect if most end-to-end time is elsewhere. Prioritize the actual bottleneck and the business outcome.
Likely interviewer follow-ups#
Is high GPU utilization proof of a compute-bound kernel? No. A busy GPU may execute inefficient instructions or wait on memory while other work proceeds. Examine the relevant pipeline and achieved roof.
Why can a bandwidth-bound kernel have low FLOPs/s? Its intensity is low, so even saturated memory bandwidth delivers relatively little arithmetic per second.
Can increasing arithmetic intensity help? Yes, by reducing physical traffic or increasing useful reuse for the same required result. Artificially adding unnecessary FLOPs raises intensity without necessarily improving useful performance.
Why distinguish bandwidth and latency? Bandwidth is the sustained transfer rate; latency is time to complete an individual access. A latency-limited kernel may have low observed bandwidth because it cannot keep enough independent accesses in flight.
Does a matrix multiply always compute-bound? No. Shape, implementation, precision, cache reuse and applicable hardware ceilings determine the actual bottleneck.
When should you stop optimizing a kernel? When further kernel changes do not improve the required end-to-end latency, throughput, cost or correctness target enough to justify complexity and risk.
Interview takeaway#
Calculate intensity and the applicable ridge point, then use measured work, traffic, time, pipeline activity and scheduler evidence to test the Roofline hypothesis. Optimize the confirmed limiting resource, validate correctness and remeasure the complete customer workload. Avoid treating every slow kernel as either saturated compute or saturated DRAM.
References
- 1.
- 2.NVIDIA Nsight Compute Profiling Guide (not live-verified)docs.nvidia.com
- 3.NVIDIA Nsight Compute CLI (not live-verified)docs.nvidia.com
- 4.NVIDIA CUDA C++ Best Practices Guide (not live-verified)docs.nvidia.com
- 5.NVIDIA Nsight Systems documentation (not live-verified)docs.nvidia.com
- 6.Python fractions documentation (not live-verified)docs.python.org
Related questions
- Explain how the CUDA execution model maps to hardware, grids, blocks, warps, SMs.
- Estimate the capacity and cost of an app with 50k DAU making 10 LLM calls each. What do you provision for?
- Prefix caching in a multi-turn chatbot: how do client-side and server-side caching cut redundant compute, and what breaks correctness?
Explore other topics:AI AgentsAI System DesignLarge Language Models