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.

26 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.

Suppose an AI coding agent generates a CUDA extension that clears its visible smoke test and reports an eye-popping 1.4x speedup on an H100 GPU. The pull request looks clean, the pull request comments celebrate the win, and the kernel merges into main. Two days later in staging, inference worker threads hang indefinitely, customer prompts with 1009 tokens trigger silent NaN outputs, and uncoalesced memory reads drop real memory bandwidth across the cluster from 3.35 TB/s down to 120 GB/s.

During post-mortem debugging, engineers discover the root cause: the model generated a single specialized branch for the exact public test shape [2, 4096]. Every non-standard row length triggered an out-of-bounds shared memory read, and a missing barrier created a race condition that passed the unit test only because thread warps ran in lockstep on an idle GPU.

Generated GPU code isn't an implementation; it's an untrusted proposal. A language model predicts token sequences based on open-source patterns rather than executing hardware instructions or reasoning about memory controllers, thread divergence, and cache lines. Promoting generated code into a production library requires undeniable empirical evidence: the candidate must preserve mathematical semantics across its full domain, execute safely without memory corruption, beat a comparable baseline fairly, and roll back instantly when production workloads disagree with lab benchmarks.

The GPU Runtime Execution Lab made host submission, device streams, static storage, fallback paths, and timing scopes explicit. Generated-kernel engineering takes ownership one layer lower: prove that the candidate symbol behind that dispatch computes the correct operator safely before the runtime ever replays or promotes it.

One realistic operator carries this process throughout the chapter: weighted root mean square normalization (RMSNorm), weighted_rmsnorm(x, weight, eps). It rescales each row across its last dimension and applies a learned feature weight. For an example row [3.0, 4.0], the mean square is (9+16)/2=12.5(9 + 16) / 2 = 12.5(9+16)/2=12.5. Divide each entry by 12.5+ϵ\sqrt{12.5 + \epsilon}12.5+ϵ​, then multiply by its corresponding weight. The positive scalar ϵ\epsilonϵ ensures an all-zero row never divides by zero.

For row index iii, feature index jjj, and row width HHH:

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 implementation is pure PyTorch. A candidate may use CUDA, Triton, or compiler code. The promotion gates stay identical. The executable examples below run on CPU: they test evaluator logic, proving how to audit a candidate before giving it device access.

AI kernel generation dynamics and common failure modes

LLMs generate CUDA and Triton by pattern-matching code patterns from open-source repositories like FlashAttention and PyTorch. They can reproduce idiomatic launch grids, shared memory declarations, and warp-reduction syntax effortlessly. Yet that high syntactic fluency hides lethal semantic blind spots: models struggle with spatial coordinate transforms, thread-block boundary conditions, and hardware memory hierarchies.

Three failure modes recur across generated GPU kernels:

  1. Subtle race conditions and missing barriers: In reduction operators like RMSNorm, threads compute partial sums and exchange them through shared memory (smem). LLMs regularly omit __syncthreads() in CUDA or block-level barriers in Triton between write and read stages, assuming warp-synchronous execution or implicit ordering. On a small test tensor where warps run in lockstep across a single Streaming Multiprocessor (SM), the test passes reliably. In production, with 132 SMs executing asynchronous warps under dynamic clock frequency scaling, the kernel suffers Read-After-Write (RAW) data hazards, corrupting outputs non-deterministically.
  2. Out-of-bounds shared memory indexing: Block tile sizes (such as 128 or 256 threads) rarely divide real-world tensor dimensions cleanly. When a sequence length or hidden dimension is prime (such as H=1009H = 1009H=1009), edge tiles must mask out inactive threads. LLMs often guard global memory reads with if (idx < H), but forget to mask the shared memory store or fail to clear reduction padding. Uninitialized shared memory floats get summed into the reduction tree, quietly poisoning the denominator.
  3. Uncoalesced memory access passing small tests by luck: Models frequently confuse column-major and row-major layout indexing, swapping threadIdx.x and threadIdx.y or indexing across rows instead of along contiguous row elements. On a tiny smoke test (such as 2×42 \times 42×4 floats), the entire tensor fits inside a single 128-byte cache line; the test reports a false speedup because there's no memory latency penalty. Under production batching (such as batch 64, sequence length 4096, hidden dim 8192), non-consecutive addresses force the memory controller to issue 32 distinct 32-byte sector transactions instead of one coalesced 128-byte transaction. Effective memory bandwidth plummets from 3.35 TB/s down to 120 GB/s.

Treating generated code as untrusted build input protects your cluster from these hidden defects.

Write the operator contract before the prompt

