GPU Kernel Baseline
When to Use
Use this skill when the user provides PyTorch logic or a kernel demo and asks to:
- Write a GPU kernel for the target platform.
- Build a baseline from scratch.
- Prepare
kernel.py, reference.py, test_kernel.py, and baseline_report.md for later profile-driven optimization.
Workflow
This stage first understands the PyTorch semantics, then learns the framework APIs (CuteDSL or FlyDSL) through <gpu-wiki>/README.md, implements kernel.py and test_kernel.py, validates correctness, records performance, writes baseline_report.md, and writes memory/v0.json.
The orchestrator exposes the knowledge base at ./gpu-wiki/ inside each campaign workspace,
referenced below as <gpu-wiki>/.
Phase 1: Understand PyTorch Semantics
- Read the user-provided PyTorch logic and
kernel_demo.
- Extract and record:
- Compute pattern, such as
GEMM, Decode Attention, Reduction, or Elementwise.
- Input/output shape, stride, dtype, layout, and device.
- Data dependencies, broadcasting, masks, boundary handling, and write-back semantics.
- Accuracy requirements, tolerance, accumulation dtype, and special-value handling.
- Determine target platform and framework:
- H100/H20/H200 -> Hopper ->
CuteDSL
- MI300X/MI308X -> CDNA3 ->
FlyDSL
- MI355X -> CDNA4 ->
FlyDSL
- If the PyTorch logic is ambiguous, first create a minimal runnable reference, then continue.
Phase 2: Learn Framework APIs from gpu-wiki
- Read
<gpu-wiki>/README.md, then use the natural-language front door:python3 gpu-wiki/tools/query_nl.py "<your description>" --brief
- State the true target product and authoritative runtime architecture exactly as supplied. Explicitly
request the complete product specification and relevant architecture/ISA facts, plus the framework,
operator, shapes, dtypes, intended implementation, and uncertainties. Do not substitute another
hardware identity or reduce the description to keywords.
- Results contain a top-level
query_id, records, and notes. Read each id-keyed record's own
canonical wiki_id, store, independent payload, source, type, and match.arch; internal
mapping keys use the internal_gpu_wiki:: namespace. Copy emitted attribution ids exactly and use
--max-bytes when a hard context limit is needed.
- Prefer records with the same framework and compute pattern. Record the stable ids and the constraints
they established in
plans/v0_plan.md.
Phase 3: Implement Baseline Kernel and Correctness Tests
- Implement a correct baseline
kernel.py based on PyTorch semantics and the learned framework APIs.Not only must the functionality be correct, but the framework implementation must also be correct, using either CuteDSL or FlyDSL.
- Write
test_kernel.py using PyTorch logic directly as the correctness reference.
- Cover representative inputs, including normal shapes, boundary shapes, and relevant dtype or stride cases.
- Example correctness check:
ref = pytorch_reference(inputs)
out = kernel_v1(inputs)
rel_err = (out.float() - ref).norm() / ref.norm()
assert rel_err < 0.01
- The default BF16 threshold is
rel_err < 0.01; lower precision formats may use task-specific relaxed thresholds.
- Add per-case timeout guard in
test_kernel.py to prevent hanging:
import signal
def timeout_handler(signum, frame):
raise TimeoutError("Test case exceeded timeout limit")
signal.signal(signal.SIGALRM, timeout_handler)
TIMEOUT_SEC = int(os.environ.get("TEST_TIMEOUT_SEC", "30"))
for case in test_cases:
signal.alarm(TIMEOUT_SEC)
try:
run_test(case)
except TimeoutError:
record_failure(case, "TIMEOUT_FAIL")
finally:
signal.alarm(0)
- If API, compilation, accuracy, performance, or hardware issues appear, query
<gpu-wiki>/ again with
the exact failure and measured evidence, and then fix the implementation.
- Record the baseline configuration, including tile size, thread organization, grid/block design, and major data-movement patterns.
Phase 4: Performance, Correctness, and Quality Gate
- Run exactly one full-workload base-seed V0 measurement through the mandatory sandbox. Do not pass
--multi-seed and do not launch a separate robustness run for V0:
python tools/sandbox.py --kind run --no-sync -- \
python test_kernel.py --version v0 --no-memory
Parse the emitted [test_kernel] RESULT_JSON=..., use its performance result and accompanying
correctness status for memory/v0.json, and avoid repeating the expensive baseline workload.
- Each individual test case must complete within 30 seconds (configurable via
TEST_TIMEOUT_SEC env var).
- If a case exceeds the timeout, mark it as
TIMEOUT_FAIL, kill the process, and record the failure in baseline_report.md.
- Common timeout causes: infinite loops in index calculation, deadlocks in synchronization, or excessive compilation time. Query gpu-wiki with the failure mode to diagnose.
- Verify all correctness cases pass and record max
rel_err plus PASS/FAIL.
- Measure baseline performance and record:
latency(us) | TFLOPS | bandwidth(GB/s) | TFLOPS peak utilization(%) | bandwidth peak utilization(%)
- Use
compute_utilization.py to calculate TFLOPS and bandwidth utilization:
python tools/compute_utilization.py --gpu <gpu> --dtype <dtype> --flops-expr '<expr>' --bytes-expr '<expr>' --time-ms <ms> --grid-blocks <blocks>
Every theoretical peak, bandwidth, and utilization calculation must cite the gpu-wiki spec sources registered in Step 0.
Write baseline_report.md with:
- Baseline kernel path
- Correctness test path
- PyTorch reference logic description
- Stable gpu-wiki record ids consulted
- Baseline configuration summary
- Correctness results: case list, max
rel_err, PASS/FAIL (include any TIMEOUT_FAIL cases)
- Baseline performance: latency(us), TFLOPS, bandwidth(GB/s), and peak utilization percentages
Write baseline iteration data to memory/v0.json using tools/memory_manager.py:
# Create the iteration file
python tools/memory_manager.py create --workspace kernel_opt_<name> --version v0
# Fill in performance and metadata
python tools/memory_manager.py update --workspace kernel_opt_<name> --version v0 \
--set 'performance.latency_us=<value>' \
--set 'performance.tflops=<value>' \
--set 'performance.bandwidth_gbps=<value>' \
--set 'performance.tflops_peak_utilization_pct=<value>' \
--set 'performance.bandwidth_peak_utilization_pct=<value>' \
--set 'optimization.action_category=baseline' \
--set 'optimization.action_description=<summary>' \
--set 'correctness.rel_err=<value>' \
--set 'correctness.status=PASS' \
--set 'quality_gate.result=PASS'
For array fields (pitfalls_and_fixes, references), update the JSON file directly or use read + manual edit + write-back. Fill in:
pitfalls_and_fixes: any errors encountered during implementation
references: stable gpu-wiki record ids and other docs referenced during learning
After the quality gate passes, commit:
git add kernel.py test_kernel.py baseline_report.md memory/v0.json README.md
git commit -m "V0: baseline kernel"
memory/ Requirements
Each iteration produces a memory/v<N>.json file following the schema defined in reference/v_iteration.schema.json. The JSON structure captures performance data, optimization actions, profile evidence, correctness results, ISA metric progress, search logs, pitfalls and fixes, and references.
Key rules:
- The
masked field defaults to false. When set to true, the file is skipped during reads.
- ISA optimization target thresholds are stored in
README.md and must be derived from <gpu-wiki>/ best practices, hardware specs, and Step 0 Roofline conclusions. Do not fabricate thresholds from experience.
Deliverables
- Runnable and correct(using either CuteDSL or FlyDSL)
kernel.py
- PyTorch
reference.py
test_kernel.py
baseline_report.md
- Created
memory/v0.json
- Git commit
Appendix: Prohibited Actions
- Do not use unspecified programming frameworks or import external projects.
1---2name: gpu-kernel-baseline3description: Learn the target framework from gpu-wiki and implement a baseline GPU kernel. Use this skill to understand compute semantics, determine the target platform and framework, search reference implementations, and produce a correct V0 baseline with performance records for later profile-driven optimization.4---56# GPU Kernel Baseline78## When to Use910Use this skill when the user provides PyTorch logic or a kernel demo and asks to:1112- Write a GPU kernel for the target platform.13- Build a baseline from scratch.14- Prepare `kernel.py`, `reference.py`, `test_kernel.py`, and `baseline_report.md` for later profile-driven optimization.1516## Workflow1718This stage first understands the PyTorch semantics, then learns the framework APIs (CuteDSL or FlyDSL) through `<gpu-wiki>/README.md`, implements `kernel.py` and `test_kernel.py`, validates correctness, records performance, writes `baseline_report.md`, and writes `memory/v0.json`.1920The orchestrator exposes the knowledge base at `./gpu-wiki/` inside each campaign workspace,21referenced below as `<gpu-wiki>/`.2223## Phase 1: Understand PyTorch Semantics24251. Read the user-provided PyTorch logic and `kernel_demo`.262. Extract and record:27 - Compute pattern, such as `GEMM`, `Decode Attention`, `Reduction`, or `Elementwise`.28 - Input/output shape, stride, dtype, layout, and device.29 - Data dependencies, broadcasting, masks, boundary handling, and write-back semantics.30 - Accuracy requirements, tolerance, accumulation dtype, and special-value handling.313. Determine target platform and framework:32 - H100/H20/H200 -> Hopper -> `CuteDSL`33 - MI300X/MI308X -> CDNA3 -> `FlyDSL`34 - MI355X -> CDNA4 -> `FlyDSL`354. If the PyTorch logic is ambiguous, first create a minimal runnable reference, then continue.3637## Phase 2: Learn Framework APIs from gpu-wiki38391. Read `<gpu-wiki>/README.md`, then use the natural-language front door:40 ```bash41 python3 gpu-wiki/tools/query_nl.py "<your description>" --brief42 ```432. State the true target product and authoritative runtime architecture exactly as supplied. Explicitly44 request the complete product specification and relevant architecture/ISA facts, plus the framework,45 operator, shapes, dtypes, intended implementation, and uncertainties. Do not substitute another46 hardware identity or reduce the description to keywords.473. Results contain a top-level `query_id`, `records`, and `notes`. Read each id-keyed record's own48 canonical `wiki_id`, `store`, independent `payload`, `source`, `type`, and `match.arch`; internal49 mapping keys use the `internal_gpu_wiki::` namespace. Copy emitted attribution ids exactly and use50 `--max-bytes` when a hard context limit is needed.514. Prefer records with the same framework and compute pattern. Record the stable ids and the constraints52 they established in `plans/v0_plan.md`.5354## Phase 3: Implement Baseline Kernel and Correctness Tests55561. Implement a correct baseline `kernel.py` based on PyTorch semantics and the learned framework APIs.Not only must the functionality be correct, but the framework implementation must also be correct, using either CuteDSL or FlyDSL.572. Write `test_kernel.py` using PyTorch logic directly as the correctness reference.583. Cover representative inputs, including normal shapes, boundary shapes, and relevant dtype or stride cases.594. Example correctness check:6061```python62ref = pytorch_reference(inputs)63out = kernel_v1(inputs)64rel_err = (out.float() - ref).norm() / ref.norm()65assert rel_err < 0.0166```67685. The default BF16 threshold is `rel_err < 0.01`; lower precision formats may use task-specific relaxed thresholds.696. Add per-case timeout guard in `test_kernel.py` to prevent hanging:7071```python72import signal7374def timeout_handler(signum, frame):75 raise TimeoutError("Test case exceeded timeout limit")7677signal.signal(signal.SIGALRM, timeout_handler)7879TIMEOUT_SEC = int(os.environ.get("TEST_TIMEOUT_SEC", "30"))8081for case in test_cases:82 signal.alarm(TIMEOUT_SEC)83 try:84 run_test(case)85 except TimeoutError:86 record_failure(case, "TIMEOUT_FAIL")87 finally:88 signal.alarm(0)89```906. If API, compilation, accuracy, performance, or hardware issues appear, query `<gpu-wiki>/` again with91 the exact failure and measured evidence, and then fix the implementation.927. Record the baseline configuration, including tile size, thread organization, grid/block design, and major data-movement patterns.9394## Phase 4: Performance, Correctness, and Quality Gate95961. Run exactly one full-workload base-seed V0 measurement through the mandatory sandbox. Do not pass97 `--multi-seed` and do not launch a separate robustness run for V0:9899```bash100python tools/sandbox.py --kind run --no-sync -- \101 python test_kernel.py --version v0 --no-memory102```103104 Parse the emitted `[test_kernel] RESULT_JSON=...`, use its performance result and accompanying105 correctness status for `memory/v0.json`, and avoid repeating the expensive baseline workload.106107 - Each individual test case must complete within **30 seconds** (configurable via `TEST_TIMEOUT_SEC` env var).108 - If a case exceeds the timeout, mark it as `TIMEOUT_FAIL`, kill the process, and record the failure in `baseline_report.md`.109 - Common timeout causes: infinite loops in index calculation, deadlocks in synchronization, or excessive compilation time. Query gpu-wiki with the failure mode to diagnose.1101112. Verify all correctness cases pass and record max `rel_err` plus PASS/FAIL.1123. Measure baseline performance and record:113114```text115latency(us) | TFLOPS | bandwidth(GB/s) | TFLOPS peak utilization(%) | bandwidth peak utilization(%)116```1171184. Use `compute_utilization.py` to calculate TFLOPS and bandwidth utilization:119120```bash121python tools/compute_utilization.py --gpu <gpu> --dtype <dtype> --flops-expr '<expr>' --bytes-expr '<expr>' --time-ms <ms> --grid-blocks <blocks>122```1231245. Every theoretical peak, bandwidth, and utilization calculation must cite the gpu-wiki spec sources registered in Step 0.1256. Write `baseline_report.md` with:126 - Baseline kernel path127 - Correctness test path128 - PyTorch reference logic description129 - Stable gpu-wiki record ids consulted130 - Baseline configuration summary131 - Correctness results: case list, max `rel_err`, PASS/FAIL (include any TIMEOUT_FAIL cases)132 - Baseline performance: latency(us), TFLOPS, bandwidth(GB/s), and peak utilization percentages1337. Write baseline iteration data to `memory/v0.json` using `tools/memory_manager.py`:134135 ```bash136 # Create the iteration file137 python tools/memory_manager.py create --workspace kernel_opt_<name> --version v0138139 # Fill in performance and metadata140 python tools/memory_manager.py update --workspace kernel_opt_<name> --version v0 \141 --set 'performance.latency_us=<value>' \142 --set 'performance.tflops=<value>' \143 --set 'performance.bandwidth_gbps=<value>' \144 --set 'performance.tflops_peak_utilization_pct=<value>' \145 --set 'performance.bandwidth_peak_utilization_pct=<value>' \146 --set 'optimization.action_category=baseline' \147 --set 'optimization.action_description=<summary>' \148 --set 'correctness.rel_err=<value>' \149 --set 'correctness.status=PASS' \150 --set 'quality_gate.result=PASS'151 ```152153 For array fields (`pitfalls_and_fixes`, `references`), update the JSON file directly or use `read` + manual edit + write-back. Fill in:154 - `pitfalls_and_fixes`: any errors encountered during implementation155 - `references`: stable gpu-wiki record ids and other docs referenced during learning1561578. After the quality gate passes, commit:158159```bash160git add kernel.py test_kernel.py baseline_report.md memory/v0.json README.md161git commit -m "V0: baseline kernel"162```163164## memory/ Requirements165166Each iteration produces a `memory/v<N>.json` file following the schema defined in `reference/v_iteration.schema.json`. The JSON structure captures performance data, optimization actions, profile evidence, correctness results, ISA metric progress, search logs, pitfalls and fixes, and references.167168Key rules:169- The `masked` field defaults to `false`. When set to `true`, the file is skipped during reads.170- ISA optimization target thresholds are stored in `README.md` and must be derived from `<gpu-wiki>/` best practices, hardware specs, and Step 0 Roofline conclusions. Do not fabricate thresholds from experience.171172## Deliverables173174- Runnable and correct(using either CuteDSL or FlyDSL) `kernel.py`175- PyTorch `reference.py`176- `test_kernel.py`177- `baseline_report.md`178- Created `memory/v0.json`179- Git commit180181## Appendix: Prohibited Actions182183- Do not use unspecified programming frameworks or import external projects.