Foundation Model Kernel Optimization in 2026: A Field Guide Across Dense, MoE, Multimodal, and Diffusion

Most “kernel optimization” conversations still start with FLOPs. In 2026 that is usually the wrong first question. Foundation-model runtime is dominated by HBM traffic, KV cache, temporary tensors, collectives, dynamic permutation, and launch overhead. FlashAttention, fused linear–cross-entropy, paged KV, MoE grouped GEMM, and DeepEP-style dispatch all share one essence: do not materialize intermediates, or make each byte travel once.

This post is a field guide to the kernel / fused-kernel / collective families that matter on critical paths — Dense Transformers, MoE, LLM train/serve, VLM / audio / video, contrastive multimodal training, Diffusion / DiT, and SSM / long convolution — plus the communication, memory, layer-structure, and model–kernel co-design moves that decide whether a fast op shows up in end-to-end tokens/s.

Scope note. “Every kernel” here means families on the critical path, not every CUDA symbol in a framework. Batch, sequence length, hidden size, GPU generation, and parallel strategy spawn different instances; symbol-level enumeration is unstable and rarely useful.

Related posts on this blog: Roofline, GPU Optimization Playbook, Large MoE Performance, torch.compile, VLM one-GPU recipe.

TL;DR

  1. Optimize data movement first, not peak FLOPs. Fusion, paging, packing, and low precision win by cutting bytes and launches.
  2. Fusion is layered. Elementwise chains are cheap wins; GEMM epilogue fusion is the safe high-ROI boundary; GEMM↔GEMM and compute↔comm fusion need shared layout/pipeline and can hurt occupancy.
  3. Train ≠ prefill ≠ decode. Prefill is large-GEMM heavy; decode is GEMV / small-GEMM + KV bandwidth; training adds backward, optimizer, and cross-rank sync.
  4. Attention co-design is hardware-asymmetric. FA1 fixed IO; FA2 fixed work partition; FA3 used Hopper TMA/WGMMA; FA4 rebalances Blackwell Tensor Core / SFU / TMEM / 2-CTA ratios.
  5. MoE is a pipeline. Router → top-k → histogram → permute → All-to-All → grouped GEMM → act → combine. Speeding only expert GEMM often amplifies communication.
  6. Overlap needs finer dependencies than “another CUDA stream.” Chunk/tile/threadblock events beat whole-tensor collectives.
  7. Memory has six levers: dematerialize, compress, pack/page/layout, recompute, shard/offload/prefetch, allocator lifetime. Peak GB alone is a bad KPI.
  8. Multimodal’s biggest lever is usually token budget (native resolution, packing, temporal sparsity) — architecture–runtime co-design, not one vision kernel.
  9. Diffusion’s unique lever is cross-timestep redundancy (cache, fewer steps, CFG parallel) — fewer full-network calls, not only faster ops.
  10. End-to-end KPIs win. Kernel TFLOP/s without graph-break / layout / exposed-comm / p99 / quality checks is storytelling.

Four layers of foundation-model kernel co-design

1. A practical performance model

For a kernel or path, a lower bound looks like:

[ T \gtrsim \max\left( \frac{F}{P_{\text{effective}}}, \frac{B_{\text{HBM}}}{BW_{\text{HBM}}}, \frac{B_{\text{net}}}{BW_{\text{net}}} \right) +T_{\text{launch}}+T_{\text{sync}}+T_{\text{imbalance}} ]

  • (F): useful FLOPs; (P_{\text{effective}}) is limited by Tensor Core use, tile choice, occupancy, dependency chains, SFU throughput.
  • (B_{\text{HBM}}): bytes that actually cross HBM — materialization, cold KV, layout copies inflate this beyond logical tensor size.
  • (B_{\text{net}}): NVLink / PCIe / IB bytes; topology, algorithm, message granularity, and congestion set effective bandwidth.
  • Launch / sync / imbalance dominate small-batch, short-sequence, fine-grained MoE, and ragged workloads.

NVIDIA’s Nsight Compute Profiling Guide splits kernels into memory- vs compute-bound. Foundation models need two more axes: network and launch / load imbalance. For the arithmetic-intensity framing, see Roofline on this blog.

1.1 Symptom → direction

Profiling symptomCommon root causePreferEasy trap
High DRAM, low Tensor CoreBandwidth-bound; repeated intermediatesFusion, in-place, low precision, reuse, packingOversized fusion → spill → more local-memory traffic
Low Tensor Core and low DRAMSmall shapes, launch-bound, SFU/deps, low occupancyPersistent kernels, batch/group, Stream-K, CUDA GraphChasing occupancy alone
High Tensor Core but far from peakBad tiles, pipeline bubbles, wave quantization, tailsAutotune, split-K/Stream-K, warp specialization, async copyOverfitting one benchmark shape
Many memcpy / layout kernelsProducer/consumer layout mismatchUnified layout, prepack, transpose/quant in prologue/epilogueBenchmarking only GEMM
Long NCCL, idle computeExposed collectiveRS/AG split, chunk/tile overlap, topology, compressionStream overlap with whole-tensor deps
NCCL and compute both slowSM / L2 / HBM / NVLink contentionCap comm CTAs, priority, double buffer, staged overlap“More overlap is always better”
MoE expert GEMM long tailUneven tokens/experts; many tiny GEMMsGrouped GEMM, block-sparse, persistent schedule, balancingCapacity padding waste; sort becomes bottleneck
Decode slows linearly with contextKV bandwidth / capacityGQA/MQA/MLA, paged/quantized KV, split-KV decodeSwapping only the prefill FlashAttention kernel
High peak memory, moderate HBM BWOverlapping activation / logits / workspace lifetimesSelective recompute, chunked loss, buffer reuseFull checkpoint everywhere

2. A dictionary of techniques

TechniqueDataflow essenceTypical targetsWhen it pays
IO-aware tilingKeep working set in register / SMEM / LDS / TMEMAttention, GEMM, FFT convArithmetic intensity available but materialization kills it
Multistage pipelineOverlap async load / MMA / epilogueGEMM, attentionLarge stable tiles; cp.async / TMA available
Warp specializationSplit producer / consumer / softmax / epilogueHopper/Blackwell attention & GEMMOne warp juggling copy+compute creates bubbles
Vertical fusionMerge consecutive opsbias→act→dropout→residual→normPointwise/reduction with large intermediates
GEMM epi/prologue fusionScale/bias/act/quant/residual while tile is on-chipLinear, MLP, projectors, DiTGEMM followed by low-intensity ops
Horizontal fusionShare one input read across opsQKV, gate+up, multi-LoRAShared HBM/L2 traffic
Persistent kernelResident CTAs pull tiles/tasks from a queueSmall/heterogeneous GEMM, decode, MoELaunch / wave quantization / dynamic schedule dominate
Split-K / Stream-KPartition K or iteration space, then reduceSkinny GEMM, decode attentionSmall M/N underfills SMs; pay partial reduction
Layout / prepack / swizzleCoalesced global→shared→MMA pathINT4/FP8 GEMM, KV, MoEOffline weight rearrange; amortize conversion
Lower precisionFewer bytes + higher TC throughputFP8/FP4/INT8/INT4, KVNative scale/dequant kernels for the target shape
SparsitySkip zero / unimportant blocksLocal/sparse attention, MoE, videoBlock-structured; index cost < savings
Packing / raggedKill padding via offsets / cu_seqlensNLP / VLM / audio / videoLarge length/resolution variance
PagingFixed pages + indirectionKV cache, LoRA adaptersDynamic serving; unpredictable lengths
RecomputationDrop cheap intermediates; recompute in bwdAttention stats, activationsCapacity-bound and recompute FLOPs are cheap
Compute–comm overlapFiner tile/chunk dependenciesTP / FSDP / EP / CPLarge enough comm with independent compute windows
Architecture co-designShrink state, tokens, branches, interaction rangeGQA/MLA, NSA, SigLIP, TeaCacheKernels near hardware limits; change the problem