Prompt engineering can't repair an underspecified operation. A code generator needs both the exact mathematical formula and the library contract surrounding it. PyTorch custom operators declare mutation, aliasing, and schemas via torch.library.custom_op, while torch.library.opcheck verifies registration, fake-tensor integration, and compilation mechanics rather than numerical correctness.[1]Reference 1The Custom Operators Manualhttps://docs.pytorch.org/docs/main/library.html Treat those as distinct 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; unsupported fast-path layouts route to referenceCandidate reads tensors as contiguous without checking
DeviceBoth tensors on same CUDA device; CPU path routes to reference implementationCandidate copies through host or mismatched device
AliasingFunctional operation returns fresh output and leaves inputs unchangedCandidate overwrites x through borrowed pointer
AutogradFast path is inference-only; active autograd routes to differentiable referenceCandidate silently detaches tensors needing gradients
Scalareps is a numeric scalar staying finite and strictly positive in FP32A tiny positive value rounds to zero in reduction dtype
NumericsMatch reference within dtype-specific tolerances; NaNs match positions and signed infinities matchCandidate passes only finite, unit-scale random values
ErrorsWrapper rejects invalid shape, dtype, device, or eps under versioned error contractCandidate silently casts or truncates values

The dispatch predicate is an active gate in the contract. Suppose the first generated kernel supports CUDA, contiguous x and weight, H divisible by 128, and all three dtypes. The wrapper must verify those conditions, check the target GPU architecture, and confirm that backward autograd isn't needed; any other valid call routes to the reference. Invalid public inputs must still raise the declared library error. A fast-path restriction is acceptable; an unannounced semantic limitation isn't.

A contiguous last dimension alone doesn't justify flattening rows: sliced outer dimensions leave gaps between them. Either compute row addresses from strides or require the entire input tensor to be contiguous. Active autograd requires both torch.is_grad_enabled() and at least one input tensor with requires_grad=True.

Use a prompt specification that exposes obligations without leaking private evaluation fixtures:

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

Exact evaluation shapes and adversarial values stay outside the model context. Structural rules remain visible so the generator implements the intended program rather than guessing benchmark inputs.

What must a reviewer be able to state before generation begins?

Answer

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

Isolate generated code and the toolchain

Generated kernel source is untrusted code. Compiling it invokes preprocessors, linkers, build scripts, dynamic linkers, and shell hooks. Run the compiler and generated binaries in a disposable sandbox with a pinned toolchain image, no credentials, no network access, tight CPU and memory limits, a wall-clock timeout, and a single writable build directory. Expose only public smoke fixtures there. An external orchestrator calls the model provider without exposing API keys to the build worker. Allow-list compiler commands and artifact types. Keep the evaluator, hidden fixtures, promotion registry, and production codebase completely outside the sandbox.

Device execution requires a second security boundary. Running untrusted binaries on a shared GPU worker risks memory snooping, kernel hangs, and driver crashes that destabilize co-located workloads. Execute tests on an isolated, short-lived GPU worker with no production traffic. Expose only evaluator-allocated input and output buffers, kill the worker process on timeout or illegal memory access, and reset or quarantine the device before reuse. A host container doesn't prevent arbitrary device code from executing illegal instructions or exhausting GPU resources. The compiler sandbox limits host-side build capabilities; the disposable GPU worker isolates hardware faults.

These boundaries mirror secure code-generation agent architectures: model output receives only the capabilities required for its task, avoiding ambient authority over the repository or secrets. Record every tool call, compiler invocation, exit code, and artifact hash. Reject attempts to modify the harness, reference, timing harness, or test suites.

Catch a candidate that only handles the visible shape

A minimal evaluator demonstrates incomplete domain coverage immediately. The CPU example below inspects a deliberately flawed candidate that computes the operator for the public contiguous 2 x 4 float32 shape, but returns zeros for any other input.

