Performance measurement · Research feature

Fine-Tuning GPT-5 for GPU Kernel Generation

The researchers evaluated GPT-5's performance in generating Triton GPU kernels using reinforcement learning within Makora's environment.

Adapted from research by Ali Tehrani, Yahya Emara, Essam Wissam and colleagues.

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

Editor’s introduction

The researchers evaluated GPT-5’s performance in generating Triton GPU kernels using reinforcement learning within Makora’s environment. Correctness increased from 43.7% to 77.0%, and the model solved 97.4% of problems in a full coding agent setup, outperforming PyTorch TorchInductor on 72.9% of tasks. The evaluation included corrections to original benchmark issues such as degenerate solutions and invalid inputs, ensuring more reliable performance assessment. The study demonstrates that reinforcement learning enables effective fine-tuning in domains where supervised learning is limited by data scarcity and compiler biases.

Introduction

Accelerators such as GPUs form the computational backbone of modern AI workloads. Their ability to execute massive numbers of parallel operations has enabled the training and inference of large language models at unprecedented scales. This shift toward accelerator-centric computing is rising rapidly with millions of GPUs being deployed in data centers in 2025 alone. This reflects a broader architectural transition from CPU-centric to accelerator-centric systems, as domain-specific hardware becomes the practical path to continued performance gains. The trend is driven both by increasing AI infrastructure demand and by limits of traditional CPU scaling. With the end of Moore’s Law and the breakdown of Dennard scaling, single-threaded CPU performance has plateaued, making parallel accelerators essential for continued performance growth across the entire computing stack.

However, programming GPUs, commonly referred to as kernel development, remains a challenging and time consuming task that requires significant expertise and careful performance tuning. Developers must navigate complex memory hierarchies (shared vs. global memory), manage thread synchronization and scheduling, optimize instruction-level parallelism, and handle data movement across heterogeneous compute units. As a result, efficient kernel development remains concentrated among a small group of highly specialized experts and the majority of optimized kernels are proprietary and unavailable to the broader research community. This expertise gap creates a critical bottleneck: as accelerators become widely deployed at scale, the ability to efficiently utilize their memory hierarchies and data movement patterns becomes the limiting factor in realizing their computational potential. Kernel programming expertise remains limited, posing a significant challenge for modern language models. Beyond general-purpose libraries, these models depend on carefully optimized, application-specific kernels that reduce memory traffic and leverage hardware parallelism to achieve competitive performance and efficiency.

Limitations of Supervised Fine Tuning for GPU Kernel Generation

Recent advances in large language models have shown strong capabilities in software engineering tasks, including code generation, program synthesis, and automated bug repair. These results also motivate applications of large language models to accelerator programming, with recent work exploring GPU kernel generation through agentic systems, reinforcement learning, and evolutionary optimization. Benchmarks such as KernelBench and datasets such as KernelBook have been introduced to support evaluation and training in this domain. Although these efforts show promise, substantial progress is still required before large language models can reliably generate production quality high performance GPU kernels. Moreover, due to numerous challenges in this domain, supervised training is significantly more difficult than in other programming settings as we describe in more detail below. Specifically, GPU kernel generation presents a set of challenges that differentiate it from general purpose code generation. These challenges can be broadly grouped into four categories: data scarcity and quality, limitations of compiler generated synthetic data, the insufficiency of functional correctness as an optimization objective, and the exponential growth of the optimization space.

Data scarcity and quality

High performance GPU kernels require deep hardware specific knowledge and are typically proprietary. Public repositories consist mainly of educational examples or suboptimal implementations, which limits the construction of large scale and high quality training datasets for supervised learning and further restricts the availability of labeled datasets. Unlike general Python or Java code, where millions of examples are available, production grade kernel implementations number in the thousands at best. For example the Python subset of the Stack v2 dataset contains 96,448,523 samples, whereas the KernelBook dataset which consists of PyTorch and synthetic Triton code only contains 18,162 examples.

Correctness is insufficient