Fusion is layered — more is not always better

2.1 Different GPU generations want different “good” kernels

PlatformCritical primitivesKernel design focus
NVIDIA A100 / SM80Tensor Core, cp.async, shared memoryWarp-level MMA, multi-stage copy/compute, FA1/FA2 + classic CUTLASS
NVIDIA H100 / SM90TMA, WGMMA, clusters, warp-groupsProducer/consumer specialization, TMA descriptors, async WGMMA; FA3 / CUTLASS 3.x — see Hopper Tuning Guide
NVIDIA B200/GB200 / SM100tcgen05.mma, TMEM, 2-CTA MMA, FP4/FP6/FP8Accumulators in TMEM, single-thread MMA issue, dual-CTA tiles; rebalance TC vs SFU/SMEM — CUTLASS tcgen05, FA4
AMD MI300X/MI350MFMA, LDS, HBM, XCD/L2, hipBLASLt/CK/RCCLWavefront/LDS banks, MFMA tiles, XCD/NUMA + RCCL topology; Triton ports need re-autotune — ROCm workload tuning

Do not copy H100 block sizes, warp counts, and stage counts onto B200 or MI300X. Tensor Core throughput often outruns SFU, register bandwidth, SMEM, and the network — the non-matmul and orchestration paths become the new Amdahl bottleneck.

3. Dense Transformer / LLM / sequence kernels

Notation: B batch, S sequence, H hidden, V vocab, D head dim. Covers train fwd/bwd, prefill, decode, loss, optimizer.

IDKernel / pathMain bottleneckHow to optimizeCo-design & references
T01Linear / GEMM (fwd, dgrad, wgrad)Large shapes compute-bound; skinny/tail under-utilized; epilogue BWHierarchical tiles; async global→SMEM; TC MMA; double buffer; warp specialization; CTA swizzle; Stream-K/split-K; bias/act/scale/quant/residual epilogue fusion; shape autotuneCUTLASS efficient GEMM, Stream-K, Triton matmul, CODA
T02Decode Linear / GEMV / small GEMMRe-read weights every token; tiny M; launch-boundWeight-only INT4/FP8; continuous batching; persistent tile scheduler; vectorized loads; L2 reuse of activations; dequant interleaved with MMAMarlin (prepack + async load + dequant–MMA overlap)
T03QKV projectionTriple read of X; three launches; layout conversionFuse weights into one GEMM; shared X; fused bias; write packed/head layout attention wants; optional Q/K RoPE + KV quant/update in epilogueDecode: fuse KV cache update; different Q/K/V dtypes or TP shards can make forced fusion worse
T04RoPE / M-RoPEElementwise; sin/cos traffic; extra transposeVectorized pair rotation; sin/cos cache; in-place; fuse into QKV epilogue or attention prologue; inverse rotate in bwdLiger Kernel; VLM M-RoPE in Qwen2-VL
T05Dense attention prefill fwd score/prob materializationTile Q/K/V; online softmax; keep score/prob in register/SMEM; causal/local mask inside tile; store LSE only; TMA/WGMMA pipeline; FP8 block scaleFA1FA2FA3FA4
T06Attention backwardMulti-pass dQ/dK/dV; recompute; atomics; imbalanceRecompute probs from saved LSE (not ); retile; split dQ vs dK/dV; sequence/head parallel; deterministic mode costs extra buffersFastest forward is not always lowest fwd+bwd
T07Decode attention (q_len≈1)Read full K/V; memory-bound; ragged batchPage/block-aware loads; split-KV across CTAs + small reduce; GQA-aware; dynamic load balance; JIT page size/head dim/mask; fuse LSEFlashInfer, flash-attention KV path
T08KV append / gather / quantNoncontiguous pages, metadata, capacityFuse append with RoPE/attention; compact page tables; vector gather; choose K/V interleave by access pattern; block-scaled FP8/INT8/INT4 KV; prefix page sharingPagedAttention / vLLM; vAttention on paging costs
T09GQA / MQA / MLAKV bytes dominate decodeShare KV across Q heads; reuse KV tiles across CTA/warp; MLA compresses to low-rank latentMQA, GQA, DeepSeek-V2 MLA — model cuts bytes first
T10Sparse / local / block attentionIrregular index; low occupancyBlock-sparse / fixed windows; tile indexes; skip empty tiles; compaction + grouped schedule; avoid token-level branchesNative Sparse Attention, Faster Neighborhood Attention
T11Softmax / masked softmaxExp/reduction + HBM; SFU limitsOn-chip per row/tile; online max/sum; warp shuffle; fuse mask/bias/scale; two-stage for long rows; skip negligible blocks when safeTriton fused softmax; Skip Softmax in TensorRT-LLM
T12RMSNorm / LayerNormTwo reductions + R/W; small-H launch-boundSingle-CTA / multi-warp row reduce; vector loads; Welford or sum-of-squares; fuse residual/cast/quant/linear prologueTriton LayerNorm, Transformer Engine normalization, Liger
T13Bias + dropout + residual + stochastic depthPointwise HBM round-trips; mask memoryOne load/store fuse; counter-based RNG; store seed/offset or recompute mask; merge with norm or GEMM epilogueTriton low-memory dropout
T14GELU / SiLU / SwiGLU / GeGLULarge gate/up intermediates; SFUHorizontal fuse gate+up GEMM; SiLU×up in epilogue; validate approximations; recompute in bwdLiger, CODA — megakernels can kill occupancy
T15Embedding gather / scatter bwdIrregular reads; atomics on repeatsVectorized gather; align vocab rows; fuse scale/position/type adds; sort/dedup or warp-local aggregate before atomicOften small, but short sequences + huge vocab/optimizer matter
T16LM-head / logits GEMMHuge B·S × V output; skinny decode GEMMVocab parallel; split/Stream-K; compute only needed tokens; low-precision weights; do not materialize logits — stream tiles into online LSE/lossCut Cross Entropy, Liger fused linear CE
T17Cross-entropy / LSE bwdO(BSV) logits/prob memoryVocab chunk; online max/sum; fuse loss / z-loss / label smoothing / grad; save per-token LSE; recompute local logits in bwdCut Cross Entropy reports 24 GB→1 MB loss memory on one Gemma2-2B setup — shape-dependent
T18Sampling (temp / top-k / top-p / multinomial)Large-V sort/scan; many launchesFuse logits→softmax→filter→sample; rejection sampling vs full sort; CUB/warp scan; device-side RNG; speculative accept/reject fuseFlashInfer sampling post, API
T19LoRA XAB + base linearMany small GEMM/GEMV per adapterSGMV/BGMV by adapter segment; rank buckets; A/B prepack; fuse scale+add into base epilogue; page adapters with KVPunica, S-LoRA
T20Quant / dequant / scale / swizzleConversion eats low-precision winsQuant in producer epilogue; dequant in consumer mainloop; align block/token/channel scales to MMA tiles; fuse amax reductionsTE FP8 primer, blockwise scaling
T21Grad accumulation / multi-tensor scale/norm/clipThousands of tiny tensorsMulti-tensor apply; merge scale/unscale/finite/norm/clip; accumulate FP32 wgrad buffers; bucket with communicationTE advanced optimizations
T22Adam / AdamW / SGDParam/grad/m/v/master multi-pass HBMMulti-tensor fused update; 8-bit blockwise state; stochastic rounding; shard/offload; lazy/step fusionApex FusedAdam, 8-bit optimizers, FlashOptim
T23SSM selective scan / MambaRecurrence; expanded state; small-op chainsChunk/parallel scan; keep state on-chip; fuse proj/conv/gate/scan; recompute in bwd; Mamba-2/SSD rewrite chunks as matmulMamba, Mamba-2/SSD, official impl
T24Long / FFT convolutionFFT transpose/complex intermediatesMap FFT factors to TC matmul; fuse FFT×pointwise×iFFT; length buckets; packed masks; precompute kernel FFTFlashFFTConv, RubiConv

