Assignment 1 Companion · Performance Engineering: Kernels, Benchmarks and the MFU Investigation

Scalable AI: Bridging Theory, Understanding, and Practice · 配套练习 A1。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley EE 290/194 Scalable AI, Fall 2026 Assignment 1 (released with Lecture 2, due 28 September 2026). Part A (40%): a Triton kernel warm-up notebook with four kernels (elementwise add, RMSNorm forward/backward, SwiGLU forward/backward, fused cross-entropy forward/backward). Part B (60%): an open-ended MFU investigation of training/SFT workloads of Nemotron-Nano-V3 on the group’s 8×H100 node, plus a report and an in-person check-in. Spring 2026 Assignment 1 had the same Part B (with a required PR). Its Part A was two notebooks instead: arithmetic intensity, and a Mixtral MFU optimization challenge.

Sources: the two public handouts (assignment_1.zip on the Fall and Spring course pages), paraphrased here; Lectures 1–3 and 5–7 of these notes. The assignment’s own notebooks and starter code are not reproduced.

What this companion is. It covers the concepts the assignment exercises, a method for the open-ended part, and practice code on different problems, so that you build the skills without reading a solution. In the course’s words, the notes “never reproduce assignment solutions”. Concretely:

  • the practice kernels are not the four Part A kernels;
  • the investigated workload is a small Transformer on a laptop CPU, not Nemotron-Nano-V3 on H100s;
  • the large-model FLOP example is an invented configuration.

Code: code/assignmentA1/ contains:

  • a Triton-language emulator, tl_emu.py, so kernels written in Triton syntax run, are bounds-checked and have their bytes counted on a laptop;
  • a check-and-benchmark toolkit, kernel_check.py;
  • four demos: practice kernels with realistic bugs, benchmark methodology, a worked MFU investigation, and FLOP conventions for hybrid MoE models.

Reading time: ~75 minutes; ~90 seconds to run all demos.


0. How to read this companion

0.1 Learning goals

After this companion you should be able to:

  1. Write a Triton-style kernel in the right shape for its class (elementwise, row-wise reduction, fused forward/backward), with correct masks, other values and block sizes, and say what each program loads and stores.
  2. Test a kernel so that bugs cannot hide: tolerances by dtype, sizes that are not powers of two, adversarial value patterns, finite-difference gradient checks.
  3. Benchmark honestly: warm-up, the right statistic, the right size regime, synchronization, noise, and a roof measured the same way.
  4. Run an MFU investigation as the handout asks: baseline, noise, profile, hypothesis with evidence, prediction, one change, interleaved measurement, ablation.
  5. State MFU with its formula for a hybrid Mamba–attention MoE model, and know which conventions inflate it.

0.2 Prerequisites and scope

  • Prerequisites: Lecture 1 (FLOP accounting, 6N), Lecture 2 (roofline, byte model, the knee), Lecture 3 (launch model, fusion, profiling, MFU), Lectures 5–7 (parallelism, collectives, FlashAttention, MoE kernels), Lecture 15 (the Nemotron-H hybrid pattern).
  • In scope: the ideas and method behind both parts, with practice on other problems.
  • Not in scope: the assignment’s kernels, its notebook answers, its configurations, or any recommendation of a specific parallelism setup for Nemotron-Nano-V3.

0.3 Section → code map

SectionIdeaCode in code/assignmentA1/
§1what the assignment asks and how it is graded–
§2.1–2.2the Triton programming model; kernel classestl_emu.py
§2.3–2.4writing and testing practice kernels01_practice_kernels.py, kernel_check.py
§2.5benchmarking a kernel02_benchmark_methodology.py
§3.1MFU and its conventions04_counting_model_flops.py
§3.2–3.5the investigation: where MFU goes, hypotheses, decisions03_mfu_investigation.py
§3.6the report–

1. What the assignment asks, and what the grading rewards

1.1 The two parts

Part A (40%) is a warm-up notebook. You write four Triton kernels: an elementwise add (its backward is given); RMSNorm forward and backward; SwiGLU forward and backward, each direction fused into one elementwise kernel; and cross-entropy forward and backward over logits of shape B × V. For cross-entropy, the forward uses the max-subtraction trick, and the backward must not write the full B × V probability matrix to HBM. The notebook contains:

  • eager references;
  • correctness tests and benchmarks;
  • a checklist of what to report.

Every check must pass in the submitted run, and you must be able to explain your kernel code in person.

Part B (60%) is an open-ended systems investigation:

  1. Choose a training/SFT stack, for example NeMo AutoModel or NeMo RL with a DTensor or Megatron-Core backend.
  2. Run Nemotron-Nano-V3 end to end, integrating support for it if the stack lacks it.
  3. Measure throughput and MFU, then profile and explain where performance is lost.
  4. Diagnose bottlenecks with evidence, design and implement interventions (parallelism, kernels, re-implemented abstractions), and measure their effect.