A functionally correct kernel that produces the right output may still be orders of magnitude slower than an optimized implementation. Even when ground-truth optimized kernels are available, the optimization strategies are hardware-specific and may not generalize across GPU architectures, such as NVIDIA Hopper versus Blackwell. Furthermore, specific devices have different hardware support even within the same hardware architecture generation. For example, within the Blackwell family of devices, the desktop-grade RTX 5090 does not include Tensor Memory Accelerators (TMA), while the server-grade B200 does. These discrepancies, along with differences in memory technology, speed, low-precision support, and distributed computing APIs, severely hamper performance portability across devices.

Reinforcement Learning for Kernel Generation

As large language models (LLMs) approach the data saturation limit for pretraining, post-training techniques such as reinforcement learning (RL) have gained significant attention. We reformulate the task of kernel generation as a reinforcement learning problem, where the model learns from execution-based feedback. This approach alleviates the dependency on large quantities of high-quality training data while enabling the model to explore the optimization space in a flexible way and discover novel kernel implementations.

Reinforcement Learning from Verifiable Rewards (RLVR)

Traditional reinforcement learning from human feedback relies on learned reward models trained on human preferences, which can be subjective, expensive to collect, and prone to reward hacking. In contrast, Reinforcement Learning from Verifiable Rewards (RLVR) uses deterministic, rule-based reward functions that provide unambiguous binary or continuous feedback based on objectively verifiable criteria.

The Role of Strong Base Models

A fundamental prerequisite for successful RLVR training is that the base model must already possess basic competency in the target domain. If the model cannot generate syntactically valid code or understand the basic structure of Triton kernels, nearly all generated samples will fail compilation, resulting in uniformly zero rewards. In such cases, the model receives no learning signal and cannot improve through RL. This cold start problem is particularly important in specialized domains like kernel programming, where even syntactically correct code requires deep understanding of hardware primitives, memory hierarchies, and parallelization patterns.

This is why we employ GPT-5, a highly capable base model that already demonstrates strong code generation abilities and understanding of GPU programming concepts. GPT-5 has existing knowledge of Triton syntax and parallel programming patterns that ensures that a substantial fraction of initial samples compile successfully and produce non-zero rewards, which provides the gradient signal necessary for RL to drive improvements. Models without this foundation would require extensive supervised pre-training or fine-tuning on kernel code before RL could be effective, which would significantly increase the data requirements that RL was meant to alleviate. The choice of base model is therefore not only a matter of initial quality but also a prerequisite for the feasibility of RL training itself. We experimented with RL training on smaller open models such as Qwen-4B, Qwen-8B and Qwen-32B and observed that the reward value quickly plateaus, which suggests that the model is able to generate kernels for a limited number of problems and can not obtain further improvements. This behavior has also been observed by other works.

Scaling RL Training for Kernel Generation

Scaling Reinforcement Fine Tuning (RFT) to kernel generation is non-trivial and requires attention to several factors. First, a curated training dataset that spans diverse computational patterns. Second, a robust evaluation infrastructure that can efficiently execute generated code and provide meaningful reward signals, mechanisms to prevent reward hacking where the model exploits loopholes in the reward function, and tools that enable the model to iteratively debug and refine kernels.

The experimental results demonstrate fine-tuning GPT-5 for Triton code generation achieves superior performance compared to existing large language models, establishing new state-of-the-art results. Specifically, with three attempts, our fine-tuned model successfully generates 221 functionally correct kernels out of 264 total test cases. Furthermore, beyond functional correctness, the model achieves a new benchmark in geometric mean speedup over TorchInductor on an expanded KernelBench test set, highlighting its capability to produce not only correct but also highly optimized kernels for modern accelerator architectures.

Difficulty Ranking via LLM Judge

To ensure that the dataset is not skewed toward simple easy problems, we assess the difficulty level of the problems in the dataset. Unlike mathematical reasoning where difficulty can be estimated from solution complexity, kernel difficulty depends on several factors including algorithmic complexity, optimization possibilities, and hardware-specific considerations.

Shape Diversification

The size of tensor shapes is critical for exposing meaningful computational cost and optimization opportunities, as trivial shapes mask performance differences. To obtain realistic shapes that better reflect the computational characteristics of each problem category, we construct a dedicated prompt and query a large language model to propose appropriate tensor dimensions for every problem. Before applying this procedure, we remove all problems that are not executable from the dataset.

Runtime-based filtering

