Performance measurement · Research feature

AI System Uses Micro-Profiling Tools to Optimize GPU Kernel Code

The study evaluates KernelPro, an AI system that generates and optimizes GPU kernel code by combining large language models with micro-profiling tools.

Adapted from research by Jiading Gai, Shuai Zhang, Kaj Bostrom and colleagues.

arXiv preprint revision · 2026-08-08 · Attribution & reuse
In this article
Editorial illustration of processor die.

Editor’s introduction

The study evaluates KernelPro, an AI system that generates and optimizes GPU kernel code by combining large language models with micro-profiling tools. It compares performance across KernelBench levels and expert-optimized kernels, showing average speedups of 2.42x to 5.30x and outperforming hand-tuned kernels by 1.23x. The system uses semantic feedback operators to convert raw hardware metrics into natural language guidance, enabling more actionable insights. Each component—micro-profiling tools, MCTS search, and tool orchestration—was tested in ablation studies, with statistically significant improvements in optimization quality. The research also demonstrates that KernelPro achieves better energy efficiency than prior systems, reducing energy use by 11.6% at matched performance. Findings are based on numerical correctness verified through torch.allclose comparisons.

Introduction

Optimizing GPU kernels demands expertise that spans hardware architecture, memory hierarchies, instruction scheduling, and vendor-specific programming models. Experienced engineers follow a disciplined cycle: profile the kernel, recognize bottleneck patterns in the metrics, diagnose root causes, apply targeted transformations, and re-profile to verify. The bottleneck shifts after each successful optimization, and the process repeats until hardware limits are reached. What makes experts effective is not the ability to read numbers from a profiler, but the pattern recognition and diagnostic reasoning they apply to those numbers–heuristics refined over years and often codified into personal scripts and tools.

Recent LLM-based CUDA optimization systems have shown that language models can generate competitive kernel code when given profiling data. However, these systems present raw or lightly summarized metrics directly to the LLM and rely on the model to implicitly replicate expert reasoning. This conflates two distinct capabilities: interpreting hardware telemetry (a structured, rule-governed task) and generating optimized code (a creative, context-dependent task). By asking the LLM to do both at once, existing agents forgo the systematic intermediate analysis that makes human experts reliable–they miss optimizations, produce inconsistent diagnoses, and cannot easily incorporate new analysis patterns without retraining.

We introduce KernelPro, a closed-loop multi-agent system that separates these concerns by encoding expert heuristics as pluggable micro-profiling tools–executable analysis functions that transform raw hardware metrics into actionable natural language guidance before the code-generation LLM sees them. Each tool implements a specific diagnostic pattern: a trigger condition (e.g., tensor core utilization below 10%), analysis logic (e.g., check whether the kernel performs reducible matrix operations), and a prescriptive recommendation (e.g., “rewrite using CUTLASS GEMM for a major expected speedup”). A two-stage invocation pipeline first classifies the kernel’s bottleneck type via roofline analysis, then dispatches only the relevant tools–reducing prompt noise and focusing the LLM on pertinent optimizations.

Several recent systems apply LLMs to CUDA kernel optimization, differing primarily in how hardware profiling data reaches the LLM. Some rely solely on end-to-end timing without hardware profiling. Others pass raw or statistically filtered ncu metrics directly into the LLM’s prompt and rely on the LLM itself to interpret them. cuPilot adds roofline-based bottleneck classification but stops at a label (memory-bound vs. compute-bound) without generating actionable directives from the underlying counters. In all cases, the LLM remains the sole interpreter of profiling data–no prior LLM-based system provides programmatic translation of hardware counters into optimization directives. The challenge predates LLMs: classical performance advisors such as GPA use instruction sampling and data-flow analysis to attribute stalls to their root causes and emit human-readable optimization suggestions, and independently observe that raw profiler output “provide[s] little insight into how to improve the code.” KernelPro adopts the same diagnose-then-prescribe philosophy but closes the loop: its micro-profiling tools translate counters into natural-language directives before any LLM involvement, and an LLM then applies the fix directly rather than leaving it to a human engineer. Our ablation (Appendix C) confirms that this tool-based interpretation significantly outperforms both no-feedback and raw-metrics-only feedback.

CUTLASS and CuTe code generation. Several agents target NVIDIA’s CUTLASS library, but at different abstraction levels. AVO and StitchCUDA generate high-level CUTLASS template instantiations–selecting tile sizes, pipeline stages, and epilogue fusions from a predefined configuration space. KernelPro operates at a lower level: it generates raw CUDA+CuTe source code by autonomously searching the CUTLASS/CuTe codebase for layout algebras, copy atoms, and MMA atoms, then composing them into novel kernels – the same workflow used by expert kernel engineers.