The report runs 1–4 pages plus an appendix:

  • setup and exact reproduction steps;
  • the baseline and “current OSS best”;
  • profiling results (Nsight screenshots);
  • evidence-backed hypotheses;
  • interventions and why they should help;
  • before/after results with ablations;
  • reproducibility notes.

A PR with before/after MFU numbers is encouraged (optional in Fall, required in Spring).

1.2 The grading, read carefully

Part B’s rubric: measurement setup + baseline reproduction 10%, diagnosis with profiling evidence 20%, intervention engineering + reproducibility 20%, report 10%. The handout states two rules plainly, in paraphrase:

  • Full credit without winning. A good diagnosis and well-reasoned interventions that did not beat the baseline can still earn full credit.
  • No full credit for ungrounded search. If you only ran an exhaustive random search over configurations, you probably cannot write a good report.

So what is graded is the path from observation to fix: what the symptom was, what you concluded the bottleneck was and on what evidence, what you changed, why it should help from first principles, and what the measured effect was. This companion is organized around that path. §3.4 works through it on a laptop example; read it as the shape of a good report, not as a recipe.


2. Part A: kernels

2.1 The Triton programming model in six rules

A Triton kernel is a Python function that runs once per program (程序实例). The grid (网格) says how many programs run. Each program asks tl.program_id(axis) which piece of the problem is its own. Six rules cover most of what goes wrong:

  1. A program owns a block. For a flat array: offs = pid * BLOCK + tl.arange(0, BLOCK). For rows: row = pid, cols = tl.arange(0, BLOCK), with addresses row * stride + cols.
  2. tl.arange needs a power of two. A row of 3,000 values is covered by BLOCK = next_power_of_2(3000) = 4096; the extra 1,096 lanes exist but must do nothing.
  3. The mask (掩码) switches lanes off. mask = cols < D on every load and store. An unmasked lane past the end reads garbage or crashes, and a lane past the end of one row silently reads the next row.
  4. other is what masked lanes hold, and it must be neutral for what you do next. For a sum, 0 is neutral. For a max, 0 is not: −∞ is. For a min, +∞. A wrong other gives a wrong answer only when masked lanes exist and the true result lies on the “wrong side” of the fill value. That is why the bug hides from power-of-two tests.
  5. Reductions happen inside a program. tl.sum(x, axis=0) and tl.max reduce a block that is already in registers. A row that fits one block is read from HBM once, reduced, and its values reused for the output. That one read is the whole benefit of a row kernel.
  6. tl.constexpr arguments are compiled in. BLOCK sizes are constexpr, so a new BLOCK means a new compiled kernel. Choose them from the problem shape (and autotune), not per call.

The emulator tl_emu.py implements these rules on CPU tensors with Triton’s names: jit, program_id, arange, masked load/store, sum/max/min, where, libdevice.rint, dtypes. A kernel written for it reads like a real one. It enforces the rules strictly:

  • an unmasked out-of-bounds access raises an error naming the program;
  • arange rejects lengths that are not powers of two;
  • masked lanes loaded without other are poisoned (NaN), so a forgotten other is loud instead of silently wrong;
  • shuffle=True runs the programs in random order, which a correct kernel must not notice.

It counts the bytes of every active lane, which is the kernel’s HBM traffic if nothing is reused. It does not model speed.

2.2 Three kernel classes, and what each one asks of you

The four Part A kernels fall into three classes, and the classes are what to learn.

Elementwise kernels (add, activation functions such as SwiGLU’s) are memory-bound (访存受限). Lecture 2 computed the arithmetic intensity of c = a + b in BF16: 1 FLOP per 6 bytes. For fp32 it is 1/12, hundreds of times below the H100’s ridge point. Their time is bytes ÷ bandwidth, and the job is to move the minimum bytes. One read of every input and one write of every output, in one kernel, is the target. Two consequences:

  • Fusing a chain of elementwise ops (an activation and the multiplication that follows) removes every intermediate write and re-read.
  • In a fused backward, the cheap thing is to recompute the forward’s intermediates from its saved inputs rather than save them: recomputing costs FLOPs, which are free here, while saving costs bytes, which are not.

Row-wise reductions (normalizations, softmax, losses) need a statistic of a whole row (a mean of squares, a max, a sum of exponentials) before any output of that row is known. The natural mapping is one program per row with BLOCK = next_power_of_2(D). Decisions to make:

  • Accumulate in fp32 even when inputs are BF16. Lecture 9 §3.5 measured BF16 accumulators losing digits.
  • Make exponentials safe: subtract the row max before exp, so the largest exponent is 0 and nothing overflows.
  • Save small statistics for the backward, for example one number per row, so the backward can rebuild what it needs without storing anything of the row’s size. Saving one fp32 per row costs D times less than saving the row.
  • Handle rows too wide for one block. For example, a vocabulary of 131,072 logits does not fit one block. The program then loops over the row in chunks, and statistics like max and sum-of-exponentials must be combined across chunks. Lecture 7 §2’s online softmax is exactly that combine rule.

