Skip to content
Skip to lesson
Back to Topics
LearnGPU Systems & LLM InferenceGPU Profiling & Kernel Optimization Lab
HardInference Optimization17 min read

GPU Profiling & Kernel Optimization Lab

A 40% faster transpose can still be wrong when the output is stale NaNs. Change one mechanism, then let correctness decide whether the timer counts.

On this page

You edit four lines of CUDA, recompile, and kernel latency drops 40%. Then verification runs and flags thousands of NaNs because your kernel skipped part of the grid and returned early. Performance engineering starts with a causal hypothesis, changes one mechanism at a time, proves correctness on edge and full shapes, and trusts the timer only after hardware counters and sanitizers agree.

In this lab you optimize an out-of-place single-precision (N×NN \times N) matrix transpose. With zero floating-point math, every launch reads and writes each element once, isolating memory coalescing, shared-memory bank conflicts, barriers, and benchmark discipline cleanly. It builds directly on CUDA for ML Training inside one reproducible workflow.

Keep one experiment stable

The kernel computes B[c,r]=A[r,c]B[c, r] = A[r, c] into a separate output buffer so fast blocks never overwrite unread input rows. Because no arithmetic modifies any value, the host checks exact 32-bit bitwise equality (+0.0f and -0.0f differ bitwise at 0x00000000 vs. 0x80000000). Input values are consecutive integers 0..N^2 - 1 (exact in float32 up to N=4096N=4096, exposing any permutation bug), and the destination buffer is pre-filled with 0xff (0xffffffff NaN) before every check so skipped stores fail immediately instead of inheriting stale data.

Three 3x3 matrices show input A, expected transpose B, and actual B when the store for A[1,2]=5 is skipped, leaving poisoned NaN (0xffffffff) at B[2,1] while signed zeros +0 (0x00000000) and -0 (0x80000000) differ bitwise. A four-stage row shows fresh-poison preflight, five warmups, event-timed iterations, and separate validation.
One skipped store leaves poisoned NaN (`0xffffffff`) at `B[2,1]`, while signed zeros show why bitwise equality catches bugs missed by absolute error. Fresh-poisoned checks bracket warmup and timed launches.

Reference verification for arithmetic and PyTorch custom ops