reject-hardcoded-candidate.py
1import torch 2 3def reference(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: 4 mean_square = x.float().square().mean(dim=-1, keepdim=True) 5 normalized = x.float() * torch.rsqrt(mean_square + 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 mean_square = x.square().mean(dim=-1, keepdim=True) 12 return x * torch.rsqrt(mean_square + 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 disp = "PASS" if passed else "FAIL" 24 print(f"{name}: {disp}") 25 return passed 26 27base = torch.tensor( 28 [[0.5, -1.0, 2.0, -0.25], [3.0, 0.25, -2.0, 1.0]], 29 dtype=torch.float32, 30) 31weight4 = torch.tensor([1.0, 0.5, -0.75, 2.0]) 32cases = [ 33 ("visible-contiguous-2x4", base, weight4), 34 ("post-freeze-scale-large", base * 3.0, weight4), 35 ("post-freeze-scale-small", base * 0.01, weight4), 36 ("post-freeze-negated", -base, weight4), 37 ("hidden-shape-3x5", torch.arange(15.0).reshape(3, 5) + 0.5, torch.ones(5)), 38 ("hidden-noncontiguous-2x4", torch.arange(8.0).reshape(4, 2).t() + 0.5, weight4), 39] 40 41assert cases[-1][1].stride() == (1, 2) 42passed = [check(name, x, weight) for name, x, weight in cases] 43assert passed == [True, True, True, True, False, False] 44disp = "PROMOTE" if all(passed) else "REJECT" 45print("candidate disposition:", disp)
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

Scaling and negation preserve tensor shape, so the candidate's hardcoded branch still passes them. The new shape and transposed view expose the missing domain. Shape specialization is acceptable when a wrapper routes unsupported calls to a verified fallback. Returning zeros for unhandled inputs violates the operator contract.

The autonomous evaluation harness: six sequential gates

An autonomous evaluation harness subjects candidate GPU code to a battery of deterministic gates. Skipping early gates to run benchmarks wastes GPU compute on broken code. The pipeline enforces six sequential checks:

Diagram showing 1. Reference Oracle Functional PyTorch contract, 2. Compile & Static Check ptxas register spills & smem, 3. Multi-Scale Numerics Powers of 2, primes, strides, and 4. Compute Sanitizer memcheck & racecheck.
1. Reference Oracle Functional PyTorch contract, 2. Compile & Static Check ptxas register spills & smem, 3. Multi-Scale Numerics Powers of 2, primes, strides, and 4. Compute Sanitizer memcheck & racecheck.

1. Reference oracle

The reference oracle defines functional ground truth. Written in pure PyTorch, it enforces the formal operator schema, checks input metadata, and produces the baseline output tensor. It operates with full precision accumulation (FP32) to prevent precision loss.

2. Compilation check and static inspection

Compiling with nvcc -O3 and target architecture flags (such as -arch=sm_90a for NVIDIA H100) produces diagnostic logs from ptxas, the PTX optimizing assembler.[2]Reference 2NVIDIA CUDA Compiler Driver NVCChttps://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/ Static inspection extracts three critical metrics:

  • Register allocation and spills: Inspect the ptxas output string (e.g., ptxas info : Used 64 registers, 0 bytes cmem, 1024 bytes spill stores, 1024 bytes spill loads). If a thread requires more registers than the hardware allows per warp, ptxas spills variables into local memory (backed by high-latency DRAM), cratering execution speed.
  • Shared memory allocation: High shared memory usage per thread block reduces active warp occupancy per SM. For instance, requesting 64 KB of shared memory on an SM with a 99 KB capacity limits concurrency to one block per SM.
  • Symbol verification: Tools like cuobjdump and nvdisasm confirm that the compiled .cubin contains the declared symbol rather than falling back to host PyTorch routines or embedding precomputed constant tables.[3]Reference 3CUDA Binary Utilitieshttps://docs.nvidia.com/cuda/cuda-binary-utilities/

3. Multi-scale numerical verification

A candidate that passes on powers of two can fail on boundary conditions. Test families must probe diverse dimensions and memory alignments:

  • Powers of two: Shapes like H∈{128,512,4096}H \in \{128, 512, 4096\}H∈{128,512,4096} test aligned, coalesced memory access paths.
  • Prime row lengths: Odd and prime dimensions like H∈{1009,4099}H \in \{1009, 4099\}H∈{1009,4099} test edge-tile boundary masks and thread reduction cleanup loops.
  • Non-contiguous views and ragged strides: Transposed matrices (x.t()), strided slices, and non-zero storage offsets test pointer arithmetic.
  • Adversarial floating-point inputs: Zeros, subnormals, numbers near overflow (101910^{19}1019 squaring to infinity in FP32), and exact NaN or infinity placements verify compliance with IEEE 754 standards.

Componentwise numerical acceptance requires a declared formula:

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

PyTorch's torch.testing.assert_close implements this rule and checks that NaNs match at identical positions.[4]Reference 4torch.allclosehttps://docs.pytorch.org/docs/stable/generated/torch.allclose Choose tolerances based on operator mathematics and reduction length. Reporting maximum absolute error, maximum relative error, and failing element counts prevents an aggregate pass from hiding localized divergence.

The script below audits input preservation, memory aliasing, and non-finite policies:

audit-rmsnorm-contract.py
1import math 2import torch 3 4def reference(x, weight, eps): 5 if x.layout != torch.strided or weight.layout != torch.strided: 6 raise ValueError("Need ordinary strided tensors.") 7 if x.ndim < 1 or x.shape[-1] <= 0 or weight.shape != (x.shape[-1],): 8 raise ValueError("Need x[..., H], H > 0, and weight[H].") 9 if x.dtype not in (torch.float16, torch.bfloat16, torch.float32) or weight.dtype != x.dtype: 10 raise ValueError("Need the same supported floating dtype.") 11 if x.device != weight.device or x.device.type not in ("cpu", "cuda"): 12 raise ValueError("Need one supported device.") 13 if type(eps) not in (float, int): 14 raise ValueError("eps must be an ordinary numeric scalar.") 15 try: 16 eps_value = float(eps) 17 except OverflowError as exc: 18 raise ValueError("eps is too large.") from exc 19 if not math.isfinite(eps_value) or eps_value <= 0: 20 raise ValueError("eps must be finite and positive.") 21 eps32 = float(torch.tensor(eps_value, dtype=torch.float32)) 22 if not math.isfinite(eps32) or eps32 <= 0: 23 raise ValueError("eps must stay finite and positive in FP32.") 24 with torch.autocast(device_type=x.device.type, enabled=False): 25 xf, wf = x.float(), weight.float() 26 scale = torch.rsqrt(xf.square().mean(dim=-1, keepdim=True) + eps32) 27 return ((xf * scale) * wf).to(x.dtype) 28 29def value_bytes(tensor): 30 flat = torch.empty(tensor.numel(), dtype=tensor.dtype, device=tensor.device) 31 flat.copy_(tensor.detach().reshape(-1)) 32 return flat.view(torch.uint8) 33 34def audit(candidate, x, weight, eps=1e-5): 35 expected = reference(x, weight, eps) 36 snapshots = [value_bytes(t) for t in (x, weight)] 37 def metadata(t): 38 return (t.shape, t.stride(), t.storage_offset(), t.dtype, t.device, 39 t.untyped_storage().data_ptr()) 40 before_metadata = [metadata(t) for t in (x, weight)] 41 actual = candidate(x, weight, eps) 42 try: 43 assert isinstance(actual, torch.Tensor) 44 torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6, equal_nan=True) 45 for current, before, original_meta in zip((x, weight), snapshots, before_metadata, strict=True): 46 assert metadata(current) == original_meta, "input metadata changed" 47 assert torch.equal(value_bytes(current), before), "input mutated" 48 if actual.numel() and current.numel(): 49 assert actual.untyped_storage().data_ptr() != current.untyped_storage().data_ptr(), "output aliases input" 50 except AssertionError: 51 return False 52 return True 53 54def mutate_after_computing(x, weight, eps): 55 y = reference(x, weight, eps) 56 x.add_(1) 57 return y 58 59def scrub_nans(x, weight, eps): 60 return reference(x, weight, eps).nan_to_num() 61 62base = torch.tensor([[3., 4.], [0., 0.]]) 63weight = torch.tensor([1., 2.]) 64special = torch.tensor([[float("nan"), 1.], [float("inf"), 2.]]) 65cases = [ 66 ("reference ordinary", reference, base.clone(), weight), 67 ("reference empty outer dimension", reference, torch.empty(0, 2), weight), 68 ("reference non-finite policy", reference, special, weight), 69 ("correct values but mutated input", mutate_after_computing, base.clone(), weight), 70 ("aliased zero output", lambda x, w, e: x, torch.zeros(1, 2), weight), 71 ("wrong output dtype", lambda x, w, e: reference(x, w, e).double(), base, weight), 72 ("silently replaced NaNs", scrub_nans, special, weight), 73] 74results = [audit(fn, x, w) for _, fn, x, w in cases] 75assert results == [True, True, True, False, False, False, False] 76for (name, *_), passed in zip(cases, results, strict=True): 77 disp = "PASS" if passed else "FAIL" 78 print(f"{name}: {disp}")
Output
1reference ordinary: PASS 2reference empty outer dimension: PASS 3reference non-finite policy: PASS 4correct values but mutated input: FAIL 5aliased zero output: FAIL 6wrong output dtype: FAIL 7silently replaced NaNs: FAIL

Checking dense tensor values, input mutation, and pointer aliasing catches bugs before device timing runs.

4. Compute Sanitizer gating

Numerical tests don't reveal undefined behavior that survived by luck. NVIDIA Compute Sanitizer isolates execution hazards into four dedicated tools:[5]Reference 5Compute Sanitizerhttps://docs.nvidia.com/compute-sanitizer/ComputeSanitizer/

  • memcheck: Detects out-of-bounds memory accesses, misaligned addresses, and device heap errors.
  • racecheck: Intercepts shared memory hazards, including Read-After-Write (RAW), Write-After-Read (WAR), and Write-After-Write (WAW) data races.
  • initcheck: Flags reads from uninitialized global or shared device memory.
  • synccheck: Identifies divergent synchronization barriers, such as threads within a block reaching different __syncthreads() calls, which deadlocks hardware warps.

Invoke the sanitizer with an explicit non-zero exit code:

terminal
1compute-sanitizer --tool memcheck --error-exitcode 1 ./test_runner 2compute-sanitizer --tool racecheck --error-exitcode 1 ./test_runner

Any report of a hazard or misaligned access halts evaluation immediately.

5. Clean CUDA event benchmarking

Accurate GPU timing requires strict methodology. Python host timers (time.time()) measure kernel launch enqueue time rather than device completion.[6]Reference 6CUDA semanticshttps://docs.pytorch.org/docs/stable/notes/cuda.html High-integrity benchmarking enforces five rules:[7]Reference 7PyTorch Benchmarkhttps://docs.pytorch.org/tutorials/recipes/recipes/benchmark.html

  • CUDA events on the work stream: Place cudaEventRecord before and after the kernel on the active stream, synchronizing on the end event before reading elapsed time.
  • Warmup passes: Run 20 to 50 warmup iterations to bring the GPU core and memory clocks out of idle power states (P-states).
  • Interleaved A-B-B-A execution: Alternate between baseline (AAA) and candidate (BBB) executions to cancel out thermal throttling and dynamic frequency variations over time.
  • Rotated buffer cache busting: If a benchmark runs the same 16 MB tensor in a tight loop on an H100 GPU (which has 50 MB of L2 cache), the tensor stays resident in L2 cache. The benchmark reports an unrealistic 12 TB/s cache speed instead of measuring HBM memory bandwidth. Cycle through a ring of separate memory buffers to force real global memory traffic.
  • Statistical reporting: Record full timing distributions (median, P90, P99) instead of cherry-picking the minimum latency.

6. Roofline sanity check

Compare measured kernel throughput against the theoretical hardware ceiling using the Roofline model.[8]Reference 8Nsight Compute Profiling Guidehttps://docs.nvidia.com/nsight-compute/ProfilingGuide/

For weighted RMSNorm, calculate the arithmetic intensity (III):

  • Operations: Sum of squares (HHH multiplies, H−1H-1H−1 adds), mean (1 divide), rsqrt (1 op), normalization (HHH multiplies), and weighting (HHH multiplies). Total: roughly 4H4H4H floating-point operations.
  • Memory traffic: Read input xxx (HHH elements), read weight www (HHH elements), and write output yyy (HHH elements). For FP16 (222 bytes/element), total memory traffic is 3⋅H⋅2=6H3 \cdot H \cdot 2 = 6H3⋅H⋅2=6H bytes.
  • Arithmetic intensity: I=4H FLOPs6H Bytes≈0.67 FLOPs/ByteI = \frac{4H \text{ FLOPs}}{6H \text{ Bytes}} \approx 0.67 \text{ FLOPs/Byte}I=6H Bytes4H FLOPs​≈0.67 FLOPs/Byte.

Because an H100 SXM5 GPU features an arithmetic intensity ridge point around 150 FLOPs/Byte, RMSNorm is deeply memory bandwidth bound. Achieved bandwidth can't exceed the physical HBM3 limit of 3.35 TB/s:

Bandwidthachieved=6⋅N⋅HLatencyseconds\text{Bandwidth}_{\text{achieved}} = \frac{6 \cdot N \cdot H}{\text{Latency}_{\text{seconds}}}Bandwidthachieved​=Latencyseconds​6⋅N⋅H​

If a benchmark reports an effective bandwidth of 5.2 TB/s on an H100, the kernel isn't fast; it's skipping computation, returning early, or dropping memory writes.

The refinement feedback loop: hardware-guided iteration

Autonomous generation agents (such as KernelAgent) don't rely on blind one-shot generation; they analyze diagnostic traces to iteratively optimize kernel code.[9]Reference 9KernelAgent: Hardware-Guided GPU Kernel Optimization via Multi-Agent Orchestrationhttps://pytorch.org/blog/kernelagent-hardware-guided-gpu-kernel-optimization-via-multi-agent-orchestration/ The harness closes the loop by feeding structured telemetry back to the model:

Diagram showing LLM Agent, Compilation & ptxas, Sanitizer & NCU Profiler, and Canary Deployment.
LLM Agent, Compilation & ptxas, Sanitizer & NCU Profiler, and Canary Deployment.

The feedback payload provides three categories of actionable signals:

  1. Compiler diagnostics: Capture ptxas warnings, register spill counts, and shared memory footprints. If local memory spills occur, the model responds by reducing unroll factors, hoisting variables, or tiling registers.
  2. Sanitizer traces: When racecheck or memcheck fails, extract the instruction pointer, memory address, thread coordinates (threadIdx=(x,y,z)), and block coordinates (blockIdx=(x,y,z)). The agent receives the exact instruction line where a barrier is missing or an address is miscalculated.
  3. Warp stall counters: Telemetry from NVIDIA Nsight Compute (NCU) reveals runtime bottlenecks via hardware performance counters:[8]Reference 8Nsight Compute Profiling Guidehttps://docs.nvidia.com/nsight-compute/ProfilingGuide/
    • smsp__warp_issue_stalled_long_scoreboard_pct: Warps waiting for global DRAM loads. Feedback prompts the model to vectorize memory loads using float4 or implement asynchronous copies (cp.async).
    • smsp__warp_issue_stalled_short_scoreboard_pct: Warps stalled on shared memory or MIO operations, signaling shared memory bank conflicts. The model pads shared memory buffers (such as __shared__ float smem[128 + 1]).
    • smsp__warp_issue_stalled_barrier_pct: Warps stalled waiting at __syncthreads(), pointing to thread divergence or poor load balancing. The model switches to warp shuffle intrinsics (__shfl_down_sync) across 32-thread warps.

To prevent prompt poisoning and benchmark memorization, enforce three strict boundaries: sanitize logs to remove raw tensors from hidden fixtures, cap the refinement loop to a maximum of 5 iterations, and hold out an untouched validation suite that runs only once after candidate generation freezes.

The promotion evidence ladder: from lab to production infrastructure

Passing laboratory unit tests is necessary, but it doesn't prove that a kernel will run reliably under messy production traffic. The promotion evidence ladder establishes four progressive validation tiers:

The promotion evidence ladder for AI-generated kernels. Four progressive tiers: Tier 1 Lab Verification (ptxas check, multi-scale numerics, Compute Sanitizer, roofline sanity), Tier 2 Shadow Execution (mirrored live traffic with async diffing), Tier 3 Canary Routing (1-5% live slice with instant fallback tripwires), and Tier 4 Production Gate (signed cryptographic receipt and automated circuit breakers).
The promotion evidence ladder turns generated code into production infrastructure. A candidate kernel must clear every laboratory gate, prove stability under zero-impact shadow replay, and maintain automated rollback tripwires during canary rollout before earning library promotion.

Tier 1: Lab verification

The candidate clears the automated harness: the operator contract passes, ptxas shows zero local memory spills, multi-scale tests verify prime lengths and adversarial floats, Compute Sanitizer reports zero hazards, and benchmark throughput aligns with the Roofline model.

Tier 2: Shadow execution

Deploy the compiled candidate to a production inference node in shadow mode. The inference runtime duplicates real customer requests: the trusted reference kernel computes the user-facing response, while the candidate kernel runs concurrently on an asynchronous stream with zero impact on user latency.

An asynchronous worker compares candidate outputs against reference tensors. Shadow execution audits three critical metrics under production traffic:

  • Numerical consistency: Verify that real input distributions (such as varying context lengths and sparsity) don't trigger unexpected precision divergence or NaNs.
  • Host and device memory leaks: Monitor virtual memory metrics (VMM) and CUDA caching allocators over millions of invocations.
  • JIT compilation cardinality: Ensure the runtime doesn't compile a new binary for every novel sequence length, which exhausts host RAM and GPU memory.

Tier 3: Canary routing

Route a small fraction of live traffic (e.g., 1% ramping to 5%) directly to the candidate kernel behind a dynamic feature flag. Execution is restricted to tested GPU architectures via dispatch predicates.

During canary routing, automated tripwires monitor three failure indicators:

  • Tail latency regressions: A sudden spike in P99 or P99.9 latency indicates warp serialization or cache thrashing.
  • Driver and hardware errors: Any GPU XID error, CUDA illegal address trap, or hardware engine reset trips the circuit breaker immediately.
  • Downstream logit drift: Sample output token distributions to ensure downstream generation remains identical.

If any tripwire triggers, the feature flag flips within milliseconds, routing all traffic back to the trusted reference without dropping requests.

Tier 4: Production gate

Full promotion commits the candidate to the core operator registry. The kernel includes an automated circuit breaker, a permanent reference fallback path, and a cryptographically signed promotion receipt.

Read benchmark scores within their boundary

Research benchmarks measure model capabilities across standardized harnesses, but they don't certify production readiness:

BenchmarkUseful signalBoundary
KernelBenchCorrect-and-faster rate across 250 PyTorch workloads under fixed thresholds[10]Reference 10KernelBench: Can LLMs Write Efficient GPU Kernels?https://arxiv.org/abs/2502.10517Uses fixed public shapes; doesn't test general layout or prime dimension coverage
KernelBench-VerifiedH200 evaluation with a TF32-enabled baseline, four distributions, and memory tracking[11]Reference 11KernelBench-Verified: Do LLM-Generated Kernels Actually Beat PyTorch?https://arxiv.org/abs/2607.16241Best-of-five selection; excludes degenerate tasks; focuses on single-turn generation
KernelBench-X176 tasks across 15 categories, precision variants, and cross-GPU hardware efficiency[12]Reference 12KernelBench-X: A Comprehensive Benchmark for Evaluating LLM-Generated GPU Kernelshttps://arxiv.org/abs/2605.04956Hardware-specific wins don't guarantee portability to untracked architectures
SOL-ExecBench235 B200-targeted problems with hardware-derived Speed-of-Light (SOL) bounds[13]Reference 13SOL-ExecBench: Speed-of-Light Benchmarking for Real-World GPU Kernels Against Hardware Limitshttps://arxiv.org/abs/2603.19173Bound calculations depend on fixed baseline software; doesn't evaluate deployment safety

Aggregate benchmark scores can mask localized regressions. A candidate might achieve a 1.5x average speedup across common shapes while silently producing incorrect results on strided views. Always evaluate candidates against your application's exact operator contract and production distribution.

Preserve a promotion receipt

Every promoted kernel requires an immutable, machine-readable promotion receipt that records its complete provenance:

promotion-receipt.json
1{ 2 "operator": "weighted_rmsnorm", 3 "contract_version": "3", 4 "status": "promoted_production_ready", 5 "candidate_source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", 6 "candidate_binary_sha256": "5f4dcc3b5aa765d61d8327deb882cf992b95bc6809623e1f5899996d9962a6b2", 7 "dispatch": "valid_inputs && tested_cuda_arch && x_contiguous && weight_contiguous && H%128==0 && !backward_needed", 8 "target": { 9 "gpu": "NVIDIA H100 80GB HBM3 (UUID: GPU-12345678)", 10 "sm": "sm_90a", 11 "driver": "550.54.14", 12 "toolkit": "12.4.1", 13 "pytorch": "2.4.0+cu124" 14 }, 15 "correctness": { 16 "suite_version": "hidden-v7", 17 "reference_sha256": "8f64243b827e834b6e5b871fa14b8a8b17b2b8e3a241270c8a81615d6c8b9d8a", 18 "status": "passed", 19 "cases_tested": 1420, 20 "cases_failed": 0, 21 "tolerance_policy": "rmsnorm-fp16-v3", 22 "case_results": "artifact://audit/correctness/rmsnorm_v3_results.parquet" 23 }, 24 "sanitizers": { 25 "memcheck": {"status": "passed", "errors": 0}, 26 "racecheck": {"status": "passed", "errors": 0}, 27 "initcheck": {"status": "passed", "errors": 0}, 28 "synccheck": {"status": "passed", "errors": 0} 29 }, 30 "benchmark": { 31 "protocol": "paired-abba-v4", 32 "baseline_revision": "torch-2.4.0-native", 33 "raw_samples": "artifact://audit/bench/rmsnorm_v3_timing.parquet", 34 "cache_regime": "rotated_buffers", 35 "speedup_median": 1.34, 36 "achieved_bandwidth_tbs": 2.82 37 }, 38 "memory": { 39 "peak_device_bytes": 16777216, 40 "workspace_bytes": 0, 41 "artifact_cache_entries": 1 42 }, 43 "approval": { 44 "reviewer": "[email protected]", 45 "signature": "30450221008f...c89012" 46 }, 47 "rollout": { 48 "feature_flag": "weighted_rmsnorm_generated_v3", 49 "canary_scope": "h100-cluster-east-1", 50 "rollback_target": "weighted_rmsnorm/reference@contract-v3" 51 } 52}

A human reviewer inspects the candidate code, verifies that dispatch predicates match the library specification, reviews licensing, and confirms that the rollback target is tested before signing the receipt.

Promotion rubric

Promotion uses hard gates before evaluating performance scores:

GatePromote conditionRequired evidence
ContractStable schema, semantics, domain, fallback, and aliasingVersioned operator specification
CorrectnessZero failures across visible, input-blind, hidden, and adversarial suitesCase results and tolerance policy
SafetyZero memory, race, initialization, and synchronization hazardsCompute Sanitizer reports with zero errors
ArtifactCandidate source and loaded binary match; no forbidden behaviorHashes, ptxas logs, symbols, dependencies
PerformancePaired improvement on target workload with baseline parityRaw CUDA event samples and hardware records
MemoryPeak, workspace, host, and cache growth remain within budgetAllocator traces and cache cardinality
OperationsReviewer, canary, alarms, owner, and one-step rollback readySigned receipt and rollout plan

No speedup justifies bypassing a safety or contract gate. Once all hard gates pass, teams can rank candidates by latency, maintainability, and resource utilization.

Mastery check

Evaluation rubric

  • Foundational: Distinguish between generated source code, benchmark pass rates, and production promotion criteria.
  • Intermediate: Design a multi-scale hidden test suite, Compute Sanitizer verification plan, and Roofline sanity check for a GPU operator.
  • Advanced: Implement a closed-loop refinement agent using NCU warp stall counters and manage canary rollouts with sub-millisecond fallbacks.

Diagnose a misleading pass

SymptomLikely gapNext check
Random values pass, but a sliced view failsTest varied values but left memory layouts contiguousAdd stride, offset, and non-contiguous view tests
Output values match, but caller's next layer corruptsKernel mutated input tensors or aliased storageVerify input byte hashes before and after execution
Candidate is faster on every run, but speed exceeds physical limitsBenchmark measures host enqueue or kernel skips workRecord CUDA events and verify achieved bandwidth vs Roofline
Fixed-shape latency is excellent, but host RAM leaksRuntime JIT-compiles a new binary for every novel dimensionMeasure compilation cache cardinality across varying shapes
Kernel runs cleanly on test machine, crashes on another GPUKernel relies on architecture-specific warp behaviorsAdd GPU architecture predicates and test on target hardware
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 kernel passes a contiguous [2, 4096] smoke test and reports a 1.4x speedup. Which missing check most directly blocks correctness promotion?

Correct answer: Running an independent test suite across prime row lengths, unaligned strides, and non-finite values

A single public fixture can't establish operator domain. The correctness gate requires independent multi-scale testing across hidden shapes, strides, dtypes, and edge cases before performance metrics have promotion value.

2.An LLM generates a CUDA kernel that achieves high speedup on small test shapes, but memory bandwidth drops to 120 GB/s on production workloads. What defect does this symptom indicate?

Correct answer: Uncoalesced memory access patterns that fit inside L1/L2 cache during small tests but saturate memory channels on large tensors

On tiny test inputs, uncoalesced memory accesses fit inside a single cache line without penalty. Under production workloads spanning gigabytes of data, uncoalesced strides force the memory controller to issue dozens of split sector transactions, crippling throughput.

3.A generated kernel supports only contiguous memory where H is divisible by 128. How must the production wrapper handle non-conforming inputs?

Correct answer: Dispatch supported shapes to the candidate kernel and route all other valid inputs to the reference implementation

A fast path may have a specialized dispatch domain as long as the wrapper explicitly routes all other valid inputs to the trusted reference. Silently casting, reinterpreting, or rejecting valid calls breaks the public contract.

4.What is the primary operational purpose of running shadow execution before canary routing?

Correct answer: Auditing numerical consistency and memory stability against live production traffic without affecting user responses

Shadow execution runs the candidate asynchronously on mirrored production traffic with zero customer impact, catching memory leaks, JIT compilation bloat, and real-world numerical drift before any user traffic is routed.

5.A benchmark for a memory-bound RMSNorm kernel on an H100 GPU (3.35 TB/s peak HBM3) reports an achieved bandwidth of 5.2 TB/s. What does this result prove?

Correct answer: The benchmark is invalid because achieved throughput exceeds the physical memory bandwidth ceiling, indicating skipped work or dead-code elimination

A kernel can't exceed the physical memory bandwidth of the GPU. Reporting 5.2 TB/s on a 3.35 TB/s bus means the benchmark is invalid: the kernel is either returning early, dead-code eliminating stores, or measuring host enqueue overhead.

6.Which NVIDIA Compute Sanitizer tool detects shared memory Read-After-Write (RAW) data races caused by missing thread barriers?

Correct answer: racecheck

racecheck specifically intercepts and analyzes shared memory access hazards between warps and threads (RAW, WAR, WAW). memcheck detects out-of-bounds accesses, while synccheck detects divergent barriers.

7.Why does an autonomous evaluation harness rotate memory buffers across timing iterations rather than reusing a single tensor?

Correct answer: Reusing the same buffer keeps data cached in L2, producing an artificial cache benchmark rather than measuring HBM memory bandwidth

Reusing the same small tensor repeatedly ensures it remains resident in the GPU's large L2 cache (such as 50 MB on H100), measuring L2 bandwidth (12 TB/s) instead of real HBM memory bandwidth (3.35 TB/s).

8.An Nsight Compute (NCU) profile shows high smsp__warp_issue_stalled_short_scoreboard_pct for an RMSNorm kernel. What optimization should the refinement feedback loop suggest to the LLM agent?

Correct answer: Pad shared memory arrays to eliminate bank conflicts during reduction passes

Stalls on the short scoreboard occur when warps wait on shared memory or MIO operations, typically caused by shared memory bank conflicts. Padding array dimensions (such as s_data[128 + 1]) offsets bank addresses and resolves the stall.

9.What is the primary risk of providing full compiler error traces and hidden test outputs directly to an LLM repair agent across many iterations?

Correct answer: The model will memorize the hidden evaluation fixtures and optimize specifically for test literals rather than fixing general semantics

Exposing raw evaluation outputs and test tensors allows the agent to overfit or hardcode specific values. Telemetry must be sanitized to expose structural error categories without leaking private fixtures.

10.All laboratory and canary gates pass for an AI-generated kernel. What final artifact makes production adoption operational, accountable, and reversible?

Correct answer: A signed promotion receipt binding source and binary hashes, accompanied by a dynamic feature flag and tested reference fallback

A cryptographic receipt binds the exact binary, source, and environment to a named reviewer, while dynamic feature flags and tested fallback paths ensure the change is operational and instantly reversible.

10 questions remaining.

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

Apply the same engineering rigor to custom low-bit arithmetic: freeze the operator contract, verify numerical degradation across hidden sequences, benchmark with rotated memory buffers, and preserve instant fallback.

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

NVIDIA CUDA Compiler Driver NVCC

NVIDIA · 2026 · Official documentation

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

CUDA Binary Utilities

NVIDIA · 2026 · Official documentation

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

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 semantics

PyTorch Contributors · 2026

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

PyTorch Benchmark

PyTorch Contributors · 2026 · Official tutorial

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

Nsight Compute Profiling Guide

NVIDIA · 2026 · Official documentation

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

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

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.