Fused forward + backward pairs add one more question: what does the backward need, and where does it come from? Write it down per kernel:

  1. Inputs re-read: tensors read again from HBM.
  2. Statistics saved by the forward: a few bytes per row.
  3. Values recomputed in registers.
  4. Outputs written: the gradient, and nothing of B × V size that is not the gradient itself.

The byte count of that list is the kernel’s minimum traffic; Lecture 3 §4 did this accounting for a fused cross-entropy over a 128k vocabulary. Deriving the backward formulas is part of the assignment. §2.4 shows how to check a derivation without trusting it.

2.3 Practice kernels (demo 01)

Demo 01 writes three kernels, one per class, that are not the assignment’s.

(a) A fused AdamW step: elementwise, 4 tensors in, 3 out. Each parameter’s update needs only its own p, g, m, v, so each program handles a block of elements. After 3 steps it matches torch.optim.AdamW to 1.2 × 10⁻⁷ (fp32), and it moves 28 bytes per parameter (reads p, g, m, v; writes p, m, v), the minimum for this update.

kernel_check.ByteCounter intercepts every eager PyTorch op and sums the bytes it reads and writes, which measures the unfused alternatives:

implementationbytes per parameterkernels touching the tensors
fused kernel (emulated)28.01
torch.optim.AdamW(foreach=False)80.08
torch.optim.AdamW(foreach=True)80.08
torch.optim.AdamW(fused=True)32.0 (counted)1

PyTorch’s own fused kernel counts 32 B only because its schema marks the gradients writable (for in-place unscaling under a gradient scaler). The counter charges a write that this update does not perform. A byte counter is a model too; read its rules.

(b) RoPE forward and backward: one program per row. RoPE rotates coordinate pairs (i, i + D/2) by an angle per position. For head_dim 96 there are 48 pairs, so BLOCK = 64 with a mask. The backward is a rotation by minus the angle, the transpose of an orthogonal matrix, and needs nothing saved except the cos/sin tables it re-reads. The deliberately buggy backward reuses the forward rotation, a transposition slip. Over head_dims 8, 64, 96 and 128 it:

  • passes every forward test, since the forward is unchanged;
  • fails the comparison with autograd;
  • fails the finite-difference gradient check.

The correct backward passes both. The emulated kernel moves 3.0 × |x| bytes (reads x and the tables, writes y); eager apply_rope moves 9.1 × |x| in 7 ops.

(c) Per-row asymmetric uint8 quantization: a masked reduction. Each row needs its min and max, then every value is coded as round(x / scale) + zero_point, with scale = (max − min)/255. The demo runs a correct kernel and four realistic bugs against seven inputs:

test inputcorrectother=0 in min/maxno zero-range guardfixed BLOCK=1024no mask
gaussian rows, D=64passpasspasspasspass
gaussian rows, D=1000passpasspasspassOOB error
gaussian rows, D=3000passpasspassWRONGOOB error
all-positive rows, D=64passpasspasspasspass
all-positive rows, D=1000passWRONGpasspassOOB error
a constant row, D=1000passWRONGWRONGpassOOB error
D=1passpassWRONGpasspass

Read the table column by column:

  • other=0 is wrong only when a row lies entirely above zero and masked lanes exist. The masked zeros then become the row’s minimum and stretch its range. On D = 64 there are no masked lanes, and the bug is invisible.
  • The missing guard divides by a zero range: a constant row, or a row of one value.
  • A fixed BLOCK silently quantizes only the first 1,024 values of a 3,000-wide row.
  • The missing mask makes each row read into the next one, and the last row read past the tensor.

On the power-of-two inputs alone, all four bugs pass every check. A test set of random power-of-two shapes is close to no test at all.

2.4 Testing a kernel so bugs cannot hide

Four checks, all in kernel_check.py:

  1. Tolerances by dtype (容差). torch.testing passes if |out − ref| ≤ atol + rtol·|ref|, with rtol about a few units in the last place: 1.3 × 10⁻⁶ for fp32, 1.6 × 10⁻² for BF16, 10⁻³ for fp16. Compute the reference in higher precision (fp32 or fp64), not in the kernel’s dtype. A reduction over K terms accumulates rounding roughly like √K ulps, so a long BF16 reduction may need a looser rtol. Say so when you loosen one, and never loosen it to make a test pass without knowing why it failed.

  2. Sizes that are not powers of two (边界情形). edge_sizes(BLOCK) returns 1, 2, 3, BLOCK−1, BLOCK, BLOCK+1, 2·BLOCK+3 and two primes. Every masking bug shows up somewhere in that list.

  3. Value patterns. Choose inputs that put the true result on the wrong side of every fill value and every special case:

    • constant rows (zero range or zero variance);
    • rows that are all positive or all negative;
    • very large values (overflow of exp or of squares in low precision);
    • zeros;
    • a single outlier.
  4. Gradient checks (梯度检验) for every hand-written backward. Two independent checks:

    • compare with autograd of the eager reference;
    • check finite differences with torch.autograd.gradcheck on fp64 inputs. gradcheck_pair(fwd, bwd, inputs) wraps your pair into an autograd Function: it perturbs each input element by ±ε and compares how the output moves with what your backward claims.

    The RoPE bug above passes every forward test and fails both of these.

