Designing an Agent That Writes and Tunes GPU Kernels
Machine LearningModel answerLast updated
Design an agent that generates and optimizes GPU kernels and compiler passes, covering validation strategy, correctness checks, numerical tolerances, and performance evaluation.
Scenario
Your team is exploring whether an AI agent could automate the writing and tuning of low-level GPU kernels and compiler transformation passes — work that today requires specialist engineers and many manual iterations.
Before committing to the idea, your tech lead wants a clear-eyed design review. They are not asking you to build the system yet; they want to know whether the concept is sound and, if so, what it would take to trust its outputs.
Your Task
Walk through the following:
- What the agent needs to do — what inputs it works from, what it produces, and what transformation space it operates in.
- How you would validate its outputs — distinguishing three separate bars: does it compile, is it numerically correct, and is it actually faster?
- How you would run generated code safely — isolation, resource limits, and why "it compiles" is not enough.
- What benchmarks and reference data you would use — representative shapes, data types, and hardware targets.
- Where the approach breaks down — fundamental limitations that would constrain how far you could deploy this in practice.
What Is Expected
A structured discussion with concrete mechanisms, not a high-level wish list. Call out trade-offs, failure modes, and where human review is still necessary. Numbers and examples strengthen the answer.
Hints
Hint 1
Start by bounding the problem: an agent with an unbounded transformation space is unverifiable, so name specific constraints (tile sizes, loop orders, data layouts) before discussing validation.
Hint 2
Separate correctness from performance — a kernel can be numerically wrong and still be faster, or numerically acceptable under a relaxed tolerance but only for certain data types. Treat these as independent checks, not a single pass/fail.
Hint 3
Think about what 'isolated execution' actually requires: a kernel that allocates too much memory, spins forever, or silently corrupts a shared buffer is a real risk. Describe the sandbox, not just the concept of one.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing the Problem
The first mistake is treating this as a code-generation question. It is really an evaluation question: how do you know the agent's output is safe to use? Every design decision flows from that constraint.
Start by bounding the transformation space. An agent that can rewrite arbitrary code cannot be verified in reasonable time. A practical scope might be: tile size selection, loop reordering, memory layout changes (row-major ↔ column-major, padding for alignment), and choice of hardware intrinsics for a fixed operation like GEMM or conv2d. Keeping the space finite means you can enumerate what transformations were applied and audit them.
What the Agent Produces
The agent takes a reference kernel (correct, unoptimized), a hardware target (e.g., NVIDIA A100 or AMD RDNA3), and a set of input shapes and data types. It outputs one or more candidate kernels, each tagged with the transformations applied. The tag is not optional — it is the audit trail.
Generated code is never treated as a replacement until it clears all three validation bars described below.
Three Validation Bars, Evaluated Independently
Bar 1 — Does it compile and link? Necessary but not sufficient. A kernel that compiles can still produce wrong results or consume unbounded resources. Flag compilation failures as feedback to the agent, but do not promote a successful compile as a quality signal.
Bar 2 — Is it numerically correct? Run the candidate and the reference on a shared set of inputs and compare outputs. For floating-point workloads you need a tolerance policy, not a bitwise match. A reasonable default for FP32 is a relative error under 1e-5 on typical inputs; for FP16 or BF16 you may need to relax to 1e-3 and document the decision explicitly. Test across at least: small inputs (catches index bugs), large inputs (catches overflow or precision drift), inputs with zeros and near-zero values, and inputs drawn from the actual production distribution if available.
Correctness must be checked before performance. Running a flawed kernel on your full benchmark suite wastes time and can corrupt shared state.
Bar 3 — Is it measurably faster? Use a microbenchmark harness that warms up the GPU, runs enough iterations for stable measurements (at minimum 100 iterations, discard the first 10), and reports median latency and the 95th-percentile latency — not just the best-case time. Compare against the reference kernel and, where available, a vendor-tuned library like cuBLAS or rocBLAS as an upper-bound baseline.
A speedup that disappears under a different batch size or input shape is not a real speedup. Run benchmarks across the full shape distribution the kernel will see in production, not just the shape it was optimized for.
Isolating Generated Code at Runtime
Generated code runs in a sandboxed subprocess with:
- A GPU memory cap (e.g., no more than 2 GB for a test kernel)
- A wall-clock timeout (e.g., 10 seconds per invocation; hang = disqualify)
- No write access to host memory outside the designated input/output buffers
- A separate CUDA context or HIP stream so a crashing kernel does not corrupt the evaluation harness
Log every invocation: the kernel binary hash, the input shape, the hardware target, and the measured outputs. This makes failures reproducible and gives the agent structured feedback — "kernel X timed out on shape [4096, 4096]" is actionable; a bare crash is not.
Representative Benchmarks
Pick shapes from actual workloads, not round numbers. A matrix multiply benchmark that only tests powers-of-two shapes will overfit to tiling strategies that fail on shapes like [1023, 768]. Include:
- Common large shapes (training batch sizes)
- Inference-time shapes (often small batch, e.g., batch size 1 or 8)
- At least two data types (FP32 and either FP16 or BF16)
- Two or more hardware generations if the kernel will be deployed across both
Run benchmarks on a dedicated machine or reserved GPU partition. Variance from concurrent workloads makes benchmark comparisons meaningless.
Where the Approach Breaks Down
Correctness is hard to specify completely. A reference kernel is only correct relative to a specification. If the spec is missing (common in legacy codebases), differential testing only tells you the candidate matches the reference — it does not tell you the reference is right.
Numerical tolerances are workload-dependent. A tolerance acceptable during training may not be acceptable during inference of a safety-critical model. The agent cannot set tolerances autonomously; those require human sign-off.
Performance generalizes poorly. A kernel tuned for one shape or hardware generation will often regress on others. The agent needs to be re-run and re-validated whenever the production distribution shifts.
The transformation space grows quickly. Even a bounded space of tile sizes, loop orders, and layout choices can produce thousands of candidates per kernel. Evaluating them all is expensive; the agent needs a sensible search strategy (e.g., Bayesian optimization or a learned cost model) or the iteration time becomes impractical.
Human review is still required at the release gate. No amount of automated testing removes the need for an engineer to review the transformations applied, check that the tolerance policy was appropriate for the use case, and approve promotion to production. The agent accelerates the search; it does not replace the decision.
Common Mistakes to Avoid
- Reporting only best-case latency from a single run — this makes almost any kernel look good.
- Skipping the numerical check for "obviously correct" transformations like padding — padding bugs are subtle and real.
- Using the same input shapes for correctness testing and performance benchmarking — you want independent sets so you do not overfit the evaluation.
- Treating a vendor library baseline as optional — without it you cannot know whether the agent's best result is competitive or just better than a naive reference.