SP

KernelEnv: the evaluator is part of the experiment

reinforcement-learninggpu-kernels

KernelEnv gives a model a PyTorch module and asks it to produce a faster GPU kernel. That makes the evaluator part of the learning problem.

I built the environment around compilation, numerical checks and timing on an H100. A submission could fail to compile, produce the wrong output or return a result that looked fast because the evaluator missed some work. Each case needed a different response.

Kernel writing looks like an ideal reinforcement learning target because the reward is verifiable. A kernel matches the reference output or it does not. It is faster or it is not. No human labels or learned reward model are involved. The catch is that a verifiable reward is only as good as its verifier. Published kernel RL work has documented models that hid work on side CUDA streams, returned cached outputs or keyed on input shapes to report speedups that did not exist. I expected the hard part of this project to be the training. It was building a judge the model could not fool.

This is an adaptation of my published KernelEnv article with additional detail from the repository. Its later training and evaluation results are reported here as article evidence. They have not been independently rerun or reconciled with every release artifact for this adaptation. [1]

An episode and its reward

The environment selects a task from a pinned KernelBench revision. The model sees the reference module and the submission rules, then returns a ModelNew class whose forward path launches generated Triton kernels. A fresh worker runs static checks, compilation and numerical comparisons against the reference on five unseen random seeds. Only valid results reach timing.

  1. Reference taskPyTorch module plus rules
  2. CandidateGenerated ModelNew
  3. EvaluatorCompile → check → time
  4. FeedbackUp to three attempts
Figure 1. The episode returns concrete failures or measurements to the model. Fresh inputs prevent a previous answer from substituting for computation.

Compile errors, mismatch statistics or timings go back to the model. The episode allows up to three attempts. The best attempt supplies the reward used by GRPO.

The environment is an OpenEnv server. A client resets an episode, receives the problem and submits code through a step call. Each observation reports the stage a submission reached and the feedback for that stage, so the model sees whether it failed static checks, compilation, correctness or timing.

with KernelEnv(base_url="http://localhost:8000").sync() as env:
    obs = env.reset(seed=0).observation
    result = env.step(KernelAction(code=my_source))
    print(result.observation.stage, result.observation.feedback, result.reward)

Invalid or incorrect submissions score zero. A correct submission starts at 0.25. The speed component uses the conservative lower bound of measured speedup:

reward = 0.25 + clip(log2(speedup_lower_bound), 0, 2)

A correct kernel that does not improve speed can still earn 0.25. A lower-bound speedup of 4x reaches the maximum reward of 2.25. The logarithm limits the influence of an extreme ratio on a group’s advantages. The trainer rewards the best validated attempt within the three turns. Repeating an unchanged correct answer earns no extra credit. That reward is only meaningful if the evaluator measures the intended work.

The repository keeps other reward modes for experiments. Its default speedup mode and a roofline mode that rewards the share of the hardware limit reached are selected through an environment variable. The corrected experiment described here used the calibrated mode above. Results from different modes are not directly comparable.

What the evaluator has to exclude

The checks cover different ways a submission could violate the contract. Every submission has to pass all of them before it is timed.

Shortcuts the evaluator blocks and the defense for each
ShortcutDefense
Calling PyTorch instead of writing a kernelAST checks for framework calls and aliases. At least one @triton.jit kernel is required.
Modifying the judgeNo attribute writes outside self, banned builtins and an import allow list.
Slowing the reference at import timeThe reference is timed before the candidate is imported.
Memorized or cached outputsFive fresh random seeds per step, never shown to the model.
Returning or modifying an inputStorage alias checks plus float64 checksums of inputs before and after.
Reporting a fake resultThe worker writes its result to a designated file instead of trusting stdout.
Hiding work on another CUDA streamProfiler evidence that only one device stream ran.
Crashes and hangsA fresh subprocess per evaluation in its own process group, with time limits that also stop child compilers.
Skipped work that looks fastTimes below 0.8 of the estimated hardware floor are rejected.

Two of those defenses came from failures rather than planning. One deliberate adversarial test launched real work on a side CUDA stream without joining it. The profiler showed the extra stream but the environment still accepted the candidate at 1.00x. The one-stream rule existed yet did not fire on that path. A validation gate caught it before any training money was spent. Fixing the path and retaining the adversarial test mattered more than the presence of the rule in source.