One more, for free: run the grid in random order (shuffle=True in the emulator). On a GPU, programs run in an unspecified order and overlap, so a result that depends on the order is a bug.

2.5 Benchmarking a kernel (demo 02)

The notebook asks for achieved bandwidth and FLOP/s. Demo 02 shows how many different numbers “the time of a kernel” can be on one machine. Its copy peak was ~230 GB/s on 256 MiB buffers, this laptop’s analogue of the H100’s 3.35 TB/s datasheet HBM bandwidth.

One kernel, four statistics. An AdamW step over 16M parameters, timed four ways (one run):

implementationfirst callmean incl. firstmedian of 15min of 15
eager for-loop (80 B/param)22.5 ms7.58 ms6.59 ms6.24 ms
fused (28 B/param)3.04 ms2.22 ms2.14 ms2.08 ms

The first call allocates the optimizer state and touches cold memory, so it is a measurement of start-up, not of the kernel. Report the median after warm-up, with a spread (p10–p90). By median, both versions run near 90–95% of the copy peak: both are memory-bound. The fused one is ~2.8× faster for 2.86× fewer bytes. The bytes are the whole gain.

Bandwidth depends on size. Fused AdamW at increasing sizes (one run):

parameterstime (warm)GB/sregime
4,09664 µs2fixed per-call cost
262,14480 µs92still mostly fixed cost
4,194,304 (117 MB/step)335 µs350 (152% of copy peak)caches help
16,777,216 (470 MB/step)2.10 ms224 (97%)memory-bound

Three lessons:

  • Small sizes measure a fixed cost, not bandwidth. From 4K to 262K parameters the bytes grow 64× and the time 1.2×.
  • A mid-size result can exceed the memory’s bandwidth. A memory-bound kernel cannot beat memory, so some of its data came from caches. On an H100, a 50 MB L2 plays that role.
  • The fair number is at the workload’s size, compared with a roof measured the same way (the demo also times a copy of the same footprint). Triton’s do_bench flushes the L2 between runs for this reason. Flushing here changed results by up to ~20% at mid sizes, so state your protocol.

Noise. Timing the same kernel against itself (an A/A test) produced fake “speedups” of 7–14% across runs (std 3–5%) with 10-call medians. Any effect smaller than that needs more repetitions or interleaved A/B runs before it is a result.

Asynchrony. GPUs run asynchronously: the call returns when the work is queued. On the Apple GPU, a 4096³ matmul timed without synchronizing “ran” at 5,000–7,000 TFLOP/s, about 1,000× the 5.4 TFLOP/s measured with torch.mps.synchronize(). CUDA behaves the same way. Use torch.cuda.synchronize() or CUDA events, or triton.testing.do_bench, which does it for you.

What to put in the results table for each kernel:

  • the size, and the dtype;
  • the median time with its spread;
  • the bytes the kernel must move, from your byte model, not from the profiler;
  • the achieved bandwidth and its fraction of the HBM peak;
  • for compute-heavy kernels, achieved FLOP/s and the fraction of the dense peak;
  • the eager reference under the same protocol.

A memory-bound kernel at 80–90% of HBM bandwidth at a realistic size is done. One at 30% has a reason worth finding: too few programs to fill the SMs, uncoalesced access, a block too small to hide latency (Lecture 3 §2–3).


3. Part B: the MFU investigation

3.1 MFU is a ratio, and its numerator is a convention (demo 04)

MFU (模型 FLOP 利用率) = model FLOPs per second achieved ÷ peak FLOP/s. The denominator is easy: the H100’s dense BF16 peak, 989.4 TFLOP/s per GPU. The numerator is where reports differ, and for a hybrid Mamba–attention MoE model like Nemotron-Nano-V3 the honest conventions disagree a lot.

Demo 04 counts FLOPs per token of a small real hybrid MoE (Mamba-2, attention and MoE layers in the pattern ME*EME). Two findings:

  • The formulas are right. The analytic per-layer forward counts equal PyTorch’s FlopCounterMode exactly for every layer kind, once attention uses PyTorch’s math kernel. That covers the Mamba-2 mixer’s projections and its two contractions, the MoE’s router + top-2 routed + shared expert, and the head.
  • The counter is not the truth either. With the fused CPU attention kernel, the counter silently counts 0 for attention (134 MFLOP missing per attention layer at this size). A FLOP counter counts only the ops it has formulas for. Check it against an analytic count once, then trust whichever you have verified.

