Measure a GPU kernel fairly
Separate correctness, kernel timing and profiling, then interpret recorded evidence.
Now test an optimisation claim: can combining two elementwise stages reduce kernel time? Keep correctness, timing and profiling as separate observations.
PyTorch
import torch
x = torch.arange(4096, dtype=torch.float32)
y = x * 2.0 + 1.0
print(y)The expression computes two mathematical stages, doubling then adding one. Eager and compiled PyTorch may launch different kernels. The native exercise fixes two CUDA variants: separate kernels with an intermediate array and a fused kernel.
Download the complete PyTorch example
Definitions
- Warm-up
- Untimed executions before collecting samples.
- CUDA event
- A marker in a GPU stream that can measure elapsed device time after completion.
- Profiler trace
- Recorded activities with timestamps and metadata; capture can affect execution.
Validate → warm up → time → inspect → change
First check every output of both variants against the CPU. Allocate and copy inputs outside the timed region. Warm up both paths; record CUDA events in the stream around repeated launches; wait for the end event before reading elapsed time. Divide by repetitions to obtain milliseconds per whole variant. Report the GPU, shape, warm-up, repetitions and all samples.
Time both separate kernels together, including their intermediate storage traffic. The fused path computes the same answer in one launch. The download alternates variant order across five samples to reduce a simple order bias. Kernel-only time excludes host transfers and allocation. A separate end-to-end experiment must state and include its boundaries.
Compare medians and ranges. If the sample ranges overlap, the median ratio alone is weak evidence for choosing the faster variant. Keep the first report and run ./benchmark-fusion > report-repeat.json with the same settings to compare a second set of samples. A ratio from one workload does not establish a universal speedup. Profile a separate run to explain a timing result: instrumentation and counter collection can perturb performance.
Run the native CUDA benchmark (requires a GPU)
Download the native CUDA benchmark
Shell · requires an NVIDIA GPU and CUDA toolkit
nvcc -O3 benchmark-fusion.cu -o benchmark-fusion
./benchmark-fusion > report.jsonThese commands require native CUDA. Browser simulation does not produce meaningful physical GPU timings. Paste the generated report into the activity below; no timings are prefilled.
Inspect a published GPU capture
The local excerpt contains eight unchanged kernel events from PyTorch Kineto’s published ResNet50 sample on Tesla V100-DGXS-32GB. It is a different workload from our fusion exercise. Toolkit version, correctness checks, warm-up and capture settings are unknown.
Download the recorded trace excerpt · Provenance and extraction · BSD licence
Without a GPU, download recorded-trace.json and open it in Perfetto (new tab) using Open trace file. The profiling appendix provides inspect-pytorch-trace.py. Follow its Python reader instructions using recorded-trace.json as the file argument. Timestamps and durations are microseconds. In the first two events, durations are 2 and 605 µs, blocks contain 256 and 128 threads, and grids contain 50 and 3136 blocks. Those launches do not say how many blocks execute simultaneously. The second event reports 128 registers per thread and 16,384 bytes of shared memory per block. Missing metrics remain unknown.
Inspect the remaining six events. Find one with a different launch shape. Explain why neither its name nor its duration proves that our fused kernel would be faster. CPU/operator correlation requires events omitted from this small excerpt.
- ValidateAll outputs of both variants must pass.
- MeasureWarm up, record completion-aware repeated timings.
- ExplainUse a separate profile to test one bottleneck hypothesis.
Inspect your timing report
Paste the complete report.json produced by the native benchmark into the report field and click Analyse report. Compare Separate and Fused using Median, Min and Max in milliseconds. Do the sample ranges overlap? If they do, the median ratio alone is weak evidence for choosing the faster variant. Repeat the native benchmark with the same settings before drawing a timing conclusion.
Hardware context
CUDA events in a stream delimit device execution. SM arithmetic, cache/device-memory traffic and launch costs can all influence kernel time. Host copies add other costs when included in an end-to-end measurement.
Read the hardware key
- Resident warp
- A warp has 32 lane positions; a small block can leave some unused. A resident warp has its state and required resources allocated on an SM. Its next instruction may still be waiting for data.
- Instruction
- One operation run by GPU hardware, such as a load, multiply or store.
- Warp scheduler
- Selects ready warp instructions for available execution hardware.
- Registers
- Hold working values associated with individual threads.
- Execution units
- Perform arithmetic and other instructions for threads; they are shared hardware.
- Load/store units
- Execute memory instructions, forming requests from active lanes’ addresses.
- L1 / L2 cache
- Keep recently used data on the GPU chip. L1 is local to an SM; L2 is shared across SMs in this simplified view.
- Shared memory
- SM-local storage allocated to blocks for explicit data exchange. It may share physical storage with L1, depending on the GPU.
- Bank
- A subdivision of shared memory that serves a group of word addresses.
- Tensor cores
- Matrix execution units used by supported warp-wide matrix instructions.
CPU side · CUDA host
Host ↔ device · copies move data; launches request execution
GPU device
GPU compute chip
SM · streaming multiprocessor
Logical groups using this SM’s resources
Issue to the appropriate units
Registers ↔ execution units · operands and results
Have their own execution hardware and registers.
Blocks may be assigned to different SMs.
Global-memory requests ↔ on-chip interconnect
Chip ↔ device memory · data transfers
Simplified NVIDIA-style architecture. Boundaries show containment; arrows name relationships. Unit counts, block placement and timing vary by GPU. A thread or warp is not a dedicated physical processor.
Apply what you found
A profile shows fewer device bytes for the fused kernel. Can you report a speedup without a timing comparison?
Compare your explanation
No. The traffic observation supports a mechanism but does not give elapsed time. Validate both variants, run comparable warm-up and repeated timings, report their spread and state the measurement boundary.
For toolkit installation and optional local execution, use desktop CUDA setup. The browser examples have been checked in functional simulation.
References CUDA Runtime API · events · PyTorch profiler recipe
External references open in a new tab and need internet access. Browser activities have no installed toolkit version; match documentation to your toolkit for native execution.
- CUDA Runtime API · events (new tab)
Check event recording and completion before reading elapsed time.
After recording start and end events around repeated launches in one stream, which event must complete before elapsed time can be read? Why divide by repetitions?
Compare your answer
Wait for the end event. Divide its elapsed time from the start event by the repetition count to obtain milliseconds per complete variant.
- PyTorch profiler recipe (new tab)
Follow capture and trace export on a supported GPU.
Can a kernel name alone identify the PyTorch operation that launched it?
Compare your answer
No. Use the capture’s CPU/operator correlation and runtime links where available. Missing correlation remains unknown.
Further GPU investigation Run this CUDA example on an NVIDIA GPU
In the CUDA source editor, open Editor tools and choose Export .cu to save the complete program. Use an NVIDIA GPU and a matching CUDA toolkit to run it outside the browser.
Browser simulation checks program behaviour; physical GPU timing requires a hardware measurement.
Enable JavaScript to save completion.