Tree search and evolutionary methods for LLM code optimization. A growing body of work integrates Monte Carlo Tree Search with LLMs. MCTSr applies UCT to mathematical olympiad problems, where each node represents an answer version refined via self-evaluation. DeepSearch embeds MCTS into the RL training loop with global frontier selection, targeting model weight updates rather than inference-time optimization. TreeRL proposes entropy-guided token-level branching that forks from high-uncertainty tokens. Tree-GRPO uses complete agent steps as tree nodes and derives process supervision signals from intra-tree relative advantages. These systems treat tree search as a mechanism for training LLMs or generating reasoning traces. AlphaEvolve takes an evolutionary approach, using population-based LLM sampling with scalar fitness to optimize algorithms including TPU kernels, but requires millions of samples over days of compute.

High-Level Pipeline

KernelPro operates as a multi-agent system with three primary agents coordinated by a search orchestrator. The Benchmarking Agent (Stage 1) analyzes the reference implementation to establish baseline performance metrics and classify the kernel’s bottleneck type (compute-bound, memory-bound, latency-bound, or mixed) via roofline analysis. The Programmer Agent generates optimized CUDA code in three modes: initial generation, debugging compilation/correctness errors, and iterative optimization based on profiling feedback. The Profiling Agent (Stage 2) executes micro-profiling tools filtered by the Stage 1 bottleneck classification, producing semantic feedback that guides the next optimization iteration. This two-stage architecture–bottleneck classification followed by filtered tool execution–reduces prompt noise and focuses the LLM on relevant optimizations.

All agents communicate with LLMs through a backend-agnostic interface built on the OpenAI Agents SDK, so the same agent code runs unmodified on AWS Bedrock or vLLM. The Bedrock path requires the most adaptation: a custom adapter translates tool definitions, multi-turn tool-use/tool-result exchanges, and structured responses between the SDK’s tool-calling protocol and the Bedrock Claude Messages API, whereas vLLM’s OpenAI-compatible endpoint is consumed directly with no protocol translation.

Benchmarking Agent (Stage 1)

The Benchmarking Agent runs once per problem at the start of optimization. It parses the reference code to identify the mathematical operations involved (GEMM, Softmax, convolution, etc.), computes a roofline estimate of theoretical peak performance from compute intensity and hardware specs, and classifies the problem as compute-bound, memory-bound, or mixed based on the CI/ridge ratio. It then profiles the reference implementation with ncu to validate this theoretical classification against measured utilization. The output is a ReferenceAnalysis object that guides downstream tool selection for the Programmer and Profiling Agents.

Profiling Agent (Stage 2)

First, the agent collects metrics from three profiling sources: ncu provides kernel-level metrics (throughput, occupancy, stalls), nsys provides system-level timeline data (launch overhead, synchronization), and SASS analysis provides instruction-level information by disassembling the compiled.so file. To obtain the binary path, KernelPro intercepts PyTorch’s load_inline compilation pipeline, capturing the ephemeral.so artifact for downstream ncu and SASS analysis. ncu profiling targets only the KernelPro-generated __global__ kernels identified via binary symbol analysis (cuobjdump -symbols, filtering for STB_GLOBAL entry points), with fallback to duration-based kernel selection for library-call solutions (e.g., cuBLAS). This multi-level fusion is essential–ncu alone cannot distinguish whether a kernel uses Ampere-style async copies or Hopper TMA, but SASS reveals this directly.

Second, the agent invokes the micro-profiling tool registry. The key function ToolRegistry.generate_prompt_guidance iterates through registered tools (filtered by Stage 1 bottleneck type), executes each tool’s analyze method on the collected metrics, and aggregates triggered findings into markdown-formatted guidance. This guidance is injected into the LLM prompt under an “Automated Bottleneck Analysis” section.

Open-Source Library Integration

We demonstrate this architecture with CUTLASS, an industry-grade library for custom tensor-core kernels (adopted in systems such as PyTorch and TensorRT); its CuTe layer provides the tensor and layout abstractions (copy atoms, MMA atoms, layout algebra) used to compose such kernels from scratch. Generating this code is challenging for LLMs: it must match hardware-specific instruction shapes and satisfy architectural conventions that are easy to violate and sparsely documented, and it depends on a precise build configuration.