One measured training step of that model, stated five ways:

numerator convention (training, per token)MFU at the same step time
C1: 6 × all parameters (every expert, embeddings)6.6%
C2: 6 × active parameters (incl. embedding table)3.0%
C3: 3 × active matmul FLOPs (projections, router, k experts, head)2.7%
C4: C3 + causal attention scores + Mamba scan (linear-time form)2.9%
C5: executed (FlopCounterMode: quadratic SSD, full-square attention)3.3%

(Laptop numbers are low because the model is tiny; the spread is the point.) Three lessons:

  1. Counting every expert inflates MFU by the inverse of the MoE’s sparsity. On an invented large hybrid (40 layers, 64 experts with top-6, 8.35B total and 1.79B active parameters) at an illustrative 30,000 tokens/s per H100, “6 × total parameters” claims 152% MFU. That is impossible, which makes it the quickest sanity check there is. “6 × active” claims 32.5%, and active matmuls + attention + scan give 28.4% at 4K context.
  2. The numerator must not depend on the implementation. C5 is higher than C4 because this implementation does more work than the model needs: it computes the Mamba mixing in its quadratic form and attention over the full square. A slower algorithm should never raise your “MFU”. Fix the numerator by the model (the work the computation needs), and let faster kernels show up as more tokens per second. If you recompute activations, report the hardware FLOP utilization HFU (硬件 FLOP 利用率) separately. In the invented example, counting one recomputed forward turns 28.4% into 37.9%.
  3. Context length matters less in a hybrid. With 4 attention layers out of 40, attention is 2.1% of model FLOPs at 4K and 14.9% at 32K. With attention in all 40 layers it would be 18.1% and 63.9%.

Rule for the report:

  • Write the formula next to the number: which parameters count as active, the attention convention (causal halving or not), how the SSM scan is counted, whether recomputation is excluded, the peak per GPU.
  • Use the same formula for the baseline, every intervention, and the “current OSS best” you compare with.
  • If the framework prints its own MFU, find out what it counts before you quote it.

3.2 Where MFU goes: the step-time ladder

MFU is low for a reason, and the reasons stack. Start from the ideal time, total model FLOPs ÷ (GPUs × peak), and add what each cause costs:

losswhat it islecturewhat it looks like in an Nsight Systems trace
small or badly shaped GEMMsbelow the knee, or wave quantization, or tiles mostly paddingL2 §5.4, L3 §2GEMM kernels at low achieved FLOP/s; short kernels with many SMs idle
memory-bound gluenorms, activations, RoPE, casts, loss: many short kernelsL2 §7, L3 §4a long tail of small kernels between the GEMMs
attentionmaterialized scores, or a kernel unsuited to the shapesL7attention kernels large relative to their FLOP share
exposed communicationTP all-reduces, EP all-to-alls, DP all-reduce / reduce-scatter not overlapped with computeL5, L6NCCL kernels on the timeline with compute streams idle
pipeline bubblesstages waiting at the start and end of a stepL6 §4idle stretches per rank, regular in time
load imbalanceMoE experts with unequal tokens; ranks with unequal workL4, L5 §6, L7 §6some ranks finish early and wait inside a collective
host overheadPython, dispatch, kernel launches outpacing nothingL3 §2, L23 §2gaps between GPU kernels while the CPU thread is busy
input pipelinedata loading, tokenization, host-to-device copies on the critical pathL9 §3GPU idle at the start of each step; long H2D memcpy
optimizer and checkpointingper-parameter loops; synchronous savesL8, L9 §4a long optimizer phase; periodic stalls
recomputeactivation checkpointing replays forward workL5, L6forward kernels appearing inside the backward

Two practical habits:

  1. Look at the step-level breakdown before the operator profile. An operator profile of forward + backward cannot show time the GPU spends waiting for data or for the host.
  2. Turn the trace into numbers. Express each item as a share of the step, then do the arithmetic: if the exposed all-to-all is 18% of the step, perfect overlap can buy at most 1/(1 − 0.18) = 1.22×. That bound is the prediction you write down before you try it.

For a hybrid MoE on one 8×H100 node, the questions that usually matter are:

  • how experts are placed across GPUs and how many tokens each receives;
  • whether all-to-all communication overlaps with compute;
  • what the Mamba layers’ kernels cost relative to their FLOPs;
  • whether the GEMM shapes per expert are big enough;
  • how much memory activations take and therefore what micro-batch fits.

Each of these questions needs evidence from your own traces. This companion gives no recipe for them.

3.3 Measurement setup: what a baseline is

The rubric gives 10% to the measurement setup, and every later claim rests on it. A baseline is:

  • The exact command and configuration, framework version and commit, container, model config, parallelism, micro-batch and global batch, sequence length, dtype, and the seed.
  • Steady-state throughput. Exclude the first steps (compilation, allocator warm-up, data-loader start-up) and report the median tokens/s over many steps, with a spread.
  • MFU with its formula (§3.1).
  • The noise floor: the same configuration measured several times, ideally interleaved with other runs. The demo’s A/A tests showed why one measurement is not a number.
  • “Current OSS best”: what the framework’s maintainers or others report for this model or a close one, measured or quoted with its own conventions, so the reader knows where your baseline stands.