3.1 What “fuse elementwise and GEMM” actually means

The safe high-ROI boundary is usually the GEMM epilogue. For Y = act(XW + b) * gate + residual:

  1. Mainloop accumulates XW on Tensor Cores.
  2. While the accumulator tile is still in register/TMEM, add bias/scale.
  3. Apply activation, gate, residual, dtype convert / quant.
  4. Write final Y to HBM once.

That avoids three-to-four large intermediates. On Blackwell, accumulators live in TMEM, so epilogue traffic and SFU scheduling differ from Hopper; CODA goes further and expresses many non-attention Transformer ops as GEMM + epilogue programs.

Do not fuse blindly when:

  • Per-thread registers explode into spills;
  • Ops want incompatible tiles / parallel axes;
  • Reductions need cross-CTA sync;
  • One producer fans out to many consumers (fusion duplicates work);
  • Dynamic shapes explode JIT variants;
  • Backward recompute turns a compute-bound path slower.

3.2 Four generations of FlashAttention

Attention optimization migrated with the hardware bottleneck

GenerationBinding constraintCore moveNotes
FlashAttention-1S×S HBM IOTiled Q/K/V + online softmaxAlgorithmic IO-awareness; no full attention matrix
FlashAttention-2Non-matmul FLOPs, parallelismFewer rescales/bounds checks; better block/head parallel & warp partitionPaper reports ~50–73% of theoretical FLOPs on A100
FlashAttention-3Underused Hopper async HWTMA producer + WGMMA consumer; warp specialization; matmul/softmax interleave; FP8Pipeline movement, MMA, SFU
FlashAttention-4Blackwell TC ahead of SFU/SMEM; TMEM / 2-CTAFully async MMA; larger tiles; software exp / conditional rescale; TMEM; 2-CTA MMAAuthor notes ~1.6 PFLOP/s BF16 (~71% peak) on specific configs — see Tri Dao’s FA4 post

Lesson: when one resource gets faster, the bottleneck moves. FA4 is not “FA3 ported to Blackwell”; it rewrites the schedule around new resource ratios.

4. MoE: optimize the whole token–expert pipeline

With T tokens, E experts, top-k=K, MoE cost is not “K expert MLPs.” It includes T×E router logits, top-k, counts/offsets, permute, cross-rank dispatch/combine, imbalance tails, and the backward inverse path. For the systems framing of memory / communication / compute walls, see Large MoE Performance on this blog.

MoE is a pipeline

IDKernel / pathMain bottleneckHow to optimizeCo-design & references
M01Router linearMid/small GEMM; large T×ELow-precision GEMM carefully; fuse bias/temperature; keep only top-k stats; shard-aware outputsKeep higher accumulation precision; DeepSeek-V3 aux-loss-free balancing
M02Top-k / gate softmaxPer-token sort/reductionWarp/block selection without full sort; specialize k∈{1,2,8}; fuse softmax+top-k+renormSmall E: one CTA; large E: hierarchical top-k
M03Histogram / prefix-sum / capacityAtomics; multi-pass; CPU syncWarp-local hist → merge; fuse scan/offsets; device-side capacity/drop; persistent queuesCapacity padding simplifies GEMM, wastes FLOPs
M04Token permute / gather / scatterNoncontiguous HBM; full copiesBlocked CSR/COO; vector gather; fuse gate/quant; emit grouped-GEMM-ready layout; reuse inverse map in bwdMegaBlocks, ScatterMoE
M05Expert dispatch All-to-AllSmall messages; cross-node; syncLocality-aware routing; FP8 dispatch+scale; NVLink/IB hierarchy; low-latency vs high-throughput kernels; async events; double bufferDeepEP
M06Expert GEMM-1 (gate/up)Heterogeneous small M; launchesGrouped GEMM; persistent CTAs; token-count buckets; horizontal gate+up; L2 reuseDeepGEMM, TritonMoE, LigerExperts
M07Expert activation / gateLarge T·K·ffn intermediatesFuse SiLU×up into GEMM-1 epilogue or GEMM-2 producer pipeline; recompute in bwdTritonMoE reports ~35% related traffic cut on their fused path — paper-specific
M08Expert GEMM-2 + local combineUneven GEMM; scatter + gate mulGrouped/persistent GEMM; epilogue×gate; scatter-add to token order; warp-local accumulate; on-chip merge of same-token top-kScatterMoE ParallelLinear; SonicMoE on IO-aware tiles
M09Combine All-to-AllInverse permute + network + sum; waits on slow expertsSend as output tiles ready; fuse gate/reduce/scatter after recv; aggregate by source rankTopology and token distribution often beat single-GPU kernels
M10Load balance / drop / shared expertSlow expert sets step tailDevice-side counts; online routing bias; expert replication; shared+routed in parallel; global batch balanceDeepSeek-V3 + DualPipe are co-design outside the kernel
M11MoE backwardInverse permute, grouped dX/dW, gate grad, two A2AsCompact route metadata; recompute acts; persistent/grouped wgrad; overlap dgrad with A2AForward-only benches mislead training ROI
M12MoE mega / fused kernelLaunch / writeback / sync at boundariesPartial megakernels; SM/CTA specialization for comm vs compute; tile queues/barriersComet, FLUX, UniEP

4.1 The right overlap granularity

Bad: full dispatch → all expert GEMMs → full combine.

Better:

  1. Chunk tokens by destination / rank / expert.
  2. Enqueue grouped-GEMM tasks as chunks arrive.
  3. Push completed output tiles into the combine send queue immediately.
  4. Specialize communication vs compute CTAs (or event-driven streams/communicators).
  5. Cap communication CTAs so they do not steal all SM/L2/HBM.

FLUX decomposes then re-fuses communication and computation at fine tiles (paper: up to ~96% communication hidden in some settings). Comet uses threadblock specialization to balance resources. The KPI is exposed communication on the critical path, not “did the NCCL kernel overlap.”

4.2 Megatron-Core MoE map (flags change by version)

