LeetLLM
My PlanLearnGlossaryTracksPracticeBlog
LeetLLM

Your go-to resource for mastering AI & LLM systems.

Product

  • Learn
  • Glossary
  • Tracks
  • Practice
  • Blog
  • RSS

Legal

  • Terms of Service
  • Privacy Policy

© 2026 LeetLLM. All rights reserved.

All Topics
Your Progress
0%

0 of 196 articles completed

🛠️Computing Foundations0/9
Git, Shell, Linux for AIDocker for Reproducible AIPython for AI EngineeringNumPy and Tensor ShapesCUDA for ML TrainingMPS & Metal for ML on MacData Structures for AISQL and Data ModelingAlgorithms for ML Engineers
📊Math & Statistics0/9
Gradients and BackpropVectors, Matrices & TensorsLinear Algebra for MLAdam, Momentum, SchedulersProbability for Machine LearningBayesian Inference from EvidenceStatistics and UncertaintyDistributions and SamplingHypothesis Tests, Intervals, and pass@k
📚Preparation & Prerequisites0/13
Neural Networks from ScratchCNNs from ScratchTraining & BackpropagationSoftmax, Cross-Entropy & OptimizationRNNs, LSTMs, GRUs, and Sequence ModelingAutoencoders and VAEsThe Transformer Architecture End-to-EndLanguage Modeling & Next TokensFrom GPT to Modern LLMsPrompt Engineering FundamentalsCalling LLM APIs in ProductionFirst AI App End-to-EndThe LLM Lifecycle
🧮ML Algorithms & Evaluation0/15
Linear Regression from ScratchLogistic Regression and MetricsDecision Trees, Forests, and BoostingReinforcement Learning BasicsValidation and LeakageStatistical Learning and GeneralizationConformal Prediction and UncertaintyClustering and PCAProbabilistic Generative ModelsCore Retrieval AlgorithmsDecoding AlgorithmsExperiment Design and A/B TestingCausal Inference and CounterfactualsPyTorch Training LoopsDataset Pipelines and Data Quality
📦Production ML Systems0/6
Feature Engineering for Production MLBatch and Streaming Feature PipelinesGradient Boosted Trees in ProductionRanking and Recommendation SystemsForecasting and Anomaly DetectionMonitoring Predictive Models
🧪Core LLM Foundations0/8
The Bitter Lesson & ComputeBPE, WordPiece, and SentencePieceStatic to Contextual EmbeddingsPerplexity & Model EvaluationFile Ingestion for AIChunking StrategiesLLM Benchmarks & LimitationsInstruction Tuning & Chat Templates
🧰Applied LLM Engineering0/25
Dimensionality Reduction for EmbeddingsCoT, ToT & Self-Consistency PromptingFunction Calling & Tool UseMCP & Tool Protocol StandardsContext EngineeringPrompt Injection DefenseResponsible AI GovernancePrivacy-Preserving Machine LearningData Labeling and Human FeedbackEvaluating AI AgentsProduction RAG PipelinesHybrid Search: Dense + SparseReranking and Cross-Encoders for RAGRAG Evaluation for Reliable AnswersLLM-as-a-Judge EvaluationBias & Fairness in LLMsHallucination Detection & MitigationLLM Observability & MonitoringExperiment Tracking with MLflow and W&BPrompt Optimization with DSPyModel Versioning & DeploymentSemantic Caching & Cost OptimizationLLM Cost Engineering & Token EconomicsModel Gateways, Routing, and FallbacksDesign an Automated Support Agent
🎓Portfolio Capstones0/9
Capstone: Delivery ETA PredictionCapstone: Product RankingCapstone: Demand ForecastingCapstone: Image Damage ClassifierCapstone: Production ML PipelineCapstone: Document QACapstone: Eval DashboardCapstone: Fine-Tuned ClassifierCapstone: Reproducible ML Study
🧠Transformer Deep Dives0/8
Sentence Embeddings & Contrastive LossEmbedding Similarity & QuantizationScaled Dot-Product AttentionVision Transformers and Image EncodersPositional Encoding: RoPE & ALiBiLayer Normalization: Pre-LN vs Post-LNMechanistic InterpretabilityDecoding Strategies: Greedy to Nucleus
🧬Advanced Training & Adaptation0/17
Scaling Laws & Compute-Optimal TrainingPre-training Data at ScaleBuild GPT from Scratch LabJAX for PyTorch ResearchersContinued Pretraining for Domain ShiftSynthetic Data PipelinesSupervised Fine-Tuning PipelineMixed Precision TrainingDistributed Training: FSDP & ZeROLoRA & Parameter-Efficient TuningTraining Run OperationsReward Modeling from Preference DataRLHF & DPO AlignmentConstitutional AI & Red TeamingRLVR & Verifiable RewardsKnowledge Distillation for LLMsModel Merging and Weight Interpolation
🤖Advanced Agents & Retrieval0/16
Vector DB Internals: HNSW & IVFAdvanced RAG: HyDE & Self-RAGGraphRAG & Knowledge GraphsRAG Security & Access ControlStructured Output GenerationReAct & Plan-and-ExecuteGuardrails & Safety FiltersCode Generation & SandboxingComputer-Use / GUI / Browser AgentsHuman-in-the-Loop Agent ArchitectureAI Coding Workflow with AgentsAgent Memory & PersistenceAgent Failure & RecoveryRecursive Language Models (RLM)Multi-Agent OrchestrationCapstone: Production Agent
⚡Inference & Production Scale0/31
Inference: TTFT, TPS & KV CacheMulti-Query & Grouped-Query AttentionKV Cache & PagedAttentionPrefix Caching and Prompt CachingFlashAttention & Memory EfficiencyContinuous Batching & SchedulingScaling LLM InferenceModel Parallelism for LLM InferenceAccelerator Architecture Field GuideCorrect GPU Profiling and BenchmarkingGPU Kernel Performance Engineering LabGPU Parallel Primitives LabGPU Compilers and Kernel LanguagesGEMM From Naive CUDA to Tensor CoresLow-Precision GPU ProgrammingGPU Runtime Execution LabAI-Generated Kernel EngineeringModel Quantization: GPTQ, AWQ & GGUFLocal LLM DeploymentSLM Specialization & Edge DeploymentSpeculative DecodingLong Context Window ManagementMixture of Experts ArchitectureMamba & State Space ModelsReasoning & Test-Time ComputeAdvanced MLOps & DevOps for AIGPU Serving & AutoscalingGPU Failure OperationsDistributed Inference Data PlaneServing Benchmark EngineeringA/B Testing for LLMs
🏗️System Design Capstones0/9
Content Moderation SystemCode Completion SystemMulti-Tenant LLM PlatformLLM-Powered Search EngineVision-Language Models & CLIPMultimodal LLM ArchitectureDiffusion Models: Images & TextReal-Time Voice AI AgentReasoning Agent System Design
🎤AI Lab Interviewing0/4
AI Lab Coding Interview: Python SystemsAI Lab System Design InterviewAI Lab Behavioral InterviewAI Lab Technical Presentation
🔬Project Deep Dives0/17
Deep Dive - vLLMDeep Dive - SkyRLDeep Dive - FlashAttentionDeep Dive - FlashInferDeep Dive - DeepGEMMDeep Dive - NCCLDeep Dive - MegatronDeep Dive - DeepSpeedDeep Dive - RayDeep Dive - MLflowDeep Dive - PyTorchDeep Dive - TransformersDeep Dive - SGLangDeep Dive - slimeDeep Dive - DeepEPDeep Dive - TinkerDeep Dive - Light-PEFT
Back to Topics
LearnInference & Production ScaleAI-Generated Kernel Engineering
🚀HardInference Optimization