Same math. A systems change should not silently change the training: different global batch, different LR schedule, dropped tokens. Demo 03 checks that 8 accumulation steps of micro-batch 2 and one step of micro-batch 16 produce the same parameters up to rounding (differences of 6 × 10⁻⁶ vs an update of 10⁻⁴). If an intervention does change the math, for example a capacity factor that drops MoE tokens, or lower precision, the report must show the loss curve is unaffected.

3.4 The method, worked on a laptop (demo 03)

Demo 03 runs the whole path on a 19.7M-parameter Transformer (d = 512, 4 layers, vocabulary 8,192) training on the CPU. The global batch is 16 × 256 = 4,096 tokens per step, so every change is a systems change. The numbers below are from one run; the decisions repeated across runs.

Baseline. 344 ms per step, 11,902 tokens/s, MFU 35.1%, with MFU computed against the CPU’s measured fp32 matmul peak. Three back-to-back measurements spanned 0.9% in this run and 11% in another, where one slow run widened the max–min spread. The demo therefore fixes a minimum effect of 2% in advance and decides every change from interleaved pairs (current, new, current, new). It never compares one run against a number remembered from earlier.

Step breakdown first. Tokenizing in the step: 0.3%. Forward + backward: 96%. Optimizer: 3.4%. Inside forward + backward, the operator profile gives GEMMs 53%, glue 35% and attention softmax + mask 6.6%.

Hypotheses, each with evidence and a prediction written before the run:

hypothesisevidencepredicted stepmeasuredgain (pairs)decision
H1 input pipeline on the critical pathtokenizing = 0.3% of the step–––ruled out by evidence, not run
H2 GEMMs too small at micro-batch 2the model’s MLP GEMM: 3,460 GFLOP/s at 512 rows vs 3,985 at 4,096300 ms269 ms1.28× (1.28, 1.28)kept
H3 attention materializes the scoressoftmax + mask = 6.5% of fwd+bwd255 ms237 ms1.11× (1.11, 1.11)kept
H4 per-parameter optimizer loopoptimizer = 5.0% of the step231 ms230 ms1.04× (1.03, 1.05)kept
H5 use all 12 cores instead of 8–154 ms242 ms0.95× (0.96, 0.94)reverted (slower)

Read it as a report would:

  • H1 costs nothing to rule out: even removing tokenization entirely could not clear the 2% bar.
  • H2’s prediction counted only the GEMMs’ speed-up (from a micro-benchmark of the model’s own shape) and missed 31 ms of the gain. The unexplained part is itself a finding. At micro-batch 2, the per-pass costs (glue kernels, framework dispatch) are paid 8 times per step. Profiling both configurations would confirm it.
  • H4 was small but consistent across pairs.
  • H5 is a negative result with a likely reason: the extra 4 cores are efficiency cores, and a data-parallel kernel waits for its slowest thread. In one run its pairs disagreed (1.00, 1.06); the decision rule then reports “inconclusive” rather than a win.

Leave-one-out ablation (逐项剔除消融) of the final configuration (229 ms, MFU 52.8%, 1.50× the baseline): removing the micro-batch change costs 1.37×, fused attention 1.12×, the fused optimizer 1.04×. What is left: GEMMs are 60% of forward + backward and glue 30%. The next hypothesis would be fusing the glue, with a prediction from the glue’s share.

Three habits from this example matter more than any of its numbers:

  1. Write the prediction before the run. When measured and predicted disagree, your model of the bottleneck was incomplete. Saying so is what separates a diagnosis from a search.
  2. Decide on interleaved pairs against a threshold fixed in advance, and allow “inconclusive” as an outcome.
  3. Ablate at the end, so the report can say which changes carry the result. Interventions interact: a fusion matters less once the batch is larger.

3.5 Interventions: where to look, and how to argue for each

The handout’s examples: parallelism strategy, communication overlap, batch/micro-batch choices, precision, activation checkpointing, kernel fusion, optimizer settings, data pipeline. For each class, the first-principles argument the report needs:

interventionwhy it should help (the argument to make)evidence that it is the right one
larger micro-batch / fewer accumulation stepsbigger GEMMs move past the knee; per-pass overheads paid fewer timesGEMMs below the knee in a micro-benchmark of your shapes; many short kernels per pass
activation checkpointing less (or more selectively)removes recomputed forward workrecompute kernels visible in the backward; memory headroom exists
different TP / EP / DP splittrades communication volume and its overlap against memory and GEMM sizeexposed collectives in the trace; the α–β model of Lecture 5 predicts the change
communication overlaphides transfer behind computeNCCL kernels serialized with compute streams; enough independent compute exists
expert load balancing / placementreduces waiting at the all-to-allper-expert token counts uneven; ranks idle inside collectives
kernel fusion / a better kernelfewer bytes for memory-bound opsglue’s share of time ≫ its share of FLOPs; the byte model of the fused kernel
lower precision (FP8)higher peak and fewer bytesGEMM-bound profile; accuracy check that the loss is unaffected
input pipelineremoves GPU idle at step startidle gaps aligned with data loading; loader time per step measured