This design follows the principle that the LLM should discover relevant patterns autonomously rather than receiving pre-selected examples. The LLM decides what to search based on the optimization context—e.g., retrieving wgmma pipeline patterns and MMA/copy atoms from the live CuTe source when generating Hopper tensor-core code—and composes them into novel kernels. This is the source-level workflow that expert engineers use, and the mechanism behind KernelPro’s from-scratch raw-CuTe kernels (Section 5.4). Contemporaneous work (GrepSeek; ) independently finds that agent-issued executable search over a raw corpus can outperform index-based retrieval.

Additionally, a constraint mining tool pre-extracts hard architectural requirements from CUTLASS source (barrier lifecycle, warp specialization rules, vectorized epilogue patterns, tile swizzle) and injects them as non-negotiable code generation constraints. A companion tool validates generated code against these requirements before compilation, catching architectural errors early.

Multi-Language Input Support

This multi-language capability addresses a key production need: automating kernel optimization and hardware migration regardless of the source abstraction. Triton kernels hitting DSL-imposed performance ceilings (e.g., Ampere-era instructions on Hopper, Section 5.4), PyTorch prototypes requiring production CUDA implementations, and legacy CUDA kernels needing re-optimization for new GPU architectures can all be optimized through a single system—eliminating the need for scarce CUDA experts at each translation boundary.

Progressive Widening with Domain-Adapted Branching

At each internal node during traversal, KernelPro computes a virtual child UCT score: the hypothetical UCT of a new child that would inherit its parent’s mean reward as a prior and receive a fair share of visits. If this virtual score exceeds the UCT of the best existing child, the search expands the node (generates a new solution as its child) rather than descending further. This mechanism provides a principled expansion criterion–new children are only created when the uncertainty about unexplored alternatives outweighs the expected value of exploiting known children.

Dead-End Pruning and ROOT Re-expansion

Two mechanisms prevent the search from stalling. First, terminal marking: when a failed node accumulates three or more repair children that all fail, it is marked terminal and excluded from future selection. This prunes dead-end subtrees where the underlying algorithmic approach is fundamentally broken, propagating upward through the tree as entire branches become exhausted.

Second, ROOT re-expansion: when UCT selects the virtual ROOT node itself (rather than any of its children), the system generates entirely fresh solutions from scratch rather than refining existing ones. This mechanism–inspired by MCTSr –injects exploration diversity as the tree deepens, preventing the search from over-committing to early seeds that happen to look promising. The progressive widening gate on ROOT ensures this happens at a controlled rate: fresh seeds are generated only when the virtual child’s UCT score at ROOT exceeds that of all existing top-level solutions, indicating that unexplored regions of the solution space may outperform known optima.

Search Memory: Cross-Iteration Learning

A fundamental challenge in iterative LLM-based optimization is that each iteration starts tabula rasa–the LLM has no memory of prior attempts beyond the immediate parent’s profiling feedback. This leads to three failure modes we observe in practice: (1) repeated errors, where the LLM re-attempts approaches that failed in earlier iterations; (2) lost discoveries, where useful search findings (file paths, API patterns) from tool calls are not carried forward; and (3) plateau behavior, where the LLM cycles between similar strategies without building toward a solution.

Pluggability and User Extensibility

KernelPro’s tools are pluggable–they can be dynamically added, removed, or modified without changing the core system via a decorator-based registration pattern (@ToolRegistry.register). Users subclass ProfilingTool, declare required metrics and thresholds, and implement an analyze method; the tool is then automatically incorporated into the proactive orchestration pipeline. This makes KernelPro a platform rather than a fixed tool: teams can encode domain-specific heuristics (e.g., MoE expert load imbalance detection), add support for new GPU architectures before official updates, or register proprietary optimizations as private tools. The full registration API and a worked example are provided in Appendix B (Listing 2).

Tool Specifications

Each tool follows the 5-tuple formalization described above. The complete tool taxonomy (15 tools organized by category and bottleneck type) and detailed specifications are provided in Appendix B, including full reference implementations (Listings 2 and 3) that make the trigger-analyze-recommend pattern concrete. We detail two representative tools below: one NCU-based analyzer and the SASS binary analysis tools.

Warp Stall Analyzers