As of mid-2026, Megatron-Core 0.17 MoE is a combinator of routing, dispatcher, parallel map, precision, fusion, overlap, and memory strategies. Authoritative sources: Megatron-Core 0.17 MoE docs and NVIDIA’s 2026 MoE tech report.

LayerChoice / flagWhat changesWhen / caveats
Router topology--moe-router-topk; group top-k via --moe-router-num-groups, --moe-router-group-topkGroup top-k aligns routing with node/rack/expert groupsCuts cross-domain traffic; constrains expert choice — train with placement
Router probability--moe-router-score-function softmax/sigmoid; --moe-router-dtype fp32Gate normalization and numeric pathDocs recommend FP32/FP64 router logits at high expert counts
Load balanceaux_loss, seq_aux_loss, global_aux_loss, sinkhorn, aux-loss-free dynamic biasChanges routing distribution and sync needsGlobal balance needs cross-rank stats; aux-loss-free still updates bias state
Dropless / capacity--moe-expert-capacity-factor, --moe-pad-expert-input-to-capacityDropless = dynamic shapes; capacity = fixed/pad/dropCapacity helps CUDA Graph; dropless needs p99 expert-load awareness
AllGather dispatcher--moe-token-dispatcher-type allgatherGather then local select — no classic token A2A, lots of activation replicationTP-only / small EP / large top-k; blows up as EP grows
NCCL All-to-All--moe-token-dispatcher-type alltoallTokens only to target expert ranksStandard EP; small-message / cross-node / dynamic-count costs
Flex + DeepEP--moe-token-dispatcher-type flex --moe-flex-dispatcher-backend deepepDrop cross-node redundant tokens; fused overlapFine-grained cross-node MoE on H100/B200
Flex + HybridEP--moe-flex-dispatcher-backend hybridepTMA / IBGDA; fewer SM for comm; MNNVL/NVL72 pathsStrongly bound to GB200 NVL72-class hardware
Expert compute--moe-grouped-gemm; TE GroupedMLP; FP8/MXFP8One grouped/persistent schedule over heterogeneous MEssential for fine-grained experts
Router / permute fusion--moe-router-fusion, --moe-permute-fusionCollapse router/top-k/aux stats and permute/unpermute/gate pathsVerify numeric modes and FP8 route maps end-to-end
Shared expert--moe-shared-expert-intermediate-size (+ --moe-shared-expert-overlap)Dense shared MLP per token; can overlap with routed A2AChanges model FLOPs/params — not a free kernel win
EP A2A batch overlap--overlap-moe-expert-parallel-comm --delay-wgrad-computeMerge adjacent µbatch fwd/bwd; split dgrad/wgrad for longer hide windowsSchedule/dependency optimization, not a faster collective
MoE Parallel FoldingAttn TP×CP×DP×PP vs MoE ETP×EP×EDP×PPDecouple process-group mapsParallel Folding
FP8 / MXFP8Hopper blockwise FP8; Blackwell MXFP8; route-map padding flagsCut activation/dispatch/param-AG bytes; pad route maps to MMA alignmentRouter usually stays high precision
Fine-grained recompute / offload--recompute-modules …, --fine-grained-activation-offloadingDrop/recompute or D2H specific submodulesPrefer cheap large moe_act; full MoE recompute repeats A2A
CUDA GraphFixed capacity or --cuda-graph-scope attnDropless shape instability vs launch savingsDo not pad huge token counts just for graphs
Dense→MoE upcycling--moe-use-upcycling, granularity flagsSplit/copy dense FFN into experts from a checkpointTraining/init strategy — reshapes grouped GEMM and comm ratios

Recommended triage order: model semantics → parallel mapping (keep EP×ETP on NVLink/MNNVL; fold Attn vs MoE) → dispatcher → GroupedGEMM + router/permute fusion + FP8 recipe → shared-expert / batch A2A overlap / CUDA Graph / recompute-offload (ablate — contention is common).

5. Cross-rank communication, parallelism, and scheduling

IDPathBottleneckHow to optimizeSystems / notes
C01AllReduce (TP/DP)Large messages; sync; topologyRing vs tree; NVLS/NVLSTree/CollNet; bucket; RS+AG decomposition; topology-aware ranksNCCL env / algorithms
C02ReduceScatterGrad / row-col parallel outputsChunk pipeline; RS as soon as compute tiles finish; low-precision comm + high-precision accumulateOften more natural than full AR for TP/FSDP
C03AllGatherNext-layer params/acts; peak memoryPrefetch next FSDP unit; consume by chunk; double buffer; swizzle before consumerMegatron-FSDP: overlap often keeps two units resident
C04TP linear overlapCoarse GEMM↔AG/RS depsSlice sequence/batch/M/N; independent streams; overlap dgrad RS with wgrad GEMMMegatron TP config
C05FSDP/ZeRO AG + grad RSPer-layer traffic vs capacityLayer/unit prefetch; flat buffers; stream separation; optimizer shard/offloadZeRO, ZeRO++
C06Pipeline P2PBubble; activation bytes1F1B / interleaved; virtual stages; µbatch tune; overlap P2P; activation quantPTD-P
C07Context / sequence parallel attentionCross-rank KV/actsUlysses A2A head↔sequence; Ring Attention streaming KV; USP combinations; overlap ring with tilesUlysses, Ring Attention, USP, DistFlashAttn
C08MoE All-to-AllSee M05/M09Hierarchical A2A; node-limited routing; FP8; chunk overlapEP scale-up is often sublinear once IB dominates
C09Fused compute + collectiveOp-boundary HBM/syncTile-complete reduce/send inside GPU kernels; fused AllReduce–RMSNorm; persistent distributed queuesFused communication, TokenWeave, TileLink
C10Graph launch / runtimeHundreds of µkernels; CPU dispatchCUDA Graph; torch.compile regions; persistent megakernels; shape buckets; device-side schedulerstorch.compile; FlashInfer load-balanced scheduler
C11Cross-op / multi-GPU persistent megakernelPer-op barriers and HBM edgesLower graph to SM-level tile graph; software pipeline across ops; in-kernel communicationMirage Persistent Kernel, ParallelKittens — high engineering cost

5.1 Four levels of overlap

LevelPracticeCan it hide communication?
L0 SequentialCollective after GEMM finishesNo
L1 Stream overlapWhole-tensor collective
L2 Chunk overlapSlice tensor; communicate chunk i while computing i+1Usually best ROI; Megatron / Domino-style
L3 Tile / CTA fusionCommunicate as tiles complete; specialize CTAsFinest grain; hardest; most hardware/topology bound

Domino splits tensors and batches into independently advancing pieces. Measure with Nsight Systems:

[ T_{\text{exposed-comm}} = T_{\text{step}} - T_{\text{ideal-compute-only}} - T_{\text{other}} ]

Do not sum stream durations. Contended NCCL kernels can look “longer” while the critical path shortens.

6. Multimodal: vision, audio, video, fusion

Three layers matter:

  1. Input pipeline — decode, resize, crop, normalize, resample, STFT/mel: GPU/HW decode, async prefetch, fewer layout copies.
  2. Modality encoders — mostly Transformer/conv kernels, but token count, window/spatiotemporal sparsity, and ragged packing dominate.
  3. Fusion & losses — projectors/resamplers, cross/joint attention, contrastive similarity, generative LM loss: kill padding, avoid / materialization, reduce global sync.