An intervention that did not help is still worth reporting when its argument was sound and its measurement careful. The rubric says so explicitly.

3.6 The report, section by section

Map each required section to its evidence:

  1. Setup and reproduction: commands, configs, versions, seeds; one script that reproduces the baseline.
  2. Baseline and “current OSS best”: tokens/s and MFU with the formula, the noise floor, and the comparison point with its source.
  3. Profiling results: trace screenshots, each annotated with its numbers (share of step, achieved FLOP/s or bandwidth of the key kernels).
  4. Diagnosis: a few hypotheses, each with its evidence and the bound it implies (“at most 1.22×”).
  5. Interventions: what changed and the first-principles reason, with the prediction.
  6. Results: before/after with spread, and the leave-one-out ablation.
  7. Reproducibility: seeds, caveats, what is brittle, and an end-to-end run.

If you open a PR, it carries items 1, 5 and 6 in miniature: the change, the reproduction, and before/after numbers measured under the same protocol.


4. Summary

  • Part A is about the programming model:
    • programs own blocks, and every load and store is masked;
    • other must be neutral for the reduction that follows;
    • one program per row for row statistics, with fp32 accumulation and max-subtraction;
    • the backward recomputes from small saved statistics.
  • Kernels hide bugs from friendly inputs. Four realistic bugs all passed on power-of-two shapes. Test with sizes that are not powers of two, adversarial value patterns, and a finite-difference gradient check of every backward.
  • A benchmark number needs its protocol: warm-up, median with spread, the workload’s size, synchronization, and a roof measured the same way. On this laptop, cold calls cost 1.3–5.5× the median, mid sizes exceeded DRAM bandwidth, and A/A tests showed 7–14% fake speedups.
  • MFU’s numerator is a convention. For a hybrid MoE, use active matmul FLOPs plus causal attention plus a linear-time scan, never total parameters (152% on the invented example). Fix it by the model, not the kernels, and write the formula next to the number.
  • Part B is graded on the path: baseline with noise → step breakdown → hypothesis with evidence and a prediction → one change → interleaved measurement → ablation. Negative results with sound arguments count; random search does not.

5. Common pitfalls

  1. Testing only power-of-two shapes. Masks, other values and block-size bugs are invisible there (demo 01).
  2. other=0 before a max or min. Use −∞ for max and +∞ for min, or tl.where(mask, x, ±inf).
  3. Checking a backward with the forward’s test. Only a gradient check (autograd comparison or finite differences) sees a wrong backward.
  4. Timing without synchronizing on a GPU: you measure the queue, not the kernel (demo 02: about 1,000× off).
  5. Benchmarking at a cache-resident size and reporting more than the HBM bandwidth.
  6. Reporting the mean of runs that include the first call, or a single run of each configuration.
  7. “MFU” from 6 × total parameters for an MoE, or from the executed FLOPs of an inefficient kernel. Both inflate it.
  8. A systems change that changes the math (global batch, dropped tokens, precision) without showing the loss is unaffected.
  9. An intervention with no prediction. Even when it works, the report cannot explain why, and the next one is a guess.
  10. Trusting a framework’s printed MFU without knowing its formula, or a FLOP counter without checking it once (demo 04: fused attention counted as 0).

6. Exercises

  1. A kernel computes y = x * sigmoid(x) for 64M BF16 values on an H100 (3.35 TB/s). What is its minimum time, and its arithmetic intensity?
AnswerBytes: read 2 B + write 2 B per element = 4 B × 64M ≈ 268 MB, so the minimum time is 268 MB / 3.35 TB/s ≈ 80 µs. FLOPs: a handful per element (exp, add, divide, multiply ≈ 4–5). The arithmetic intensity is ~1 FLOP/B, hundreds of times below the ridge point (≈ 295 FLOP/B for dense BF16), so the kernel is purely memory-bound. Report its achieved bandwidth, not its FLOP/s.
  1. A row kernel for a row-wise max uses tl.load(..., mask=mask, other=0.0). For which inputs is it wrong? Which edge_sizes would catch it?
AnswerIt is wrong when every true value in a row is negative and masked lanes exist: the masked 0 becomes the max. Masked lanes exist when D is not a multiple of BLOCK, so D = BLOCK − 1, BLOCK + 1, 2·BLOCK + 3, or a prime would catch it, combined with all-negative rows. Power-of-two D with BLOCK = D never would.
  1. Your fused backward passes the comparison with autograd at fp32 for D = 4096 but fails at D = 4095. What do you suspect first?
