Instructions to use ik6626/Qwen3.8-27B-HIP-kernel-RL with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use ik6626/Qwen3.8-27B-HIP-kernel-RL with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3.8-27B") model = PeftModel.from_pretrained(base_model, "ik6626/Qwen3.8-27B-HIP-kernel-RL") - Notebooks
- Google Colab
- Kaggle
Qwen3.8-27B HIP kernel RL (LoRA)
A LoRA adapter for Qwen/Qwen3.8-27B that writes HIP GPU kernels
for AMD Instinct MI300X. Given a PyTorch module, the model answers with one complete .hip file whose
forward computes the same result in its own __global__ kernels. It was trained with reinforcement
learning on one MI300X, with a grader that compiles each answer, checks it against PyTorch on three random
inputs, and times it.
Code: training, grader, evaluation and reproduction:
moonmath-ai/Qwen3.8-27B-HIP-kernel-RL
(full results in RESULTS.md,
write-up in docs/PAPER.md).
Nothing in it is needed to use the adapter.
Results
Correct = the answer compiles and matches PyTorch (rtol = atol = 1e-4) on 3 random inputs. Pass@1 over
4 samples per task at temperature 1; gains with a paired bootstrap 95% CI over tasks.
| Set | Base | This adapter | Gain |
|---|---|---|---|
| Validation: 100 tasks, never used for training or checkpoint choice (14,000 tokens) | 0.335 | 0.540 | +20.5 [14.3, 27.0] |
| Held-out A: 200 tasks (14,000 tokens) | 0.289 | 0.515 | +22.6 [18.1, 27.1] |
| Held-out A at 20,000 tokens (adapter only) | 0.536 | +2.1 [β1.5, +5.8] vs the adapter at 14,000 |
Held-out A by difficulty (14,000 tokens): L1 (single op) 0.34 β 0.53, L2 (fused ops) 0.21 β 0.50, L3 (larger modules) 0.23 β 0.51.
Other held-out A numbers (14,000 tokens):
| Base | Adapter | |
|---|---|---|
| Answers that compile | 0.64 | 0.78 |
| Answers cut off at the token limit | 0.19 | 0.16 |
| Correct and β₯ 1.1Γ faster than PyTorch eager (of 800 answers) | 116 | 169 |
| Median speedup of correct answers vs PyTorch eager | 1.10Γ | 0.90Γ |
The gain is correctness, not speed. On the 108 held-out tasks both models solve, the adapter's kernels are as fast as the base model's (per-task speed ratio 1.05Γ, 95% CI [0.92, 1.23]); the 40 tasks only the adapter solves mostly come with slow kernels (median 0.65Γ), so more than half of all its correct answers are slower than PyTorch eager. Held-out A was also used to choose the checkpoint (step 75 scored highest), so its number is slightly optimistic; the validation row is the unbiased one.
Learning curve on held-out A: 0.25 at the start of RL, 0.40 (step 20), 0.42 (25), 0.43 (50) at 12,288 tokens; 0.46 (50), 0.52 (75), 0.49 (100), 0.51 (125) at 14,000. Steps 75β125 are within noise of each other; training was stopped at 125.
Regressions (this adapter vs base, same server; 12,288 tokens, reasoning_effort="low"; HumanEval+ and MBPP+
at temperature 1, the others greedy; gain with a paired bootstrap 95% CI over problems):
| Benchmark | Base | This adapter | Gain |
|---|---|---|---|
| HumanEval+ (157 Γ 2) | 0.933 | 0.943 | +1.0 [β1.0, +3.2] |
| MBPP+ (375 Γ 2) | 0.809 | 0.821 | +1.2 [β0.1, +2.7] |
| IFEval (300, greedy) | 0.887 | 0.883 | β0.3 [β3.0, +2.3] |
| MMLU-Pro (300, greedy) | 0.790 | 0.757 | β3.3 [β6.7, 0.0] |
| MATH-500 (300, greedy) | 0.943 | 0.950 | +0.7 [β1.3, +2.7] |
The largest drop is MMLU-Pro, 3.3 points (19 questions worse, 9 better), at the edge of significance; the other benchmarks change by at most 1.2 points, none significantly.
Files
| Path | What |
|---|---|
adapter_model.safetensors, adapter_config.json |
the adapter: RL step 75 (final) |
step125/ |
RL step 125, the last step trained (held-out A 0.509, same as step 75 within noise) |
make_prompt.py |
builds the exact training prompt for your own PyTorch module (standard library only) |
check_answer.py |
builds an answer and checks it against PyTorch on 3 seeds, then times it |
convert_to_sglang.py |
converts an adapter for SGLang serving (needs only torch and safetensors) |
example_prompt.json |
one held-out task as chat messages, exactly as the model saw it |
example/ |
that task's module.py and functional.py, and one of the adapter's correct answers (answer.md, kernel.hip) |
Each adapter folder also has training_info.json. Each adapter is 1.8 GB (rank 64, float32). Nothing else is
needed: the base model Qwen/Qwen3.8-27B, this repo, and
Transformers + PEFT or SGLang.
Use
Three steps: write the prompt, generate, check the answer. Get the repo first (the commands below run in it):
hf download ik6626/Qwen3.8-27B-HIP-kernel-RL --local-dir hip-rl && cd hip-rl
1. Prompt
The model was trained on one prompt format; use it. The user message gives a PyTorch module, the same
computation as a function module_fn, and the build interface. make_prompt.py writes it for you:
python make_prompt.py example/module.py example/functional.py > messages.json # == example_prompt.json
module.py: annn.ModulenamedModel, withget_inputs()andget_init_inputs()(KernelBench style).functional.py: the same computation asmodule_fn(...), and aModelwhoseforwardtakesfn=module_fnand passes it its parameters (seeexample/functional.py). The model'sforwardreplacesmodule_fn, so it receives exactly the argumentsmodule_fnwould.
The chat template is applied with reasoning_effort="low". The system prompt is:
You are an expert GPU kernel engineer targeting AMD Instinct MI300X (gfx942, ROCm/HIP). Answer with one complete .hip file in a single ```cpp code block.
The user message is:
<instruction>
<context>
PyTorch module:
```python
<module.py>
```
Functional version (your `forward` replaces `module_fn`):
```python
<functional.py>
```
Interface (this is how your file is built and checked):
- It is compiled with torch.utils.cpp_extension for ROCm (hipcc, gfx942) and must define
`PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &forward, ...); }`.
- `forward` replaces `module_fn` in the functional version below: it receives the same arguments in the same order
(torch.Tensor -> torch::Tensor, float -> double, int -> int64_t, bool -> bool, str -> std::string,
tuple/list of ints -> std::vector<int64_t>) and must return the same tensor(s), shape and dtype.
- Inputs live on the GPU. Do the computation in your own __global__ kernels.
- For the current stream, `#include <ATen/cuda/CUDAContext.h>` and use `at::cuda::getCurrentCUDAStream()`
(the build hipifies both).
<instruction> and <context> are the task's question_instruction and question_context from
amd/AIG-Datasets; make_prompt.py defaults to the
CUDA-Agent-Ops-6K wording, which all held-out and validation tasks use (--instruction / --context to change
them). It reproduces the training prompts of all 300 held-out and validation tasks exactly.
2. Generate
Answers are a short reasoning block followed by the .hip file; use the last ```cpp block. Sample at
temperature 1 with up to 14,000 new tokens, as in training and evaluation.
Transformers + PEFT (a quick check; plain generate is slow for a 27B model):
import json, torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3.8-27B")
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3.8-27B", dtype=torch.bfloat16, device_map="auto")
model = PeftModel.from_pretrained(base, "ik6626/Qwen3.8-27B-HIP-kernel-RL") # step 75 (final)
# model = PeftModel.from_pretrained(base, "ik6626/Qwen3.8-27B-HIP-kernel-RL", subfolder="step125")
messages = json.load(open("messages.json"))["messages"]
inputs = tok.apply_chat_template(messages, add_generation_prompt=True, reasoning_effort="low",
return_tensors="pt", return_dict=True).to(model.device)
out = model.generate(**inputs, max_new_tokens=14000, do_sample=True, temperature=1.0, top_p=1.0, top_k=0)
open("answer.md", "w").write(tok.decode(out[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True))
Checked with transformers 5.12.1 and peft 0.18.1 on an MI300X: the adapter loads, the chat template reproduces the training prompts token for token, and on 8 held-out answers (27,634 tokens) the per-token logprobs match the training-time sampler to 0.0054 nats/token (base vs base: 0.0049, the bf16 noise floor), against 0.026 between adapter and base.
SGLang (for anything beyond a quick check). PEFT saves Qwen3.8's fused linear-attention projection
in_proj_qkv; SGLang loads it as separate in_proj_q/k/v. Convert once with
convert_to_sglang.py (the split is exact):
python convert_to_sglang.py . ../hip-rl-sglang # step 75 (final)
# python convert_to_sglang.py step125 ../hip-rl-sglang-125
python -m sglang.launch_server --model-path Qwen/Qwen3.8-27B --enable-lora \
--lora-paths hip=../hip-rl-sglang --lora-target-modules all --max-lora-rank 64
On ROCm the first start takes several minutes longer: SGLang's AITER backend compiles its attention kernels on
the first requests (and again in every new container). Then apply the chat template yourself and select the adapter
per request with lora_path:
import json, requests
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3.8-27B")
messages = json.load(open("messages.json"))["messages"]
ids = tok.apply_chat_template(messages, add_generation_prompt=True, reasoning_effort="low", tokenize=True,
return_dict=True)["input_ids"]
r = requests.post("http://127.0.0.1:30000/generate", json={"input_ids": ids, "lora_path": "hip",
"sampling_params": {"max_new_tokens": 14000, "temperature": 1.0, "top_p": 1.0, "top_k": -1}})
open("answer.md", "w").write(r.json()["text"])
Checked with SGLang 0.5.21 on ROCm: served this way, the adapter gives the same per-token logprobs as the training-time sampler on the 8 sequences above. vLLM is untested.
3. Check the answer
On a ROCm machine with PyTorch for ROCm:
python check_answer.py answer.md functional.py
# example: python check_answer.py example/answer.md example/functional.py
# -> correct on 3 seeds; PyTorch eager 1.096 ms, kernel 0.301 ms, speedup 3.64x
It takes the last ```cpp block, builds it with torch.utils.cpp_extension.load for gfx942 (set
PYTORCH_ROCM_ARCH for another GPU) in a temporary directory, runs the functional Model with module_fn and
with the compiled forward on 3 input seeds, and requires torch.testing.assert_close(rtol=1e-4, atol=1e-4), as
in training. The timing is a quick CUDA-event measurement; training timed the whole call end to end, so its
speedups differ (2.56Γ for this answer). Model-written code runs with your permissions when it is built and
loaded: run this in a container or VM without network access. Checked with PyTorch 2.14.1+rocm7.2 on an
MI300X.
Training
| Start | SFT on 2,343 verified answers (1,722 of the base model's own correct answers on training tasks + 621 dataset reference kernels), 1 epoch, LR 1e-4 linear decay. SFT alone did not raise the held-out score (0.274 β 0.254) but halved truncation |
| RL | GRPO-style: 25 tasks Γ 4 samples per step, group-centred advantages, importance-sampling loss, no KL penalty, LR 1e-5, temperature 1; 125 steps |
| Reward | 0 for no code block, no own __global__ kernel, or a forbidden call (file, process, environment, network, dynamic loading); 0.1 if it compiles but is wrong; if correct, 1 + 0.5 Γ clip(log2 speedup, 0, 3), with speedups under 1.1Γ counted as 1. Speedup is end to end against PyTorch eager |
| Grader | each answer is built with torch.utils.cpp_extension (hipcc, gfx942) and run in its own network-less container; outputs are compared outside it on 3 random input seeds; correct answers are timed alone |
| LoRA | rank 64, alpha 32, on attention (q/k/v/o_proj), Gated DeltaNet (in_proj_qkv, in_proj_z, out_proj), MLP and lm_head |
| Prompting | single turn, no tools, no compiler feedback; reasoning_effort="low"; 12,288 tokens per answer for steps 1β57, 14,000 from step 58 |
| Data | 4,572 PyTorch tasks from the CUDA-Agent-Ops-6K and AI-CUDA-Engineer subsets of amd/AIG-Datasets. Records are grouped into tasks by normalised code, number-masked code and op name, and the 200 held-out A + 100 validation tasks (all CUDA-Agent-Ops) are split off by task |
| Hardware | one AMD Instinct MI300X (virtual function, 192 GB); trainer and SGLang sampler share the GPU in alternating phases; ~41 min per step (median) |
Limitations
- In-distribution: held-out and validation tasks come from the same sources as the training tasks.
- The source datasets are public and agent-generated, so similar kernels may be in the base model's pretraining data; compare base and adapter rather than reading absolute pass rates as capability.
- Mostly general ML operators (elementwise, reductions, losses, small fused modules), not tuned serving kernels. Speed was rewarded, but most of the gain is in correctness.
- Correctness is checked on 3 random inputs at the task's shapes, not other shapes or edge cases.
- One seed. Temperature-1 re-runs of one checkpoint differ by a few points on 200 tasks.
Data attribution
Training tasks come from amd/AIG-Datasets, built from
CUDA-Agent-Ops-6K (BytedTsinghua-SIA, CC-BY-4.0)
and AI-CUDA-Engineer-Archive (SakanaAI, CC-BY-4.0).
See that dataset's LICENSES_AND_PROVENANCE.md.
- Downloads last month
- 2
Model tree for ik6626/Qwen3.8-27B-HIP-kernel-RL
Base model
Qwen/Qwen3.8-27B