IDPathBottleneckHow to optimizeCo-design & references
V01JPEG/PNG/video decodeCPU serial; host copiesGPU/NVJPEG / HW decoder; decode+crop; pinned + async prefetch; resolution bucketsDALI image_crop decoder
V02Resize / crop / color / normalize / HWC↔CHWMany BW-bound passesFuse crop-resize-normalize-cast-layout; vectorized loads; emit model dtype/layoutKeep decoder output layout aligned with patch embed
V03Patchify / patch embeddingunfold/im2col materializationStrided Conv2D / implicit GEMM; fuse normalize/cast; channels-last; CLS/pos in epilogueViT; cuDNN Graph API
V042D/3D RoPE / vision PECoord gen + elementwisePrecompute/compress coords; vectorized rotations; fuse into QK / attention prologueQwen2-VL M-RoPE
V05Global vision attentionMany image tokens; ragged resolutionsFlashAttention varlen; packing + cu_seqlens; tile masks; fused QKV; CP for long imagesNaViT; NeMo packed sequence
V06Window / neighborhood attentionPartition/reverse copies; small matsNo window materialization; address calc in-kernel; window BMM; fuse shift/maskNeighborhood Attention, Faster NA
V07Token prune / merge / poolSelection/reindex overheadBlock/warp top-k; compaction + prefix sum; fixed budgets; consume compact layout next layerWorth it only if later layers shrink — prune at layer ends
V08Dynamic resolution / multimodal packingPadding to max image/videoPack by token budget; varlen offsets; resolution buckets; packed attention isolation; joint loss/position metadataQwen2-VL, Qwen2.5-VL, Open-Qwen2VL, VeOmni
V09Vision/audio projectorRagged inputs; layout copiesPack then one large GEMM; fuse gate+up/norm; write LLM embedding layout; FP8Layout/padding often cost more than the GEMM
V10Resampler / Q-Former / PerceiverCross-attn over many modality tokensFixed latent queries; IO-tiled cross-attn; cache K/V; fixed latent count for CUDA GraphPay one cross-attn to shrink every later LLM layer
V11Cross-modal / joint attentionHeterogeneous lengths; complex masksTile-local block masks; modality-specific RoPE/bias fused; cache static-modality K/VEarly fusion raises interaction and ; late/cross-attn enables KV cache
V12CLIP-style similarity GEMMGlobal embedding AllGather; B_global²Fuse normalize+cast; overlap AG with local similarity tiles; 2D tiling; do not store full pairwise matrixGlobal negatives couple objective and communication
V13Contrastive softmax / sigmoid lossRow/col LSE; logitsChunked online LSE; stream similarity tiles into loss; recompute tiles in bwdSigLIP pairwise sigmoid changes global-norm needs — negatives still matter
V14Mixup / CutMix / random eraseHost/device round-tripsFuse with decode/normalize; device RNG; in-place; sync label mixHeavy aug can dominate step time
V15–V17Audio decode / STFT / mel / CMVNVariable length; FFT plans; sparse melGPU decode; length buckets; batched cuFFT; fuse window→mag→mel→log; Welford CMVNDALI ops, spectrogram example, mel filter bank
V18Audio subsample conv / encoder attnRagged padding; long audio attnPacked/bucketed conv; channels-last; varlen FA; chunked/streaming KVStreaming fixed chunks stabilize shapes, change receptive field
V19CTC / RNN-T DP lossT×U×V stateLog-space scan; keep DP frontier only; chunk vocab projection; length buckets; recompute bwdNVIDIA CTC/WFST memory note
V20Video tubelet / 3D patch embed3D decode/resize; token explosionTubelet Conv3D implicit GEMM; temporal stride; packed tokensTemporal/spatial stride is first-order token co-design
V21Video temporal/spatial attention(T·H·W)²; cross-frame redundancyFactorized / window / block sparse; KV/feature cache; FP8+structured sparsity tiles; CP; frame/patch pruneFPSAttention, video sparse attention

6.1 Multimodal priority is usually tokens, not patch kernels

Approx. VLM cost with visual tokens (S_v): per-layer linear ~(O((S_t+S_v)H^2)), global attention ~(O((S_t+S_v)^2 H)).

  • 2× faster patch embedding touches one shallow op.
  • 2× fewer (S_v) cuts linear, attention, activation, KV, and communication on every later layer.
  • Removing 40% padding via packing compounds the same way without changing semantics.

That is why NaViT native-resolution packing, Qwen2-VL dynamic resolution, resampler latents, and video spatiotemporal sparsity so often beat an isolated CUDA micro-optimization. Practical one-GPU stacking notes: Optimizing VLM Training on One GPU.

7. Diffusion, DiT, U-Net, generative video

Diffusion’s distinctive structure is “the same denoiser, many times.” Optimize reuse across timesteps, solver step count, CFG branching, and cross-device patch/pipeline — not only per-step kernels.

IDPathBottleneckHow to optimizeCo-design & references
D01Text encoder / conditioningRepeated across stepsFA / fused MLP; cache prompt embeddings/KV; batch prompts; cache negative promptsDo not re-run text encoder every denoising step
D02U-Net Conv2D/Conv3DLarge feature-map BW; workspacecuDNN/MIOpen autotune; NHWC; TC conv; implicit GEMM; conv+bias+act fuse; reuse skip bufferscuDNN Graph API
D03GroupNorm + SiLU + scale/shiftReduction + pointwise chatterSingle-CTA/warp group reduce; fuse norm+affine+SiLU + conditioning scale-shiftMany small ops; total share is large
D04ResBlock / skip concatFeature copies; concat materializationFuse residual with norm/act; view/offset concat or dual-source next conv; careful in-placeCheckpoint high-res blocks first
D05U-Net self/cross attentionHigh-res tokens; repeated stepsFA/SDPA; fused QKV; cache prompt K/V; window/local; attention slicing only if capacity-boundConditioning cacheable; Q from changing features is not
D06DiT / MMDiT linear + attentionMany image/video tokens; multimodal weightsReuse T01–T14; FA; gate+up; FP8/FP4; CP; joint attention masks; patch packingDiT, SD3 / MMDiT
D07AdaLN / modulationMany elementwise passes from timestep/condBatch small modulation GEMMs; fuse norm+modulation+residual gateHigh frequency in DiT — excellent vertical fusion target
D08Timestep / sinusoidal embeddingTiny kernels; launch noiseVectorize / table sin/cos; CUDA Graph embedding MLP; keep scheduler scalars on deviceRarely worth more engineering than the denoiser path
D09Classifier-free guidance2× denoiserBatch as 2B; CFG-parallel across devices; fuse u + s(c-u); guidance distillation removes the second passxDiT; 2B raises peak memory
D10Scheduler / noise updateMany scalar pointwise kernels; host syncFuse scale/guidance/variance/clamp/x_t→x_{t-1}; device RNG; graph whole stepFewer steps via DPM-Solver / LCM is algorithmic co-design
D11VAE encode/decodeHigh-res conv; peak activationTiled encode/decode with overlap blend; channels-last; fused QKV; pipeline decode with postprocessDiffusers AutoencoderKL
D12Cross-timestep feature cacheAdjacent-step redundancyCache stable high-level blocks; skip by change metric; layered intervals; keep consumer layoutsDeepCache, TeaCache — validate quality across prompts/resolutions/steps
D13Diffusion quantActivation outliers; conversion taxNative W8A8/FP8/INT4 kernels; per-token/channel/block scales; dequant+bias in epilogue; keep sensitive layers high precisionSVDQuant; INT8 DiT fused GEMM — unfused quant can be slower
D14Patch / pipeline parallelSingle-sample latency; per-step device trafficSpatial patches; displaced/async boundaries from prior-step features; PipeFusion + sequence parallel + CFG parallelDistriFusion, PipeFusion, xDiT
D15Video diffusion attention / temporalHuge spatiotemporal tokens; multi-stepSpatiotemporal factorization, window/block sparsity, CP, FP8, cache, pruneToken/step reduction usually beats micro-tuning