AnswerA masking problem: a load without a mask or with the wrong `other`, a store that writes masked lanes, or a reduction that includes masked lanes. Only D = 4095 has masked lanes when BLOCK = 4096. Numerical tolerance is an unlikely explanation for a change of one element.
  1. A training step takes 1.00 s; Nsight shows 220 ms of all-to-all kernels with the compute streams idle. What is the best speedup from perfect overlap, and what evidence would you need before trying it?
AnswerAt most 1/(1 − 0.22) ≈ 1.28×, if all 220 ms is hidden. You need independent compute available to overlap with (for example, the shared expert, or the next micro-batch's attention), enough SMs left free so the communication kernels do not slow the compute, and a check that the all-to-all time is bandwidth-bound and not waiting on stragglers. If it is load imbalance (some ranks idle waiting), overlap does not help: balancing does.
  1. Two reports give 45% and 31% MFU for the same run of a 30B-total / 3B-active MoE. Give two conventions that could explain the difference.
AnswerPossibilities: (i) one counts 6 × total parameters (or more experts than are active), the other 6 × active; (ii) one includes recomputed forward passes (HFU), the other does not; (iii) one counts attention over the full square at long context, the other the causal half or none; (iv) one includes the embedding table as a matmul. Demo 04 shows each of these moving the number.
  1. Your intervention measured 1.03× in one run. The A/A test on your node gave up to 4% fake speedups. What do you do?
AnswerNothing is shown yet. Run interleaved pairs (baseline, new, baseline, new, …) for more repetitions, and decide against a minimum effect you fixed beforehand. If the pairs disagree, report "no measurable effect", together with the argument for why the change was expected to help and the evidence that it did not.

7. Enhancing the assignment

The course gives 10% of the assignment grade for enhancing an assignment. Ideas that build on this companion, none of which is part of the graded solution:

  • A byte-model check in the notebook: compute each kernel’s minimum bytes from its signature, and report achieved bandwidth as a fraction of it at three sizes (overhead-bound, cache-resident, memory-bound).
  • An edge-case test generator for row kernels (the edge_sizes × value-pattern matrix of demo 01), runnable against any kernel with a reference.
  • An “MFU formula” helper for the course’s model family that prints every convention side by side, so reports state theirs.
  • A trace-to-table script that turns an Nsight Systems export into the step-time ladder of §3.2 (share of the step per category, exposed communication), making the diagnosis section reproducible.

8. Further reading

  • Triton documentation and tutorials (vector add, fused softmax, layer norm): the programming model of §2.1 with real kernels.
  • Horace He, Making Deep Learning Go Brrrr From First Principles: compute, memory and overhead as the three regimes of §2.5 and §3.2 (linked from the course page).
  • The course’s linked GPU performance engineering resources (wafer-ai), and How to Write a Fast Matrix Multiplication from Scratch with Tensor Cores (linked on the course page).
  • NVIDIA Nsight Systems user guide: reading timelines, NVTX ranges, CUDA and NCCL rows.
  • Lectures 2, 3, 5, 6 and 7 of these notes.

术语表 (Glossary, English → 中文)

English中文
program (instance) / program id / grid程序实例 / 程序编号 / 网格
block / BLOCK size / constexpr块 / 块大小 / 编译期常量
mask / masked lane / other掩码 / 被屏蔽的通道 / 屏蔽通道的填充值
poison (poisoned value)毒化值(故意设为 NaN,使错误显形)
elementwise kernel / row-wise reduction逐元素核函数 / 按行归约
memory-bound / compute-bound访存受限 / 计算受限
byte model / minimum traffic字节模型 / 最小访存量
fusion / recomputation融合 / 重计算
max-subtraction (numerically safe exp)减最大值(数值稳定的指数)
online softmax在线 softmax(分块合并统计量)
tolerance (rtol, atol) / ulp容差(相对、绝对)/ 末位单位
edge case / value pattern边界情形 / 取值模式
gradient check / finite difference梯度检验 / 有限差分
eager execution / dispatch即时执行 / 算子分派
warm-up / median / spread (p10–p90)预热 / 中位数 / 分布范围
cache-resident / cache flush驻留缓存 / 清缓存
A/A test / noise floor / minimum effectA/A 对照测试 / 噪声底 / 最小效应
interleaved A/B measurement交错 A/B 测量
asynchronous execution / synchronize异步执行 / 同步
MFU / HFU模型 FLOP 利用率 / 硬件 FLOP 利用率
active parameters (MoE)激活参数(混合专家)
step-time ladder步时间阶梯(逐项损失分解)
exposed communication / overlap暴露的通信 / 通信计算重叠
load imbalance / straggler负载不均 / 拖后腿的节点
leave-one-out ablation逐项剔除消融
current OSS best当前开源最佳水平
← 返回课程目录