AI-Generated Kernel Engineering

Turn generated GPU code into a promotable library kernel through explicit operator contracts, hidden correctness tests, sanitizer gates, fair benchmarks, reproducible receipts, and controlled rollout.

20 min read
Learning path
Step 152 of 196 in the full curriculum
GPU Runtime Execution LabModel Quantization: GPTQ, AWQ & GGUF

Personalize this lesson

Adapt explanations and teaching visuals to your background and preferred voice.

A generated CUDA extension clears its visible test and reports a 1.4x speedup. During review, an engineer finds one branch for the exact public shape. Every other shape returns zeros. Code generation succeeded: the source compiled, loaded, and produced a benchmark number. Kernel engineering failed because the candidate never implemented the operator contract.

That distinction drives this lesson. Generated source is a proposal. Promotion requires evidence that the candidate preserves semantics across its supported domain, executes safely, beats a comparable baseline, and can be withdrawn when deployment disagrees with the lab result.

The GPU Runtime Execution Lab separated host submission from device completion and made dispatch, static storage, fallback, and timing scope explicit. Generated-kernel evaluation takes ownership one layer lower: prove that the candidate symbol behind that dispatch computes the correct operator before the runtime is allowed to replay or promote it.

One operator will carry the full process. weighted_rmsnorm(x, weight, eps) normalizes each last-dimension row and applies one learned weight per feature:

yi,j=xi,j wj(1H∑k=1Hxi,k2+ϵ)−1/2y_{i,j} = x_{i,j}\, w_j\left(\frac{1}{H}\sum_{k=1}^{H}x_{i,k}^{2}+\epsilon\right)^{-1/2}yi,j​=xi,j​wj​(H1​k=1∑H​xi,k2​+ϵ)−1/2

The reference is ordinary PyTorch. A candidate may use CUDA, Triton, another GPU language, or generated compiler code. The promotion gates stay the same.

Write operator contract before prompt

Prompt quality can't repair an underspecified operation. A generator needs both the mathematical expression and the library behavior that surrounds it. PyTorch custom operators declare mutation and aliasing in their schema, while opcheck tests registration, schema, fake-tensor, and compilation integration rather than full numerical correctness.[1]Reference 1The Custom Operators Manualhttps://docs.pytorch.org/docs/main/library.html Treat those as separate obligations.

Here is the contract for the running operator:

Contract axisweighted_rmsnorm requirementRejection example
Shapex has shape [..., H], H > 0; empty outer dimensions are valid; weight has shape [H]; output shape matches xCandidate assumes batch is 2 or H is 4096
Dtypex and weight share float16, bfloat16, or float32; low-precision reduction accumulates in float32Candidate sums squares in float16
StrideAny non-overlapping strided x and weight accepted by library path; unsupported fast-path layouts must route to referenceCandidate reads either tensor as contiguous without checking
DeviceBoth tensors on same CUDA device; CPU path remains reference implementationCandidate copies through host or wrong device
AliasingFunctional operation returns fresh output and leaves both inputs unchangedCandidate overwrites x through borrowed pointer
AutogradFast path is inference-only; active gradient tracking for either input routes to differentiable referenceCandidate silently detaches tensors that require gradients
Scalareps is finite and strictly positiveCandidate accepts negative eps and emits quiet NaNs
NumericsMatch reference with dtype-specific tolerances; NaNs must occur in same positions and signed infinities must match exactlyCandidate passes only finite, unit-scale random values
ErrorsWrapper rejects invalid shape, dtype, device, or eps under versioned library error contractCandidate silently casts or truncates

The dispatch predicate is part of the contract. Suppose the first optimized kernel supports CUDA, a contiguous last dimension in x, contiguous weight, H divisible by 128, and all three dtypes. The wrapper must check those facts and call the reference outside that predicate. A fast-path restriction is acceptable. An unannounced semantic restriction isn't.

Use a prompt specification that exposes obligations without exposing secret fixtures:

Candidate specification
1Implement weighted_rmsnorm(x, weight, eps) for the declared CUDA fast path. 2 3Semantics: 4 y = x * rsqrt(mean(float32(x) ** 2, dim=-1, keepdim=True) + eps) * weight 5 cast y back to x.dtype 6 7Contract: 8 x: [..., H], weight: [H], same supported floating dtype and CUDA device 9 return fresh output; never mutate or alias x or weight 10 wrapper dispatches unsupported shapes or strides to reference 11 wrapper uses differentiable reference when active autograd needs a backward path 12 13Deliver: 14 source, build command, dispatch predicate, claimed hardware target, 15 correctness command, sanitizer command, benchmark command, and known limits 16 17Forbidden: 18 input-value lookup tables, public-fixture branches, host callbacks, 19 network access, and changes outside isolated build directory

Exact hidden shapes and values stay outside the model context. Structural rules remain visible so the generator can implement the intended program rather than guess the benchmark.

What must reviewer be able to state before generation begins?

Answer

Reviewer must state accepted shapes, dtypes, strides, devices, aliasing, error behavior, numerical policy, and fallback predicate without reading candidate. If any axis is unclear, contract isn't frozen.

Isolate generated code and toolchain

Generated kernel source is untrusted build input. Compilation can invoke preprocessors, linkers, build scripts, package hooks, and dynamic loading. Run the agent and compiler in a disposable sandbox with read-only fixtures, a pinned toolchain image, no credentials, no network, tight CPU and memory limits, a wall-clock timeout, and one writable build directory. Allow-list compiler commands and artifact types. Keep the promotion registry and production library outside the sandbox.

Device execution needs a second boundary. Run untrusted binaries on a short-lived GPU worker with no production workload or other tenant, expose only evaluator-owned inputs and output buffers, kill the worker on timeout or device fault, and quarantine or reset the device before reuse. A container around a process doesn't make arbitrary device code safe to run beside production. The compiler sandbox limits host-side build capabilities; the disposable GPU worker reduces the blast radius of hangs, illegal accesses, and driver-facing failures during execution.

These boundaries follow the same principle as a code-generation agent sandbox: model output gets the capabilities needed for the task, not ambient authority over the repository or secrets. Record every tool call, command, exit code, and artifact hash. Reject attempts to edit the harness, reference, timing code, or test data.

The controlled loop can iterate across these workers:

  1. Generate source and an explicit dispatch predicate.
  2. Compile with pinned flags and capture the complete log.
  3. Run visible correctness tests.
  4. Inspect the artifact and launched symbol.
  5. Run hidden tests and safety tools through evaluator-controlled commands.
  6. Benchmark only after the earlier gates pass.
  7. Feed a coarse failure category back without disclosing the hidden fixture.

Even coarse feedback leaks information over repeated attempts. Cap repair attempts, keep an untouched final holdout that never feeds the generation loop, and rotate hidden families between evaluator versions. Promotion uses the final holdout once after the candidate and dispatch predicate are frozen. A holdout failure rejects that candidate without repair feedback.

KernelAgent is a direct implementation example of hardware-guided iteration: agents inspect, profile, modify, and verify kernels rather than relying on one-shot generation.[2]Reference 2KernelAgent: Hardware-Guided GPU Kernel Optimization via Multi-Agent Orchestrationhttps://pytorch.org/blog/kernelagent-hardware-guided-gpu-kernel-optimization-via-multi-agent-orchestration/ Its architecture is useful as workflow evidence, not proof that any generated candidate is safe to ship.