and retain only problems whose baseline runtime falls within this interval. This runtime filtering ensures that performance improvements can be measured reliably, evaluation overhead during RL remains tractable, and kernels fall into regimes where optimization is practically meaningful. To avoid over-representing tasks that are too easy and provide limited learning signal, we additionally retain only examples with predicted difficulty level greater than 2.

Constructed subsets

From the pool of kernels with measured runtimes, we construct two training subsets of size 100 and 1,000 using the sampling strategy described above. These subsets are designed to study the effect of training set scale on RFT while preserving a representative difficulty profile. Training on the full set of 11,363 examples is ongoing.

KernelBench as evaluation set

Our evaluation benchmark, KernelBench, contains 264 PyTorch reference problems spanning diverse computational patterns, including matrix operations such as multiplication, transpose, and attention, convolutions, reductions such as sum, max, and softmax, and element wise operations such as activation functions and normalization. We use an extended variant of KernelBench that adds an additional problem level and corrects several issues in the original benchmark related to input configurations and problem validity. The original KernelBench dataset contained artifacts that could distort performance evaluation. Some problems admitted degenerate solutions, for example kernels solvable through constant value fills, no op computations, or removal of redundant operations, rather than executing the intended computation. Other problems exhibited inconsistent input sizes across instances, weakening the comparability of measured performance. In the extended variant, we remove no op and degenerate problems, enforce consistent and meaningful input sizes, and ensure that each benchmark requires nontrivial computation, yielding a clearer and more reliable assessment of kernel performance.

Tools

We equip the model with tools that enable reasoning about the correctness and performance of generated kernels. These tools allow the model to obtain implementation examples, search the web for additional details, retrieve existing kernels, and profile kernels. While these tools are currently used at inference time, incorporating tool usage during training remains work in progress.

Kernel Search Tool

This tool allows the model to explore additional strategies for kernel optimization and error correction, rather than relying solely on generating an optimized kernel from the reference code in a single step. This effectively builds on prior trajectories by using a valid starting kernel implementation and exploring the optimization space starting from that point.

Web Search Tool

The web_search tool enables the model to issue external queries to retrieve information from publicly available sources. When the model encounters failure modes in kernel optimization on a specific hardware platform, it can use this tool to gather evidence about established optimization strategies, including memory tiling, register allocation schemes, or parallel scheduling patterns found in expert discussions and technical documentation. The tool receives a single parameter, which is the search query.

Profiler Tool

We also equip the model with a profiler tool to support more fine-grained reasoning about kernel performance. By a profiler, we refer to a system that collects detailed runtime measurements of generated kernels, such as execution time breakdowns and hardware level utilization signals. Compared to aggregate metrics such as end to end speedup, these measurements provide more informative feedback about the underlying performance bottlenecks and optimization opportunities. Access to profiling information can enable the model to reason explicitly about how design choices affect performance and to guide targeted optimizations. Empirical evaluation of the profiler tool during training and inference are left as future work.

Caching

To improve system efficiency, we implement a caching mechanism that stores reference code, generated kernels, and their associated evaluation results in a database. When the model produces a kernel that matches a previously evaluated candidate during training, the system retrieves the cached results rather than re-executing the reference and kernel code. This eliminates redundant executions and substantially accelerates training. To further increase cache hit rates, we apply AST-based code canonicalization prior to cache lookup. Specifically, we parse both the reference and optimized kernels into abstract syntax trees (ASTs), remove docstrings and comments, and normalize formatting using ast.unparse. This procedure maps semantically equivalent programs that differ only in whitespace, formatting, or documentation to the same canonical representation, enabling cache reuse despite superficial textual differences. Over a three-week period, this preprocessing increased the cache hit rate to approximately 16%, avoiding 227.6 hours of redundant evaluations and reducing computational cost while preserving evaluation fidelity.

LLM as a Judge

Our second defense relies on an auxiliary LLM, GPT-5, acting as a judge. We design a prompt that enumerates known categories of reward hacking and apply it only after reachability analysis succeeds. The judge analyzes the generated kernel to detect semantic inconsistencies or degenerate behaviors. We additionally include an unknown_category label that allows the judge to flag previously unseen forms of hacking. Together, static reachability analysis and LLM based judging discourage the generation of kernels that are non meaningful or not useful.

Experimental Results