When a kernel does perform floating-point arithmetic (such as fused multiply-add, norms, or reductions), rounding order differs between CPU double-precision references and GPU fmaf. Never rely on a scalar checksum where errors can cancel; verify every element against an explicit tolerance rule (PyTorch's allclose):[1]

∣yi−ri∣≤atol+rtol ∣ri∣|y_i - r_i| \le \text{atol} + \text{rtol}\,|r_i|

Relative tolerance (rtol) scales with nonzero magnitudes while absolute tolerance (atol) bounds values near zero. Always allocate each test's exact logical length (never an oversized scratch buffer that hides an off-by-one tail write) and exercise edge sizes (n=0,1,255,256,257n = 0, 1, 255, 256, 257, zeros, and extreme magnitudes). When exposing a custom CUDA or Triton kernel to PyTorch, register its schema, aliasing, and fake-tensor metadata with torch.library.custom_op and run torch.library.opcheck to mechanically verify torch.compile and autograd integration alongside numerical equivalence.[2]

Inside this transpose lab, one executable packages five variants on the same allocation layout and timer:

VariantMechanism isolatedTimed?
copySame-volume coalesced read/write reference (not a transpose)yes
naiveCoalesced row reads, stride-NN column storesyes
tiled32×3232 \times 32 shared-memory tile for coalesced global reads and writesyes
padded32×3332 \times 33 shared tile to remove column bank conflictsyes
brokenPadded tile missing __syncthreads() to trigger a shared-memory raceno

Build the lab on an NVIDIA GPU

Place the CUDA source, its host-checking header, and the recovery template together on a machine with nvcc, Compute Sanitizer, and Nsight Compute (ncu). Snapshot GPU model, clocks, toolkit versions, and file hashes before compiling with -lineinfo -Xptxas=-v so ptxas reports static shared memory, registers per thread, and local-memory spills upfront:[3]

build-and-verify.sh
mkdir -p artifacts/run-01
set -euo pipefail
nvidia-smi -L | tee artifacts/run-01/gpu.txt
nvcc --version | tee artifacts/run-01/nvcc.txt
nvcc -std=c++17 -O3 -arch=native -lineinfo -Xptxas=-v \
  -o transpose_lab transpose_lab.cu 2>&1 | tee artifacts/run-01/build.txt

# 1. Partial-tile edge shapes before benchmarking.
for n in 1 7 31 32 33 65 257; do
  ./transpose_lab all "$n" 1 > "artifacts/run-01/check-${n}.csv"
done

# 2. Repeated alternating rounds at N=4096 to cancel clock/thermal drift.
for round in 1 2 3 4 5; do
  order=(naive tiled padded)
  (( round % 2 == 0 )) && order=(padded tiled naive)
  for v in "${order[@]}"; do
    ./transpose_lab "$v" 4096 100 | tail -n 1
  done
done | tee artifacts/run-01/repeated-benchmark.csv

Verify in build.txt that transpose_tiled<0> reserves 32×32×4=409632 \times 32 \times 4 = 4096 B of static shared memory and transpose_tiled<1> reserves 32×33×4=422432 \times 33 \times 4 = 4224 B.

CUDA event timing and L2 cache residency

Never time GPU kernels with an unsynchronized CPU wall clock, which measures host launch submission rather than device execution. Place cudaEventRecord(start, stream) and cudaEventRecord(stop, stream) around the launch, wait with cudaEventSynchronize(stop), and read cudaEventElapsedTime (~0.5 µs resolution; average a batch for sub-microsecond kernels).[4]

Watch cache residency closely. An H100 has a 50 MB L2 cache: repeatedly timing the same 11 MiB tensor can stay L2-resident and report effective bandwidth above HBM spec. Label your regime explicitly. To measure cold HBM streaming, either rotate buffer sets whose total footprint exceeds 2×2\times device L2 capacity or sweep a large dummy buffer between timed launches (and verify HBM traffic in Nsight counters rather than assuming eviction). Compare repeated sample distributions across alternating rounds before declaring a speedup.

Read the naive memory path

On NVIDIA GPUs (compute capability 6.0+), global memory transactions service 32-byte sectors. A full 32-lane warp reading consecutive aligned float32 words spans 128 bytes across four sectors (100% payload efficiency).[5]

transpose-naive.cu
__global__ void transpose_naive(float* output, const float* input, int n) {
  const int x = blockIdx.x * kTile + threadIdx.x;
  const int y = blockIdx.y * kTile + threadIdx.y;
  for (int offset = 0; offset < kTile; offset += kBlockRows) {
    if (x < n && y + offset < n) {
      output[static_cast<size_t>(x) * n + y + offset] =
          input[static_cast<size_t>(y + offset) * n + x];
    }
  }
}

Trace one 32-lane warp (threadIdx.x = 0..31, fixed threadIdx.y) at N=4096N = 4096:

  1. Input load ((y + offset) * n + x): 32 adjacent floats hit 4 sectors (100% payload utilization).
  2. Output store (x * n + y + offset): Adjacent lanes stride by 4,096 floats (16 KiB), landing in 32 distinct sectors. Only 128 of 1,024 sector bytes carry useful payload (12.5% efficiency).

Each launch moves 2N2×42N^2 \times 4 logical bytes (134,217,728134{,}217{,}728 B = 128 MiB at N=4096N=4096). Dividing by mean CUDA-event time yields effective GB/s (in 10910^9 B/s):

effective GB/s=2N2⋅4time (s)⋅109\text{effective GB/s} = \frac{2N^2 \cdot 4}{\text{time (s)} \cdot 10^9}

Profile before editing

Start wide enough to know where time goes, then zoom into one kernel. NVIDIA splits those jobs across four distinct instruments:[6][7][8]

QuestionToolWhat it revealsWhat it misses alone
Why is the app waiting?Nsight Systems (nsys)CPU stalls, launch gaps, H2D/D2H transfers, stream overlapsPer-instruction bottleneck inside one kernel
Why is this kernel slow?Nsight Compute (ncu)SpeedOfLight roofs, sector/cache/DRAM traffic, bank conflicts, warp stalls, occupancyEnd-to-end host latency or correctness
Is execution memory/race-safe?Compute SanitizerIllegal accesses, shared-memory races, uninitialized reads, bad barriersNormal uninstrumented speed
How fast is completed GPU work?CUDA eventsStream-ordered device elapsed timeRoot cause of that duration

Profile the single first timed naive launch (--launch-skip 6 skips preflight + 5 warmups). Never take benchmark times from an ncu --set full run because multi-pass replay distorts latency:[9]

profile-naive.sh
ncu --set full --kernel-name-base function --kernel-name transpose_naive \
  --launch-skip 6 --launch-count 1 --force-overwrite \
  -o artifacts/run-01/naive ./transpose_lab naive 4096 1
ncu --import artifacts/run-01/naive.ncu-rep --page details > artifacts/run-01/naive.txt

Inspect naive.txt in order: confirm kernel identity and 32x8 block in LaunchStats, compare memory vs. compute ceilings in SpeedOfLight (dram__throughput.avg.pct_of_peak_sustained_elapsed), and check L1/TEX Sectors/Req separately for loads (predict 4) and stores (predict 32). Combine Roofline bounds[10] with these counters to record a falsifiable baseline hypothesis before writing code.

Coalesce both global directions

Staging a 32×3232 \times 32 block in shared memory turns scattered column stores back into contiguous row writes: each warp reads adjacent input elements into tile[ty + offset][tx], waits at __syncthreads(), then reads tile[tx][ty + offset] and writes adjacent output elements.[11]

transpose-tiled.cu
template <int Padding>
__global__ void transpose_tiled(float* output, const float* input, int n) {
  __shared__ float tile[kTile][kTile + Padding];
  const int input_x = blockIdx.x * kTile + threadIdx.x;
  const int input_y = blockIdx.y * kTile + threadIdx.y;

  for (int offset = 0; offset < kTile; offset += kBlockRows) {
    if (input_x < n && input_y + offset < n) {
      tile[threadIdx.y + offset][threadIdx.x] =
          input[static_cast<size_t>(input_y + offset) * n + input_x];
    }
  }
  __syncthreads();  // Unconditional: every thread in the block must reach this.

  const int output_x = blockIdx.y * kTile + threadIdx.x;
  const int output_y = blockIdx.x * kTile + threadIdx.y;
  for (int offset = 0; offset < kTile; offset += kBlockRows) {
    if (output_x < n && output_y + offset < n) {
      output[static_cast<size_t>(output_y + offset) * n + output_x] =
          tile[threadIdx.x][threadIdx.y + offset];
    }
  }
}

Keep __syncthreads() outside both if bounds checks so partial-tile threads never skip the barrier and hang or corrupt the block.

Comparison of global memory access at N=4096 for one aligned 32-lane warp. Reading row 0 of A loads 32 adjacent floats across four 32-byte sectors (100% coverage). A naive write to column 0 scatters lanes across 4,096-word (16 KiB) strides touching 32 sectors (12.5% coverage), while a shared-tile transpose swaps tile[ty][tx] to tile[tx][ty] so output writes touch four sectors again.
Swapping coordinates inside shared memory turns 32-sector strided column stores back into 4-sector coalesced row writes.

Check the edge-tile mapping without a GPU

At N=33N=33, edge block (1, 0) activates only one input column (A[r, 32]) and one output row (B[32, r]). Because the input bounds guard checks (input_y + offset, input_x) and the output guard checks the exact swapped coordinates (output_y + offset, output_x), every active output lane reads a shared slot populated by a matching in-bounds producer before the barrier.

Diagram of edge block (1,0) for N=33. Three matrices connected by arrows trace input column A[r,32] (tx=0 active) into shared column tile[r,0] and out to output row B[32,r] (32 lanes at ty=0). Below, a 4x8 grid shows shared rows r=0 through 31 with r=1 highlighted, paired with producer (tx=0, ty=1, Warp 1), the 256-thread __syncthreads() barrier, and consumer (tx=1, ty=0, Warp 0).
For N=33 edge block (1,0), Warp 1 writes A[1,32] into tile[1,0] before the 256-thread barrier and Warp 0 reads tile[1,0] into B[32,1].

Verify index coverage across partial tiles, shared bank strides, and global sector coverage directly in Python:

transpose-index-model.py
import numpy as np

def check_mapping(n: int) -> None:
    src = np.arange(n * n, dtype=np.int64).reshape(n, n)
    dst = np.full((n, n), -1, dtype=np.int64)
    for by in range((n + 31) // 32):
        for bx in range((n + 31) // 32):
            smem = np.full((32, 33), -1, dtype=np.int64)
            for ty in range(8):
                for tx in range(32):
                    for off in range(0, 32, 8):
                        r, c = by * 32 + ty + off, bx * 32 + tx
                        if r < n and c < n:
                            smem[ty + off, tx] = src[r, c]
            for ty in range(8):
                for tx in range(32):
                    for off in range(0, 32, 8):
                        r, c = bx * 32 + ty + off, by * 32 + tx
                        if r < n and c < n:
                            dst[r, c] = smem[tx, ty + off]
    assert np.array_equal(dst, src.T)

for n in (1, 7, 31, 32, 33, 65, 257):
    check_mapping(n)
print("7 shapes (1..257): exact transpose mapping verified")

lanes = np.arange(32, dtype=np.int64)
for stride in (32, 33, 34):
    banks, counts = np.unique((lanes * stride) % 32, return_counts=True)
    print(f"shared stride {stride}: {banks.size} banks, {int(counts.max())} words/bank")

def sector_coverage(words):
    addr = np.asarray(words, dtype=np.int64)
    sectors = np.unique((4 * addr) // 32).size
    return sectors, (4 * np.unique(addr).size) / (32 * sectors)

for label, addr in (
    ("aligned row N=4096", np.arange(32)),
    ("row 1 N=33 (unaligned)", np.arange(33, 65)),
    ("naive col N=4096", np.arange(32) * 4096),
):
    s, frac = sector_coverage(addr)
    print(f"{label:24s}: {s:2d} sectors ({frac:.1%} payload)")
Output
7 shapes (1..257): exact transpose mapping verified
shared stride 32: 1 banks, 32 words/bank
shared stride 33: 32 banks, 1 words/bank
shared stride 34: 16 banks, 2 words/bank
aligned row N=4096      :  4 sectors (100.0% payload)
row 1 N=33 (unaligned)  :  5 sectors (80.0% payload)
naive col N=4096        : 32 sectors (12.5% payload)

Profiling tiled (Padding = 0) confirms global store sectors drop from 32 to 4 per aligned warp, while exposing a new bottleneck: shared-memory bank conflicts. Shared memory interleaves 32-bit words across 32 banks via bank⁡(k)=k mod 32\operatorname{bank}(k) = k \bmod 32. In tile[32][32], lane ii reading column cc hits offset 32i+c32i + c, so every lane maps to bank cc for a 32-way bank conflict (check l1tex__data_bank_conflicts_pipe_lsu_mem_shared_op_ld.sum in ncu).

Change the shared-memory stride

Padding one extra float per row (__shared__ float tile[32][33]) shifts the column stride from 32 to 33 words (+128 bytes per block, 4,224 B total) without touching a single global address:[11]

bank⁡(i)=(33i+c) mod 32=(i+c) mod 32\operatorname{bank}(i) = (33i + c) \bmod 32 = (i + c) \bmod 32

Because gcd⁡(33,32)=1\gcd(33, 32) = 1, all 32 warp lanes hit 32 distinct banks in one wavefront. By contrast, tile[32][34] has gcd⁡(34,32)=2\gcd(34, 32) = 2 and still suffers a 2-way conflict across 16 even banks.

Comparison of shared-memory strides 32, 33, and 34 for scalar 32-bit reads on column 0. A bank map and padded tile diagram show stride 32 collapsing onto Bank 0, stride 33 visiting all 32 banks once, and stride 34 hitting 16 even banks twice. A bar chart plots 32, 1, and 2 predicted conflict-free service groups alongside 4,096, 4,224, and 4,352 bytes per tile.
Stride 32 collapses all 32 lanes onto Bank 0; stride 33 visits all 32 banks conflict-free (+128 B/tile); stride 34 leaves a 2-way conflict across 16 banks.

Loop unrolling and instruction-level parallelism

Each of the 256 threads in a 32x8 block copies four rows (offset = 0, 8, 16, 24). Adding #pragma unroll before the loop can remove loop-control instructions and let the compiler schedule independent global loads ahead of dependent shared stores.[12] Because nvcc already unrolls small constant-trip loops automatically, inspect SASS assembly and -Xptxas=-v register counts before attributing any timing delta to the pragma. Unrolling increases live register pressure, which can lower occupancy or trigger local-memory spills; keep global loads inside their bounds guards and barriers outside them.

Occupancy is a constraint, not a score

Occupancy is the ratio of active warps per SM to the hardware maximum. More warps help hide memory latency, yet 100% occupancy loses if threads execute extra instructions or stall on bank conflicts.[5] Registers per thread, static shared memory (4096 B vs. 4224 B), thread count (256), and barriers all cap resident blocks.

Comparison of the fixed baseline against three single-variable optimization branches. The baseline pairs a 32x8 block (256 threads, 8 warps), a 32x32 shared tile (4,096 B), and loop offsets 0, 8, 16, and 24. Branch A pads the tile to 32x33 (4,224 B, +128 B). Branch B applies #pragma unroll across the four offsets. Branch C doubles the block to 32x16 (512 threads, 16 warps).
Hold the 32x8 baseline constant and test padding (+128 B), unrolling, and block height (32x16) on separate branches, checking SASS, registers, correctness, and repeated timings for each.

Pair the Nsight Occupancy limiter with stall and memory counters to choose your next experiment: shared-memory-limited occupancy suggests shrinking tiles; register-limited occupancy with local traffic suggests trimming live state; high memory throughput at modest occupancy means cutting transferred bytes rather than chasing 100% occupancy.

Deliberately remove the barrier

Variant broken removes __syncthreads() from the padded kernel so consumer warps can read tile before producer warps finish writing it. Because warp scheduling can accidentally serialize producer before consumer on one run, matching outputs alone never clear a race.

Side-by-side timelines compare block synchronization on shared tile[1,0]. With __syncthreads(), Warp 1 writes 65 from A[1,32], all 256 threads wait at the barrier, and Warp 0 reads 65 and stores it at B[32,1]. Without the barrier, one schedule lets Warp 0 read an unwritten stale value before Warp 1 writes 65, storing corrupted data at B[32,1].
Without `__syncthreads()`, Warp 0 can read stale uninitialized data from `tile[1,0]` before Warp 1 writes 65, corrupting `B[32,1]`.

NVIDIA Compute Sanitizer provides four specialized checkers; run memcheck first (with --padding 32 to catch global tail overruns) before racecheck or synccheck:[8]

CheckerDefect class caughtBehavior on broken transpose
memcheckOut-of-bounds global/shared/local accesses, misaligned loads, bad pointersClean (all addresses are in bounds)
racecheckShared-memory RAW, WAR, and WAW data hazardsFlags RAW/WAR hazards from missing barrier
initcheckReads of uninitialized global device memoryClean (inputs are initialized)
synccheckDivergent or invalid __syncthreads() / warp barriersClean (barrier was omitted, not misused)
sanitize-broken-and-repaired.sh
for tool in memcheck racecheck initcheck synccheck; do
  compute-sanitizer --tool "$tool" --error-exitcode 99 \
    ./transpose_lab padded 33 1 > "artifacts/run-01/padded-33-${tool}.txt" 2>&1
done

Decide between transpose, reduction, and scan

Before reusing shared-memory tiling on another kernel, match the parallel primitive to the output dependency graph:

PrimitiveOutput ruleTypical use
TransposeSame element count, permuted 2D coordinatesRow-major / column-major layout swap
ReductionCombine many inputs into fewer summaries via associative opLoss sum, max error, mismatch count[13]
ScanPrefix aggregate for every positionExclusive offsets for stream compaction, cumulative lengths
For mismatch flags [0, 1, 0, 1, 1, 0] at indices [0, 1, 2, 3, 4, 5], a reduction sums flags to scalar count 3. An exclusive scan computes prefix offsets [0, 0, 1, 1, 2, 3] and writes failing indices 1, 3, and 4 into compacted slots [1, 3, 4]. A transpose preserves all six values (a through f) while swapping a 2x3 layout to 3x2.
A reduction counts total mismatches (3); an exclusive scan computes destination offsets `[0, 0, 1, 1, 2, 3]` to compact failing indices `[1, 3, 4]`; a transpose remaps 2D coordinates without combining values.

Overlap work with streams, events, and CUDA Graphs

Optimizing a kernel's memory path removes stalls inside the kernel, yet Nsight Systems traces of small-batch LLM decode often reveal a different culprit: tiny idle gaps between kernels because the GPU finishes one operation before the CPU finishes submitting the next. Closing runtime launch overhead requires understanding stream ordering, event dependencies, and CUDA Graph capture/replay.[14][15]

Two clocks, stream ordering, and event handoffs

Every GPU launch runs on two overlapping clocks: host submission time (CPU enqueue loop, returning asynchronously before the GPU executes) and device elapsed time (CUDA-event span on the stream, including any inter-kernel idle gaps inside the markers). Never add host submission time and device event time together; measure end-to-end synchronized wall time separately.

Operations inside one CUDA stream execute strictly in FIFO issue order. Operations on distinct streams can overlap copies and independent kernels when three rules hold:

  1. Avoid the legacy default stream trap: Under default legacy semantics, stream 0 (the NULL stream) implicitly synchronizes with every blocking stream in the same CUDA context. Create explicit non-blocking streams with cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking) and use pinned host memory (cudaMallocHost) for asynchronous H2D/D2H transfers so host copies do not serialize compute.[16]
  2. Coordinate cross-stream dependencies with events: Record a marker after producer work (cudaEventRecord(ready, copy_stream)), then enqueue a device-side wait on the consumer (cudaStreamWaitEvent(compute_stream, ready, 0)) without stalling the CPU. Always record before waiting: an unrecorded event represents empty work and adds no dependency.[4]
  3. Protect allocation lifetimes across streams: Keep shared buffers alive until consumer streams finish (using tensor.record_stream(consumer_stream) in PyTorch so the caching allocator never recycles a buffer while a consumer kernel is still queued).[17]

CUDA Graphs capture, replay, and bucketed pools

When short decode kernels are launch-bound, CUDA Graphs record a stream's kernel DAG once (cudaStreamBeginCapture / torch.cuda.graph()), validate and compile it (cudaGraphInstantiate), and replay the entire sequence in one host submission (cudaGraphLaunch).[15][17] Graph capture pays off once per-iteration savings amortize upfront capture and instantiation:

Break-even Iterations=Setup CostEager Time−Replay Time\text{Break-even Iterations} = \frac{\text{Setup Cost}}{\text{Eager Time} - \text{Replay Time}}

If eager execution takes 18 µs/iter, graph replay takes 12 µs/iter (6 µs saved), and setup takes 12 ms, both break even at 2,000 iterations (36 ms), and iteration 2,001 wins.

Because continuous batching varies batch sizes dynamically, serving engines (vLLM, SGLang) pre-capture bucketed graph pools (e.g., batch sizes [1, 2, 4, 8, 16]), pad live batches up to the next bucket, and fall back to eager mode for outliers.[18] Zero-padding alone is never enough for correctness: an affine op like 2x+12x + 1 turns dummy zeros into 1, and unmasked dummy slots can corrupt reductions or live KV-cache entries unless every reduction and cache write masks padded positions explicitly:

CheckCalculationResult
CUDA Graph break-even (12 ms12\text{ ms} setup, 18→12  μs18 \to 12\;\mu\text{s}/iter)12,000/(18−12)=2,00012{,}000 / (18 - 12) = 2{,}000 (+1 for net win)Breaks even at iter 2,000 (36 ms); first net win at iter 2,001
Bucket-8 affine op (2x+1)2(2x+1)^2 on 6 valid inputs [1..6]True sum vs. 2 zero-padded slots ((2⋅0+1)2=1(2 \cdot 0 + 1)^2 = 1 each)True/masked sum 454 vs. unmasked 456 (corrupted by +2)

Report the result you measured

An optimization claim stands only when every row shares the exact shape, timing loop, cache regime, and verification gates, backed by raw logs (.ncu-rep, sanitizer transcripts, ptxas output, timing CSV, and source hash):

VariantOne changeCorrectness & SanitizerExpected profiler shiftDecision
naiveBaselineExact + clean4 load sectors, 32 store sectorsBaseline
tiled32×3232 \times 32 shared tile + barrierExact + cleanStore sectors drop to 4; 32-way bank conflicts appearIntermediate step
paddedtile[32][33] (+128 B)Exact + cleanShared bank conflicts drop to 0Keep if repeated timings improve
brokenRemove __syncthreads()Fails racecheckTiming invalidatedReject and document recovery
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 6 answered
1.One full warp reads consecutive float32 words numbered 7 through 38 from a 32-byte-sector-aligned array base. How many sectors are touched, and what is useful payload divided by touched sector volume?
2.A kernel transposes a 73x73 row-major matrix using 32x8 blocks covering 32x32 tiles. For edge block (bx, by) = (2, 0), how many valid input values does it load, how many threads hit __syncthreads(), and where does A[1, 64] land?
3.A 32x32 shared tile is padded to row stride 36 float32 words. All 32 warp lanes read column 0 of consecutive rows. With bank = word_index mod 32, what bank mapping and tile byte size result?
4.Two CUDA events bracket 40 launches of a 2048x2048 float32 transpose, measuring 4.00 ms total. What combined logical read+write rate does this support?
5.A shared-memory kernel passes 64 output tests, memcheck, and synccheck, but racecheck flags a write-after-read hazard. What is the right verdict?
6.Mismatch flags at indices 0..5 are [1, 0, 1, 0, 0, 1]. What are the exclusive scan offsets, compacted failing indices, and reduction sum?

6 questions remaining.

References

torch.allclose

PyTorch Contributors · 2026 · Official documentation

https://docs.pytorch.org/docs/stable/generated/torch.allclose

The Custom Operators Manual

PyTorch Contributors · 2026 · Official PyTorch documentation

https://docs.pytorch.org/docs/main/library.html

NVIDIA CUDA Compiler Driver NVCC

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/

CUDA Runtime API: Event Management

NVIDIA · 2026

https://docs.nvidia.com/cuda/cuda-runtime-api/cuda_runtime_api/group__CUDART__EVENT.html

CUDA C++ Best Practices Guide

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/

Nsight Systems User Guide

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/nsight-systems/UserGuide/

Nsight Compute Profiling Guide

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/nsight-compute/ProfilingGuide/

Compute Sanitizer

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/compute-sanitizer/ComputeSanitizer/

Nsight Compute CLI

NVIDIA · 2026

https://docs.nvidia.com/nsight-compute/NsightComputeCli/

Roofline: An Insightful Visual Performance Model for Multicore Architectures

Williams, S., Waterman, A., & Patterson, D. · 2009

https://doi.org/10.1145/1498765.1498785

An Efficient Matrix Transpose in CUDA C/C++

Harris, M. · 2013

https://developer.nvidia.com/blog/efficient-matrix-transpose-cuda-cc/

C/C++ Language Extensions

NVIDIA · 2026

https://docs.nvidia.com/cuda/cuda-programming-guide/05-appendices/cpp-language-extensions.html

Optimizing Parallel Reduction in CUDA

Harris, M. · 2007 · NVIDIA Developer Technology

https://developer.download.nvidia.com/compute/cuda/1.1-Beta/x86_website/projects/reduction/doc/reduction.pdf

CUDA Programming Guide

NVIDIA · 2026

https://docs.nvidia.com/cuda/cuda-programming-guide/

CUDA Programming Guide: CUDA Graphs

NVIDIA · 2026

https://docs.nvidia.com/cuda/cuda-programming-guide/04-special-topics/cuda-graphs.html

CUDA Stream Synchronization Behavior

NVIDIA · 2026

https://docs.nvidia.com/cuda/cuda-runtime-api/stream-sync-behavior.html

CUDA semantics

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/2.14/notes/cuda.html

CUDA Graphs

vLLM Project · 2026

https://docs.vllm.ai/en/latest/design/cuda_graphs/

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.