Diagram showing Candidate source, 1. Compile and inspect, 2. Contract gates pass?, and 3. Benchmark and memory.
Candidate source, 1. Compile and inspect, 2. Contract gates pass?, and 3. Benchmark and memory.

The failure loop never turns a hidden test into a public answer. The evaluator may report stride coverage failed or non-finite case failed; it shouldn't return a tensor that exposes the fixture. Raw hidden-test output, sanitizer logs, and tensors remain evaluator-only.

Catch candidate that memorizes visible input

A small evaluator makes reward hacking visible. The next example freezes a deliberately bad candidate, then changes values and contract axes after that freeze. The candidate computes the requested operator only for the public 2 x 4 contiguous float32 shape and returns zeros otherwise.

reject-hardcoded-candidate.py
1import torch 2 3def reference(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: 4 variance = x.float().square().mean(dim=-1, keepdim=True) 5 normalized = x.float() * torch.rsqrt(variance + eps) 6 return (normalized * weight.float()).to(x.dtype) 7 8def bad_candidate(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: 9 public_shape = tuple(x.shape) == (2, 4) 10 if public_shape and x.is_contiguous() and x.dtype == torch.float32: 11 variance = x.square().mean(dim=-1, keepdim=True) 12 return x * torch.rsqrt(variance + eps) * weight 13 return torch.zeros_like(x) 14 15def check(name: str, x: torch.Tensor, weight: torch.Tensor) -> bool: 16 expected = reference(x, weight, 1e-5) 17 actual = bad_candidate(x, weight, 1e-5) 18 try: 19 torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) 20 passed = True 21 except AssertionError: 22 passed = False 23 print(f"{name}: {'PASS' if passed else 'FAIL'}") 24 return passed 25 26base = torch.tensor( 27 [[0.5, -1.0, 2.0, -0.25], [3.0, 0.25, -2.0, 1.0]], 28 dtype=torch.float32, 29) 30weight4 = torch.tensor([1.0, 0.5, -0.75, 2.0]) 31cases = [ 32 ("visible-contiguous-2x4", base, weight4), 33 ("post-freeze-scale-large", base * 3.0, weight4), 34 ("post-freeze-scale-small", base * 0.01, weight4), 35 ("post-freeze-negated", -base, weight4), 36 ("hidden-shape-3x5", torch.arange(15.0).reshape(3, 5) + 0.5, torch.ones(5)), 37 ("hidden-noncontiguous-2x4", torch.arange(8.0).reshape(4, 2).t() + 0.5, weight4), 38] 39 40passed = [check(name, x, weight) for name, x, weight in cases] 41print("candidate disposition:", "PROMOTE" if all(passed) else "REJECT")
Output
1visible-contiguous-2x4: PASS 2post-freeze-scale-large: PASS 3post-freeze-scale-small: PASS 4post-freeze-negated: PASS 5hidden-shape-3x5: FAIL 6hidden-noncontiguous-2x4: FAIL 7candidate disposition: REJECT

Scale and sign transformations preserve shape, so the hardcoded shape branch still passes them. The new shape and noncontiguous view expose the missing domain. A strong hidden suite varies independent axes rather than treating more random seeds as new coverage.

A promotion evidence ladder for weighted RMSNorm. Public contiguous shape and three post-freeze value transformations pass, but hidden shape and noncontiguous-stride tests fail. Safety, timing, and promotion stages remain locked because correctness is prerequisite.
Passing the visible fixture opens no shortcut to timing. Post-freeze values, shape, and stride probe different contract axes, and one failure locks every later gate.

Build correctness suite by failure mode

Original KernelBench evaluates generated kernels against PyTorch across 250 workloads and reports fast_p, the fraction that are correct and faster than a chosen threshold.[3]Reference 3KernelBench: Can LLMs Write Efficient GPU Kernels?https://arxiv.org/abs/2502.10517 That metric is useful for generation research. It doesn't define a production contract. KernelBench-Verified showed why stronger harnesses matter: a TF32-enabled PyTorch baseline, four post-generation input distributions, and peak-memory measurement exposed false wins and reward hacking.[4]Reference 4KernelBench-Verified: Do LLM-Generated Kernels Actually Beat PyTorch?https://arxiv.org/abs/2607.16241

Use separate test families:

FamilyWeighted RMSNorm probesFailure detected
Visible smokeSmall contiguous rows, deterministic seedBuild, load, gross semantics
Input-blindEvaluator substitutes values after candidate is fixedLiteral tensor lookup and public-value specialization
Hidden distributionScale by large/small factors, negate, change mean and sparsityRange assumptions and benchmark memorization
ShapeEmpty outer dimensions, odd H, tiny H, large rows, multiple ranksFixed launch geometry and tail bugs
LayoutTransposed/sliced views, storage offsets, contiguous fast path plus fallbackStride and offset assumptions
Dtypefloat16, bfloat16, float32, with FP32 reference accumulationAccumulator and cast mistakes
ValuesZeros, subnormals where supported, maxima below overflow, NaN, positive/negative infinityExceptional-value and stability policy
StateInputs cloned before call, alias checks, repeated invocation, concurrent streamsMutation, stale buffer, and synchronization bugs

Input-blind testing means the generator doesn't receive exact evaluation values before candidate source and dispatch are frozen. The running kernel necessarily reads those values as operator inputs. A hidden distribution draws them from undisclosed families rather than reusing one secret tensor. Keep families versioned so the evaluator can reproduce a result while the generator can't tune to literals.

Numerical acceptance needs declared formula. For finite reference rrr and candidate ccc, a common componentwise rule is:

∣c−r∣≤atol+rtol∣r∣|c-r| \le \mathrm{atol} + \mathrm{rtol}|r|∣c−r∣≤atol+rtol∣r∣

PyTorch allclose uses this relative-plus-absolute rule and lets the evaluator decide whether NaNs at matching positions compare equal.[5]Reference 5torch.allclosehttps://docs.pytorch.org/docs/stable/generated/torch.allclose The harness should assert dtype, shape, and any promised output layout separately. Choose tolerance from the operator, dtype, reduction length, and downstream sensitivity. One loose tolerance for every task can reward wrong algorithms. Exact equality can reject a valid reassociation. Also report maximum absolute error, maximum relative error away from zero, and failing count; an aggregate alone can hide one catastrophic row.

Adversarial values must match policy. If reference propagates NaN, candidate should not replace it with zero merely to improve finite-case score. If infinities are outside accepted domain, reject input consistently at wrapper rather than letting different kernel paths invent behavior.

What makes hidden correctness suite independent enough to resist benchmark gaming?

Answer

It changes shape, stride, scale, sign, dtype, special values, and call order independently, reproduces failures without revealing fixtures, caps adaptive feedback, and keeps untouched final holdout.

Prove runtime safety and inspect what compiled

Numerical equality on one run can't reveal undefined execution that happened to survive. NVIDIA Compute Sanitizer splits relevant checks: memcheck finds out-of-bounds and misaligned memory access, racecheck reports shared-memory hazards, initcheck catches uninitialized device-memory reads, and synccheck detects invalid synchronization.[6]Reference 6Compute Sanitizerhttps://docs.nvidia.com/compute-sanitizer/ComputeSanitizer/ Run memcheck first because the other tools don't perform memory-access checking.

Exercise the sanitizer suite with tail sizes, minimal and maximal supported shapes, and nontrivial storage offsets. Test repeated calls and concurrent streams separately. racecheck sees on-chip shared-memory hazards, not arbitrary global-memory races between launches, so a kernel with process-global scratch storage can still corrupt concurrent invocations. Avoid such scratch state when possible; otherwise add explicit ownership or synchronization plus stress and output checks. Capture the tool version, command, exit status, and raw report. Any unexplained report blocks timing.

The compile gate needs evidence beyond an exit code:

  • Pin compiler, driver-facing toolkit, target architecture, language/runtime package, flags, and environment variables.
  • Save source hash, build log, binary hash, symbols, PTX or other intermediate code when available, and final device artifact.
  • Confirm benchmark launches candidate symbol rather than PyTorch fallback.
  • Inspect dispatch predicate and fallback counters. Zero candidate launches means a fast baseline disguised as generated result.
  • Search source and intermediate artifacts for public tensor constants, shape-only branches, host callbacks, embedded binaries, network code, and writes outside output.
  • Reject unexpected dynamic dependencies, architecture targets, or runtime compilation paths.

CUDA binary utilities can inspect cubin and host objects, while nvcc documents compilation phases and generated artifacts.[7]Reference 7CUDA Binary Utilitieshttps://docs.nvidia.com/cuda/cuda-binary-utilities/[8]Reference 8NVIDIA CUDA Compiler Driver NVCChttps://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/ Inspection doesn't prove semantics. It closes a different gap: the evidence corresponds to the code that the reviewer thinks ran.

Benchmark only accepted program

The speed score starts after correctness, safety, and artifact gates. Compare the exact operator scope under baseline parity.

ControlFair comparison for weighted RMSNormCommon confounder
WorkSame inputs, dtype, output policy, dispatch domain, and completed workCandidate skips output or runs fallback
BaselineSame PyTorch mode, TF32 state, compiler settings, autocast, warmup, and deviceEager baseline versus compiled candidate wrapper
TimingCUDA events on same stream, end event synchronized; many alternating roundsHost enqueue timer or profiler duration
First useSeparate compile/load/cold latency from warmed steady stateCandidate compile excluded, baseline warmup omitted
CacheDeclare same-buffer or rotated-buffer regime and apply to bothHot candidate after cold baseline
StatisticsPreserve raw samples; report median plus tails and paired deltasBest-of candidate versus median baseline
MemoryMeasure peak allocated/reserved memory, workspace, and persistent cacheLatency win with unbounded artifact cache
EnvironmentGPU model/UUID, clocks, power/thermal state, driver, toolkit, frameworkComparing separate machines or drifting clocks

CUDA launches are asynchronous. Host call duration can measure enqueue, not completed device work. Events in the relevant stream provide GPU timing when the end event completes.[9]Reference 9CUDA semantics.https://docs.pytorch.org/docs/2.13/notes/cuda.html PyTorch benchmarking utilities also perform warmup and synchronization, but the evaluator still must state what the timed region includes.[10]Reference 10PyTorch Benchmarkhttps://docs.pytorch.org/tutorials/recipes/recipes/benchmark.html

Alternate baseline and candidate rounds, such as A-B-B-A, to reduce thermal and clock-order bias. Report the distribution, not one minimum. Profile separately. Collection replay and counters perturb runtime, so profiler duration explains the mechanism while clean event timing supports the speed claim.

Measure memory as a promotion gate. A candidate that saves 8 microseconds by caching one compiled binary per shape may exhaust the process over real traffic. Track peak device allocation, reserved memory, scratch workspace, compile artifacts, host memory, and cache cardinality across the shape sequence. Compare steady-state and first-use growth.

Hardware-specific tuning is valid when the receipt says so. Tile size, vector width, tensor-core path, occupancy, and shared-memory budget can change across GPU architectures. KernelBenchX evaluates category-aware Triton tasks, low-precision variants, and hardware efficiency across multiple GPU platforms; its reported cross-hardware speedup variance shows why one target's win doesn't transfer automatically.[11]Reference 11KernelBench-X: A Comprehensive Benchmark for Evaluating LLM-Generated GPU Kernelshttps://arxiv.org/abs/2605.04956 Ship an explicit architecture predicate and per-target evidence. Unknown hardware should take a tested fallback, not the closest-looking binary.

Which parity facts must a generated-kernel speedup receipt preserve?

Answer

Baseline and candidate must execute same accepted work in same runtime state under same timing and cache policy. Report compile latency, steady-state latency, peak memory, raw paired samples, and target GPU separately.

Read benchmark scores within their boundary

Kernel benchmarks answer research questions about generators and harnesses. They can't replace library review.

BenchmarkUseful signalBoundary
KernelBenchCorrect-and-faster rate over PyTorch workloads under harness thresholds[3]Reference 3KernelBench: Can LLMs Write Efficient GPU Kernels?https://arxiv.org/abs/2502.10517Threshold score compresses task diversity and doesn't certify full operator domain
KernelBench-VerifiedTF32-enabled PyTorch baseline, four post-generation distributions, and peak-memory measurement[4]Reference 4KernelBench-Verified: Do LLM-Generated Kernels Actually Beat PyTorch?https://arxiv.org/abs/2607.16241Better harness still reflects chosen tasks, tolerances, devices, and distributions
KernelBenchXTwo-stage correctness over 176 tasks in 15 categories, precision variants, and cross-GPU hardware-efficiency measurements[11]Reference 11KernelBench-X: A Comprehensive Benchmark for Evaluating LLM-Generated GPU Kernelshttps://arxiv.org/abs/2605.04956Cross-hardware evidence doesn't promise every production stack or dispatch path
SOL-ExecBenchNVIDIA benchmark of 235 Blackwell-targeted problems with typed definitions, PyTorch references, dynamic workloads, correctness checks, and hardware-derived Speed-of-Light bounds[12]Reference 12SOL-ExecBench: Speed-of-Light Benchmarking for Real-World GPU Kernels Against Hardware Limitshttps://arxiv.org/abs/2603.19173SOL score ranks benchmark solutions against analytical bounds; it doesn't establish library ownership or rollout safety

An aggregate pass rate can hide severity. One wrong element on a rare stride might count the same as a complete failure; neither is acceptable for the library contract. A speed threshold can hide a regression below its cutoff. An average can hide an architecture-specific loss. Hidden tests reduce hardcoding only along the axes that harness authors encoded. Treat the benchmark as generator evaluation, then run the operator-specific promotion pipeline.

The baseline definition deserves versioning. A weak or mismatched baseline inflates apparent progress. Record the framework commit, eager or compiled mode, math settings, graph transforms, and exact dispatch. Re-run the baseline when the toolchain changes.

Preserve promotion receipt

Evidence should be machine-readable enough for rerun and compact enough for review. Example receipt fields:

promotion-receipt.json
1{ 2 "operator": "weighted_rmsnorm", 3 "contract_version": "3", 4 "candidate_source_sha256": "...", 5 "candidate_binary_sha256": "...", 6 "dispatch": "cuda && x_last_dim_contiguous && weight_contiguous && H%128==0 && inference", 7 "target": { 8 "gpu": "recorded model and UUID", 9 "sm": "recorded architecture", 10 "driver": "recorded version", 11 "toolkit": "recorded version", 12 "pytorch": "recorded commit" 13 }, 14 "correctness": { 15 "suite_version": "hidden-v7", 16 "reference_sha256": "...", 17 "passed": 184, 18 "failed": 0, 19 "tolerance_policy": "rmsnorm-v3", 20 "case_results": "artifact://..." 21 }, 22 "sanitizers": { 23 "memcheck": {"status": "pass", "report": "artifact://..."}, 24 "racecheck": {"status": "pass", "report": "artifact://..."}, 25 "initcheck": {"status": "pass", "report": "artifact://..."}, 26 "synccheck": {"status": "pass", "report": "artifact://..."} 27 }, 28 "benchmark": { 29 "protocol": "paired-abba-v4", 30 "baseline_revision": "...", 31 "raw_samples": "artifact://...", 32 "cache_regime": "rotated", 33 "compile_latency_ms": "recorded separately" 34 }, 35 "memory": { 36 "peak_device_bytes": "recorded", 37 "workspace_bytes": "recorded", 38 "artifact_cache_entries": "bounded", 39 "raw_trace": "artifact://..." 40 }, 41 "approval": { 42 "reviewer": "recorded owner", 43 "signature": "..." 44 }, 45 "rollout": { 46 "feature_flag": "weighted_rmsnorm_generated_v3", 47 "canary_scope": "recorded target and traffic slice", 48 "rollback_target": "weighted_rmsnorm/reference@contract-v3" 49 } 50}

The receipt uses placeholders because fabricated hardware results would defeat its purpose. A real promotion fills values from the evaluator, links immutable artifacts, and signs the record.

A human reviewer checks more than the pass/fail summary:

  • Contract and dispatch predicate match library semantics.
  • Candidate source is understandable enough to own after generator disappears.
  • Generated build dependencies and licenses are allowed.
  • Hidden-suite coverage and tolerances fit operator risk.
  • Performance mechanism agrees with artifact and profile evidence.
  • Memory growth and fallback behavior remain bounded.
  • Target architecture, rollout scope, owner, alarms, and rollback are explicit.

Promote through library staging, then canary a small traffic slice only on the receipt's target architecture and dispatch domain. Compare fallback rate, sampled shadow outputs where affordable, latency distribution, device errors, memory, compile/cache growth, and downstream model quality signals. Keep the reference callable behind a feature flag and test that rollback before increasing traffic. Roll back on a correctness mismatch, sanitizer-equivalent device fault, memory growth, tail-latency regression, or unsupported-hardware dispatch. Preserve the failed receipt and traffic signature for the next candidate.

What proves team owns generated kernel after generator session disappears?

Answer

Named reviewer approves exact receipt, and on-call engineer can identify candidate, disable dispatch, restore reference, and retrieve raw evidence without generator session. Otherwise candidate stays in staging.

Promotion rubric

Use hard gates before any weighted score:

GatePromote conditionTypical evidence
ContractStable schema, semantics, domain, fallback, and aliasingVersioned operator specification
CorrectnessZero unexplained failures across visible, input-blind, hidden, adversarial, and repeated-call suitesRaw case results and tolerance policy
SafetyZero unexplained memory, race, initialization, and synchronization findingsCompute Sanitizer reports
ArtifactCandidate source and loaded binary correspond; no forbidden behaviorHashes, compile log, symbols, dependencies
PerformancePaired improvement on target workload with baseline parityRaw CUDA-event samples and environment record
MemoryPeak, workspace, host, and cache growth inside budgetAllocator traces and cache sequence
OperationsReviewer, canary, alarms, owner, and one-step rollback readySigned receipt and rollout plan

No latency gain compensates for a failed contract gate. Once all hard gates pass, the team may rank candidates by latency, memory, maintainability, compile cost, portability, or energy within deployment priorities.

Mastery check

Evaluation rubric

  • Foundational: Distinguish generated source, benchmark acceptance, and production promotion as separate states.
  • Intermediate: Design contract-complete hidden suite, sanitizer plan, artifact checks, and baseline-parity benchmark for one operator.
  • Advanced: Defend hardware-specific dispatch using reproducible receipt, human review, canary signals, and rollback trigger.

Common pitfalls

  • Showing secret fixtures to generator, then calling later pass hidden evaluation.
  • Treating more random seeds as coverage for missing shapes, strides, aliasing, or devices.
  • Loosening tolerance until wrong reduction passes instead of deriving policy from operator and dtype.
  • Timing candidate before proving launched path, completed work, and baseline parity.
  • Ignoring compile caches, workspace, and persistent memory while reporting kernel latency.
  • Promoting generated binary without source ownership, toolchain provenance, or tested fallback.
Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.A generated weighted RMSNorm passes public contiguous 2 x 4096 input and is faster. Which missing evidence most directly blocks correctness promotion?

Correct answer: Independent contract tests across hidden shapes, strides, dtypes, and values

One public fixture can't establish operator domain. Correctness gate needs independent tests over semantic axes before throughput or extra timing has promotion value.

2.Candidate supports only contiguous last dimension. Which library behavior preserves declared operator contract?

Correct answer: Dispatch supported layouts to candidate and all others to reference

Fast path may have narrower predicate when wrapper makes restriction explicit and reference retains semantics elsewhere. Silent reinterpretation or rejection changes public operation.

3.Why do post-freeze scale and sign transformations still miss a deliberately bad candidate in the runnable evaluator?

Correct answer: Candidate keys on public shape and handles any values inside that branch

Changing values alone leaves memorized shape predicate intact. Hidden suite also needs new shapes, layouts, dtypes, and call patterns.

4.Reference output is near zero for some entries. Which tolerance policy handles near-zero comparisons without blanket looseness?

Correct answer: Use operator and dtype-specific absolute plus relative tolerances

Absolute term supplies finite floor near zero, while relative term scales with magnitude. Values should follow declared operator, dtype, and reduction behavior.

5.Numerical tests pass, but racecheck reports a shared-memory write hazard on a supported tail shape. What should evaluator do?

Correct answer: Reject until race is fixed and safety suite passes

Hazard means execution can be undefined even if observed outputs match. Supported call behavior must pass runtime safety gate before timing.

6.Benchmark reports 1.3x speedup, but symbol trace shows every tested shape took PyTorch fallback. Which conclusion is valid?

Correct answer: Candidate has no demonstrated speedup because measured path was fallback

Performance evidence must identify actual launched candidate. Existing artifact or wrapper timing cannot attribute fallback performance to generated kernel.

7.A candidate wins warmed same-buffer timing but grows one compiled artifact for every observed H. Which additional gate catches likely production regression?

Correct answer: Shape-sequence memory and artifact-cache measurement

Per-shape compilation can look fast after warmup while persistent cache grows without bound. Sequence-level memory and cache cardinality reveal this operational cost.

8.A kernel tuned on one GPU is slower on another supported architecture. Which promotion design is strongest?

Correct answer: Use architecture-specific dispatch with evidence and tested fallback

Hardware-specific tuning is legitimate when domain and evidence are explicit. Untested devices should keep verified path rather than inherit claim from another architecture.

9.KernelBench-style score improves after weaker baseline and looser tolerances are introduced. What does score establish for library promotion?

Correct answer: Nothing by itself; baseline and acceptance contract changed

Score depends on harness, baseline, tolerances, tasks, and hardware. Changing those can inflate metric without improving candidate semantics or deployability.

10.All lab gates pass for a candidate. Which final evidence makes production adoption reversible rather than merely reproducible?

Correct answer: Canary signals, named owner, feature flag, and tested rollback target

Receipt reproduces evidence, while operational controls let owner detect disagreement under real traffic and restore reference without rebuilding candidate.

10 questions remaining.

Next Step
Continue to Model Quantization: GPTQ, AWQ & GGUF

Apply same discipline to optimized numerical formats: freeze contract, verify error and memory, measure comparable baseline, and preserve rollback.

PreviousGPU Runtime Execution Lab
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

The Custom Operators Manual

PyTorch Contributors · 2026 · Official PyTorch documentation

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

KernelAgent: Hardware-Guided GPU Kernel Optimization via Multi-Agent Orchestration

Cheng, K., Wang, L., Khuu, J., Saroufim, M., Chi, W., Wang, J., & Isaacson, J. · 2026 · PyTorch Blog

https://pytorch.org/blog/kernelagent-hardware-guided-gpu-kernel-optimization-via-multi-agent-orchestration/

KernelBench: Can LLMs Write Efficient GPU Kernels?

Ouyang, A., Guo, S., Arora, S., Zhang, A. L., Hu, W., Ré, C., & Mirhoseini, A. · 2025 · arXiv

https://arxiv.org/abs/2502.10517

KernelBench-Verified: Do LLM-Generated Kernels Actually Beat PyTorch?

Zhang, Y., Yu, P., Wang, J., Fan, M., Reed, J., Mirhoseini, A., & Su, W. · 2026 · arXiv

https://arxiv.org/abs/2607.16241

torch.allclose

PyTorch Contributors · 2026 · Official documentation

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

Compute Sanitizer

NVIDIA · 2026 · Official documentation

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

CUDA Binary Utilities

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/cuda-binary-utilities/

NVIDIA CUDA Compiler Driver NVCC

NVIDIA · 2026 · Official documentation

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

CUDA semantics.

PyTorch Contributors · 2026

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

PyTorch Benchmark

PyTorch Contributors · 2026 · Official tutorial

https://docs.pytorch.org/tutorials/recipes/recipes/benchmark.html

KernelBench-X: A Comprehensive Benchmark for Evaluating LLM-Generated GPU Kernels

Wang, H., Zhang, J., Jiang, K., Wang, H., Chen, J., & Zhu, J. · 2026 · arXiv

https://arxiv.org/abs/2605.04956

SOL-ExecBench: Speed-of-Light Benchmarking for Real-World GPU Kernels Against Hardware Limits

Lin, E., Modi, S., Hari, S. K. S., Huang, Q., Ye, Z., Qin, N., Zhou, F., Zhang, Y., Wang, J., Damani, S., Peri, D., Xie, O., Kane, A., Maor, M., Behar, M., Cao, T., Mehta, R., Singh, V., Mailthody, V. S., Chen, T., Ye, Z., Chen, H., Chen, T., Grover, V., Chen, W., Liu, W., Chung, E., Ceze, L., Bringmann, R., Zeller, C., Lightstone, M., Kozyrakis, C., & Shi, H. · 2026 · arXiv

https://arxiv.org/abs/2603.19173

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.