When triggered, the tool translates the raw stall percentage into a structured diagnostic: a root cause explaining why the stall occurs (e.g., “warps are waiting for global memory operations to complete—400+ cycle latency with no prefetching”), followed by ranked actionable recommendations tailored to the dominant stall type. Memory dependency stalls produce guidance such as “use shared memory to cache frequently accessed data” and “implement vectorized loads (float4) for better bandwidth”; barrier stalls recommend “use warp-level primitives (__shfl_sync, __ballot_sync) instead of __syncthreads” with a code example showing the correct pattern; scoreboard stalls suggest increasing instruction-level parallelism or using async copies (cp.async) on Ampere+; and branch resolving stalls recommend replacing conditionals with arithmetic predication (e.g., result = cond * val1 + (1-cond) * val2). This translation is what enables the LLM to act on profiler output without requiring GPU architecture expertise—the tool bridges the gap between “47% memory dependency stalls” (a number) and “add shared memory tiling with __syncthreads between load and compute phases” (an action). The complete implementation, including the per-stall-type root causes and recommendations, is given in Listing 3 (Appendix B).

SASS Binary Analysis Tools

While ncu tools analyze runtime counters, SASS tools analyze the compiled binary itself (what hardware instructions were actually emitted by nvcc). ncu can report “tensor core utilization = 0%” but cannot explain whether the kernel lacks tensor core instructions entirely, uses an older generation (HMMA vs WGMMA), or delegates to cuBLAS (whose tensor-core kernels run as separate library launches, absent from the user kernel’s compiled.so). KernelPro extracts SASS via cuobjdump —dump-sass on the compiled.so and counts instruction patterns across five tensor core generations (WGMMA, HMMA, IMMA, DMMA, BMMA), memory operations (LDGSTS, TMA), and register spilling (STL/LDL). Full 5-tuple specifications for both SASS tools are given in Appendix B.

RegisterSpillDetector combines SASS evidence (STL/LDL counts prove spills exist) with ncu metrics to determine whether spills actually cause harm. Not all spills are pathological, so the tool triggers only under three multi-signal conditions—spill-induced latency bubbles, bandwidth contention from local-memory traffic, or register-bound occupancy that starves the scheduler—avoiding false alarms on harmless spills while catching cases where register pressure is the root bottleneck. (Exact thresholds in Appendix B.)

Results and Evaluation

We evaluate KernelPro along three axes—SOTA comparison on KernelBench, controlled ablations of each design component, and production validation on expert-optimized kernels—and close with a preliminary energy-aware extension. Throughout all experiments, a kernel is numerically correct if its output satisfies torch.allclose(out, ref, atol=1e-2, rtol=1e-3).

State-of-the-Art Comparison on KernelBench

KernelPro outperforms KernelBlaster on all three levels, with the largest margin on Level 3 (+253%)—full model architectures where MCTS-guided multi-step optimization and micro-profiling tools provide the most actionable guidance. KernelPro achieves complete task coverage: 100/100 on Level 1, 100/100 on Level 2, and 50/50 on Level 3. Despite KernelBlaster’s use of RL-style exploration and a persistent knowledge base, KernelPro achieves higher speedups with a simpler approach grounded in micro-profiling tools as expert surrogates. A comprehensive comparison with five additional concurrent systems (CudaForge, StitchCUDA, KernelFoundry, AVO, and others) confirming KernelPro’s advantage across hardware platforms and metric types is provided in Appendix A.

Energy-Aware Kernel Optimization: A Preliminary Study

Power is increasingly the limiting factor in AI scaling, and GPU energy is dominated by data movement rather than compute. This makes energy a first-class measure of kernel efficiency—yet existing LLM-based kernel agents target latency alone. KernelPro is the first CUDA kernel coding agent to optimize energy efficiency; we explore whether its profiling-driven search can reduce kernel energy, and where that reduction is separable from speedup.

Memory optimizations provide broad but incremental gains

MemoryCoalescing and Vectorization fire in 37–41 of 42 tasks but have low hit rates (4–6%). Memory access patterns are the most common bottleneck on A100 but are harder for the LLM to fix correctly—coalescing requires non-trivial data layout changes, while vectorization requires careful alignment handling.

Production Inference Kernels

To confirm the effect holds beyond KernelBench, we repeat the with-tools-versus-without-tools ablation on six representative Triton inference kernels covering common transformer serving patterns (NVIDIA A100). The kernels are: layer_norm (fused forward layer normalization with affine transform), vec_matmul (single-vector matrix multiplication for decoding), persistent_vec_matmul (persistent-loop variant that reuses thread blocks across output tiles), gemm_split_k (split-K GEMM with atomic accumulation for high-parallelism reduction), fused_moe (fused Mixture-of-Experts token routing and batched expert GEMM from vLLM), and kernel_paged_attention (paged multi-head attention with online softmax over non-contiguous KV-cache blocks from vLLM, supporting GQA). Both configurations receive identical ncu/nsys/SASS raw metrics; the only difference is whether the tool-generated guidance is included in the LLM prompt.