7.1 Do not mix three kinds of speedup

CategoryExamplesWhat changedRisk
KernelFused GroupNorm–SiLU, FA, FP8 GEMMOp implementationUsually semantics-preserving; watch numerics
Runtime / systemCUDA Graph, DistriFusion, PipeFusion, CFG parallelSchedule, devices, communicationTopology/shape binding; peak memory; bubbles
Algorithm / modelFew-step solvers, LCM, DeepCache/TeaCache, sparse attnCall count or compute graphQuality / stability / generalization

Report ablations separately. “8 steps instead of 50” is not a kernel win.

8. Memory system: six levers, not only checkpointing

LeverTypical movesSavesCostsBest when
DematerializeFA, fused linear-CE, GEMM epilogue, implicit GEMM, view concatIntermediate acts/logits/windowsHarder kernels; possible recomputeAlmost always first
Low precision / compressFP8/FP4, INT8/INT4, 8-bit optim, quantized KVParams, KV, optimizer, comm bytesScales, conversion, accuracyDecode, huge train, bandwidth-bound comm
Pack / page / layoutVarlen packing, PagedAttention, LoRA paging, prepackPadding, fragmentation, copiesIndirection, metadata, variantsDynamic serving, multimodal ragged
RecomputationSelective activation CKPT; recompute attention probsForward activationsBackward FLOPs/latencyCapacity-bound + cheap recompute
Shard / offload / prefetchFSDP/ZeRO, CPU/NVMe offload, layer prefetchResident params/grads/optPCIe/network, double buffersBeyond single-GPU/node capacity
Lifetime / allocatorStatic buffers, workspace pools, in-place, CUDA Graph poolsFragmentation & overlapping peaksStatic address/shape constraintsStable serving shapes; long training

8.1 By object

Parameters & optimizer. BF16 weights + FP32 master + FP32 m/v can dwarf the weights. FSDP/ZeRO is the capacity lever; fused/8-bit optimizers are the bandwidth/state lever. INT4 weight-only becomes decode speed only with prepacked layout + dequant-in-mainloop (Marlin-class designs). FP8/MXFP8/NVFP4 scale granularity must match GEMM tiles; TE distinguishes communication-compact vs GEMM-ready layouts and swizzles between them.

Activations. Dematerialize first, checkpoint second. Prefer selective recompute on “large storage, cheap FLOPs” ops. Reducing Activation Recomputation in Large Transformer Models combines sequence parallel with selective recompute. PyTorch’s activation checkpointing techniques and compile min-cut partitions help — until graph breaks intervene.

KV cache. Capacity ≈ layers × tokens × KV_heads × head_dim × 2 × bytes. GQA/MQA cut heads; MLA uses low-rank latents; quant cuts bytes; paging cuts fragmentation; prefix sharing cuts duplicates. Smaller pages → less fragmentation, more indirection; larger pages reverse that. KV quant must include scale reads and dequant; decode is usually BW-bound, so a little extra arithmetic often still wins.

Workspace & allocator. Faster cuBLASLt/cuDNN/CUTLASS/collective algos may want large workspace — OOM is not always “model tensors.” Preallocate max workspace; avoid per-token cudaMalloc; CUDA Graph wants stable addresses. For dynamic serving, track allocated / reserved / payload / fragmentation / page metadata separately from max_memory_allocated.

8.2 Sequence packing boundaries

Packing kills padding only if attention knows segment edges:

  • Describe segments with cu_seqlens / offsets;
  • Reset causal masks inside each segment;
  • Remap position ids, RoPE/M-RoPE, and loss masks together;
  • Persist multimodal special tokens, image grids, audio time indexes with pack metadata;
  • Honor boundaries in backward and context parallel.

Concat + vanilla causal attention leaks across samples. See also Why Variable Sequence Length Breaks DDP Throughput.

9. Compilers, DSLs, libraries, megakernels

LayerBest forStrengthLimits
cuBLASLt / cuDNN / NCCL / hipBLASLt / MIOpen / RCCLStandard GEMM/conv/collectivesVendor-tuned, broad coveragePass real shape/layout/epilogue/workspace; library edges leave fusion gaps
CUTLASS / CuTe / Composable KernelHW-specific GEMM, attention, grouped GEMM, epiloguesFine control of tile/pipeline/TMA/WGMMA/TMEMHigh maintain cost; retune per GPU gen
TritonPointwise/reduction/fused norm/loss, custom GEMM, NVIDIA/AMD prototypesPython DSL + autotuneExtreme async / newest ISA / lowest-bit kernels may still need CuTe/CUDA/HIP
torch.compile / TorchInductorGraph-level horizontal/vertical/epilogue fusion, memory planningNo model rewrite; improving dynamic shapesGraph breaks / data-dependent control / custom ops shrink regions — see torch.compile mental model
nvFuser / XLA / MLIR-classSubgraph fusion + codegenAutomatic combination searchNeeds good cost models; compile time / variant explosion
Specialized libsFA/FlashInfer, TE, Liger, DeepGEMM/DeepEP, MarlinAlgorithm × hardware × shape co-designedAPI/layout/version/HW constraints — A/B end-to-end
Persistent megakernelDecode, small-op chains, cross-op/cross-GPU pipelinesCuts launch/HBM boundariesRegisters/SMEM, debugging, preemption, portability

Further reading: TorchInductor design notes, torch.compile tutorial, Triton persistent matmul, block-scaled matmul, ThunderKittens.

Division of labor that usually works:

  1. Compile away peripheral pointwise/reshape/simple reduction/epilogue; clear graph breaks.
  2. Call specialized kernels for attention, linear-CE, MoE, low-bit GEMM, decode KV, sampling.
  3. Unify layouts at those boundaries so transpose/cast/contiguous copies disappear.
  4. AOT/autotune-cache hot shapes; robust fallbacks for the long tail.
  5. Only write a megakernel when profiles prove the op boundary itself is top bottleneck and shapes are stable.

10. Model–kernel co-design that actually moves the needle