The current evaluator requires profiler evidence of one device stream for both eager and graph replay runs. Additional streams and missing stream evidence are rejected. Joined multi-stream kernels are also unsupported, which is a deliberate restriction rather than a claim that such kernels are invalid in general.

The roofline as a detector

A speedup cap such as flagging anything above 50x is a weak detector. A stronger one computes the minimum possible time for the task. The environment counts FLOPs on the reference for matrix multiplication, convolution and attention, counts compulsory bytes for inputs, parameters and outputs, then uses datasheet peaks for the GPU:

t_min = max(FLOPs / peak_flops, bytes / peak_bandwidth)

A reported time below 0.8 times t_min is rejected as physically implausible. That is an operational threshold based on a model of required work. Its assumptions must match the actual precision and work.

The roofline also exposed a precision loophole. On an fp32 matrix multiplication, Triton’s tl.dot uses TF32 tensor cores by default and still passes a 1e-2 tolerance. That can produce a 2x speedup from lower precision rather than better kernel design. The environment now uses the TF32 roof for fp32 tasks and reports each kernel’s achieved share of the roof, its arithmetic intensity and whether it is compute or memory bound. A speed ratio no longer hides what limit a kernel reached.

When correctness checks were too loose

Some checks accepted wrong answers because the inputs or tolerances could not distinguish them. For the Softmax and Frobenius norm tasks, the original absolute tolerance was larger than the outputs themselves. A kernel returning near-zero values could pass. Those tasks now scale the absolute tolerance to the reference magnitude, reject non-finite values and check the defining property: nonnegative Softmax rows sum to one and the Frobenius output has a global norm of one. Correctness trials also add constant, peaked, signed and sparse inputs.

Activation tasks had a different gap. Their input generators produced only nonnegative values, so an identity copy could pass ReLU and several related activations. Correctness trials for ReLU, LeakyReLU, ELU, Softplus and the GPT GELU variant now include signed inputs in the range of plus or minus 32 plus zeros at the original shape. The prompts disclose the broader correctness inputs. Timing still uses the original generator so speed results stay comparable.

The evaluator also checks PyTorch tensor operations inside the candidate’s forward path at runtime during both correctness and timing. Allocation, layout changes and device-local copies are allowed. Tensor arithmetic, reductions, scalar extraction and copies off the device are rejected as format violations. The repository is explicit that this dispatch guard is not a native-code sandbox. It does not inspect arbitrary custom extensions or graphs captured during initialization.

Timing as a learning signal

The initial timing setup had a reported standard deviation of 0.031 against a gap of 0.073 that the experiment needed to detect. Noise was large enough to influence which answer looked better within a group. GRPO compares answers within a group, so a noisy reward would have trained on sampling luck.

I captured the reference and candidate in CUDA graphs, then ran seven paired rounds with alternating order. Alternation spreads clock drift across both arms. A noise band reduced the reward to a conservative speedup estimate. The reported noise fell to 0.0085. These figures describe the calibration in the original article; they are not a general accuracy guarantee for GPU timing.

The repository documents the corrected protocol in more detail. Each arm gets one validated eager warmup and three validated graph warmups. Every measured replay is checked on fresh values. The reported time is the amortized interval between graph replay events, which includes launch, submission and idle overhead rather than pure kernel time. The band is the largest of 2% of the median, the sample interquartile range and a calibrated empty-graph floor. The repository describes these bands as engineering margins, not statistical confidence intervals.

Using the lower bound makes the reward harder to earn through a fortunate sample. It also makes uncertainty visible to the training setup. If a comparison is too noisy to distinguish the candidates, changing the policy optimizer does not fix that measurement.

When the contract was too strict

Some failures came from rejecting useful implementations. The first level-2 evaluation accepted zero of 48 answers. Those tasks combine a matrix multiplication or convolution with elementwise work. The rules had banned calls such as nn.Linear and nn.Conv* outright.

A revised hybrid contract allowed vendor matrix multiplication and convolution in host code under the stated precision restrictions while requiring the elementwise chain to use a generated kernel. Vendor calls are not allowed in fp16 or bf16 under that contract. The article reports that 29 of 35 previously rejected answers then passed. The evaluation question changed to match that contract. It should not be compared to a fully custom-kernel task without stating the difference.