In this section, we present and analyze the results obtained after fine tuning GPT-5 for Triton kernel generation. We compare the performance of the RL fine tuned GPT-5 model against the base GPT-5, Gemini 2.5 Pro, Claude, and Grok across multiple evaluation metrics, including functional correctness, outperforming TorchInductor. We report speedup using the Geometric Mean, as it more accurately captures relative gains and losses in performance, including both speedups and slowdowns, compared to the arithmetic mean. This comparison demonstrates the effectiveness of our reinforcement fine tuning framework in improving both the correctness and efficiency of the generated kernels. Additionally, for comparison purposes, we include Makora’s most advanced agent for kernel generation known as MakoraGenerate. MakoraGenerate is a multi-agent evolutionary system that evolves prompts by dynamically injecting parent kernels, top performers, and diverse candidates, using an exploit/explore selection strategy and tools for code generation, evaluation, documentation lookup, and optimization planning.

Setup

To ensure fair comparisons across models, all evaluations are conducted with a maximum of 3 retries to mitigate potential time out or connection failures during API calls. We further cap the maximum number of refinement steps at 3, where attempts and steps are used interchangeably, allowing each model to iteratively correct errors from the previous attempt, including syntax mismatches, incorrect indexing, or missing memory annotations. We first report results under a single attempt setting, where no refinement steps are permitted.

Tools Impact

We evaluate the impact of tool usage at inference time. Although training with tools can teach when and how to invoke tools and how to leverage their outputs, it increases latency and context length, and RFT with tool calling is still in progress. We therefore limit tool usage to inference here and analyze its effects on correctness and performance.

We consider three tools: WS (web_search), KE (kernel_evaluator), and KS (kernel_search). Each example is evaluated for up to three attempts, where later attempts include additional interaction history. Tool usage is capped at three calls per example per attempt.

LLMs have showed significant success in code generation, and recently there has been a line of works focusing on developing agentic systems or training or fine-tuning LLMs for GPU Kernel code generation. For example, EvoEngineer proposes an LLM-based framework for evolving CUDA kernels by decomposing optimization tasks into traversal strategies, enabling systematic exploration of the optimization landscape. In contrast, Sakana AI’s CUDA-Engineer introduces an agentic system that integrates benchmarking, formal verification, and optimization techniques to iteratively improve kernel performance and correctness. Astra represents the first multi-agent system that employs several LLM-based agents collaborating to optimize GPU kernels. The framework operates through an iterative process in which agents generate, test, and propose improvements to existing CUDA implementations, thereby progressively enhancing performance, correctness, and efficiency through coordinated reasoning and feedback. CUDA-LLM introduces a refinement loop in which each iteration leverages feedback from previous iterations to progressively enhance the generated CUDA kernels. This iterative process enables the model to identify inefficiencies, correct errors, and improve both the functional correctness and performance of the resulting GPU code over time. Recent research has also focused on fine tuning large language models for GPU kernel generation. For instance, Kevin introduces a multi turn reinforcement learning framework to train the QwQ 32B model for CUDA code generation. This approach leverages iterative feedback across multiple conversational turns to progressively improve the model’s ability to generate syntactically correct and performance optimized CUDA kernels.

Conclusion

As the capabilities of LLMs continue to grow, leveraging them for automatic performant kernel code generation becomes increasingly promising. Unlike general purpose code generation, kernel code generation involves strict correctness requirements, low level hardware constraints, and performance critical design choices. In this work, we develop infrastructure and post training techniques that significantly advance LLM based kernel code generation, achieving state of the art results. Our empirical results show substantial improvements in functional correctness and measurable gains in kernel performance.

Our fine tuned model is deployed in production as a core component of the MakoraGenerate agent. MakoraGenerate is an evolutionary multi agent system for GPU kernel optimization that explores the search space using parallel agents and additional test time compute. Relative to using the fine tuned model in isolation, MakoraGenerate introduces a clear delta by explicitly maintaining an evolution space of candidate kernels ranked by speedup and by iteratively reusing strong prior solutions across attempts. At each attempt, the system generates a batch of candidates and applies diversity based selection with controlled randomness, enabling the inheritance of effective structural patterns while mitigating premature convergence. This agent level search and reuse mechanism allows additional test time compute to be exploited more effectively than single pass generation, translating higher quality and more reusable initial candidates into progressively improved kernel performance.