Model / algorithm changeWhat happens in kernelsMain winCost / risk
MQA / GQAShared KV; one KV tile serves more Q headsKV cache & bandwidth scale with KV headsQuality/migration; kernels must actually reuse
MLALow-rank latent KV; absorb some projectionsMuch smaller KV; better long-context decodeComplex transforms; specialized RoPE/latent paths
Native / block sparse attentionSchedule only selected blocksAvoid useless FLOPs/bytesIndexing, training stability, utilization
FlashAttentionOnline softmax + tiling (math-equivalent)No materializationHW-specific; mask/dropout/head-dim variants
SwiGLU + fused gate/upShared input read; epilogue multiplyOne fewer X read; no gate/up writebackWeight concat / TP shard / layout alignment
Fused linear CELogits GEMM tiles stream into online lossKill BSV logitsBwd recompute; cover complex loss semantics
Dropless block-sparse MoEDynamic token→expert → grouped/block-sparse GEMMAvoid capacity pad/dropImbalance + tiny experts; comm may dominate
Aux-loss-free / locality routingRouting controls load and network destinationsLess tail / cross-node A2A / objective interferenceTraining algorithm change; long-run stability
Dynamic visual res + packingSchedule only real visual tokens; varlen attnEvery later layer’s FLOPs/acts/KV/comm dropDynamic shapes; quality vs budget; metadata
Resampler / fixed latentsOne cross-attn → fixed token countStable LLM path; graph-friendlyInformation bottleneck; front-end cross-attn cost
Sigmoid contrastive lossNo global softmax norm; stream pairwise tilesEasier chunking; weaker global-norm couplingNegatives still designed/communicated
Mamba scan / SSDRecurrence via scan or chunk matmulLinear sequence cost; small stateDifferent expressivity/parallelism; custom kernels
Diffusion feature cacheSkip low-change blocks across stepsFewer full layer callsApprox error across prompts/steps
Few-step diffusion / distillationFar fewer network invocationsMultiplicative E2E gainRetrain / quality tradeoffs
Quant-aware architectureOutlier redistribute / low-rank absorb / scale-friendly blocksMakes INT4/INT8/FP8 native kernels usableCalibration, training complexity, HW format binding
CP-friendly head layoutHead/sequence splits match collectivesPipeline attention with communicationTopology binding; short sequences may lose

10.1 Two judgment criteria

A — Does the win compound across layers? Fewer tokens / KV / denoising steps ride through tens or hundreds of layers. A 2× faster projector does not.

B — Does the new structure map to regular tiles? Block sparsity, fixed latents, small top-k experts, and block scaling tend to run well. Random token-level sparsity and arbitrary tiny ragged ops often look great on paper FLOPs and lose to dense on GPUs.

10.2 Parallel decoder / Parallel Transformer Block

Here “parallel” is not tensor or pipeline parallel. It rewrites one decoder block’s dependency graph.

Serial pre-norm:

[ u=x+\operatorname{Attn}(\operatorname{Norm}_a(x)),\qquad y=u+\operatorname{MLP}(\operatorname{Norm}_m(u)) ]

Parallel Transformer Block (PaLM / shared-norm form):

[ z=\operatorname{Norm}(x),\qquad y=x+\operatorname{Attn}(z)+\operatorname{MLP}(z) ]

Falcon-style separate-norm variant:

[ y=x+\operatorname{Attn}(\operatorname{Norm}_a(x))+\operatorname{MLP}(\operatorname{Norm}_m(x)) ]

Because MLP no longer depends on attention output, systems gain scheduling freedom: branch-level parallelism, shared input/norm reads, horizontal QKV vs gate/up scheduling, potential collective merge after local branch combine, and freer backward reordering. It does not magically cut major GEMM FLOPs, and concurrent branches can contend for Tensor Cores, HBM, L2, and SMs.

PaLM uses parallel layers. MegaScale applies PTB in Megatron-LM and pipelines SP/TP AllGather/ReduceScatter with FFN linears; on a 175B / 256-GPU ablation they report MFU 47.7%→52.3% (+4.6 pp), and 53.3% with sliding-window attention — workload-specific. NeMo’s Megatron-Core customization docs list Falcon’s parallel-attention/MLP variant.

NameWhat changedChanges model semantics?
Parallel Transformer BlockAttn ∥ MLP inside one blockYes — needs train/continued-pretrain validation
Tensor ParallelismColumn/row shard weights & actsUsually math-equivalent (reduction order)
Pipeline ParallelismLayers across stages + µbatchesUsually math-equivalent; schedule/bubble change
Blockwise Parallel TransformerStream attention/FFN along sequence blocksCan be math-equivalent IO algorithm — different idea (BPT)

PTB is worth considering for full pretraining (or large continued-pretrain budget) when attention and MLP durations are comparable or one branch can cover the other’s collectives, TP/SP layouts allow clean merge, and schedulers can limit resource fights. It is usually not a lossless kernel swap onto an existing Llama-class checkpoint for short fine-tunes.

10.3 Algorithmic speedups to book separately

ChangeGraph changeWhere systems winExtra validation
PTB / parallel decoderAttn ∥ MLPShorter deps; shared input; more collective overlap spaceCheckpoint compat, convergence, branch contention
Sliding-window / local–global layersS·W (+ few global layers)Sparse/local tiles; less KV/CP trafficReceptive field; long-range quality
MQA/GQA/MLAFewer KV heads / latent KVDecode KV bytes/cache/networkQuality; conversion
Multi-Token PredictionExtra future-token headsAmortize hidden state; aids speculative decodingExtra train GEMM/loss; accept rates
Parallel FoldingSeparate Attn vs MoE process groupsAttn high TP/CP; MoE low ETP/high EPPP boundaries; shard maps
Shared + routed expertsDense branch + top-k sparseShared compute can cover A2AExtra FLOPs/replication; overlap contention
Group top-k / locality routingSelect group then expertLess cross-node trafficQuality vs load bias
Aux-loss-free routingDynamic expert biasStable grouped GEMM/A2A without aux-loss interferenceBias stability; early OOM
Dense→MoE granular upcyclingSplit/copy dense FFNReuse checkpoint; new expert shapesCollapse; fine-expert comm share
Attention–SSM hybridSome layers linear recurrenceLinear long-seq scan; few global attn layersState/kernels; CP mapping; quality
Dynamic visual tokens / resamplerCompress modality tokensEvery later layer shrinksDetail loss; dynamic shapes
Diffusion cache / few-step solversSkip layers or cut callsCross-timestep reuse multipliesQuality/generalization/stability
Large-batch optimizer/schedule co-designBigger global batch / different µbatch–PP phaseLess pipeline bubble; better GEMM/comm amortizationSample efficiency; final quality

Book these as algorithmic speedup, then ablate against kernel, communication, and runtime gains — otherwise you cannot tell whether you won by computing less, rewriting the graph, hiding communication, or making one op faster.

11. Priority lists by scenario

Dense LLM training

  1. Confirm BF16/FP8 GEMM and FlashAttention are actually running; clear layout/cast fallbacks.
  2. Fused RMSNorm/RoPE/SwiGLU and fused linear-CE to kill large intermediates/logits.
  3. Sequence packing + selective recompute for padding and activation peaks.
  4. Chunk-overlap TP/FSDP AG/RS with GEMM; then pipeline schedule.
  5. Fused optimizer / multi-tensor grad norm; only then chase embeddings and tiny pointwise.

LLM prefill / high-throughput serving

  1. FlashAttention varlen + continuous batching for the right head dim / mask / precision.
  2. Large-GEMM epilogue fusion, FP8, shape buckets, CUDA Graph.
  3. Paged KV writes, prefix sharing, chunked prefill to protect decode.
  4. TP collective overlap; jointly schedule TTFT, throughput, and decode p99 — not only prefill TFLOP/s.