A zero percent pass rate looked like a model failure. It was an environment that could not accept a reasonable answer. That is worth checking before spending money on a stronger policy.

Making training practical

Other fixes separated correctness from timing eligibility and removed operational bottlenecks. Each one was found by a run that stopped or slowed down.

Every paid stage sat behind a recorded validation gate: evaluator validation, reward calibration and a learning-signal pilot. Each run was bound to a hashed contract of its code and configuration, so a result can be traced to the environment that produced it. The total spend was about $60 of Modal GPU time against a $200 cap, with one H100 for validation, two for training and four for evaluation.

The later experiment

The published article reports Qwen2.5-Coder-7B-Instruct with a 12-step SFT LoRA warm start on 28 verified level-1 teacher kernels. The later GRPO run used LoRA for 64 steps with eight generations per task and a leave-one-out baseline per trajectory, using TRL with colocated vLLM. Its training setup lists 14 level-1 tasks plus 18 level-2 fusion tasks.

The comparison below uses an evaluation suite of 30 tasks with four samples per task, or 120 attempts for each model. The base, SFT and RL variants were evaluated with the same prompts and evaluator. The task groups and evaluation attempts must not be confused with the training inventory.

Correctness percentages reported in the later article experiment
Evaluation groupBaseSFTRL
Overall15.8%15.0%20.0%
Training tasks81.2%68.8%93.8%
Reserved transfer15.6%21.9%21.9%
Held-out level 22.8%0%5.6%
Held-out level 10%0%0%

The reported aggregate RL correctness is higher. RL is best or tied in every group. Every reported 95% bootstrap interval for the comparisons touches or crosses zero, however. This evaluation does not establish a statistically significant improvement. The held-out level-1 result remains zero for all three models. More samples or tasks could change the interpretation.

The SFT drop on training tasks has a plausible explanation in the data: its teachers were all level-1 kernels, while the training tasks include level-2 fusions. The RL run recovered that group. On held-out level 2, the RL model’s pass@4 was 22.2%, which measures whether any of four samples succeeded rather than the per-attempt rate in the table.

The article also reports a mean speedup of 1.64x for correct RL kernels on transfer tasks versus 1.30x for the base model. The share of kernels clearly faster than PyTorch rose from 3.1% to 9.4%. Both figures are conditional on producing a correct kernel. They should be read alongside the low correctness rates rather than as the expected speedup for an arbitrary submitted task.

Keep the pilot separate

The older public release card describes a 16-step pilot with ten tasks. The later article reports the 64-step training run and 30-task evaluation above. Those are different experiments. Their step counts, task counts and aggregate outcomes are not interchangeable. [2]

The article’s strongest single-kernel example also came from an earlier pilot: a held-out GELU solved on a second attempt after a compile error, reported at 8.8x faster than eager PyTorch. The roofline explains the mechanism. The kernel fused PyTorch’s chain of elementwise operations into one memory pass and reached about 85% of the memory roof where the reference reached about 10%. That example does not summarize the later evaluation or establish transfer across the benchmark.

What I would do again

What remains uncertain

The original article identifies a remaining static-analysis gap: ordinary host-side tensor arithmetic such as x + y is not fully caught statically. The current repository adds the runtime dispatch guard described above, which rejects tensor arithmetic during correctness and timing. That guard has its own documented limits for custom extensions and captured graphs. The evaluator should be treated as a set of tested defenses with known limits. Numerical checks on fresh seeds are strong evidence for the tested inputs, but they are not a proof of correctness for every possible input.

The next useful evaluation would use 16 samples per task to tighten the intervals and retain the full per-task distributions. It should preserve the run contract, precision rules and environment version. Longer training on more fusion tasks is now affordable because a step takes under three minutes. That would make it possible to distinguish a stronger policy from a change in which programs the judge accepts.

Sources

  1. Original KernelEnv article, Shreyansh Pathak. Source of the later run, evaluator narrative, operational numbers and uncertainty statements.
  2. KernelEnv repository, including the environment README and release model-card source. Source of the roofline, tolerance, dispatch guard and timing protocol details. The older pilot is a separate evidence set.
  3. KernelEnv Space and Fusion-RL model. Public destinations linked by the original article.
  4. KernelBench. Source task benchmark. Consult each run’s pinned revision for reproducibility.