diff --git a/radiance-sycl.md b/radiance-sycl.md new file mode 100644 index 00000000..ea69d54c --- /dev/null +++ b/radiance-sycl.md @@ -0,0 +1,200 @@ +# Task: native Intel GPU (SYCL / Level Zero) backend for radiance + +You are working in a clone of https://codeberg.org/StillDeadcode/radiance, a C++/HIP inference +server that currently runs on AMD RDNA4 GPUs (kernel library `libr4d`) and on CPU (`libavx`, with +`libref` as the reference implementation). Your job is to add a **native Intel GPU backend** so the +engine serves models on the GPU in this machine, and to keep testing and fixing until it works. + +Target hardware: **Intel Arc Pro B65** (Xe2 / Battlemage, 20 Xe cores, 160 XMX engines, 32 GB GDDR6, +PCIe 5.0), one card, Linux. Toolchain: Intel oneAPI DPC++ (`icpx -fsycl`) on Level Zero. + +This is a long, multi-session job. Work in phases, keep a written log, and never trade correctness +for apparent progress. + +--- + +## Ground rules (read these twice) + +1. **The AMD and CPU paths must not change behaviour.** After every phase, the existing + `ctest --test-dir build -LE 'gpu|oot'` run must pass exactly as before. The HIP build must still + compile. Do not edit `libr4d` kernels except where a shared header genuinely has to move. +2. **No faking.** Do not skip, disable or delete failing tests. Do not loosen tolerances beyond what + `libr4d`'s own tests use for the same op and dtype. Do not route a "GPU" op through the CPU and + call it done. If an op is not implemented on the Intel backend, it must fail loudly (or be visibly + reported by `--debug-graph`), never silently fall back. +3. **`libref` is the oracle.** Every Intel kernel is checked against `libref` (or against the + existing selftest pattern in `libr4d`, e.g. `r4d_selftest`) on randomised inputs, including odd + shapes, tails that are not multiples of the tile size, and the dtypes the recipes actually use. +4. **Keep a log.** Maintain `docs/SYCL_PROGRESS.md`: what is done, what is next, every open bug, every + decision and why, and the exact commands to reproduce the current state. Update it before you + stop for any reason, so a fresh session can resume from it alone. +5. **Small commits**, each building and passing the host tests, with a clear message. +6. If you are truly blocked (missing driver, hardware fault, a design question only the user can + answer), write the blocker into the log and tell the user exactly what you need. Do not guess + around it. + +--- + +## Models + +- The model library is at **`/mnt/model-library`**. Treat it as read-only: never modify, rename, + move or delete anything there. +- Before using a model, **copy it to `/models`** and run it from there, never directly from the + library. Check free space with `df -h /models` first, copy only the models the current step + needs, and confirm the copy matches the source (same size; `cmp` or a checksum for the first copy + of each file). +- Before starting, list what is in the library (`ls -lh /mnt/model-library`) and record in + `docs/SYCL_PROGRESS.md` which models are available and which you plan to use for each milestone. +- If a model you need is not in the library, write that into the log and ask the user. Do not + download or convert it on your own. +- When a model is no longer needed and `/models` is running low on space, you may delete *your + copy* in `/models`. Never touch the original. + +--- + +## Benchmarks and Discord reports + +- Benchmark with **BetterBench** (https://github.com/GGZ14/BetterBench). Install it once in its own + virtualenv outside the radiance repo: clone it, then `pip install -e .` (Python 3.10+, numpy). + If installation fails, stop and ask the user; do not substitute another tool. +- Quick runs only, decode and prefill, against the radiance server's OpenAI-compatible API with the + model copied to `/models`: + + ```sh + betterbench run --endpoint http://127.0.0.1:8000/v1 --model \ + --quick --decode --prefill --no-update-check \ + --name sycl-- --out /results.json \ + --note backend=sycl --note gpu=arc-pro-b65 --note commit= + ``` + + Add `--api-key` if the server was started with one. `--quick` is 1 warmup and 5 passes: good for + tracking progress, not for publishing numbers, so label them as quick runs everywhere. +- Read the numbers from the run's `results.json` (median and 1%-low prefill and decode tok/s). Keep + the HTML report next to it and note its path in the log. +- When to run: after each milestone, and after each performance change in Phase 4. Only benchmark + a build whose correctness tests pass; a fast wrong kernel is not a result. +- Record every run in `docs/SYCL_PROGRESS.md`: date, git commit, model, backend, flags, prefill and + decode numbers, and the change since the previous run of the same model. +- **Send each result to Discord** through a webhook. The webhook URL is in the environment variable + `DISCORD_WEBHOOK_URL`, loaded from `~/.config/radiance-bench.env`. It is a secret: never print it, + log it, write it into the repo or a commit, or put it in this file. If the variable is missing, + say so and continue without posting. +- Write a small script, e.g. `scripts/bench_report.sh`, that runs the quick benchmark and posts the + summary with `curl -H 'Content-Type: application/json' -d @payload.json "$DISCORD_WEBHOOK_URL"`. + Build the JSON with `jq` so quoting is safe. Keep the message under Discord's 2000-character + limit: model, commit, GPU, prefill tok/s (median and 1% low), decode tok/s (median and 1% low), + and the delta versus the last run. BetterBench has no webhook support of its own, so the script + parses `results.json` and does the posting. Check + the HTTP status and report a failed post instead of ignoring it. + +--- + +## Phase 0: environment check + +- Confirm the toolchain and device: `icpx --version`, `sycl-ls` (the B65 must appear as a Level Zero + GPU), `clinfo -l` if present, and the kernel driver (`xe` or `i915`) via `lspci -k`. +- Record device limits from a tiny SYCL program: max work-group size, supported sub-group sizes, + local memory, global memory, whether `sycl::ext::oneapi::experimental::matrix` (joint_matrix) is + available and which element types/shapes it supports on this device, USM host/device/shared + support, and fp16/bf16/fp64 support. +- Check what Xe2 XMX does and does not do natively (I believe FP8 is not a native XMX input on + Battlemage, while bf16/fp16/int8 are; verify on the device, don't trust this sentence). +- Build the current tree's host backend (`./build.sh --no-hip`) and run the host tests to get a + baseline. Save the results in the log. + +If anything here is missing, stop and tell the user what to install. + +## Phase 1: understand the codebase before writing code + +Read, in this order: `README.md`, `spec.md`, `docs/PLUGIN.md`, `docs/OPS.md`, `docs/KERNELS.md`, +`docs/GUIDE.md` (sections on memory, placement and tests), `CMakeLists.txt`, `CMakePresets.json`, +`build.sh`, the `abi/` headers, then `core/`, `libref/`, `libavx/` and `libr4d/`. + +Produce `docs/SYCL_PORTING.md` containing: + +- **Every place the core depends on HIP** (runtime calls, headers, types, `hipMalloc`/streams/events/ + graphs/pinned memory/IPC/P2P, Resizable BAR handling, kernel-argument staging, device queries, + CMake logic). Use grep, list file and line, and classify each as "already behind the plugin ABI" + or "core calls HIP directly". +- How the **host backend** avoids HIP. This is your template for a second non-HIP backend. +- The **full op vocabulary** from `docs/OPS.md`, with, for each op: dtypes used by real recipes, + which models need it, and how `libr4d` implements it. +- A **minimal op set** needed to serve the smallest LLM end to end (MiniCPM5-2B bf16, then fp8), + using `--debug-graph` on the host backend to list exactly which ops and kernels a model resolves. +- The proposed design (below), adjusted to what you actually found. + +## Phase 2: design + +Default design, change it only with a written reason in the porting doc: + +- **Device runtime abstraction.** If the core calls HIP directly, introduce a small device-runtime + interface (allocate/free device and pinned host memory, copies, streams/queues, events, launch + context, device info) with the HIP implementation being a thin, behaviour-identical wrapper over + today's code, plus a SYCL/Level Zero implementation. Prefer extending the existing plugin ABI over + inventing a parallel one, and version it the way `abi/` already versions things. +- **New kernel library plugin**, e.g. `libxe2/`, built and loaded exactly like the bundled plugins + (it must also pass the `oot` out-of-tree rebuild test). One `sycl::queue` per device, in-order, + USM device allocations. +- **Build integration.** CMake option `RAD_SYCL` (off by default), `build.sh --sycl`, a preset, and a + `sycl` ctest label analogous to `gpu`. The HIP and SYCL backends must be able to coexist in one + build, or, if that is impractical, be mutually exclusive with a clear configure-time error. +- **Single card only for now.** Tensor parallelism and the all-reduce wires are out of scope; make + `--tp > 1` on the Intel backend stop at startup with a clear message. + +## Phase 3: correctness-first kernels + +Implement ops in the order the minimal set needs them. For each op: + +1. Write the simplest correct SYCL kernel first (plain work-groups, no XMX). +2. Add a unit test comparing it with `libref` on randomised inputs and edge shapes, at the same + tolerances `libr4d` uses. Wire it into ctest under the `sycl` label. +3. Run it on the B65. Fix until it passes. + +Typical early ops: embeddings/gather, RMSNorm and its variants, rotary embeddings, elementwise and +fused activations (SiLU/GELU-mul), softcap, softmax, matmul/GEMV in bf16, attention (prefill and +decode, with the KV cache layout the core expects, bf16 and fp8 KV), sampling, and whatever +`--debug-graph` says MiniCPM5-2B needs. Then fp8 weights (dequantised in-register to bf16 or a +format XMX accepts), then the 4-bit paths (MXFP4, int4 GPTQ/AWQ, w4a8) needed by the 27B and 31B +containers that fit in 32 GB. + +Milestone A: `radiance --model minicpm5-2b-bf16.rad` serves on the B65, `/v1/chat/completions` +returns coherent text, and greedy outputs match the host backend token for token on a fixed prompt +set (or, where reduction order differs, logits agree within a stated KL bound you measure and record). + +Milestone B: the same for `minicpm5-2b-fp8.rad`, then Qwen3.8-27B MXFP4 (19 GiB) or Gemma 4 31B w4a8 +(20 GiB), with speculative decoding (MTP / DFlash2 / DSpark) working. + +## Phase 4: performance + +Only after Milestone A is correct: + +- Use `--debug-graph`, `rad-kbench` and the dashboard's stats to find where time goes. +- Move GEMMs and attention onto XMX via `joint_matrix` (or ESIMD/DPAS where joint_matrix cannot + express what you need). oneDNN/oneMKL are acceptable for a first fast GEMM if they handle the + layouts; record any dependency added. +- Tune sub-group size (16 is usually right on Xe2), work-group shapes, SLM tiling, and prefetch. +- Minimise host round-trips per decode step; check whether queue submission overhead dominates + small-batch decode and batch or graph-record submissions if so (SYCL graphs extension if + available). +- Add a row for the B65 to `docs/KERNELS.md` with measured numbers. Re-run every correctness test + after each optimisation. + +## Phase 5: broaden and finish + +- Extend to the other models in the README table that fit in 32 GB on one card (image models such + as FLUX.3 klein and Krea 2 Turbo, Breeze-TTS-2, Qwen3-ASR, EmbeddingGemma 2), each with an + end-to-end check against the host backend. +- Document the Intel backend in `README.md`, `docs/GUIDE.md` and `docs/PLUGIN.md`: requirements + (oneAPI version, driver, Resizable BAR), build commands, supported models, known limits. +- Optional: a Dockerfile stage for Intel. + +## Definition of done + +- `./build.sh --sycl` configures, builds and runs the fast tests on this machine. +- `ctest -L sycl` passes on the B65; `ctest -LE 'gpu|oot'` still passes unchanged; the HIP build + still compiles; the `oot` test rebuilds the new plugin out of tree. +- At least MiniCPM5-2B (bf16 and fp8) and one 19–22 GiB model serve end to end on the B65 through the + OpenAI-compatible API, with outputs verified against the host backend. +- `docs/SYCL_PROGRESS.md` and `docs/SYCL_PORTING.md` are current. + +Start with Phase 0 now. Report briefly at the end of each phase, then continue to the next.