LLM decode / low-latency serving

  1. Cut KV bytes first: MQA/GQA/MLA, KV dtype, context, page/prefix hits.
  2. Paged / split-KV decode attention; JIT/autotune batch/head/page.
  3. INT4 weight-only / FP8 GEMV–small GEMM; continuous batching; persistent kernels.
  4. CUDA Graph, fused sampling, LoRA SGMV/BGMV; shrink CPU scheduler/launch.
  5. Multi-GPU: account for per-token TP AllReduce — small batches can be network-latency dominated.

MoE train / serve

  1. Plot token→expert/rank histograms and stage times — is it GEMM, permute, A2A, or tail?
  2. Grouped/persistent GEMM + fused gate/up/activation/combine.
  3. DeepEP-class dispatch/combine; FP8; hierarchical topology; chunk overlap.
  4. Routing locality, placement/replication, capacity/dropless policy.
  5. Only then micro-optimize router/top-k or bet on a full-path megakernel.

VLM / image / video / audio

  1. Measure effective tokens vs padding; dynamic resolution, buckets, packing.
  2. Async decode/resize/normalize/resample/STFT into target dtype/layout.
  3. Varlen attention, conv fusion, local/spatiotemporal sparsity in encoders.
  4. Align projector/resampler with LLM layouts; fixed latents buy backend shape stability.
  5. Contrastive: chunk similarity/loss and analyze AllGather; generative VLMs reuse LLM loss tricks.

Diffusion / DiT / video generation

  1. Break down one step (conv/attn/GEMM, CFG, scheduler, VAE) × step count.
  2. BF16/FP8, FA/SDPA, channels-last, compile, fused QKV/norm/act.
  3. Prompt/KV cache, CUDA Graph, CFG batching/parallel, scheduler fusion.
  4. DeepCache/TeaCache / few-step solvers — report quality separately.
  5. Multi-GPU single-sample: DistriFusion / PipeFusion / xDiT; topology and resolution set break-even.

12. Reproducible benchmarking & profiling

From end-to-end to kernel

  1. Freeze the workload: model commit, dtype, batch/token budget, length/resolution distribution, train vs serve mode, hardware, topology, software versions, power/clocks.
  2. E2E baseline: train → step time / tokens/s / MFU / peak memory; serve → TTFT, TPOT, tokens/s, p50/p95/p99, KV footprint; diffusion → latency + quality metrics.
  3. Nsight Systems / rocprof: holes, CPU launch, copies, exposed collectives, stream overlap, tails.
  4. Nsight Compute / ROCm Compute Profiler: roofline, TC/MFMA, HBM/L2, occupancy, spills, SMEM/LDS, warp stalls, branches, wave quantization on top kernels.
  5. Microbench real shapes from histograms — not only tidy 4096³. Include warmup, JIT/autotune, workspace, layout conversion.
  6. Return to E2E after each swap: new copies, graph breaks, comm contention, allocator behavior, or quality loss can erase kernel wins.

Fields worth reporting per kernel

CategoryFields
InputB/S/H/V/D, ragged distribution, dtype, layout, alignment, mask/sparsity, page size, top-k/expert histogram
HardwareGPU SKU/count, SM/CU, HBM, interconnect/topology, power/clock, MIG/shared state
SoftwareDriver, CUDA/ROCm, PyTorch, compiler, kernel/library commit, flags, deterministic/TF32
PerformanceLatency distribution, GB/s, TFLOP/s, useful FLOPs, launches, workspace, peak memory, exposed comm
ResourcesRegisters/thread, SMEM/LDS/CTA, occupancy, active warps, L2 hit, spill, TC util
CorrectnessAbs/rel error, ULP/distribution, grads, loss curves, convergence, task quality, seeds/dropout
End-to-endTokens/s, step time, TTFT/TPOT/p99, cost/energy; same batch/quality vs baseline

Common benchmark mistakes

  • Mixing theoretical FLOPs (including skipped padding/sparse blocks) with executed FLOPs.
  • Giving the new kernel prepacked inputs while charging the baseline for conversion.
  • Only testing large steady batches when serving is dynamic small-batch + long-tail context.
  • Forward-only numbers for training decisions.
  • Comparing CUDA-Graph’d launches against a Python/CPU-scheduled baseline.
  • Quant GEMM without calibration / dequant / scale / quality / unsupported-shape fallbacks.
  • Summing overlapped stream durations instead of critical path / exposed communication.
  • Average expert load instead of p99 expert/rank load.
  • Diffusion latency without steps, resolution, CFG, seed, scheduler, and quality.
  • Numeric checks on one random tensor — miss extremes, NaN/Inf, long sequences, masks, empty experts, tail pages, unaligned shapes.

For an end-to-end PyTorch profiling workflow, see Profiling a PyTorch Training Job End to End.

13. An executable decision tree

flowchart TD A["End-to-end profile"] --> B{"What time is exposed?"} B -->|HBM / intermediates| C["Fusion / packing / low precision / paging"] B -->|Tensor Core / MFMA| D["Tile / pipeline / layout / Stream-K"] B -->|Communication| E["Cut bytes / topology / chunk overlap"] B -->|Launch / dynamic imbalance| F["Graph / persistent / grouped schedule"] C --> G["Re-measure E2E + numerics"] D --> G E --> G F --> G G --> H{"Near a resource ceiling?"} H -->|No| A H -->|Yes| I["Model co-design: fewer tokens / KV / experts / steps"]

If you only have a month of engineering time

  • Week 1: Shape/time/bytes dashboard; clear graph breaks, fallbacks, explicit copies; freeze a correctness harness.
  • Week 2: Integrate/upgrade mature specialized kernels (FA / TE / Liger / DeepGEMM / Marlin / FlashInfer, …) and unify layouts.
  • Week 3: One or two fused kernels on the largest memory-bound path; chunk overlap on the largest communication path.
  • Week 4: E2E tuning, long-tail shape/failure fallbacks, numerics/convergence, p99 / multi-node retest; lock a regression matrix.

Do not start by writing a megakernel. That investment pays when profiles show the op boundary itself is the top bottleneck and shapes/deployments are stable enough to amortize the cost.

14. Primary-source index

Attention, KV, serving

GEMM, fusion, precision, training kernels

MoE, distributed systems, communication

Multimodal, diffusion, other architectures

Hardware / tooling docs cited inline

15. Closing judgment

In 2026, foundation-model kernel work is four-layer co-design:

  1. On-chip dataflow — tiles, async copy, warp specialization, TMEM/LDS, epilogues;
  2. Operator graph — fusion, recompute, layout, paging, persistent scheduling;
  3. Multi-GPU dataflow — collective decomposition, tile overlap, topology, expert/token scheduling;
  4. The model itself — GQA/MLA, sparse attention, dynamic visual tokens, MoE routing, SSM, diffusion cache / fewer steps.

The strongest recipes usually move two or three layers at once:

  • MLA + paged/quantized KV + split-KV decode kernel
  • Dropless MoE + grouped GEMM + DeepEP + tile-level overlap
  • Dynamic resolution + multimodal packing + varlen FlashAttention
  • DiT + FP8 fused GEMM/attention + temporal cache + patch parallel
  • Parallel decoder block + TP/SP chunk overlap + fused branch output/collective
  • MoE Parallel Folding + GroupedGEMM + Flex dispatcher + shared-expert/A2A overlap

So the right question is not “which kernel is fastest?” It is: under real shapes, real topologies, and real precision constraints, which model expression and data layout make critical bytes cross HBM/network as rarely as possible — and keep the remaining compute saturating the machine?