Compare commits

...
23 Commits
Author SHA1 Message Date
pascallinxweilerandClaude Opus 5.5 6174d5ee5c tests: kbench_m2xfp4 only in a HIP build -- it loads libr4d
The test from the m2xfp merge names --kernels libref:libr4d; a CPU-only or SYCL build has no
libr4d, so the replay loaded nothing and failed in 0.02 s. Guarded on RAD_HIP_FOUND as the tree's
other libr4d tests are. ctest -LE 'gpu|oot' after the merge: 84/89, the five known failures
(images_test and videos_test: no FFmpeg; glm5next, gbnf_shard2, quant_ggml: CPU budget).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 23:30:24 +02:00
pascallinxweilerandClaude Opus 5.5 6fbe59b7b0 Merge hugypufy/radiance m2xfp: M2XFP4 weights (upstream PR #203)
The M2XFP4 encoding (e2m1 codes, e8m0 per-32 scales, a u8 per-subgroup metadata plane, learned
Givens rotations): libref and libavx kernels, libr4d HIP kernels, the packer and the tests, as on
the branch (8 commits on 9eaf10d, radiance 1.11.0). Taken for Qwen3.8-27B-DFLASH2-PARO-M2XFP4,
the container used for testing and optimisation from now on; merged without conflicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 23:09:18 +02:00
pascallinxweilerandClaude Opus 5.5 e74e5b2413 sycl: profile_decode.sh reports calls and us a call; the BetterBench runs recorded
The decode profile now prints calls a step and the time a call for every op, from the same two
differenced runs. SYCL_PROGRESS records the a869226 run that was missing from the table and the
b07da2a run: decode 51.8 / 41.4 tok/s (median / 1% low), prefill 1575.6 tok/s @2000.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 23:01:05 +02:00
pascallinxweilerandClaude Opus 5.5 b07da2a121 libxe2: the long-K decode GEMV splits K two ways in the work-group -- decode 55 -> 57 tok/s
At M = 1 a GEMV is N / 2 sub-groups: for down_proj (N=2048, K=6144) that is a tenth of the card's
threads, each walking K alone. With K >= 4096 the work-group's sub-groups now take two halves of K
for the same columns and add the halves in order through local memory (deterministic, one kernel).
Per shape, cold: 59.7 -> 52.2 us; 4-16 ways no better, and splitting the K=2048 shapes slowed them,
so they keep one.

rad-kbench 361/361 and 350/350; KL mean 6.0e-4; greedy against libref 7/8 (the eighth a near-tie).
Decode 57.3 tok/s at a short context, 51.4 after a 1797-token prompt.

SYCL_PROGRESS records the per-shape times, the variants dropped, and what was taken from reading
GRIMOIRE (ideas only: it is GPL-3.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 22:13:39 +02:00
pascallinxweilerandClaude Opus 5.5 10455f2e1a sycl: rad_memcpy_ranges_async reads its range list on the device, as the contract says
The SYCL backend read the list on the host at the call. device.h says the kernel reads it when it
runs, so it may live in device memory or be written by earlier work on the stream; rad-kbench's
timer keeps it on the card, and --bench / --timing-only segfaulted in calibration. The prefix is
now one copy and the ranges one kernel after it (a work-group a range, 4-byte words, as the HIP
card's aql_copy_ranges), so a range over the prefix still lands last. device_test_sycl passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 21:38:30 +02:00
pascallinxweilerandClaude Opus 5.5 7a58b31c80 libxe2: the decode GEMV takes two output columns a sub-group -- gemm_nt 9.1 -> 8.5 ms a step
At M = 1 a sub-group now streams two weight rows at once; the band of 2..16 rows keeps one column a
sub-group. The accumulators are sized by the band at compile time, since four columns at sixteen
rows spilled and ran slower than one. Measured at a 1.8k context: one column 9.1 ms of gemm_nt a
step, two 8.5 (~465 GB/s against the ~600 GB/s a plain read kernel reaches on the card, measured
with incompressible data), four 10.9.

rad-kbench 361/361 and 350/350; KL against libref mean 6.0e-4, p99 2.9e-3, top-1 98.4%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 21:09:38 +02:00
pascallinxweilerandClaude Opus 5.5 580d438d2b libxe2: attention scores a key a lane with 16-byte loads -- decode 32 -> 55 tok/s
Each sub-group now takes sixteen keys a step, one a lane: the lane scores its key in full against
the query in local memory, one max and one sum update the flash state, and the value rows are added
with each key's weight taken from its lane. bf16 cache rows are read 16 bytes at a time, and each
row's own visible span is split evenly 32 ways on the device instead of the context limit (which
left most partitions empty at a short context).

rad-kbench 138/138 and 132/132; KL against libref mean 5.7e-4, p99 3.1e-3, top-1 98.6%.
MiniCPM5-2B on the B65: decode 55 tok/s at a short context and 49 tok/s after a 1797-token prompt
(was 32 and 30); that prompt's prefill 1.62 s, 1109 tok/s (was 4.61 s).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 20:58:52 +02:00
pascallinxweilerandClaude Opus 5.5 f5614a03bb libxe2: the norm and the fp8 quantisers 3-4x faster at decode, still bit-identical to libref
At one row a work-group, rmsnorm_quant_fp8 took 108 us and gated_quant_fp8 84 us a call (26% and 10%
of a decode step at a 1.8k context). The ordered sum of squares now reads its squares eight at a
time and adds them in the same order; quant_group computes a group's values once into registers and
writes out_bf16 itself; gated_quant_fp8 spreads a row's independent groups over ceil(groups/16)
work-groups. rad-kbench: 208/208 and 206/206 at rel_l2 0.

scripts/sycl/profile_decode.sh isolates decode steps' per-op device time (two profiled runs of the
same request, 1 and 1 + STEPS tokens, differenced). Decode at 1.8k context: 34.8 -> 26.6 ms of
device time a step; the two ops 9.1 -> 3.7 and 3.5 -> 0.9 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 20:47:13 +02:00
pascallinxweilerandClaude Opus 5.5 880c218375 libxe2: split-KV attention -- a kv head's keys read once for its query heads, decode across the card
The long-context decode profile was 70% attention: one work-group a (row, head) left most of the
card idle at one row and read each kv head eight times. xe2_attn_paged now splits a row's keys into
partitions of 32 or more across work-groups, each work-group a (row, kv head, partition) whose
sub-groups are the kv head's query heads, the partial softmax states merged from 64 MiB of scratch
(the scratch hook); prefill-sized row counts take one partition and write directly.

rad-kbench 138/138 and 132/132, KL against libref mean 5.8e-4, p99 3.2e-3, top-1 98.5%. Decode
after a 1797-token prompt 16.2 -> 29.8 tok/s; short-context decode 32 tok/s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 20:42:38 +02:00
pascallinxweilerandClaude Opus 5.5 355dc1b112 libxe2: Phase 4 step 2 -- bf16 XMX GEMM for prefill and a one-pass paged attention
xe2_gemm_nt_xmx / xe2_logits_gemm_xmx (M >= 17, bf16): joint_matrix M8 N16 K16 with use::b loaded
column-major straight from the [N, K] weight, eight sub-groups a work-group on one 64-column slice
so a B tile is in cache for all of them; tail rows go to the GEMV and shapes the tiles cannot read
to the exact kernel. xe2_attn_paged: one pass with an online softmax, keys over eight sub-groups,
head_dim over lanes, libref's masks, windows, ragged batches and fp8 descales. Both keep their
exact twins under XE2_EXACT=1.

rad-kbench: fixture 499/499, MiniCPM5-2B 482/482 (worst rel_l2 1.7e-4). KL against the libref
reference over 1914 positions: mean 5.8e-4, p99 3.2e-3, top-1 98.7% -- inside the bound.
Prefill of a 1795-token prompt: 4.57 s, 393 tok/s (was ~17); decode 33.2 tok/s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 20:34:02 +02:00
pascallinxweilerandClaude Opus 5.5 a869226800 libxe2: Phase 4 step 1 -- a bandwidth-bound decode GEMV and an ordered sum from local memory
The profile of a MiniCPM5-2B decode step on the B65 (232.8 ms) was 79% gemm_nt, reading its
weights at 62 GB/s, and 13% the norms' serial sum of squares.

- xe2_gemm_nt_gemv / xe2_logits_gemm_gemv (priority 10, M <= 16, bf16): a sub-group an output
  column, 16-byte coalesced weight loads, a tree reduction. Not libref's order: rad-kbench passes
  them at the gemm tolerance (fixture 361/361, MiniCPM5 180/180, worst rel_l2 1.6e-4), and
  XE2_EXACT=1 sends every launch to the exact kernel for bisecting.
- The norms form their squares in parallel into local memory and add them in index order: still
  bit-identical to libref.

Decode 4.2 -> 35.5 tok/s. Against a libref-only host build, over 1914 positions of the repo's docs
with every position through the GEMV: KL mean 5.9e-4, p99 3.5e-3, top-1 98.5% -- libavx's own
distance from libref is 5.7e-4 / 3.0e-3 / 98.6%. The exact path scores KL 0, top-1 100%.

docs/SYCL_PROGRESS.md: the profile, the KL bound (D13), and the user's decision to use the bf16
container for Milestone B instead of the fp8 one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 19:48:40 +02:00
pascallinxweilerandClaude Opus 5.5 43d84111c2 libxe2: the DSpark drafter's ops -- speculative decoding on the B65, greedy-identical
Every op MiniCPM5-2B bf16's DSpark drafter issues now has a libxe2 row, each libref's arithmetic in
libref's order: gemm_nt_q over fp8a8 block-scaled codes (quant_dot per output, the scale grids
worked out on the host as make_scales does), gemm_nt_q_gated with the gated fp8 epilogue, the w2a8
vocabulary head (gemm_zp; b_scale in libref's joined planes form through a copy of libref's layout
hook, so both libraries ask for the same stored bytes, its planes found on the device),
quant_act_i8, silu_mul, row_topk and dflash_select.

rad-kbench: MiniCPM5-2B 191/191 at rel_l2 0. The fixture found the gated GEMM refusing a 27B
geometry its row accepted (it held the whole N-wide row in local memory); it now keeps the n gated
values and declares N <= 57344. The engine oracle with speculation on: 1500/1500 issues
bit-identical, the w2a8 head included. Greedy with speculation on matches libref's greedy without
it on all eight prompts.

Install and oot: a SYCL build installs librad_sycl.so and libxe2.so, its executables find the
backend through $ORIGIN/../lib, and tests/oot_plugins.sh rebuilds libxe2 out of tree with icpx when
RAD_OOT_ICPX is set; it passes in build-sycl.

scripts/sycl/bench_report.sh: the report's screenshot is a JPEG, rendered with fonts (this host has
none, and the first post had no text). docs/SYCL_PROGRESS.md: the first quick benchmark (4.2 tok/s
decode, 17.3 tok/s prefill at 2000 tokens), Milestone B part 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 19:31:29 +02:00
pascallinxweilerandClaude Opus 5.5 874f8d28b1 libxe2: strided cast and libref's sigmoid -- MiniCPM5-2B serves on the B65, greedy-identical
Serving MiniCPM5-2B bf16 on the Arc Pro B65 found two things rad-kbench's dense operands did not:

- cast is handed the q slice of the fused qkv row (2048 of every 2560 elements) and refused it,
  stopping the first step by name. It now walks any strides in libref's offlin order.
- gated_quant_fp8 took sigmoid with an f32 exp, within rad-kbench's tolerance but not libref's
  double exp: now and then an ulp in silu moved the bf16 narrowing and one E4M3 code, in some of
  the 42 layers, enough to flip a greedy near-tie tokens later. The engine's own op oracle
  (RADIANCE_OP_ORACLE='*', which runs libref on the operands the device kernel was handed) found
  it: 9 of 600 issues before, 600 of 600 bit-identical after, over a 26-token prefill.

With both, a greedy run on the B65 matches a libref-only host server token for token on all eight
prompts of scripts/sycl/greedy_compare.py (64 tokens each), and the top-5 logprobs agree exactly
over 96 decode steps. /v1/chat/completions answers coherently, reasoning split out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 16:49:14 +02:00
pascallinxweilerandClaude Opus 5.5 94923fbb53 libxe2: the thirteen sampler ops
Each is libref's arithmetic on the card. The serial stages (penalties, DRY, the n-gram ban, top-p,
min-p, typical, XTC, the pick) run libref's loops unchanged, one work-item a row, so their sums keep
libref's order. Temperature and the grammar mask are one work-item an element. argmax, top-k and
logprobs scan the vocabulary with one work-group a row, reducing a 64-bit key -- the value's
order-preserving bits above the complemented index -- so the largest value wins and ties go to the
lower id, libref's rule; top-k is libref's topk_next k times, and a greedy row takes no rounds.
DRY's per-token map is replaced by a first-occurrence scan that computes the same maxima.

rad-kbench against libref: the whole fixture with libxe2 first, 1101/1101; MiniCPM5-2B's sampler
cases 56/56, all at rel_l2 0. With this, every op MiniCPM5-2B bf16 issues with speculation off has
a device row in libxe2 (13 model ops, 13 sampler ops).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 16:21:22 +02:00
pascallinxweilerandClaude Opus 5.5 bcd4ddc91b libxe2: kv_store and attn_paged, correctness first
The paged cache in libref's and libr4d's layout. attn_paged runs one work-group a (query row, head)
in libref's order: each key's dot summed over d serially by its lane, the max over the group, then
weights by chunk in local memory with the sum and every acc[d] accumulated in key order, exp in
double. Scores are recomputed rather than kept, since 131072 keys of them do not fit local memory.
Masks, sliding windows, ragged batches and fp8 descales are libref's. kv_store skips a slot past
the cache instead of refusing the launch, which would need the host to read device memory.

rad-kbench against libref: fixture 178/178, MiniCPM5-2B 160/160 (rel_l2 0).

docs/SYCL_PROGRESS.md: the HIP build compiles (785/785 targets for gfx1201 in the ROCm 10.1
container) at the commit holding every core-side change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 16:12:32 +02:00
pascallinxweilerandClaude Opus 5.5 c52f76c33e libxe2: gemm_nt and logits_gemm, correctness first
One work-item an output, f32 over ascending k from zero with no fused multiply-add: libref's
gemm_plain order, so MiniCPM5-2B's projections and its 130560-row head agree with the reference
exactly. Slow on purpose; the XMX kernels of Phase 4 are checked against this and libref. The rows
take float weights only (a dtype constraint); a quantised weight is gemm_nt_q's.

rad-kbench against libref: fixture 276/276, MiniCPM5-2B 164/164 (rel_l2 0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 16:09:17 +02:00
pascallinxweilerandClaude Opus 5.5 fca4cbe3b5 libxe2: rope, embed_lookup, gather_rows, cast
rope builds its frequency ladder on the host per launch exactly as libref's rope_freqs does (a
double pow, then YaRN or llama3 from rad_yarn.h) and takes cos and sin of the f32 angle in double on
the card, as libref does; positions reach 131072 at MiniCPM5's context. neox and gptj with one
position component; the row says so with a mode constraint and the launch refuses anything else by
name.

The gathers write a zero row for an index outside the table, libr4d's rule: libref instead checks
every index on the host before running, which a launch cannot do without waiting on its stream.

rad-kbench against libref: fixture 127/127 and MiniCPM5-2B 94/94, rel_l2 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 16:05:59 +02:00
pascallinxweilerandClaude Opus 5.5 b2cdcb4420 libxe2: rmsnorm, rmsnorm_quant_fp8, quant_act_fp8, gated_quant_fp8
One work-group a row; a quantisation group a sub-group. The arithmetic is libref's step for step,
and two things made it so on the card:

- Device code is generated at link time (AOT), so the flags that shape it now go to the link as
  well as the compile: -ffp-contract=off, -ffp-model=precise, and -foffload-fp32-prec-div/-sqrt.
  Without correctly rounded division a group's scale amax * (1/448) came out one ulp off, and
  bf16 inputs sit exactly on E4M3 rounding ties often enough that 1780 of 524288 codes moved
  (a standalone host/device comparison showed it; with the flags, none).
- The sum of squares is libref's ascending f32 sum, by one work-item. A tree reduction moved
  normed values across bf16 ties on MiniCPM5-2B's real weights and failed rmsnorm_quant_fp8 at
  M=1 (rel 7.7e-3 against its 4e-3 tolerance).

rad-kbench against libref: the fixture 228/228 and MiniCPM5-2B's container 140/140, worst rel_l2
1e-7, inside guarded allocations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 16:02:58 +02:00
pascallinxweilerandClaude Opus 5.5 41a3c32a65 libxe2: the Intel kernel library's skeleton, and its first op, add
libxe2 is a kernel plugin like any other, built by rad_add_plugin from the icpx sub-build into the
build tree's $RADIANCE_HOME. It declares no schemas (every op it serves is libref's vocabulary), only
device rows, written with designated initialisers. xe2_common.h holds what every kernel needs: the
launch's queue (rad_sycl.h), row views over padded operands, refusals that name the geometry, and
libref's own dtype conversions so results round where the reference's do.

add passes rad-kbench against libref at tolerance zero, on the recorded fixture (30 cases) and on
MiniCPM5-2B's container (20 cases), inside guarded allocations. In a SYCL build the kbench replays
run libxe2 on the card, so they are labelled sycl there, as they are gpu in a HIP build.

scripts/sycl/notify.sh posts to the Discord webhook when the port needs the user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 15:55:39 +02:00
pascallinxweilerandClaude Opus 5.5 370a906c70 device: the SYCL backend -- Intel GPUs through oneAPI over Level Zero
A fourth DeviceBackend, in librad_sycl.so: in-order sycl::queues on one context, events as
barriers, copies and fills on the queue, gates as a spin kernel on a pinned flag, and the core's
advance and weight-table kernels as SYCL twins of their .hip files. RadStreams are RadSyclStreams
(abi/rad_sycl.h). Pinned host memory is page-aligned memory registered for device copies, since
O_DIRECT cannot read into SYCL's malloc_host pages; event timing is opt-in (RADIANCE_SYCL_TIMING=1)
because profiling queues cost ~20 us of host time a submission.

The SYCL code is its own CMake project, sycl/, configured with icpx through ExternalProject, so the
engine and every host plugin stay on the main compiler: a SYCL build's host code is the default
build's. RAD_SYCL (default OFF), build.sh --sycl, the sycl presets; HIP and SYCL in one build are
refused at configure.

On the SYCL backend --tp > 1 and ops resolved only to host kernels stop the start, since the Intel
backend runs on one card and never puts an op on the CPU. A SYCL build that sees no GPU warns that
it runs on the CPU and names the missing oneAPI environment.

device_test runs on the Arc Pro B65 as device_test_sycl (label sycl): 36 cases pass, 12 skip
(elastic memory, not provided; host-backend-only cases). Host tests hide Level Zero GPUs with
ONEAPI_DEVICE_SELECTOR. The host tier is the baseline's in both the default and the SYCL build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 15:38:42 +02:00
pascallinxweilerandClaude Opus 5.5 a3dc47b79a abi: rad_sycl.h -- what a RadStream is under the SYCL backend
A SYCL kernel library has no hipLaunchKernel for the engine to serve, so under the SYCL backend a
RadStream points to a RadSyclStream: a magic, its own version, and the engine's in-order
sycl::queue. rad_sycl_queue() hands a plugin the queue or null for any other stream. The struct is
versioned by RAD_SYCL_STREAM_VERSION rather than RAD_ABI_VERSION, since no shape an existing plugin
compiles against changes; rad_abi.h and rad_types.h say so.

The layout tests cover it: strict C11 in abi_c_test.c, and its rows in abi_layout_rows.h, where a
struct the frozen table predates is allowed without a version bump.

docs/SYCL_PROGRESS.md: D6 revised. Building everything with icpx fails in libavx (_pdep_u64 without
-mbmi2, which GCC accepts and clang refuses), so the main build stays GCC and only SYCL code is
built by icpx, as shared libraries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 15:38:42 +02:00
pascallinxweilerandClaude Opus 5.5 ec4dbb6464 sycl: Phase 1 -- docs/SYCL_PORTING.md: where the core meets HIP, the op set, the design
The core's HIP use is already behind the DeviceBackend vtable except three core kernels (advance,
wtab, xprefetch), the engine's interposed hipLaunchKernel that plugins launch through, and build
switches; each site is listed with file and line. The minimal set for MiniCPM5-2B is measured with
--debug-graph on the test suite's synthetic llama containers (13 model ops, 13 sampler ops; fp8 adds
gemm_nt_q / gemm_nt_q_gated), since no MiniCPM5 container is in the model library.

The design: a fourth DeviceBackend over SYCL, a RadSyclStream hand-off for plugins with its own
version instead of an ABI bump, libxe2 AOT for bmg-g31, and on that backend a fatal error where the
planner would otherwise put a weighted op on the CPU.

scripts/sycl/op_inventory.sh generates the 238-op appendix: libref's schemas through rad-schemas,
libr4d's 407 rows parsed from source by r4d_rows.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 15:38:42 +02:00
pascallinxweilerandClaude Opus 5.5 c25f610fda sycl: Phase 0 of the Intel backend -- the B65's limits and XMX types, the host baseline
scripts/sycl/probe.sh builds and runs two probes on the Arc Pro B65 (Level Zero, xe driver): the
device's limits and joint_matrix combinations, and an ESIMD DPAS check of E4M3 / E5M2 against bf16
and s8 controls in the same harness. bf16, fp16, s8 and tf32 XMX are exact; fp8 DPAS compiles for
bmg-g31 but returns garbage, so fp8 weights are widened to bf16 in-register (exact for E4M3).

docs/SYCL_PROGRESS.md is the resume log: device tables, the host baseline (82/88 of -LE 'gpu|oot';
the six failures are FFmpeg-less builds and CPU-time budgets on this VM), BetterBench setup, the
model library survey and the open blockers (no MiniCPM5 container in the library, no ROCm here).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 15:38:42 +02:00
54 changed files with 6701 additions and 21 deletions

No files matched your search

+65
View File
@@ -84,6 +84,38 @@ elseif(NOT RAD_HIPCC)
"/opt/rocm/llvm/bin and $ROCM_PATH.")
endif()
# ---------------------------------------------------------------- SYCL detection
# The Intel GPU backend (docs/SYCL_PORTING.md). Off by default. SYCL code is compiled and linked by
# icpx in a sub-build of its own (sycl/CMakeLists.txt, added below), so everything else stays on
# this project's compiler: a SYCL build's host code is the default build's.
#
# RAD_SYCL_TARGETS names the AOT targets (icpx -fsycl-targets spelling); the default is the Arc Pro
# B65's Battlemage G31.
set(RAD_SYCL "OFF" CACHE STRING "ON | OFF | AUTO -- build the SYCL (Intel GPU) backend with icpx")
set_property(CACHE RAD_SYCL PROPERTY STRINGS ON OFF AUTO)
set(RAD_SYCL_TARGETS "intel_gpu_bmg_g31" CACHE STRING "AOT targets for SYCL device code")
set(RAD_SYCL_FOUND OFF)
if(NOT RAD_SYCL STREQUAL "OFF")
find_program(RAD_ICPX icpx HINTS ENV CMPLR_ROOT PATH_SUFFIXES bin
PATHS /opt/intel/oneapi/compiler/latest/bin)
if(RAD_ICPX)
set(RAD_SYCL_FOUND ON)
elseif(RAD_SYCL STREQUAL "ON")
message(FATAL_ERROR "RAD_SYCL=ON but icpx was not found. Install the oneAPI DPC++ compiler, or "
"source /opt/intel/oneapi/setvars.sh first.")
endif()
endif()
if(RAD_SYCL_FOUND AND RAD_HIP_FOUND)
# Both could be compiled side by side in principle; nothing has tested one engine holding both,
# so a build picks one (docs/SYCL_PORTING.md §4.5).
message(FATAL_ERROR
"radiance: RAD_SYCL and the HIP backend are both on. One build holds one device backend: "
"configure the SYCL build with -DRAD_WITH_HIP=OFF (build.sh --sycl does).")
endif()
if(RAD_SYCL_FOUND)
message(STATUS "radiance: SYCL backend ON, ${RAD_ICPX}, targets ${RAD_SYCL_TARGETS}")
endif()
# ASan + UBSan for host code only. AMD's amdgcn ASan needs xnack+ for its page-fault-based shadow,
# and RDNA has no xnack, so the generator expressions keep the flags off HIP. Device kernels rely on
# rad-kbench's red zones instead: a poisoned margin around every operand and scratch allocation,
@@ -309,6 +341,39 @@ if(NOT RAD_WITH_FFMPEG STREQUAL "OFF")
endif()
endif()
# ---------------------------------------------------------------- the icpx sub-build
# sycl/ is its own CMake project, configured with icpx, so -fsycl code never meets this project's
# compiler. rad_core links librad_sycl.so (the device backend) as an imported library; the kernel
# library libxe2 lands in ${RAD_PLUGIN_OUT}/kernels beside the others.
if(RAD_SYCL_FOUND)
include(ExternalProject)
set(RAD_SYCL_BINARY_DIR ${CMAKE_BINARY_DIR}/sycl)
ExternalProject_Add(rad_sycl_build
SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/sycl
BINARY_DIR ${RAD_SYCL_BINARY_DIR}
CMAKE_ARGS -DCMAKE_CXX_COMPILER=${RAD_ICPX}
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
-DRAD_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}
-DRAD_SYCL_TARGETS=${RAD_SYCL_TARGETS}
-DRAD_PLUGIN_OUT=${RAD_PLUGIN_OUT}
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON
BUILD_ALWAYS ON
INSTALL_COMMAND ""
BUILD_BYPRODUCTS ${RAD_SYCL_BINARY_DIR}/librad_sycl.so
USES_TERMINAL_BUILD ON)
add_library(rad_sycl_rt SHARED IMPORTED GLOBAL)
set_target_properties(rad_sycl_rt PROPERTIES
IMPORTED_LOCATION ${RAD_SYCL_BINARY_DIR}/librad_sycl.so
IMPORTED_NO_SONAME ON)
add_dependencies(rad_sycl_rt rad_sycl_build)
# Installed: the backend beside the other libraries, libxe2 where every kernel plugin goes
# (cmake/RadAddPlugin.cmake's destination), and executables that find the backend there.
set(CMAKE_INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}")
install(FILES ${RAD_SYCL_BINARY_DIR}/librad_sycl.so DESTINATION ${CMAKE_INSTALL_LIBDIR})
install(FILES ${RAD_PLUGIN_OUT}/kernels/libxe2.so
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance/kernels)
endif()
add_subdirectory(vendor)
add_subdirectory(core)
# Kernel plugins, one root directory each. Each holds its kernels, row table and layouts and links
+17 -1
View File
@@ -21,12 +21,20 @@
"inherits": "default",
"binaryDir": "${sourceDir}/build-tsan",
"cacheVariables": { "RAD_TSAN": "ON", "RAD_ASAN": "OFF", "RAD_WITH_HIP": "OFF" }
},
{
"name": "sycl",
"displayName": "The Intel GPU (SYCL) backend, its code built by icpx, in build-sycl/",
"inherits": "default",
"binaryDir": "${sourceDir}/build-sycl",
"cacheVariables": { "RAD_SYCL": "ON", "RAD_WITH_HIP": "OFF" }
}
],
"buildPresets": [
{ "name": "default", "configurePreset": "default" },
{ "name": "asan", "configurePreset": "asan" },
{ "name": "tsan", "configurePreset": "tsan" }
{ "name": "tsan", "configurePreset": "tsan" },
{ "name": "sycl", "configurePreset": "sycl" }
],
"testPresets": [
{
@@ -59,6 +67,14 @@
"inherits": "base",
"filter": { "include": { "label": "^gpu$" } }
},
{
"name": "sycl",
"displayName": "The tests that need an Intel GPU, one at a time (load the oneAPI environment first)",
"inherits": "base",
"configurePreset": "sycl",
"filter": { "include": { "label": "^sycl$" } },
"execution": { "jobs": 1, "noTestsAction": "error" }
},
{
"name": "perf",
"displayName": "The wall-clock checks, one at a time",
+2 -1
View File
@@ -16,7 +16,8 @@ extern "C" {
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h or rad_sample.h. Every
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
* load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a
* change of shape: a plugin without it gets the default. */
* change of shape: a plugin without it gets the default. rad_sycl.h is versioned on its own
* (RAD_SYCL_STREAM_VERSION), since only SYCL kernel libraries read it. */
#define RAD_ABI_VERSION 26u
/* ================================================================== plugin identity */
+56
View File
@@ -0,0 +1,56 @@
#ifndef RAD_SYCL_H
#define RAD_SYCL_H
/* rad_sycl.h -- what a RadStream is under the SYCL device backend (docs/SYCL_PORTING.md §4.2).
*
* On an AMD card a kernel plugin launches through hipLaunchKernel, which the engine serves on its
* own queues (docs/PLUGIN.md §5). SYCL has no launch entry point the engine could serve, so a SYCL
* kernel library is handed the queue itself: under the SYCL backend a RadStream points to a
* RadSyclStream, whose `queue` is an in-order sycl::queue the engine owns. Under every other
* backend a RadStream is not one, and `magic` says so.
*
* The struct carries its own version instead of moving RAD_ABI_VERSION, because no shape an
* existing plugin compiles against changes; only SYCL plugins read it, and rad_sycl_queue() refuses
* a struct of another version. Bump RAD_SYCL_STREAM_VERSION on any change below.
*
* What a launch may do with the queue mirrors docs/PLUGIN.md §5: submit kernels, copies and fills
* to it. It must not wait on it (a launch never synchronises), allocate (scratch comes from the
* `scratch` hook), submit host tasks, or keep the queue past the launch. */
#include <stdint.h>
#include "rad_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define RAD_SYCL_STREAM_MAGIC 0x4C435953u /* "SYCL", little-endian */
#define RAD_SYCL_STREAM_VERSION 1u
typedef struct RadSyclStream {
uint32_t magic; /* RAD_SYCL_STREAM_MAGIC */
uint32_t version; /* RAD_SYCL_STREAM_VERSION */
void* queue; /* sycl::queue*, in order, owned by the engine */
int32_t device; /* the device index the queue submits to (rad_dev_set's numbering) */
int32_t reserved;
} RadSyclStream;
#ifdef __cplusplus
} /* extern "C" */
#endif
#if defined(__cplusplus) && defined(SYCL_LANGUAGE_VERSION)
#include <sycl/sycl.hpp>
/* The queue behind `s`, or null when `s` is not a SYCL stream of this version (another backend's
* stream, or a plugin built against a different rad_sycl.h); the launch then returns
* RAD_E_DEVICE. */
inline sycl::queue* rad_sycl_queue(RadStream s) {
const RadSyclStream* r = (const RadSyclStream*)s;
if (!r || r->magic != RAD_SYCL_STREAM_MAGIC || r->version != RAD_SYCL_STREAM_VERSION)
return nullptr;
return (sycl::queue*)r->queue;
}
#endif
#endif /* RAD_SYCL_H */
+3 -2
View File
@@ -326,8 +326,9 @@ typedef uint32_t rad_kvgroup;
/* Opaque: the core never dereferences one. On a card it is the engine's own queue, not a
* hipStream_t. A kernel plugin may use it only with hipLaunchKernel (and so <<<>>>),
* hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync, which the engine implements itself, and
* must pass it to nothing else in HIP (docs/PLUGIN.md, "What a launch may do"). Under the host
* backend the host kernels ignore it. */
* must pass it to nothing else in HIP (docs/PLUGIN.md, "What a launch may do"). Under the SYCL
* backend it points to a RadSyclStream holding the engine's sycl::queue (rad_sycl.h). Under the
* host backend the host kernels ignore it. */
typedef void* RadStream;
#ifdef __cplusplus
+6
View File
@@ -15,6 +15,8 @@
# ./build.sh --no-hip force the host backend even where hipcc exists
# ./build.sh --asan AddressSanitizer + UBSan, host backend, in build-asan/
# ./build.sh --tsan ThreadSanitizer, host backend, in build-tsan/
# ./build.sh --sycl the Intel GPU (SYCL) backend, in build-sycl/: the engine as usual, its
# SYCL code built by icpx (oneAPI); docs/SYCL_PORTING.md
# ./build.sh --debug CMAKE_BUILD_TYPE=Debug
# ./build.sh -b DIR build in DIR instead of build/ (or build-asan/, build-tsan/)
#
@@ -33,6 +35,7 @@ while [ $# -gt 0 ]; do
--no-hip) CMAKE_ARGS="$CMAKE_ARGS -DRAD_WITH_HIP=OFF" ;;
--asan) SAN=asan ;;
--tsan) SAN=tsan ;;
--sycl) SAN=sycl ;;
--debug) CMAKE_ARGS="$CMAKE_ARGS -DCMAKE_BUILD_TYPE=Debug" ;;
-b) shift; BUILD="$1" ;;
*) echo "build.sh: unknown option $1" >&2; exit 2 ;;
@@ -47,6 +50,9 @@ case "$SAN" in
BUILD=${BUILD:-build-asan} ;;
tsan) CMAKE_ARGS="$CMAKE_ARGS -DRAD_TSAN=ON -DRAD_ASAN=OFF -DRAD_WITH_HIP=OFF"
BUILD=${BUILD:-build-tsan} ;;
# Not a sanitiser, but likewise a configuration with a directory of its own.
sycl) CMAKE_ARGS="$CMAKE_ARGS -DRAD_SYCL=ON -DRAD_WITH_HIP=OFF"
BUILD=${BUILD:-build-sycl} ;;
*) BUILD=${BUILD:-build} ;;
esac
[ "$CLEAN" = 1 ] && rm -rf "$BUILD"
+8
View File
@@ -37,6 +37,14 @@ if(RAD_FFMPEG_FOUND)
target_link_libraries(rad_core PUBLIC PkgConfig::RAD_FFMPEG)
endif()
if(RAD_SYCL_FOUND)
# The SYCL device backend lives in librad_sycl.so, built by icpx (sycl/CMakeLists.txt);
# device/sycl.cpp compiles to nothing here. CMake's build RPATH finds it in the build tree, and
# an installed binary finds it in ../lib (CMAKE_INSTALL_RPATH, top-level CMakeLists.txt).
target_compile_definitions(rad_core PUBLIC RAD_HAVE_SYCL=1)
target_link_libraries(rad_core PUBLIC rad_sycl_rt)
endif()
if(RAD_HIP_FOUND)
target_compile_definitions(rad_core PUBLIC RAD_HAVE_HIP=1)
target_link_libraries(rad_core PUBLIC ${RAD_HIP_RUNTIME} ${RAD_HSA_RUNTIME})
+1 -1
View File
@@ -156,7 +156,7 @@ typedef void* RadTape;
* no VRAM tier), the selector (only RAD_DOMAIN_HOST can run) and tests that skip device-only
* assertions. */
bool device_is_host();
const char* device_backend_name(); /* "host" or "aql" */
const char* device_backend_name(); /* "host", "aql" or "sycl" */
/* ------------------------------------------------------------------ two contract notes
*
+29
View File
@@ -8,6 +8,9 @@
*/
#include "device.h"
#include "../rad_internal.h"
#if defined(RAD_HAVE_SYCL) && RAD_HAVE_SYCL
#include "sycl_host.h"
#endif
#include <algorithm>
#include <cstdarg>
@@ -84,7 +87,33 @@ static void warn_cwsr_off() {
static DeviceBackend g_host_beside_hip;
#endif
#if defined(RAD_HAVE_SYCL) && RAD_HAVE_SYCL
/* What librad_sycl.so reaches of the engine (sycl_host.h). */
static const SyclHost g_sycl_host = {
kSyclHostVersion,
[] { return (int)log_level(); },
[](int level, const char* file, int line, const char* msg) {
log_emit((Log)level, file, line, "%s", msg);
},
[](const char* msg) { device_set_error("%s", msg); },
};
#endif
static const DeviceBackend* select_backend() {
#if defined(RAD_HAVE_SYCL) && RAD_HAVE_SYCL
/* A SYCL build has no HIP (configure refuses both, docs/SYCL_PORTING.md §4.5). */
if (const DeviceBackend* b = rad_sycl_backend(&g_sycl_host)) {
RAD_INFO("device: SYCL backend, %d device(s) [%s]", b->count(),
device_inventory(b).c_str());
return b;
}
/* A warning, not Info: on a machine whose card is there, this is the GPU being skipped. The
* usual cause is a missing oneAPI environment, since the runtime loads its Level Zero adapter
* and that adapter's libraries (libumf) from the oneAPI tree at run time. */
RAD_WARN("device: built with SYCL but no Level Zero GPU is visible -- using the host backend "
"(CPU). If this machine has an Intel GPU, load the oneAPI environment first "
"(. /opt/intel/oneapi/setvars.sh); ONEAPI_DEVICE_SELECTOR may also be hiding it");
#endif
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
if (const DeviceBackend* b = aql_backend_if_present()) {
RAD_INFO("device: AQL backend, %d device(s) [%s]", b->count(),
+875
View File
@@ -0,0 +1,875 @@
/* sycl.cpp -- the SYCL device backend: Intel GPUs through oneAPI's SYCL runtime over Level Zero.
*
* Every stream is an in-order sycl::queue on one context holding every device, and a RadStream is
* a RadSyclStream (abi/rad_sycl.h), so a SYCL kernel library submits to the engine's queue itself.
* Events are barriers on those queues: a record is a barrier whose event completes once everything
* before it has, and a wait is a barrier on the waiting queue that depends on that event, so no
* host thread blocks for either.
*
* Thin by design, like hip.cpp: each entry point is one runtime call plus error capture, and the
* contract is the host backend's (docs/IMPLEMENTATION.md). Where the runtime is more permissive
* than a card's contract (rad_memset_async on pageable memory, device.h note 1) the refusal is
* made here, so code developed on the host backend sees the same answer on this one.
*
* What this backend leaves out, each a supported configuration (device.h): recorded passes, elastic
* memory, the DMA lane and link holds, the expert prefetch, gates, chained launches. Peer access is
* refused, since the Intel backend serves one card (docs/SYCL_PORTING.md §4.7).
*
* Timing is opt-in. A queue made with enable_profiling costs ~20 us of host time per submission
* against ~4.5 us without (measured on the Arc Pro B65, docs/SYCL_PROGRESS.md D9), which at ~550
* launches a decode step is most of a step. So queues carry it only under RADIANCE_SYCL_TIMING=1,
* and otherwise rad_event_elapsed_ms refuses, naming the variable (--profile-ops, rad-kbench).
*
* Built by icpx into librad_sycl.so (sycl/CMakeLists.txt); the engine reaches it through
* rad_sycl_backend() and hands it its logger (sycl_host.h). core/CMakeLists.txt globs this
* directory into the engine, built without SYCL, where the file compiles to nothing.
*/
#if defined(SYCL_LANGUAGE_VERSION)
#include "device.h"
#include "sycl_host.h"
#include "../rad_internal.h"
#include "rad_sycl.h"
#include <sycl/sycl.hpp>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <atomic>
#include <cstring>
#include <map>
#include <mutex>
#include <new>
#include <string>
#include <vector>
namespace rad {
namespace {
namespace syclex = sycl::ext::oneapi::experimental;
/* ------------------------------------------------------------------ the runtime's state
*
* Built once, on first use: the Level Zero GPUs in the platform's order and one context over all
* of them (USM pointers are valid only within their context). */
struct Runtime {
std::vector<sycl::device> devs;
sycl::context* ctx = nullptr;
};
Runtime& rt() {
static Runtime* r = [] {
auto* x = new Runtime();
try {
for (const sycl::device& d : sycl::device::get_devices(sycl::info::device_type::gpu))
if (d.get_backend() == sycl::backend::ext_oneapi_level_zero) x->devs.push_back(d);
if (!x->devs.empty()) x->ctx = new sycl::context(x->devs);
} catch (const sycl::exception& e) {
RAD_DEBUG("device: SYCL device enumeration failed: %s", e.what());
x->devs.clear();
}
return x;
}();
return *r;
}
/* RADIANCE_SYCL_TIMING=1: queues are made with enable_profiling (see the file header). */
bool timing_on() {
static const bool on = [] {
const char* e = std::getenv("RADIANCE_SYCL_TIMING");
return e && e[0] == '1';
}();
return on;
}
/* Per thread, matching hipSetDevice: one thread per rank, one device per rank (spec §1). */
thread_local int t_device = 0;
int sycl_fail(const sycl::exception& e, const char* who) {
device_set_error("%s: %s", who, e.what());
const std::error_code c = e.code();
if (c == sycl::errc::memory_allocation) return RAD_E_NOMEM;
if (c == sycl::errc::invalid || c == sycl::errc::nd_range) return RAD_E_INVAL;
if (c == sycl::errc::feature_not_supported) return RAD_E_UNSUPPORTED;
return RAD_E_DEVICE;
}
#define SYCL_TRY(who, ...) \
do { try { __VA_ARGS__; } \
catch (const sycl::exception& _e) { return sycl_fail(_e, who); } } while (0)
bool valid_device(int device) { return device >= 0 && device < (int)rt().devs.size(); }
/* Asynchronous errors (a kernel fault) arrive here from wait_and_throw. A device fault is not
* recoverable in-process (rad_device.h), so the error is recorded for the thread that waited and
* every later wait reports it too. */
std::mutex g_async_m;
std::string g_async_error;
void async_handler(sycl::exception_list errs) {
for (const std::exception_ptr& p : errs) {
try {
std::rethrow_exception(p);
} catch (const sycl::exception& e) {
std::lock_guard<std::mutex> lk(g_async_m);
if (g_async_error.empty()) g_async_error = e.what();
RAD_WARN("device: asynchronous SYCL error: %s", e.what());
}
}
}
int async_status(const char* who) {
std::lock_guard<std::mutex> lk(g_async_m);
if (g_async_error.empty()) return RAD_OK;
device_set_error("%s: the device reported an error earlier: %s", who, g_async_error.c_str());
return RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ devices */
int d_count(void) { return (int)rt().devs.size(); }
int d_set(int device) {
if (!valid_device(device)) {
device_set_error("rad_dev_set(%d): %d SYCL device(s)", device, d_count());
return RAD_E_INVAL;
}
t_device = device;
return RAD_OK;
}
/* RadDeviceProps::arch, the name a kernel library's build_target names: the oneAPI architecture
* enum's own spelling. A device this table does not know is "intel_gpu" plus its IP version, so
* a library built for a named architecture never claims it. */
std::string arch_name(const sycl::device& d) {
try {
switch (d.get_info<syclex::info::device::architecture>()) {
case syclex::architecture::intel_gpu_bmg_g21: return "intel_gpu_bmg_g21";
case syclex::architecture::intel_gpu_bmg_g31: return "intel_gpu_bmg_g31";
case syclex::architecture::intel_gpu_lnl_m: return "intel_gpu_lnl_m";
case syclex::architecture::intel_gpu_ptl_h: return "intel_gpu_ptl_h";
case syclex::architecture::intel_gpu_ptl_u: return "intel_gpu_ptl_u";
case syclex::architecture::intel_gpu_acm_g10: return "intel_gpu_acm_g10";
case syclex::architecture::intel_gpu_acm_g11: return "intel_gpu_acm_g11";
case syclex::architecture::intel_gpu_acm_g12: return "intel_gpu_acm_g12";
case syclex::architecture::intel_gpu_pvc: return "intel_gpu_pvc";
default: break;
}
char b[32];
std::snprintf(b, sizeof b, "intel_gpu_%llx",
(unsigned long long)d.get_info<syclex::info::device::architecture>());
return b;
} catch (const sycl::exception&) {
return "intel_gpu";
}
}
int64_t free_bytes(const sycl::device& d) {
if (!d.has(sycl::aspect::ext_intel_free_memory)) return -1;
try {
return (int64_t)d.get_info<sycl::ext::intel::info::device::free_memory>();
} catch (const sycl::exception&) {
return -1;
}
}
int d_integrated(int device) {
if (!valid_device(device)) return 0;
/* Unified host memory is how SYCL tells an integrated GPU, whose "device memory" is host
* memory shared with every process. */
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
try {
return rt().devs[device].get_info<sycl::info::device::host_unified_memory>() ? 1 : 0;
} catch (const sycl::exception&) {
return 0;
}
#pragma clang diagnostic pop
}
int d_props(int device, RadDeviceProps* out) {
if (!out) return RAD_E_INVAL;
if (!valid_device(device)) {
device_set_error("rad_dev_props(%d): %d SYCL device(s)", device, d_count());
return RAD_E_INVAL;
}
const sycl::device& d = rt().devs[device];
std::memset(out, 0, sizeof *out);
SYCL_TRY("rad_dev_props", {
const std::string name = d.get_info<sycl::info::device::name>();
std::snprintf(out->name, sizeof out->name, "%.*s", (int)(sizeof out->name) - 1, name.c_str());
const std::string arch = arch_name(d);
std::snprintf(out->arch, sizeof out->arch, "%.*s", (int)(sizeof out->arch) - 1, arch.c_str());
out->device_id = device;
out->n_cu = (int)d.get_info<sycl::info::device::max_compute_units>();
/* The sub-group the kernel libraries use: 16 where offered (Xe2's native width). */
const std::vector<size_t> sg = d.get_info<sycl::info::device::sub_group_sizes>();
out->warp_size = sg.empty() ? 1 : (int)sg.front();
for (size_t s : sg)
if (s == 16) out->warp_size = 16;
out->vram_bytes = (int64_t)d.get_info<sycl::info::device::global_mem_size>();
const int64_t fr = free_bytes(d);
out->vram_free = fr >= 0 ? fr : out->vram_bytes;
out->lds_bytes = (int64_t)d.get_info<sycl::info::device::local_mem_size>();
});
out->supports_p2p = 0;
out->is_host_backend = 0;
return RAD_OK;
}
/* One card only (docs/SYCL_PORTING.md §4.7): no peer is reachable. */
int d_peer_access(int self, int peer) { return self == peer ? 1 : 0; }
int d_enable_peer(int self, int peer) {
if (self == peer) return RAD_OK;
device_set_error("rad_dev_enable_peer(%d, %d): the SYCL backend serves one card; tensor "
"parallelism is not supported on it", self, peer);
return RAD_E_UNSUPPORTED;
}
int d_pci_address(int device, char* out, int cap) {
if (!out || cap <= 0) return RAD_E_INVAL;
if (!valid_device(device)) return RAD_E_INVAL;
const sycl::device& d = rt().devs[device];
if (!d.has(sycl::aspect::ext_intel_pci_address)) return RAD_E_UNSUPPORTED;
std::string a;
SYCL_TRY("rad_dev_pci_address", a = d.get_info<sycl::ext::intel::info::device::pci_address>());
unsigned dom = 0, b = 0, dv = 0, f = 0;
if (std::sscanf(a.c_str(), "%x:%x:%x.%x", &dom, &b, &dv, &f) != 4) {
device_set_error("ext_intel_pci_address(%d): '%s' is not a PCI address", device, a.c_str());
return RAD_E_IO;
}
std::snprintf(out, (size_t)cap, "%04x:%02x:%02x.%x", dom, b, dv, f);
return RAD_OK;
}
int d_runtime_version(char* out, int cap) {
if (!out || cap <= 0) return RAD_E_INVAL;
if (rt().devs.empty()) return RAD_E_UNSUPPORTED;
SYCL_TRY("rad_dev_runtime_version", {
const sycl::device& d = rt().devs[0];
std::snprintf(out, (size_t)cap, "SYCL %s, Level Zero driver %s",
d.get_platform().get_info<sycl::info::platform::version>().c_str(),
d.get_info<sycl::info::device::driver_version>().c_str());
});
return RAD_OK;
}
/* VRAM in use by all processes, from the driver's free count. Answered once props() has read the
* device, as the contract asks; the query does not enter a queue. */
int d_vram_used(int device, int64_t* out) {
if (!out || !valid_device(device)) return RAD_E_INVAL;
const sycl::device& d = rt().devs[device];
const int64_t fr = free_bytes(d);
if (fr < 0) return RAD_E_UNSUPPORTED;
int64_t total = 0;
SYCL_TRY("rad_dev_vram_used", total = (int64_t)d.get_info<sycl::info::device::global_mem_size>());
*out = total - fr;
return RAD_OK;
}
/* ------------------------------------------------------------------ memory
*
* Pinned host memory (RAD_MEM_HOST_PINNED and _MAPPED) is ordinary page-aligned memory registered
* with the driver (prepare_for_device_copy), not SYCL's malloc_host. The driver maps malloc_host
* pages itself, and O_DIRECT cannot read into them (EFAULT), while the mover reads the file tier
* straight into pinned buffers (directio.h). Registered memory copies at the same rate (28.4 GB/s
* either way on the Arc Pro B65) and kernels reach it through system USM, which the Intel driver
* provides (aspect usm_system_allocations). The runtime does not know such a pointer, so the
* ranges are kept here for host_ptr, device_ptr and the memset check. */
std::mutex g_pinned_m;
std::map<uintptr_t, size_t> g_pinned; /* base -> bytes */
bool in_pinned(const void* p) {
const uintptr_t a = (uintptr_t)p;
std::lock_guard<std::mutex> lk(g_pinned_m);
auto it = g_pinned.upper_bound(a);
if (it == g_pinned.begin()) return false;
--it;
return a < it->first + it->second;
}
/* Device bytes this process holds through rad_dev_alloc, for the room check's message. */
std::atomic<int64_t> g_device_bytes{0};
std::mutex g_dev_sizes_m;
std::map<uintptr_t, int64_t> g_dev_sizes;
std::string human(int64_t b) {
char buf[32];
if (b >= ((int64_t)1 << 30)) std::snprintf(buf, sizeof buf, "%.2f GiB", (double)b / (1 << 30));
else if (b >= ((int64_t)1 << 20)) std::snprintf(buf, sizeof buf, "%.1f MiB", (double)b / (1 << 20));
else std::snprintf(buf, sizeof buf, "%lld B", (long long)b);
return buf;
}
/* True when the card can take `bytes` more. Level Zero may accept an allocation past the free
* figure and fault later, so the backend refuses it itself, as the AQL backend does. If the driver
* gives no figure the allocation is allowed. */
bool card_has_room(int device, int64_t bytes, const char* what) {
const int64_t avail = free_bytes(rt().devs[device]);
if (avail < 0 || bytes <= avail) return true;
device_set_error("%s(%s) on card %d: the driver has %s left to give on it. Of the memory in "
"use on it, this process holds %s through rad_dev_alloc. Memory another "
"process took after the VRAM budget was measured is the usual cause",
what, human(bytes).c_str(), device, human(avail).c_str(),
human(g_device_bytes.load()).c_str());
return false;
}
void* d_alloc(int64_t bytes, int kind) {
if (bytes <= 0) {
device_set_error("rad_dev_alloc(%lld): size must be positive", (long long)bytes);
return nullptr;
}
if (!valid_device(t_device)) {
device_set_error("rad_dev_alloc: no SYCL device %d", t_device);
return nullptr;
}
void* p = nullptr;
try {
switch (kind) {
case RAD_MEM_DEVICE:
if (!card_has_room(t_device, bytes, "rad_dev_alloc")) return nullptr;
p = sycl::malloc_device((size_t)bytes, rt().devs[t_device], *rt().ctx);
if (p) {
g_device_bytes += bytes;
std::lock_guard<std::mutex> lk(g_dev_sizes_m);
g_dev_sizes[(uintptr_t)p] = bytes;
}
break;
case RAD_MEM_HOST_PINNED:
case RAD_MEM_HOST_MAPPED: {
/* Registered page-aligned memory (see above): one address on both sides, so
* host_ptr and device_ptr are the pointer itself. */
const size_t n = (size_t)((bytes + 4095) / 4096 * 4096);
if (posix_memalign(&p, 4096, n) != 0) p = nullptr;
if (!p) break;
try {
syclex::prepare_for_device_copy(p, n, *rt().ctx);
} catch (...) {
std::free(p);
throw;
}
std::lock_guard<std::mutex> lk(g_pinned_m);
g_pinned[(uintptr_t)p] = n;
break;
}
case RAD_MEM_HOST:
/* Pageable, page-aligned so it can be an O_DIRECT target. */
if (posix_memalign(&p, 4096, (size_t)((bytes + 4095) / 4096 * 4096)) != 0) p = nullptr;
break;
default:
device_set_error("rad_dev_alloc: unknown memory kind %d", kind);
return nullptr;
}
} catch (const sycl::exception& e) {
sycl_fail(e, "rad_dev_alloc");
return nullptr;
}
if (!p) device_set_error("rad_dev_alloc(%lld, kind %d): out of memory", (long long)bytes, kind);
return p;
}
void d_free(void* p, int kind) {
if (!p) return;
switch (kind) {
case RAD_MEM_DEVICE:
try {
sycl::free(p, *rt().ctx);
} catch (const sycl::exception& e) {
RAD_WARN("device: rad_dev_free(%p): %s", p, e.what());
}
{
std::lock_guard<std::mutex> lk(g_dev_sizes_m);
auto it = g_dev_sizes.find((uintptr_t)p);
if (it != g_dev_sizes.end()) {
g_device_bytes -= it->second;
g_dev_sizes.erase(it);
}
}
break;
case RAD_MEM_HOST_PINNED:
case RAD_MEM_HOST_MAPPED: {
{
std::lock_guard<std::mutex> lk(g_pinned_m);
if (!g_pinned.erase((uintptr_t)p)) {
RAD_WARN("rad_dev_free(%p): not pinned memory this backend gave out; leaked "
"rather than freed with the wrong allocator", p);
break;
}
}
try {
syclex::release_from_device_copy(p, *rt().ctx);
} catch (const sycl::exception& e) {
RAD_WARN("device: rad_dev_free(%p): %s", p, e.what());
}
std::free(p);
break;
}
case RAD_MEM_HOST:
std::free(p);
break;
default:
RAD_WARN("rad_dev_free(%p): unknown memory kind %d; leaked rather than freed with the "
"wrong allocator", p, kind);
break;
}
}
/* What `p` is to the device: USM device memory, host memory it reaches (SYCL's or this backend's
* registered pinned ranges), or unknown (pageable). */
sycl::usm::alloc ptr_kind(const void* p) {
if (in_pinned(p)) return sycl::usm::alloc::host;
try {
return sycl::get_pointer_type(p, *rt().ctx);
} catch (const sycl::exception&) {
return sycl::usm::alloc::unknown;
}
}
void* d_host_ptr(void* p) {
if (!p) return nullptr;
const sycl::usm::alloc k = ptr_kind(p);
return k == sycl::usm::alloc::host || k == sycl::usm::alloc::shared ? p : nullptr;
}
void* d_device_ptr(void* p) {
if (!p) return nullptr;
return ptr_kind(p) != sycl::usm::alloc::unknown ? p : nullptr;
}
/* ------------------------------------------------------------------ streams */
/* `pub` first, so the RadStream handed out is the RadSyclStream a plugin reads. */
struct SyclStream {
RadSyclStream pub;
sycl::queue q;
std::atomic<int> gates{0}; /* closed gates on this stream (rad_stream_gate) */
SyclStream(const sycl::context& c, const sycl::device& d, const sycl::property_list& pl)
: pub{}, q(c, d, async_handler, pl) {}
};
SyclStream* as_stream(RadStream s) { return (SyclStream*)s; }
/* A null stream is refused, as on every backend (device.h note 2). */
int check_stream(RadStream s, const char* who) {
if (s) return RAD_OK;
device_set_error("%s: null stream -- radiance does not use the default stream, "
"create one with rad_stream_create", who);
return RAD_E_INVAL;
}
int d_stream_create(RadStream* out, int high_priority) {
if (!out) return RAD_E_INVAL;
if (!valid_device(t_device)) {
device_set_error("rad_stream_create: no SYCL device %d", t_device);
return RAD_E_INVAL;
}
SyclStream* s = nullptr;
SYCL_TRY("rad_stream_create", {
using sycl::property::queue::enable_profiling;
using sycl::property::queue::in_order;
using sycl::ext::oneapi::property::queue::priority_high;
sycl::property_list pl;
if (high_priority && timing_on())
pl = sycl::property_list{in_order{}, enable_profiling{}, priority_high{}};
else if (high_priority)
pl = sycl::property_list{in_order{}, priority_high{}};
else if (timing_on())
pl = sycl::property_list{in_order{}, enable_profiling{}};
else
pl = sycl::property_list{in_order{}};
s = new (std::nothrow) SyclStream(*rt().ctx, rt().devs[t_device], pl);
});
if (!s) {
device_set_error("rad_stream_create: out of memory");
return RAD_E_NOMEM;
}
s->pub.magic = RAD_SYCL_STREAM_MAGIC;
s->pub.version = RAD_SYCL_STREAM_VERSION;
s->pub.queue = &s->q;
s->pub.device = t_device;
*out = (RadStream)s;
return RAD_OK;
}
/* Drains rather than discards, as the host backend's destroy does. */
void d_stream_destroy(RadStream st) {
if (!st) return;
SyclStream* s = as_stream(st);
try {
s->q.wait_and_throw();
} catch (const sycl::exception& e) {
RAD_WARN("device: rad_stream_destroy: %s", e.what());
}
s->pub.magic = 0;
delete s;
}
int d_stream_sync(RadStream st) {
if (!st) {
device_set_error("rad_stream_sync: null stream");
return RAD_E_INVAL;
}
if (as_stream(st)->gates.load() > 0) {
device_set_error("rad_stream_sync: the stream waits at a closed gate, which only "
"rad_gate_open releases");
return RAD_E_STATE;
}
SYCL_TRY("rad_stream_sync", as_stream(st)->q.wait_and_throw());
return async_status("rad_stream_sync");
}
/* ------------------------------------------------------------------ events
*
* An event holds its latest record. `recorded` counts records, so a never-recorded event is
* complete and waiting on it is a no-op (the mover relies on that, host.cpp). */
struct SyclEvent {
std::mutex m;
sycl::event ev;
uint64_t recorded = 0;
bool host = false; /* RAD_EVENT_HOST_WAIT: rad_event_sync may block on it */
};
int d_event_create(RadEvent* out, unsigned flags) {
if (!out) return RAD_E_INVAL;
auto* e = new (std::nothrow) SyclEvent();
if (!e) {
device_set_error("rad_event_create: out of memory");
return RAD_E_NOMEM;
}
/* RAD_EVENT_LOCAL has no scope to choose here: a barrier's completion is visible to the host
* and to every queue of the context alike. */
e->host = (flags & RAD_EVENT_HOST_WAIT) != 0;
*out = (RadEvent)e;
return RAD_OK;
}
/* A queued barrier that waits on the event holds its own reference, so dropping ours is safe. */
void d_event_destroy(RadEvent ev) { delete (SyclEvent*)ev; }
int d_event_record(RadEvent ev, RadStream st) {
if (!ev || !st) {
device_set_error("rad_event_record: null %s", ev ? "stream" : "event");
return RAD_E_INVAL;
}
auto* e = (SyclEvent*)ev;
sycl::event b;
SYCL_TRY("rad_event_record", b = as_stream(st)->q.ext_oneapi_submit_barrier());
std::lock_guard<std::mutex> lk(e->m);
e->ev = b;
++e->recorded;
return RAD_OK;
}
int d_event_wait(RadStream st, RadEvent ev) {
if (!ev || !st) {
device_set_error("rad_event_wait: null %s", ev ? "stream" : "event");
return RAD_E_INVAL;
}
auto* e = (SyclEvent*)ev;
sycl::event dep;
{
std::lock_guard<std::mutex> lk(e->m);
if (e->recorded == 0) return RAD_OK;
dep = e->ev;
}
SYCL_TRY("rad_event_wait", as_stream(st)->q.ext_oneapi_submit_barrier({dep}));
return RAD_OK;
}
bool event_done(const sycl::event& ev) {
return ev.get_info<sycl::info::event::command_execution_status>() ==
sycl::info::event_command_status::complete;
}
int d_event_query(RadEvent ev) {
if (!ev) return RAD_E_INVAL;
auto* e = (SyclEvent*)ev;
std::lock_guard<std::mutex> lk(e->m);
if (e->recorded == 0) return 1;
try {
return event_done(e->ev) ? 1 : 0;
} catch (const sycl::exception& x) {
return sycl_fail(x, "rad_event_query");
}
}
int d_event_sync(RadEvent ev) {
if (!ev) return RAD_E_INVAL;
auto* e = (SyclEvent*)ev;
if (!e->host) {
device_set_error("rad_event_sync: the event was made without RAD_EVENT_HOST_WAIT");
return RAD_E_INVAL;
}
sycl::event w;
{
std::lock_guard<std::mutex> lk(e->m);
if (e->recorded == 0) return RAD_OK;
w = e->ev;
}
SYCL_TRY("rad_event_sync", w.wait_and_throw());
return async_status("rad_event_sync");
}
int d_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
if (!a || !b || !out) return RAD_E_INVAL;
if (!timing_on()) {
device_set_error("rad_event_elapsed_ms: the SYCL backend times events only under "
"RADIANCE_SYCL_TIMING=1 (profiling queues cost ~20 us a submission)");
return RAD_E_UNSUPPORTED;
}
auto stamp = [](RadEvent ev, uint64_t* t) -> int {
auto* e = (SyclEvent*)ev;
std::lock_guard<std::mutex> lk(e->m);
if (e->recorded == 0) return RAD_E_STATE;
SYCL_TRY("rad_event_elapsed_ms", {
if (!event_done(e->ev)) return RAD_E_STATE;
*t = e->ev.get_profiling_info<sycl::info::event_profiling::command_end>();
});
return RAD_OK;
};
uint64_t ta = 0, tb = 0;
RAD_TRY(stamp(a, &ta));
RAD_TRY(stamp(b, &tb));
*out = (float)(((double)tb - (double)ta) / 1e6);
return RAD_OK;
}
/* USM host memory is coherent for the device at submission: nothing to make visible. */
void d_host_wrote(void) {}
/* ------------------------------------------------------------------ copies and fills */
int d_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_async"));
if (bytes == 0) return RAD_OK;
if (!dst || !src || bytes < 0) {
device_set_error("rad_memcpy_async(%p <- %p, %lld): invalid argument", dst, src,
(long long)bytes);
return RAD_E_INVAL;
}
SYCL_TRY("rad_memcpy_async", as_stream(st)->q.memcpy(dst, src, (size_t)bytes));
return RAD_OK;
}
int d_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch, int64_t width,
int64_t height, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_2d_async"));
if (width == 0 || height == 0) return RAD_OK;
if (!dst || !src || width < 0 || height < 0 || dpitch < width || spitch < width) {
device_set_error("rad_memcpy_2d_async(%p/%lld <- %p/%lld, %lld x %lld): invalid argument",
dst, (long long)dpitch, src, (long long)spitch, (long long)width,
(long long)height);
return RAD_E_INVAL;
}
SYCL_TRY("rad_memcpy_2d_async",
as_stream(st)->q.ext_oneapi_memcpy2d(dst, (size_t)dpitch, src, (size_t)spitch,
(size_t)width, (size_t)height));
return RAD_OK;
}
int d_memset_async(void* dst, int value, int64_t bytes, RadStream st) {
RAD_TRY(check_stream(st, "rad_memset_async"));
if (bytes == 0) return RAD_OK;
if (!dst || bytes < 0) {
device_set_error("rad_memset_async(%p, %lld): invalid argument", dst, (long long)bytes);
return RAD_E_INVAL;
}
/* The runtime fills pageable memory too; a card's contract does not (device.h note 1). */
if (ptr_kind(dst) == sycl::usm::alloc::unknown) {
device_set_error("rad_memset_async(%p): the destination is not device-accessible "
"(pageable host memory)", dst);
return RAD_E_UNSUPPORTED;
}
SYCL_TRY("rad_memset_async", as_stream(st)->q.memset(dst, value & 0xff, (size_t)bytes));
return RAD_OK;
}
/* The prefix as one copy, then one kernel in which work-group i copies range i in 4-byte words
* (ranges are only 4-byte aligned), as the HIP card's aql_copy_ranges does. The list is read by the
* kernel when it runs: it may live in device memory, or be written by earlier work on the stream
* (rad-kbench's timer keeps it on the card). The in-order queue puts the ranges after the prefix,
* so a range over the prefix wins, which a single kernel copying both at once would leave to
* scheduling. */
constexpr size_t kRangeWg = 256;
constexpr int kRangeWords = 16;
int d_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadCopyRange* ranges,
int n, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_ranges_async"));
/* The card's copy kernel moves 16-byte pieces (aql.cpp), and the host backend refuses what it
* cannot copy; the same calls are refused here, so the three backends agree. */
if (!dst || !src || prefix < 0 || (prefix & 15) || n < 0 || (n > 0 && !ranges)) {
device_set_error("rad_memcpy_ranges_async(%p <- %p, prefix %lld (a multiple of 16), %d "
"ranges): invalid argument", dst, src, (long long)prefix, n);
return RAD_E_INVAL;
}
if (prefix == 0 && n == 0) return RAD_OK;
if (((uintptr_t)dst | (uintptr_t)src) & 15) {
device_set_error("rad_memcpy_ranges_async(%p <- %p): both bases must be 16-byte aligned",
dst, src);
return RAD_E_UNSUPPORTED;
}
sycl::queue& q = as_stream(st)->q;
char* d = (char*)dst;
const char* s = (const char*)src;
SYCL_TRY("rad_memcpy_ranges_async", {
if (prefix > 0) q.memcpy(d, s, (size_t)prefix);
if (n > 0) {
q.parallel_for(sycl::nd_range<1>{(size_t)n * kRangeWg, kRangeWg}, [=](sycl::nd_item<1> it) {
const size_t t = it.get_local_id(0);
const RadCopyRange r = ranges[it.get_group(0)];
const uint32_t* s4 = (const uint32_t*)(s + r.src);
uint32_t* d4 = (uint32_t*)(d + r.dst);
const int64_t nw = r.bytes / 4;
for (int64_t base = 0; base < nw; base += (int64_t)kRangeWg * kRangeWords) {
uint32_t v[kRangeWords];
for (int k = 0; k < kRangeWords; ++k) {
const int64_t w = base + (int64_t)k * kRangeWg + (int64_t)t;
v[k] = s4[w < nw ? w : nw - 1];
}
for (int k = 0; k < kRangeWords; ++k) {
const int64_t w = base + (int64_t)k * kRangeWg + (int64_t)t;
if (w < nw) d4[w] = v[k];
}
}
});
}
});
return RAD_OK;
}
/* ------------------------------------------------------------------ gates
*
* A gate is a one-work-item kernel that spins until a flag in pinned host memory turns 1; the
* in-order queue holds everything behind it. rad_gate_open sets the flag. The flag's memory is
* freed only once the kernel has finished (reaped on later gate calls), since the kernel may still
* be reading it when the host opens. A gate held for seconds can trip the driver's job timeout;
* rad-kbench holds one for a batch. */
struct SyclGate {
uint32_t* flag = nullptr;
SyclStream* s = nullptr;
sycl::event spin;
};
std::mutex g_gate_m;
std::vector<std::pair<sycl::event, uint32_t*>> g_gate_graveyard;
void gate_reap() {
std::lock_guard<std::mutex> lk(g_gate_m);
for (size_t i = 0; i < g_gate_graveyard.size();) {
bool done = true;
try {
done = event_done(g_gate_graveyard[i].first);
} catch (const sycl::exception&) {
}
if (!done) { ++i; continue; }
d_free(g_gate_graveyard[i].second, RAD_MEM_HOST_PINNED);
g_gate_graveyard[i] = g_gate_graveyard.back();
g_gate_graveyard.pop_back();
}
}
int d_stream_gate(RadStream st, void** out) {
RAD_TRY(check_stream(st, "rad_stream_gate"));
if (!out) return RAD_E_INVAL;
gate_reap();
SyclStream* s = as_stream(st);
auto* g = new (std::nothrow) SyclGate();
uint32_t* flag = (uint32_t*)d_alloc(64, RAD_MEM_HOST_PINNED);
if (!g || !flag) {
delete g;
if (flag) d_free(flag, RAD_MEM_HOST_PINNED);
device_set_error("rad_stream_gate: out of memory");
return RAD_E_NOMEM;
}
*flag = 0;
try {
g->spin = s->q.single_task([=] {
sycl::atomic_ref<uint32_t, sycl::memory_order::relaxed, sycl::memory_scope::system,
sycl::access::address_space::global_space> f(*flag);
while (f.load() == 0) {
}
sycl::atomic_fence(sycl::memory_order::acquire, sycl::memory_scope::system);
});
} catch (const sycl::exception& e) {
delete g;
d_free(flag, RAD_MEM_HOST_PINNED);
return sycl_fail(e, "rad_stream_gate");
}
g->flag = flag;
g->s = s;
++s->gates;
*out = g;
return RAD_OK;
}
int d_gate_open(void* p) {
auto* g = (SyclGate*)p;
if (!g || !g->flag) return RAD_E_INVAL;
std::atomic_ref<uint32_t>(*g->flag).store(1, std::memory_order_release);
--g->s->gates;
{
std::lock_guard<std::mutex> lk(g_gate_m);
g_gate_graveyard.emplace_back(g->spin, g->flag);
}
delete g;
return RAD_OK;
}
/* A Level Zero queue has no fixed depth, so nothing behind a gate waits for room; the figure only
* bounds how far a caller runs ahead. */
int64_t d_gate_room(RadStream st) { return st ? 4096 : 0; }
const DeviceBackend g_sycl = {
.name = "sycl",
.count = d_count, .set = d_set, .props = d_props, .enable_peer = d_enable_peer,
.alloc = d_alloc, .free = d_free, .host_ptr = d_host_ptr, .device_ptr = d_device_ptr,
.stream_create = d_stream_create, .stream_destroy = d_stream_destroy,
.stream_sync = d_stream_sync,
.event_create = d_event_create, .event_destroy = d_event_destroy,
.event_record = d_event_record, .event_wait = d_event_wait, .event_query = d_event_query,
.event_sync = d_event_sync, .event_elapsed_ms = d_event_elapsed_ms,
.host_wrote = d_host_wrote,
.memcpy_async = d_memcpy_async, .memcpy_2d_async = d_memcpy_2d_async,
.memset_async = d_memset_async, .memcpy_ranges_async = d_memcpy_ranges_async,
/* memcpy_list_async, link_hold, link_gate: null (dispatch.cpp copies segment by segment and
* holds nothing). Recorded passes, elastic memory: null. */
.vram_used = d_vram_used,
/* code_mark / code_runs: null for now, so every plugin runs; a build with libr4d beside the
* SYCL backend is refused at configure (docs/SYCL_PORTING.md §4.5). */
.integrated = d_integrated,
.peer_access = d_peer_access,
.pci_address = d_pci_address,
.runtime_version = d_runtime_version,
/* Expert prefetch: null. */
.stream_gate = d_stream_gate, .gate_open = d_gate_open, .gate_room = d_gate_room,
};
} /* namespace */
extern const SyclHost* g_sycl_host; /* sycl_host.cpp */
} /* namespace rad */
extern "C" __attribute__((visibility("default")))
const rad::DeviceBackend* rad_sycl_backend(const rad::SyclHost* host) {
if (!host || host->version != rad::kSyclHostVersion) {
std::fprintf(stderr, "librad_sycl: the engine's host table is version %u, this library "
"reads %u; rebuild them together\n",
host ? host->version : 0u, rad::kSyclHostVersion);
return nullptr;
}
rad::g_sycl_host = host;
if (rad::rt().devs.empty()) {
/* Supported configuration (host backend); dispatch.cpp logs it at Info. */
RAD_DEBUG("device: no Level Zero GPU visible to SYCL");
return nullptr;
}
return &rad::g_sycl;
}
#endif /* SYCL_LANGUAGE_VERSION */
+41
View File
@@ -0,0 +1,41 @@
/* sycl_host.cpp -- inside librad_sycl.so: the engine's logger and error slot, over the table the
* engine hands rad_sycl_backend() (sycl_host.h). Built by the icpx sub-build; in the engine's own
* build (core/CMakeLists.txt globs this directory) it compiles to nothing. */
#if defined(SYCL_LANGUAGE_VERSION)
#include "sycl_host.h"
#include "../rad_internal.h"
#include <cstdarg>
#include <cstdio>
namespace rad {
const SyclHost* g_sycl_host = nullptr;
Log log_level() {
return g_sycl_host ? (Log)g_sycl_host->log_level() : Log::Warn;
}
void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
char buf[2048];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof buf, fmt, ap);
va_end(ap);
if (g_sycl_host) g_sycl_host->log((int)l, file, line, buf);
else std::fprintf(stderr, "%s\n", buf);
}
void device_set_error(const char* fmt, ...) {
char buf[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof buf, fmt, ap);
va_end(ap);
if (g_sycl_host) g_sycl_host->set_error(buf);
}
} /* namespace rad */
#endif /* SYCL_LANGUAGE_VERSION */
+32
View File
@@ -0,0 +1,32 @@
/* sycl_host.h -- the seam between the engine and librad_sycl.so, the SYCL device backend.
*
* The SYCL backend is compiled and linked by icpx into a shared library of its own, while the
* engine stays a GCC build (docs/SYCL_PORTING.md §4.5, docs/SYCL_PROGRESS.md D6). The library
* reaches the engine's logger and error slot through this table, so it links nothing of the
* engine's, and the engine reaches the library through one C entry point.
*
* Inside the library, sycl_host.cpp defines rad::log_level, rad::log_emit and
* rad::device_set_error over the table, so the backend's source uses rad_internal.h's macros as
* hip.cpp does. Bump kSyclHostVersion on any change to the table.
*/
#pragma once
#include <cstdint>
namespace rad {
struct DeviceBackend;
constexpr uint32_t kSyclHostVersion = 1;
struct SyclHost {
uint32_t version; /* kSyclHostVersion */
int (*log_level)(void); /* rad::log_level() as an int */
void (*log)(int level, const char* file, int line, const char* msg);
void (*set_error)(const char* msg); /* rad::device_set_error("%s", msg) */
};
} /* namespace rad */
/* The backend, or null when no Level Zero GPU is visible or `host` is of another version. The
* table must outlive the backend. */
extern "C" const rad::DeviceBackend* rad_sycl_backend(const rad::SyclHost* host);
+24 -1
View File
@@ -1225,6 +1225,7 @@ int Engine::declare() {
{
std::vector<MissReport> rep;
for (auto& r : ranks_) rep.push_back(miss_report(r->program, device_is_host()));
const bool sycl = std::strcmp(device_backend_name(), "sycl") == 0;
bool same = true;
for (size_t i = 1; i < rep.size(); ++i) if (!(rep[i] == rep[0])) same = false;
@@ -1237,9 +1238,23 @@ int Engine::declare() {
"one of them cannot run:", who.c_str(), rep[i].device.size());
for (const std::string& l : rep[i].device) RAD_ERR(" %s", l.c_str());
}
if (!rep[i].host_only.empty()) RAD_INFO("%s", rep[i].host_only.c_str());
if (!rep[i].host_only.empty()) {
if (sycl) RAD_ERR("%s", rep[i].host_only.c_str());
else RAD_INFO("%s", rep[i].host_only.c_str());
}
if (!rep[i].host.empty()) RAD_INFO("%s", rep[i].host.c_str());
}
/* On the SYCL backend a host-only op is a hole, not a placement: the Intel backend runs
* its ops on the card or not at all, so a kernel it lacks stops the start by name rather
* than running that op on the CPU (docs/SYCL_PORTING.md §4.4). --debug-graph serves
* nothing and prints the graph regardless. */
if (sycl && !cfg_.debug_graph)
for (const MissReport& m : rep)
if (!m.host_only.empty()) {
RAD_ERR("not starting: on the SYCL backend every op runs on the card, and the "
"op(s) above have no device kernel in the loaded libraries");
return RAD_E_UNSUPPORTED;
}
/* A hole refuses startup: the bands come from this run's limits, so a request can land in
* one, and that step would fail at issue and stop the engine. --debug-graph serves nothing,
* so it continues to print the graph and reports the holes in its exit status
@@ -3306,6 +3321,14 @@ int Engine::start() {
devnote_ = devnote;
if (s < 0) { RAD_ERR("no usable device"); return s; }
/* One card on the SYCL backend (docs/SYCL_PORTING.md §4.7): it has no all-reduce kernels, and a
* second rank would wait on one. */
if (cfg_.tp > 1 && std::strcmp(device_backend_name(), "sycl") == 0) {
RAD_ERR("--tp %d: the SYCL (Intel GPU) backend serves one card; tensor parallelism needs "
"all-reduce kernels it does not have. Use --tp 1", cfg_.tp);
return RAD_E_UNSUPPORTED;
}
if ((int)devs.size() < cfg_.tp) {
RAD_ERR("--tp %d needs %d devices of one architecture; %zu are usable [%s]",
cfg_.tp, cfg_.tp, devs.size(), inventory.c_str());
+3 -1
View File
@@ -15,7 +15,9 @@ int wtab_patch(const WtabPatch& p, RadStream s) {
for (uint32_t i = 0; i < p.n; ++i) *p.dst[i] = p.val[i];
return RAD_OK;
}
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
#if (defined(RAD_HAVE_HIP) && RAD_HAVE_HIP) || (defined(RAD_HAVE_SYCL) && RAD_HAVE_SYCL)
/* The launcher: wtab.hip on the AQL backend, wtab_sycl.cpp (in librad_sycl.so) on the SYCL
* one. A build holds one of the two. */
return rad_wtab_patch_launch(&p, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE;
#else
(void)s;
+28
View File
@@ -0,0 +1,28 @@
/* wtab_sycl.cpp -- the weight-table patch kernel under the SYCL backend: one work-item a write. See
* wtab.h; wtab.hip is the AMD twin. Built by icpx into librad_sycl.so; in the engine's own build
* (core/CMakeLists.txt globs this directory) it compiles to nothing. */
#if defined(SYCL_LANGUAGE_VERSION)
#include <sycl/sycl.hpp>
#include "rad_sycl.h"
#include "wtab.h"
extern "C" __attribute__((visibility("default")))
int rad_wtab_patch_launch(const rad::WtabPatch* p, void* stream) {
if (!p || p->n == 0) return 0;
sycl::queue* q = rad_sycl_queue((RadStream)stream);
if (!q) return -1;
const rad::WtabPatch w = *p;
try {
q->parallel_for(sycl::nd_range<1>{64, 64}, [=](sycl::nd_item<1> it) {
const uint32_t i = (uint32_t)it.get_local_id(0);
if (i < w.n) *w.dst[i] = w.val[i];
});
} catch (const sycl::exception&) {
return -1;
}
return 0;
}
#endif /* SYCL_LANGUAGE_VERSION */
+3 -1
View File
@@ -15,7 +15,9 @@ int step_advance(const AdvanceArgs& a, RadStream s) {
for (int i = 0; i < a.n_seq; ++i) adv_row(a, i);
return RAD_OK;
}
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
#if (defined(RAD_HAVE_HIP) && RAD_HAVE_HIP) || (defined(RAD_HAVE_SYCL) && RAD_HAVE_SYCL)
/* The launcher: advance.hip on the AQL backend, advance_sycl.cpp (in librad_sycl.so) on the
* SYCL one. A build holds one of the two. */
return rad_step_advance_launch(&a, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE;
#else
(void)s;
+39
View File
@@ -0,0 +1,39 @@
/* advance_sycl.cpp -- the advance kernel under the SYCL backend: one work-item per row of the batch
* it patches, in stream order on the rank's queue. See advance.h; advance.hip is the AMD twin.
*
* Built by icpx into librad_sycl.so (sycl/CMakeLists.txt); core/CMakeLists.txt globs this directory
* into the engine, built without SYCL, where the file compiles to nothing. There is no chained form:
* chained launches are the AQL backend's (rad_dev_chain_enabled is 0 here).
*/
#if defined(SYCL_LANGUAGE_VERSION)
#include <sycl/sycl.hpp>
#include "advance_impl.h"
#include "rad_sycl.h"
namespace {
constexpr int kThreads = 64;
} // namespace
extern "C" __attribute__((visibility("default")))
int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream) {
if (!args || args->n_seq <= 0) return 0;
sycl::queue* q = rad_sycl_queue((RadStream)stream);
if (!q) return -1;
const rad::AdvanceArgs a = *args;
const size_t blocks = (size_t)((a.n_seq + kThreads - 1) / kThreads);
try {
q->parallel_for(sycl::nd_range<1>{blocks * kThreads, kThreads}, [=](sycl::nd_item<1> it) {
const int i = (int)it.get_global_id(0);
if (i < a.n_seq) rad::adv_row(a, i);
});
} catch (const sycl::exception&) {
return -1;
}
return 0;
}
#endif /* SYCL_LANGUAGE_VERSION */
+551
View File
@@ -0,0 +1,551 @@
# Porting radiance to Intel GPUs (SYCL / Level Zero)
What the core depends on, what the Intel backend has to provide, and the design. The running log
(status, blockers, commands, benchmark runs) is `docs/SYCL_PROGRESS.md`. Written against the tree at
`87ec3c1` (radiance 1.11.0, `RAD_ABI_VERSION` 26).
---
## 1. Where the core depends on HIP
Reproduce the raw list with:
```sh
grep -rn -E '\bhip[A-Z][A-Za-z]*\b|hip/hip_|__HIP|RAD_HAVE_HIP|RAD_HIP_FOUND|__global__|__device__|<<<' \
--include=*.cpp --include=*.h --include=*.hip --include=*.cc --include=*.c \
--include=CMakeLists.txt --include=*.cmake . | grep -v -E '^\./(vendor|libr4d|build|tests/r4d_emu)/'
```
288 lines outside `libr4d/` and `vendor/`; 47 of them are comments that only name a HIP call. The
substance, classified:
### 1.1 Already behind the device ABI (`abi/rad_device.h` + the `DeviceBackend` vtable)
The device layer is a vtable (`core/device/device.h:178`, `struct DeviceBackend`), chosen once in
`select_backend()` (`core/device/dispatch.cpp:87`). Every `rad_dev_*` / `rad_stream_*` /
`rad_event_*` / `rad_memcpy*` call above the device layer goes through it. Today it has three
implementations:
| backend | file | runtime calls |
|---|---|---|
| host | `core/device/host.cpp` | none (worker threads, `malloc`) |
| HIP | `core/device/hip.cpp` | `hipMalloc`, `hipFree`, `hipSetDevice`, `hipGetDevice(Count)`, `hipGetDeviceProperties`, `hipDeviceGetAttribute`, `hipMemGetInfo`, `hipDeviceGetPCIBusId`, `hipDeviceCanAccessPeer`, `hipDeviceEnablePeerAccess`, `hipPointerGetAttributes`, `hipHostGetDevicePointer`, `hipRuntimeGetVersion` |
| AQL (the one a card actually runs) | `core/device/aql.cpp`, `aql_code.cpp`, `aql_blit.hip` | HIP for allocation, properties, peer access, IPC, code registration; HSA for everything on the queues: `hsa_queue_*`, `hsa_signal_*`, `hsa_amd_memory_pool_*`, `hsa_amd_vmem_*` (elastic memory), `hsa_executable_*` / `hsa_code_object_reader_*` (it loads plugins' code objects itself), `hsa_amd_profiling_*`, `hsa_amd_memory_lock_to_pool` (pinning) |
What the AQL backend implements that matters for a port (from `aql.cpp`'s header and
`device.h`):
- **Streams** are HSA queues the engine owns; every kernel, copy, fill and fence is an AQL packet it
writes (6 ns per dispatch versus 0.5-1.3 us through `hipLaunchKernel`, ~1600 dispatches per rank
per decode step).
- **Kernel-argument staging**: a ring of 1 KiB slots written by the host, in VRAM through the BAR
when the BAR spans VRAM, in pinned host memory otherwise (`aql_force_host_kargs`, `device.h:476`),
with a system-scope acquire at least once per half lap.
- **Resizable BAR handling** is exactly that placement choice. Nothing else in the core reads the
BAR size.
- **Events**: barrier packets with agent-scope (`RAD_EVENT_LOCAL`) or system-scope release;
`RAD_EVENT_HOST_WAIT` adds an interrupt signal.
- **Graphs**: "tapes" (`DeviceBackend::tape_*`, `device.h:227`) record a pass's packets and replay
them. They are optional; null means every pass is issued.
- **Elastic memory** (`vmem_*`, `device.h:271`) shares VRAM between KV and experts. Optional; null
sizes pools once at startup.
- **Pinned memory**: `RAD_MEM_HOST_PINNED` / `RAD_MEM_HOST_MAPPED`; the host arena locks file
mappings to the pool (`hsa_amd_memory_lock_to_pool`).
- **P2P / IPC**: `enable_peer`, `peer_access`; IPC lives in libr4d's collectives, not the core.
- **DMA lane, link holds, rides, gates, expert prefetch** (`memcpy_list_async`, `link_hold`,
`xp_*`, `stream_gate`): all optional, null on a backend without them.
### 1.2 The core calls HIP directly
These are the places a second device backend has to touch. None is a HIP call from generic engine
code: each is a device-code launcher or a build switch.
| site | what | classification / what the Intel backend needs |
|---|---|---|
| `core/sched/advance.cpp:18` + `core/sched/advance.hip` | the per-step advance kernel (one thread per batch row), launched through `hipLaunchKernel` | **core device kernel**, every decode step. The row logic is shared host/device code in `core/sched/advance_impl.h` (`RAD_ADV_FN`, `:10`, is `__host__ __device__` under `__HIPCC__`). Needs a SYCL launcher calling the same `adv_row` |
| `core/runtime/wtab.cpp:18` + `core/runtime/wtab.hip` | the weight-table patch kernel (one thread per pointer write) | **core device kernel**; needs a SYCL launcher (19 lines of HIP) |
| `core/runtime/xprefetch.cpp:11` + `core/runtime/xprefetch.hip` | MoE expert prefetch (router logits, plan) | **core device kernel**, MoE only. Gated by `rad_xp_supported`; the Intel backend reports 0 and the prefetch is off (supported configuration) |
| `core/device/aql_blit.hip` | copy / fill kernels behind the AQL backend's memcpy / memset | AQL-only; SYCL has `queue::memcpy` / `memset` / `fill` |
| `core/CMakeLists.txt:73` | the engine exports `hipLaunchKernel`, `hipMemcpyAsync`, ..., `__hipRegisterFatBinary` so plugins' HIP launches bind to the AQL backend | **the plugin launch contract**: a plugin launches device work with HIP calls the engine serves (`abi/rad_types.h:325`, `docs/PLUGIN.md` §5). A SYCL plugin needs its own hand-off (§4.2 below) |
| `core/device/dispatch.cpp:60, 88`; `core/device/device.h:465` | backend selection and AQL-only hooks under `RAD_HAVE_HIP` | selection gains a SYCL branch |
| `core/engine_diag.cpp:60` | `device_build` fact for the startup report | becomes "HIP or SYCL" |
| `abi/rad_philox.h:16`, `abi/rad_yarn.h:16`, `core/sched/advance_impl.h:10` | `__host__ __device__` qualifiers under `__HIPCC__` | header-only device code; under SYCL device compilation the qualifier is empty (SYCL device code is plain C++), so these need an `#elif defined(SYCL_LANGUAGE_VERSION)` that defines the macro to `inline` |
| `CMakeLists.txt:17-77, 132-156, 229-236, 297` | `RAD_WITH_HIP`, `RAD_HIP_FOUND`, `RAD_GPU_TARGETS`, `enable_language(HIP)`, `RAD_HAVE_HIP` on `rad_abi`, `add_subdirectory(libr4d)` | build integration; `RAD_SYCL` mirrors it |
| `cmake/RadAddPlugin.cmake:68-121` | `HIP_SOURCES`, `rad_hipify`, per-source `-cuid` | gains `SYCL_SOURCES` |
| `tests/CMakeLists.txt:236, 313, 328, 342, 523, 551, 579`; `tests/plugin_test.cpp:93`; `tests/host_kargs_main.h:21` | card tests (`device_test`, `mem_test`, `place_test`, `runtime_test` on a card, `r4d_selftest`, `kbench` gpu label, ops_doc and oot over libr4d) | the `sycl` label and its tests |
| `tools/vmemprobe.cpp` | a HIP diagnostic tool | AMD-only; not ported |
Comments only (no code dependency): `core/engine_bringup.cpp:3656`, `core/mem/pools.cpp:221`,
`core/format/radfile.h:82`, `core/runtime/ctx.h:12`, `core/device/host.cpp:267, 445, 496`,
`libavx/avx_ngram.cpp:8`, `abi/rad_types.h:327`.
---
## 2. How the host backend avoids HIP (the template)
- `select_backend()` returns `host_backend()` when the build has no HIP
(`core/device/dispatch.cpp:100`). `RadDeviceProps::is_host_backend = 1`, arch `"host"`.
- **Streams** are queues run by worker threads; **device memory** is host memory; events are
counters (`core/device/host.cpp`).
- **Kernels**: libref and libavx declare `RAD_DOMAIN_HOST` rows and are plain shared objects built by
`rad_add_plugin` with `SOURCES` only. They ignore the `RadStream` they are handed
(`abi/rad_types.h:330`).
- **Core device kernels** branch on `device_is_host()` *before* the `RAD_HAVE_HIP` branch: drain the
stream, then run the shared row function on the host (`core/sched/advance.cpp:13`,
`core/runtime/wtab.cpp`). Without HIP the device branch returns `RAD_E_UNSUPPORTED`.
- **Optional features** (tapes, vmem, DMA lane, prefetch, gates) are null, which the engine treats as
a supported configuration.
- **Build**: `RAD_WITH_HIP=OFF` (or AUTO without `hipcc`) leaves `RAD_HIP_FOUND` off; libr4d is not
added, `RAD_HAVE_HIP` is not defined, the HIP-only tests are not registered.
A SYCL backend follows the same shape: a fourth `DeviceBackend`, a third branch in the core
kernels' launchers, its own kernel library, its optional features null until measured worth it.
---
## 3. The op vocabulary
`docs/OPS.md` documents 238 ops: **205 that libref implements** (the oracle for `rad-kbench` and for
the Intel kernels' tests) and **33 device-only** ops that only libr4d declares (no host fallback and
no oracle; libr4d's own `r4d_selftest` patterns are their checks). Appendix A is the full table,
generated by `scripts/sycl/op_inventory.sh` (libref's schemas through `rad-schemas`; libr4d's 407
`kKernels` rows parsed from `libr4d/r4d_rows.cpp` by `scripts/sycl/r4d_rows.py`, since a build
without HIP has no `libr4d.so`; the architectures column is a grep of `arch/` and over-counts).
How libr4d implements the ops a dense LLM needs (from the rows' prose and `libr4d/README.md`):
- **GEMM**: one geometry per entry point. bf16 (`gemm_bf16_nt_m16`/`m64` skinny with split-K and
16x16x16 WMMA, `gemm_bf16_nt_tiled` for M > 64), each quantised format its own family
(`gemm_fp8a8_*`, `gemm_w4a8_*`, `gemm_mxfp4a8_*`, `gemm_i8a8_*`, ...), a skinny decode kernel
(M <= 16..128) and a tiled prefill kernel per format; weights pre-permuted into WMMA fragment
order by a `relayout` hook at load. Deterministic reductions: the split-K slices are summed in a
fixed order, and "BYTE-IDENTICAL" siblings are stated in the rows.
- **Attention**: paged (block 16) prefill and split-KV decode, one instantiation per
(head_dim, gqa, kv dtype): `attn_decode_h128_gqa{1,2,4,8}_{bf16,fp8}kv`,
`attn_window_h<HD>_gqa<G>_<kv>` templates, fp8 KV with per-(seq, head) descales.
- **Norms and elementwise**: one workgroup a row (`rmsnorm_quant_fp8` "two passes, the second L1-hot"),
fused quantisers (`gated_quant_fp8`, `quant_act_fp8`) writing E4M3 with an f32 scale per
(row, 128 columns).
- **Vocabulary edge**: `logits_gemm_{bf16,fp8,i8}` writing f32 logits, `embed_lookup_bf16`.
- **Sampling**: f32 stages (`r4d_sample_stages_f32.hip`), `sample_argmax_f32`.
### 3.1 The minimal set: MiniCPM5-2B
No MiniCPM5 container is in the model library (`SYCL_PROGRESS.md`, blocker 1), so the set below was
measured on the test suite's synthetic llama (`tests/tiny_model.h`, the same `llama_dense_fp8`
graph: `rad-convert` with no recipe for bf16, the e2e test's `llama.recipe` for the block-fp8 trunk)
with `radiance --model <tiny>.rad --debug-graph` on the host backend. The geometry differs (the tiny
model is head_dim 64, gqa 2, n_embd 128; MiniCPM5 is head_dim 128, 16 q over 2 kv heads = gqa 8,
n_embd 2048, ffn 6144, vocab 130560), the op list does not.
**MiniCPM5-2B bf16: 13 model ops.** (`docs/PLUGIN.md` §10 also says 13.)
| op | params as declared | count per layer / model | dtype |
|---|---|---|---|
| `embed_lookup` | n_embd, n_vocab | 1 / model | bf16 table |
| `rmsnorm_quant_fp8` | n, eps, group=128 | 2 / layer | bf16 in; writes bf16 `h` plus E4M3 `h.q` and f32 scale `h.s` |
| `gemm_nt` | N, K | 4 / layer (qkv, o, gate_up, down) | bf16 |
| `rope` | head_dim, n_head, n_head_kv, theta, mode=neox, rotary_dim | 1 / layer | bf16 |
| `cast` | n, from=bf16, to=bf16 | 1 / layer | copy-out of q |
| `kv_store` | head_dim, n_head_kv, block_size=16 | 1 / layer | bf16 KV, or `fp8_e4m3` at `--kv-cache-dtype fp8` |
| `attn_paged` | head_dim, gqa, causal=1, window=0, block_size=16 | 1 / layer | q bf16; kv bf16 or `fp8_e4m3` |
| `quant_act_fp8` | n, group=128 | 1 / layer | bf16 -> E4M3 + f32 scale |
| `gated_quant_fp8` | n, group=128, act=silu | 1 / layer | SwiGLU, bf16 out plus E4M3 |
| `add` | n | residual | bf16 |
| `rmsnorm` | n, eps | final norm | bf16 |
| `gather_rows` | | last-token rows for the head | |
| `logits_gemm` | n_vocab, n_embd | 1 / model | bf16 head, **f32 logits** |
**Sampler: 13 ops** (`docs/PLUGIN.md` says 11; the measured list is): `sample_penalties`,
`sample_dry`, `sample_ngram_ban`, `sample_temp`, `sample_mask`, `sample_topk`, `sample_argmax`,
`sample_topp`, `sample_minp`, `sample_typical`, `sample_xtc`, `sample_pick`, `sample_logprobs`.
Greedy decoding uses `sample_argmax`; the token-for-token comparison in Milestone A runs greedy.
**MiniCPM5-2B fp8** (block-fp8 trunk, 128x128 scales): `gemm_nt` becomes `gemm_nt_q` at
`dtype=fp8a8 group=128`, plus **`gemm_nt_q_gated`** (gate_up GEMM with the SiLU-gate fused,
`act=silu`) as the alternative the fp8 path declares. Everything else is the same list. With an fp8
or int8 lm_head (`llama_fp8head`, `llama_i8head`), `logits_gemm` stays one op and selects the kernel
by the head's encoding.
**The 4-bit paths**, measured the same way on the tiny llama: int4 (compressed-tensors, asymmetric)
issues `gemm_nt_q` at `w4a16_asym` and `w4a8i8_asym` plus `quant_act_i8g`; MXFP4 issues `gemm_nt_q`
at `mxfp4a8 group=32`. The real 27B / 31B containers add their architectures' own ops (gated delta
net for qwen35, Gemma's norms and soft-caps); those are listed when a container is available.
**Speculative decoding** (DSpark, 5 layers, block 7) adds the draft block's ops: fp8a8 GEMMs at
128x128 blocks and the `u2` 2-bit draft head; to be measured on a container that carries a drafter.
---
## 4. Design
The brief's default design, with what the code showed. Each decision is also in
`SYCL_PROGRESS.md` under Decisions.
### 4.1 Device runtime: a fourth `DeviceBackend`, not a new abstraction
The brief proposes a device-runtime interface if the core calls HIP directly. It does not: the
`DeviceBackend` vtable already *is* that interface (§1.1), with every call the brief lists
(allocate/free device and pinned memory, copies, streams, events, device info), and the HIP/AQL
implementations are already behind it. So no wrapper is introduced and the HIP path is not touched.
`core/device/sycl.cpp`, compiled only when `RAD_SYCL=ON`, defines `sycl_backend_if_present()`:
| vtable entry | SYCL / Level Zero |
|---|---|
| `count`, `set`, `props` | GPU devices of the Level Zero platform; `props.arch` from `ext::oneapi::experimental::info::device::architecture` (`"intel_gpu_bmg_g31"`); `n_cu` = `max_compute_units` (160), `warp_size` = 16 (the sub-group the kernels use), `lds_bytes` = `local_mem_size`, `vram_free` from `ext::intel::info::device::free_memory` |
| `alloc` | `RAD_MEM_DEVICE` -> `malloc_device` behind a room check; `HOST_PINNED` and `HOST_MAPPED` -> page-aligned memory registered with `prepare_for_device_copy` (not `malloc_host`, which O_DIRECT cannot target; D10), same address both sides; `HOST` -> plain `malloc` |
| streams | one in-order `sycl::queue` per stream on one shared `sycl::context`; `high_priority` -> `ext::oneapi::property::queue::priority_high`; no `enable_profiling` unless `RADIANCE_SYCL_TIMING=1` (it costs ~20 us of host time a submission, D9) |
| events | `queue::ext_oneapi_submit_barrier()` returns the record; `event_wait` = `ext_oneapi_submit_barrier({e})` on the waiting queue (no host sync); `query` / `sync` on the event; `elapsed_ms` from profiling info, under `RADIANCE_SYCL_TIMING=1` only |
| copies, fills | `queue::memcpy`, `memset`; 2-D copy as `ext_oneapi_copy2d` or a row loop; ranges and lists as one small kernel / a loop of copies |
| `host_wrote` | nothing: USM host allocations are coherent for the device at submission |
| `vram_used` | `ext::intel::info::device::free_memory` |
| `pci_address` | `ext::intel::info::device::pci_address` |
| `runtime_version` | the SYCL platform version string |
| tapes | null at first; later `sycl_ext_oneapi_graph` (Phase 4, if submission overhead dominates decode) |
| gates | a one-work-item kernel spinning on a flag in pinned host memory |
| vmem, DMA lane, link holds, rides, prefetch | null (each a supported configuration) |
`select_backend()` tries, in order: AQL (if built with HIP and an AMD card is visible), SYCL (if built
with SYCL and a Level Zero GPU is visible), host. `RADIANCE_DEVICE_BACKEND=sycl|aql|host` (new)
chooses explicitly in a build with both.
### 4.2 Plugin launches: a SYCL stream contract
On a card the engine serves plugins' `hipLaunchKernel`. SYCL has no launch symbol to interpose, so
a SYCL kernel library needs the queue itself. Under the SYCL backend a `RadStream` points to
```c
/* abi/rad_sycl.h (new, C-compatible) */
#define RAD_SYCL_STREAM_MAGIC 0x4C435953u /* "SYCL" */
typedef struct RadSyclStream {
uint32_t magic; /* RAD_SYCL_STREAM_MAGIC */
uint32_t version; /* RAD_SYCL_STREAM_VERSION, bumped on any change of this struct */
void* queue; /* sycl::queue*, in-order, owned by the engine */
} RadSyclStream;
```
with an inline C++ helper `rad_sycl_queue(RadStream)` that checks the magic and version and returns
the `sycl::queue&` (or null, which the launch turns into `RAD_E_DEVICE`). The engine and every SYCL
plugin load the same `libsycl.so`, so the object is valid across the boundary.
Why a new header with its own version rather than a bump of `RAD_ABI_VERSION`: nothing an existing
plugin compiles against changes shape (`rad_types.h` keeps `typedef void* RadStream`; only its
comment gains the SYCL case), so a bump would force every out-of-tree plugin to rebuild for no
reason. A SYCL plugin checks `version` at each launch's first call and refuses by name on a
mismatch, which is the same guarantee for the only plugins that read the struct.
What a SYCL launch may do mirrors `docs/PLUGIN.md` §5: submit to that queue only; no `wait`, no
allocation (scratch from the `scratch` hook), no host tasks.
### 4.3 The kernel library: `libxe2/`
Built by `rad_add_plugin(libxe2 kernels SYCL_SOURCES ...)`, AOT for `bmg-g31` (`-fsycl-targets=
intel_gpu_bmg_g31`), `build_target "intel_gpu_bmg_g31"`. Device rows only; kernels launch on the
stream's queue with sub-group 16. A library with no code for the card is left out of selection, as
for AMD (`docs/PLUGIN.md` §10): the SYCL backend's `code_runs` answers from the plugin's
`build_target` against `props.arch`, so libr4d's rows can never be selected on the B65 in a build
with both (and libxe2's never on an AMD card).
Built and loaded like every bundled plugin, so `tests/oot_plugins.sh` rebuilds it out of tree when
`icpx` is available.
### 4.4 No silent CPU fallback
On a device backend the engine places an op that has weights and no device kernel on the host and
logs it once at INFO ("host-only ops: ... Not a hole", `core/engine_bringup.cpp:146`). That is a
CPU route for a GPU op, which the brief forbids. **On the SYCL backend that message becomes a fatal
startup error naming the ops**, unless `--debug-accept-host-ops` (new, debug-only) is given; ops
without weights already fail as holes. `--debug-graph` shows the resolution either way.
### 4.5 Build integration
- `RAD_SYCL` (`OFF | ON | AUTO`, default **OFF**), `build.sh --sycl`, a `sycl` preset, a `sycl` ctest
label (card tests, `SKIP_RETURN_CODE 77` without a Level Zero GPU, like `gpu`).
- **Compiler.** CMake has no SYCL language, and `-fsycl` sources need `icpx`. The first plan, the
whole build on `icpx`, failed: libavx calls `_pdep_u64` without `-mbmi2`, which GCC accepts and
clang refuses (`SYCL_PROGRESS.md` D6). So **the main build stays on its own compiler in every
configuration**, and the SYCL code is a separate CMake project, `sycl/`, configured with `icpx`
through `ExternalProject`: `librad_sycl.so` (the device backend with the core's SYCL kernels;
one C entry point, `rad_sycl_backend`, and a callback table for the engine's logger and error
slot, `core/device/sycl_host.h`) and later `libxe2.so`. Host code in a SYCL build is therefore the
default build's. `icpx` defaults to `-fp-model=fast`; the sub-build passes `-ffp-model=precise`.
- **Run time.** The SYCL runtime `dlopen`s its Level Zero adapter, which needs oneAPI's `umf/`
libraries, so the engine runs under the oneAPI environment (`. /opt/intel/oneapi/setvars.sh`).
Without it no GPU is visible and the engine warns that it is running on the CPU.
- **HIP and SYCL in one build**: allowed in principle (HIP is its own CMake language), but untestable
here (no ROCm). The first version refuses `RAD_SYCL=ON` together with a found HIP at configure
time with a clear message; lifting that is a later change made on a machine with both.
### 4.6 Core device kernels under SYCL
`advance` and `wtab` get SYCL launchers (`core/sched/advance_sycl.cpp`, `core/runtime/wtab_sycl.cpp`,
`-fsycl`) as a third branch after `device_is_host()`. `RAD_ADV_FN`, `RAD_PHILOX_HD`, `RAD_YARN_HD`
gain a SYCL case so the shared row code compiles for the device. `xprefetch` stays off
(`rad_xp_supported` = 0).
### 4.7 Single card
`--tp > 1` on the SYCL backend stops at startup: "the Intel backend serves one card (--tp 1); tensor
parallelism needs the all-reduce kernels it does not have". No collective rows are declared.
### 4.8 Numerics
- fp8 is OCP E4M3 everywhere the engine reads it (`docs/PLUGIN.md` §10). XMX has no fp8 input on this
part (`SYCL_PROGRESS.md`, Phase 0), so fp8 and MXFP4 weights are widened to bf16 in registers;
int8 uses s8 DPAS.
- Tolerances come from the matching libr4d rows and `rad-kbench`'s checks for that op and dtype,
never looser.
- Reductions: the first kernels use a fixed reduction order per output so results do not depend on
work-group scheduling. Where that differs from libref's order, greedy outputs may diverge after a
near-tie, and Milestone A then states a measured KL bound (the engine has a KL tool: `core/kld.cpp`).
---
## Appendix A. Every op
Generated by `scripts/sycl/op_inventory.sh`; regenerate after a vocabulary change. Columns: whether
libref implements the op (the oracle), libr4d's kernels for it, the dtype prose of up to three of
those rows, and the architecture plugins whose source names it (a grep: `common` is
`arch/common`, the shared blocks every LLM uses).
| op | libref | libr4d kernels | libr4d dtypes (first three rows' prose) | architectures naming it |
|---|---|---|---|---|
| `act_mul` | yes | act_mul_bf16 | bf16 in and out, f32 arithmetic, libm silu / erf / tanh | common, embgemma2, gemma4, minimaxmusic3, sdxl |
| `add` | yes | add_bf16, add_f32 | bf16 in and out, fp32 arithmetic; f32 in and out | anima, breeze, common, embgemma2, flux3, gemma3, gemma4, gemma4_bf16, krea2, lfm2_bf16, ltx2, minimaxh3, minimaxmusic3, qwen3asr_bf16, qwenimage21, sdxl, unlimitedocr_bf16 |
| `add_rmsnorm` | no | add_rmsnorm_bf16 | bf16 x / a / y, f32 or bf16 gain, fp32 reduction; byte-identical to add_bf16 + rmsnorm_bf16 | common |
| `all_gather` | yes | ar_gather_2rank, ar_gather_3rank, ar_gather_4rank, ar_gather_8rank | any payload -- the bytes are moved, never summed, so the (u32 id, f32 logit) pairs the vocab-parallel sampler gathers survive intact | common, krea2, minimaxh3, qwenimage21 |
| `all_reduce` | yes | ar_oneshot_2rank_exact, ar_oneshot_2rank_exact_lane, ar_oneshot_2rank_wht6, ar_oneshot_2rank_wht6_lane, ar_oneshot_3rank_exact, ar_oneshot_4rank_exact, ar_oneshot_8rank_exact, ar_twoshot_3rank_exact, ar_twoshot_3rank_ti8, ar_twoshot_4rank_exact, ar_twoshot_4rank_exact_lane, ar_twoshot_4rank_ti8, ar_twoshot_4rank_ti8_lane, ar_twoshot_8rank_exact | bf16 / fp16 / fp32 payload, fp32 accumulate in ascending rank order, bit-identical across ranks; bf16 / fp16 / fp32 payload, fp32 accumulate in ascending rank order, bit-identical across ranks and to ar_oneshot_3rank_exact; bf16 / fp16 / fp32 payload, fp32 accumulate in ascending rank order, bit-identical across ranks and to the wide row | common, flux3, gemma3, gemma4, gemma4_bf16, krea2, llama_fp8, minimaxh3, minimaxmusic3, qwen35_bf16, qwen35_fp8, qwen3asr_bf16, qwen4exp_fp8, qwenimage21, unlimitedocr_bf16 |
| `ar_gather_hc_write` | no | ar_gather_hc_write, ar_gather_hc_write_4rank | bf16 throughout; the gather's sums and narrows are moe_gather's (round-to-nearest-even, the shared arm's product rounded before the add), the reduction and the write ar_hc_write's on the same wire -- byte-identical to the three kernels it replaces; bf16 throughout; the gather's sums and narrows are moe_gather's (round-to-nearest-even, the shared arm's product rounded before the add), the sum in fp32 in ascending rank order and rounded to bf16 exactly as the four-rank exact all-reduce stores it, and the write in hc_write's arithmetic over that bf16 value -- byte-identical to the three kernels it replaces | common |
| `ar_hc_write` | no | ar_hc_write, ar_hc_write_4rank | bf16 throughout; the sum in fp32 in ascending rank order and rounded to bf16 exactly as the four-rank exact all-reduce stores it, and the write in hc_write's arithmetic over that bf16 value -- byte-identical to the pair it replaces; bf16 throughout; the sum rounded to bf16 exactly as the standalone all-reduce of the SAME wire stores it and the write in hc_write's arithmetic over that bf16 value -- byte-identical to the pair it replaces | common |
| `ar_ln_had_quant_i8` | no | ar_ln_had_quant_i8 | bf16 in, int8 out with an f32 per-row scale carrying 1/sqrt(had), optional bf16 out | -- |
| `ar_rmsnorm_had_quant_i8g` | no | ar_rmsnorm_had_quant_i8g | bf16 in, int8 out with an f32 scale per (row, 128 columns) and an optional bf16 out of the UNROTATED norm output; x and the residual are ar_rmsnorm_quant_fp8's bytes, and the codes rmsnorm_had_quant_i8g's over the same norm output | common, qwen35_fp8 |
| `ar_rmsnorm_post_quant_fp8` | no | ar_rmsnorm_post_quant_fp8 | bf16 in, E4M3 out with an f32 scale per (row, 128 columns); x receives the reduced sum | gemma3 |
| `ar_rmsnorm_quant_fp8` | no | ar_rmsnorm_quant_fp8 | bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; codes taken over the BF16-ROUNDED norm output, and the reduced sum rounded to bf16 exactly as the standalone all-reduce of the SAME wire stores it -- byte-identical to the pair it replaces | common |
| `ar_rmsnorm_quant_i8` | no | ar_rmsnorm_quant_i8, ar_rmsnorm_quant_i8_4rank | bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale; the reduced sum rounded to bf16 as the standalone exact all-reduce stores it | gemma3, gemma4_bf16 |
| `attn_cross` | yes | attn_cross_h128_bf16, attn_cross_h64_bf16 | bf16 query / key / value / out, bf16 operands, fp32 accumulate | anima, flux3, ltx2, sdxl |
| `attn_dense` | yes | attn_dense_h1152_bf16, attn_dense_h128_bf16, attn_dense_h256_gqa2_bf16, attn_dense_h256_gqa4_bf16, attn_dense_h256_gqa8_bf16, attn_dense_h384_bf16, attn_dense_h512_bf16, attn_dense_h512_gqa2_bf16, attn_dense_h512_gqa4_bf16, attn_dense_h512_gqa8_bf16, attn_dense_h64_bf16, attn_dense_h768_bf16, attn_dense_small_h256_bf16, attn_vit_h72_bf16 | bf16 query / key / value / out, bf16 operands, fp32 accumulate; bf16 query / key / value / out, f16 operands, fp32 accumulate; bf16 query / key / value / out, fp32 scores and accumulate | anima, breeze, common, embgemma2, flux3, krea2, lfm2_bf16, ltx2, minimaxh3, minimaxmusic3, qwen3asr_bf16, qwenimage21, sdxl |
| `attn_local_rel` | yes | attn_local_rel_bf16 | bf16 q / k / v / relk / out, bf16 or f32 per-dim scale, f32 softmax | embgemma2 |
| `attn_na3d` | yes | attn_na3d_h64 | bf16 or f32 q / k / v / out, fp32 accumulate | ltx2 |
| `attn_paged` | yes | attn_decode_h128_gqa1_bf16kv, attn_decode_h128_gqa1_fp8kv, attn_decode_h128_gqa2_bf16kv, attn_decode_h128_gqa2_fp8kv, attn_decode_h128_gqa2w_bf16kv, attn_decode_h128_gqa2w_fp8kv, attn_decode_h128_gqa4_bf16kv, attn_decode_h128_gqa4_fp8kv, attn_decode_h128_gqa8_bf16kv, attn_decode_h128_gqa8_fp8kv, attn_decode_h256_gqa12_bf16kv, attn_decode_h256_gqa12_fp8kv, attn_decode_h256_gqa12_fp8v4, attn_decode_h256_gqa12_k6v4, attn_decode_h256_gqa2_bf16kv, attn_decode_h256_gqa2_fp8kv, attn_decode_h256_gqa4_bf16kv, attn_decode_h256_gqa4_fp8kv, attn_decode_h256_gqa6_bf16kv, attn_decode_h256_gqa6_bs4_bf16kv, attn_decode_h256_gqa6_bs4_fp8kv, attn_decode_h256_gqa6_bs4_fp8v4, attn_decode_h256_gqa6_bs4_k6v4, attn_decode_h256_gqa6_fp8kv, attn_decode_h256_gqa6_fp8v4, attn_decode_h256_gqa6_k6v4, attn_decode_h256_gqa8_bf16kv, attn_decode_h256_gqa8_fp8kv, attn_prefill_h128_gqa1_bf16kv, attn_prefill_h128_gqa1_fp8kv, attn_prefill_h128_gqa2_bf16kv, attn_prefill_h128_gqa2_fp8kv, attn_prefill_h128_gqa2w_bf16kv, attn_prefill_h128_gqa2w_fp8kv, attn_prefill_h128_gqa8_bf16kv, attn_prefill_h128_gqa8_fp8kv, attn_prefill_h256_gqa12_bf16kv, attn_prefill_h256_gqa12_fp8kv, attn_prefill_h256_gqa12_fp8v4, attn_prefill_h256_gqa12_k6v4, attn_prefill_h256_gqa2_bf16kv, attn_prefill_h256_gqa2_fp8kv, attn_prefill_h256_gqa4_bf16kv, attn_prefill_h256_gqa4_fp8kv, attn_prefill_h256_gqa6_bf16kv, attn_prefill_h256_gqa6_bs4_bf16kv, attn_prefill_h256_gqa6_bs4_fp8kv, attn_prefill_h256_gqa6_bs4_fp8v4, attn_prefill_h256_gqa6_bs4_k6v4, attn_prefill_h256_gqa6_fp8kv, attn_prefill_h256_gqa6_fp8kv_pv8, attn_prefill_h256_gqa6_fp8kv_qk8, attn_prefill_h256_gqa6_fp8kv_qk8pv8, attn_prefill_h256_gqa6_fp8v4, attn_prefill_h256_gqa6_fp8v4_pv8, attn_prefill_h256_gqa6_fp8v4_qk8, attn_prefill_h256_gqa6_fp8v4_qk8pv8, attn_prefill_h256_gqa6_k6v4, attn_prefill_h256_gqa6_k6v4_pv8, attn_prefill_h256_gqa6_k6v4_qk8, attn_prefill_h256_gqa6_k6v4_qk8pv8, attn_prefill_h256_gqa8_bf16kv, attn_prefill_h256_gqa8_fp8kv, attn_prefill_h64_gqa4_bf16kv, attn_prefill_h64_gqa4_fp8kv, attn_window_h<HD>_gqa<G>_<KVN> | bf16 query and probabilities rounded to e4m3, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out; bf16 query and probabilities rounded to e4m3, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), K and V as e4m3 in LDS, bf16 out; bf16 query and probabilities rounded to e4m3, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), K and V as e4m3 in LDS, bf16 out | breeze, common, gemma3, gemma4, gemma4_bf16, lfm2_bf16, minimaxmusic3, unlimitedocr_bf16 |
| `attn_paged_gate_quant` | no | attn_decode_gq_h256_gqa12_bf16kv, attn_decode_gq_h256_gqa12_fp8kv, attn_decode_gq_h256_gqa12_fp8v4, attn_decode_gq_h256_gqa12_k6v4, attn_decode_gq_h256_gqa6_bs4_bf16kv, attn_decode_gq_h256_gqa6_bs4_fp8kv, attn_decode_gq_h256_gqa6_bs4_fp8v4, attn_decode_gq_h256_gqa6_bs4_k6v4 | bf16 query, bf16 kv cache, bf16 gated out, E4M3 codes with an f32 scale per 128 columns; bf16 query, fp8-e4m3 kv cache, bf16 gated out, E4M3 codes with an f32 scale per 128 columns; bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns | common |
| `attn_paged_qrow` | no | attn_qrow_decode_h256_gqa2_bf16kv, attn_qrow_decode_h256_gqa2_fp8kv, attn_qrow_h128_gqa8_bf16kv, attn_qrow_h128_gqa8_fp8kv, attn_qrow_h<HD>_gqa<G>_<KVN> | bf16 query (any row pitch), <KVDOC> kv cache, bf16 out, f32 partials; bf16 query (any row pitch, a multiple of 4), bf16 kv cache, bf16 out, f16 partials; bf16 query (any row pitch, a multiple of 4), fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials | common, gemma4, gemma4_bf16, unlimitedocr_bf16 |
| `attn_prefix_self` | yes | attn_prefix_self_h128_bf16 | bf16 q/k/v/out and cache, bf16 operands, fp32 accumulate; or i8 Q.K codes, i32 accumulate; or E4M3 V codes and P, fp32 accumulate | breeze, minimaxh3, minimaxmusic3, qwenimage21 |
| `attn_vsa` | yes | attn_vsa_h128_bf16 | bf16 q / k / v / coarse / gate / out, i32 segs / geom / sel; bf16 operands, fp32 accumulate; or i8 Q.K codes, i32 accumulate; or E4M3 V codes and P, fp32 accumulate | minimaxh3 |
| `bwe_up` | yes | bwe_up | bf16 or f32 operands | ltx2 |
| `cast` | yes | cast_bf16_bf16, cast_bf16_f16, cast_bf16_f32, cast_f32_bf16, cast_f32_f32 | bf16 in, bf16 out, byte-for-byte; bf16 in, f16 out, rounded to nearest even (a value past f16's range becomes an infinity); bf16 in, f32 out, exact | breeze, common, embgemma2, gemma3, gemma4, gemma4_bf16, glm5next, llama_fp8, ltx2, minimaxh3, minimaxmusic3, qwen35_fp8, sdxl, unlimitedocr_bf16 |
| `causal_conv1d` | yes | causal_conv1d_bf16 | bf16 activations, weights and conv state; i32 cu, slots, has_init and num_accepted | lfm2_bf16 |
| `cfg_topk_sample` | yes | cfg_topk_sample | f32 or bf16 logits, i32 picks | breeze, minimaxmusic3 |
| `chan_affine` | yes | chan_affine_bf16, chan_affine_f32 | bf16; f32 | anima, flux3, krea2, minimaxh3, qwenimage21, sdxl |
| `chan_split` | yes | chan_split_bf16 | bf16 | minimaxmusic3 |
| `chan_stats` | yes | chan_stats_bf16, chan_stats_f32 | bf16; f32 x and y, bf16 or f32 statistics, every step rounded to f32 | flux3, ltx2 |
| `clamp` | yes | clamp_bf16 | bf16 in and out | embgemma2, minimaxh3 |
| `conv1d` | yes | conv1d_bf16, conv1d_f32 | bf16 rows, weight, bias and residual, fp32 accumulate, one rounding; act none, tanh or clamp; f32 rows, weight, bias and residual, f32 accumulate; act none, tanh or clamp | breeze, ltx2, minimaxh3, minimaxmusic3 |
| `conv1d_dw` | yes | conv1d_dw_bf16 | bf16 x / w / y, i32 cu_seqlens, f32 accumulate | breeze, embgemma2 |
| `conv2d` | yes | conv2d_bf16 | bf16 x / w / y, i32 cu_seqlens and mask, f32 accumulate | embgemma2, qwen3asr_bf16 |
| `conv2d_nhwc` | yes | conv2d_nhwc_bf16 | bf16 image, weight and bias, fp32 accumulate, one rounding | common, ltx2, sdxl |
| `conv2d_unfold` | yes | conv2d_unfold_bf16 | bf16 x / y, i32 cu_seqlens and mask | common, qwen3asr_bf16 |
| `conv3d_ndhwc` | yes | conv3d_ndhwc_bf16 | bf16 voxels, weight and residual, bf16 or f32 bias, fp32 accumulate | ltx2, minimaxh3 |
| `conv_t1d` | yes | conv_t1d_bf16, conv_t1d_f32 | bf16 rows, weight and bias, fp32 accumulate, one rounding; f32 rows, weight and bias, f32 accumulate | breeze, ltx2, minimaxh3, minimaxmusic3 |
| `cu_repeat` | yes | cu_repeat | i32 | anima, breeze, flux3, krea2, minimaxh3, minimaxmusic3, sdxl |
| `d2s3d` | yes | d2s3d | bf16 or f32 x and y, i32 geom | ltx2 |
| `d2s_add` | yes | d2s_add_bf16 | bf16 | anima, common, flux3, krea2 |
| `dequant` | yes | -- | | -- |
| `dequant_w4` | no | dequant_w4_bf16 | 4-bit in with an f16 scale and a zero in the dword's high half, bf16 out | -- |
| `dflash_conv` | yes | dflash_conv_t2_g16_bf16 | bf16 x / delta / base / out, fp32 accumulate | common |
| `dflash_select` | yes | dflash_select_bf16 | i32 candidate ids, f32 unary logits, bf16 hp and both codebooks, i32 tokens out | common |
| `dsa_pool` | yes | dsa_pool_fp8 | bf16 keys/gates, f32 position bias; FP8 codes and f32 scale | common |
| `dsa_query` | yes | dsa_query_fp8 | bf16 input, E4M3 codes and power-of-two f32 scale | common |
| `dsa_score` | yes | dsa_score_fp8 | E4M3 codes, f32 scales and gates | common |
| `embed_lookup` | yes | embed_lookup_bf16 | i32 tokens, bf16 table and output | anima, breeze, common, embgemma2, flux3, gemma3, gemma4, gemma4_bf16, glm5next, krea2, lfm2_bf16, llama_fp8, ltx2, minimaxh3, minimaxmusic3, qwen35_bf16, qwen35_fp8, qwen3asr_bf16, qwen4exp_fp8, qwenimage21, sdxl, unlimitedocr_bf16 |
| `embed_lookup_q` | yes | embed_lookup_q_bf16 | i32 tokens, an E4M3 table with a bf16 or f32 scale or a plain bf16 one, bf16 output | common |
| `end_status` | yes | end_status | i32 | breeze, minimaxmusic3 |
| `expert_scale` | no | expert_scale_bf16 | i32 ids, bf16 table and weights | gemma4 |
| `fill` | yes | fill_bf16, fill_f32 | bf16 out; the value rounds to nearest even once; f32 out, the value exactly | anima, breeze, common, flux3, krea2, ltx2, sdxl |
| `flow_euler` | yes | flow_euler_bf16 | bf16 | anima, flux3, krea2, minimaxmusic3, qwenimage21 |
| `flow_renoise` | yes | flow_renoise_f32 | f32 latent and sigma, u32 seed words | ltx2, minimaxh3 |
| `flow_x0_step` | yes | flow_x0_step_f32 | f32 state, f32 or bf16 velocity | minimaxh3 |
| `fourier_embed` | yes | fourier_embed_bf16 | f32 time and w, bf16 out | minimaxmusic3 |
| `frame_mix_store` | yes | frame_mix_store_bf16 | bf16 planes and rows, f32 logits and scale | minimaxmusic3 |
| `frame_store` | yes | frame_store | i32 | breeze |
| `gate_add` | yes | gate_add_bf16 | bf16 | anima, flux3, krea2, ltx2, qwenimage21 |
| `gate_quant_fp8` | no | gate_quant_fp8 | bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; the codes are taken over the BF16-ROUNDED product | common, krea2 |
| `gated_had_quant_fp8` | no | gated_had_quant_fp8 | bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out that receives the UNROTATED product; the codes are taken over the rotated BF16-ROUNDED product, and the residual factor of 128 is folded into the stored weight scale at convert, not here | common |
| `gated_had_quant_i8` | yes | gated_had_quant_i8 | bf16 in, int8 out with an f32 per-row scale carrying 1/sqrt(had) | -- |
| `gated_had_quant_i8g` | no | gated_had_quant_i8g | bf16 in, int8 out with an f32 scale per (row, 128 columns) and an optional bf16 out that receives the UNROTATED product; the codes are taken over the rotated BF16-ROUNDED product, byte-identical to the product + had_quant_act_i8g | common, qwen35_fp8 |
| `gated_quant_fp8` | yes | gated_quant_fp8 | bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; the codes are taken over the BF16-ROUNDED product | common |
| `gather_rows` | yes | gather_rows_bf16, gather_rows_u8 | i32 indices, bf16 rows; i32 indices, u8 rows | breeze, common, flux3, gemma3, gemma4, gemma4_bf16, glm5next, krea2, lfm2_bf16, llama_fp8, minimaxmusic3, qwen35_bf16, qwen35_fp8, qwen3asr_bf16, qwen4exp_fp8, qwenimage21, sdxl, unlimitedocr_bf16 |
| `gather_rows2` | yes | gather_rows2_bf16 | bf16 | anima, krea2 |
| `gdn_chunk_scan` | yes | gdn_chunk_scan_k128_v128_c64_bf16 | bf16 q/k/v/A, fp32 gate/beta, bf16 out; the state cache is f32 or f16 | common |
| `gdn_conv_prep` | yes | gdn_conv_prep_w4_h128_bf16 | bf16 x / weights / conv state / q,k,v out, fp32 a,b and gate/beta out | common |
| `gdn_conv_recurrent_update` | yes | gdn_conv_recurrent_update_k128_v128_bf16 | bf16 x / conv weights / conv state / a,b / out; the state cache is f32 or f16. Byte-identical to gdn_conv_update followed by gdn_recurrent_update | common |
| `gdn_conv_update` | yes | gdn_conv_update_w4_h128_bf16 | bf16 x / weights / conv state / q,k,v out | common |
| `gdn_gated_norm_had_quant_i8` | no | gdn_gated_norm_had_quant_i8 | bf16 x and z, f32 norm weight, int8 out with an f32 per-row scale carrying 1/sqrt(had) | -- |
| `gdn_gated_rmsnorm` | yes | gdn_gated_rmsnorm_h128_bf16 | bf16 x / z / out, fp32 weight | common |
| `gdn_kkt_solve` | yes | gdn_kkt_solve_k128_c64_bf16 | bf16 k and A out, fp32 beta / gate / gram / inverse | common |
| `gdn_recurrent_update` | yes | gdn_recurrent_update_k128_v128_bf16_fp32state | bf16 q/k/v and out, fp32 a,b; the state cache is f32 or f16 and the operand says which | common |
| `gelu` | yes | gelu_bf16 | bf16 in and out, fp32 arithmetic | anima, breeze, common, lfm2_bf16, qwen3asr_bf16, sdxl |
| `gelu_mul` | yes | gelu_mul_bf16 | bf16 in and out, fp32 arithmetic | breeze, gemma3, gemma4_bf16, ltx2 |
| `gelu_mul_quant_i8` | no | gelu_mul_quant_i8 | bf16 gate_up in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale, optional bf16 out; the codes taken over the bf16-rounded product | gemma3, gemma4_bf16 |
| `gelu_quick` | yes | gelu_quick_bf16 | bf16 or f32 in and out (one dtype), f32 arithmetic | sdxl |
| `gelu_tanh` | yes | gelu_tanh_bf16 | bf16 | common, embgemma2, gemma4, krea2, lfm2_bf16, ltx2, qwenimage21 |
| `gemm_nt` | yes | gemm_bf16_nt_m16, gemm_bf16_nt_m64, gemm_bf16_nt_tiled | bf16 A / W / C, fp32 accumulate, deterministic reduction; bf16 A / W / C, fp32 accumulate. BYTE-IDENTICAL to gemm_bf16_nt_m64: the same WMMA sequence a tile and the same split count, the slices summed in the same order from 0.f | anima, breeze, common, embgemma2, flux3, gemma3, gemma4, gemma4_bf16, lfm2_bf16, ltx2, minimaxmusic3, qwen3asr_bf16, qwenimage21, sdxl, unlimitedocr_bf16 |
| `gemm_nt_bias` | yes | gemm_bf16_nt_bias_tiled, gemm_f32_nt_bias | bf16 A / W / C / res, bf16 or f32 bias, fp32 accumulate, three RNE roundings in the store; f32 A / W, f32 or bf16 bias, f32 accumulate, C f32 or bf16 with res in C's dtype (each epilogue step rounded to C's dtype) | anima, breeze, common, embgemma2, krea2, lfm2_bf16, ltx2, minimaxh3, minimaxmusic3, qwen3asr_bf16, sdxl |
| `gemm_nt_f32` | yes | gemm_nt_f32_bf16 | bf16 input, f32 weights and output | common |
| `gemm_nt_q` | yes | gemm_fp8a16_nt_m1, gemm_fp8a8_f32scale, gemm_fp8a8_nt_m16, gemm_fp8a8_tiled, gemm_i8a8_nt_m16, gemm_i8a8_tiled, gemm_mxfp4a8_decode, gemm_mxfp4a8_nt_m64, gemm_mxfp4a8_tiled, gemm_w2a8_nt, gemm_w4a16_asym_nt_m64, gemm_w4a16_nt_m64, gemm_w4a8_nt_m64, gemm_w4a8_prefill, gemm_w4a8_tiled, gemm_w4a8i8_tiled, gemm_w5a16_nt_m64, gemm_w5a8i8_tiled, gemm_w8a16_nt_m64, gemm_w8a8_nt_m64, gemm_w8a8_tiled | E4M3 A with an f32 scale per (row, 128 K), E4M3 W with a bf16 scale per 128x128 tile, bf16 C. The split-K finisher sums its planes in INDEX order, so a run repeats exactly; but the split COUNT is chosen from M, so the same row computed at M=1 and at M=8 is not bit-identical. That is why a speculative decode diverges from a non-speculative one on a near-tie. NOTHING PINS IT TODAY: --deterministic reaches placement and the sampler, not this kernel; E4M3 A with an f32 scale per (row, 128 K), E4M3 W with a bf16 scale per 128x128 tile, bf16 C; each 128-K block's product folded into the f32 accumulator with one fma; E4M3 codes, F32 scales, BF16 output | common, gemma3, gemma4_bf16 |
| `gemm_nt_q_bias` | yes | gemm_fp8a8_bias_nt_m16 | E4M3 A with an f32 scale per (row, 128 K), E4M3 W with a bf16 scale per 128x128 tile, a bf16 bias added to the f32 accumulator before its one rounding, bf16 C | minimaxh3 |
| `gemm_nt_q_gated` | yes | gemm_fp8a8_gated_nt_m16 | E4M3 A with an f32 scale per (row, 128 K), E4M3 W with a bf16 scale per 128x128 tile, and the QUANTISER's outputs: E4M3 codes, an f32 scale per (row, 128 columns) and an optional bf16 product. Byte-identical to gemm_nt_q followed by gated_quant_fp8 -- the accumulator is rounded to bf16 before the gate and the multiply, and the amax is an fmaxf reduction, which is exact and order-free however it is regrouped across the waves | common |
| `givens_dense_quant` | yes | givens_dense_quant | bf16 in, int8 or E4M3 out in PLAIN ROW-MAJOR order, parts side by side, with an f32 scale (amax/127 or amax/448) per (row, part, 128 columns); f16 matrices and f32 channel scales | common |
| `givens_rotate` | yes | givens_rotate | bf16 in, f16 out, parts side by side; the tables are the weight's int32 pairs, f32 angles and f32 channel scales | common |
| `gram_accum` | yes | gram_accum, gram_accum_bf16 | E4M3 plus an f32 scale per (row, 128 columns) in; an f32 [n][n] accumulator in and out; bf16 in, no scale operand; an f32 [n][n] accumulator in and out | common, gemma3 |
| `grid_embed` | yes | grid_embed_bf16 | bf16 x, bf16 or f32 table, i32 coord, f32 taps | common |
| `grid_embed_aa` | yes | grid_embed_aa_bf16 | bf16 x, bf16 or f32 table, i32 coord, f32 taps | lfm2_bf16 |
| `grid_pos3` | yes | grid_pos3 | f32 | minimaxh3 |
| `group_norm` | yes | group_norm | bf16 or f32 rows, bf16 or f32 gain, bias and modulation, f32 statistics | common, ltx2, minimaxh3, sdxl |
| `had_quant_act_fp8` | yes | had_quant_act_fp8 | bf16 in, E4M3 out in PLAIN ROW-MAJOR order with an f32 scale per (row, 128 columns); the sqrt(128) the unnormalised transform leaves behind is NOT undone here, because <Hw,Ha> = 128<w,a> and the whole factor is folded into the stored weight scale at convert | common |
| `had_quant_act_i8` | yes | had_quant_act_i8 | bf16 in, int8 out with an f32 per-row scale that also carries the 1/sqrt(had) normalisation | -- |
| `had_quant_act_i8g` | yes | had_quant_act_i8g | bf16 in, int8 out in PLAIN ROW-MAJOR order with an f32 scale of amax/127 per (row, 128 columns); the factor of 128 of the unnormalised transform is left to the weight's stored scale (dtype i8a8h) | common |
| `hc_enter` | yes | hc_enter_bf16 | bf16 in and out | common |
| `hc_project` | yes | hc_project_bf16 | bf16 stream, f32 direction, i32 switch | common |
| `hc_read` | yes | hc_read_bf16, hc_read_e4m3 | bf16 stream and mixing matrices, f32 gain, bf16 out, E4M3 + f32 scale for the optional twin; bf16 stream, E4M3 mixing matrices with f32 scales in each row (128-column groups for mix_down, a quarter row for mix_up), f32 gain, bf16 out, E4M3 + f32 scale for the twin | common |
| `hc_write` | yes | hc_write_bf16 | bf16 throughout | common |
| `head_gate` | yes | head_gate | bf16 logits, bf16 or f32 x | ltx2 |
| `im2col_nhwc` | yes | im2col_nhwc_bf16 | bf16 in and out, copied bit for bit | sdxl |
| `int_affine` | yes | int_affine | i32 | ltx2 |
| `interleave2` | yes | interleave2_bf16 | bf16 or f32 in, f32 out | minimaxh3, minimaxmusic3 |
| `iota` | yes | iota | i32 | anima, breeze, common, flux3, krea2, ltx2, minimaxh3, minimaxmusic3, sdxl |
| `join_add_scale` | no | join_add_scale_bf16 | bf16 activations, f32 gains, bf16 scalar | gemma4 |
| `kd_input` | yes | kd_input_bf16 | f32 lanes, bf16 y | sdxl |
| `kd_step` | yes | kd_step_bf16 | bf16 model output, f32 lanes, history and preview, f32 arithmetic | sdxl |
| `kda_update` | yes | kda_update_k128_v128_bf16 | bf16 activations, f32 gates and state | common |
| `kv_len_trim` | no | kv_len_trim | int32 in, int32 out, clamped at zero | gemma4_bf16 |
| `kv_store` | yes | kv_store_bf16, kv_store_fp8, kv_store_fp8v4, kv_store_k6v4 | bf16 k / v / cache, i32 slot mapping; bf16 k / v, E4M3 K and int4 V in groups of 32 with f16 scales, i32 slot mapping; bf16 k / v, fp8-e4m3 cache, i32 slot mapping, scalar k_scale / v_scale descales | breeze, common, gemma3, gemma4, gemma4_bf16, lfm2_bf16, minimaxmusic3, qwenimage21, unlimitedocr_bf16 |
| `l2norm_chan` | yes | l2norm_chan_bf16 | bf16 | common |
| `lane_gather` | yes | lane_gather_w32 | bf16 | anima, flux3, krea2, minimaxh3, qwenimage21 |
| `lane_store` | yes | lane_store_w32 | bf16 | anima, flux3, krea2, qwenimage21, sdxl |
| `layernorm` | yes | layernorm_bf16 | bf16 or f32 x, bf16 y, f32 or bf16 gain and bias | breeze, common, embgemma2, lfm2_bf16, minimaxh3, minimaxmusic3, qwen3asr_bf16, sdxl |
| `ln_mod` | yes | ln_mod_bf16 | bf16 | qwenimage21 |
| `ln_mod_quant_fp8` | yes | ln_mod_quant_fp8_bf16 | bf16 in, E4M3 codes with f32 scales out | qwenimage21 |
| `logit_rerank` | yes | logit_rerank, logit_rerank_i8 | bf16 in, f32 values + i32 ids out, ties to the lower id | common |
| `logit_softcap` | yes | logit_softcap_bf16, logit_softcap_f32 | bf16 in and out, fp32 arithmetic; f32 in and out — the 1.3.0 sampling chain carries the logits as f32 from the gemm | gemma4, gemma4_bf16 |
| `logits_gemm` | yes | logits_gemm_bf16, logits_gemm_bf16_cols, logits_gemm_fp8, logits_gemm_i8 | bf16 x and lm_head, F32 LOGITS OUT, fp32 accumulate; bf16 x and lm_head, F32 LOGITS OUT, fp32 accumulate. BYTE-IDENTICAL to logits_gemm_bf16; bf16 x, E4M3 head with a bf16 scale per 128x128 tile stored PER ROW, F32 LOGITS OUT, fp32 accumulate | breeze, common, gemma3, gemma4, gemma4_bf16, glm5next, lfm2_bf16, llama_fp8, qwen35_bf16, qwen35_fp8, qwen3asr_bf16, qwen4exp_fp8, unlimitedocr_bf16 |
| `lora_expand` | yes | lora_expand_scalar, lora_expand_tiled | f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y | -- |
| `lora_expand_mm` | yes | lora_expand_mm_wmma | f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y | -- |
| `lora_shrink` | yes | lora_shrink_scalar, lora_shrink_wmma, lora_shrink_wmma_q | bf16 / f16 / f32 a, or fp8_e4m3 / fp8_e5m2 / i8 a with its f32 scale stream; bf16 lora_a; i32 slot; f32 t; bf16 a; bf16 lora_a; i32 slot; f32 t; fp8_e4m3 / fp8_e5m2 / i8 a with its f32 scale stream; bf16 lora_a; i32 slot; f32 t | -- |
| `ltx_guide` | yes | ltx_guide | f32 latent, bf16 or f32 velocities | ltx2 |
| `mhc_contract` | yes | mhc_contract_bf16 | bf16 | glm5next |
| `mhc_post` | yes | mhc_post_bf16 | bf16 activation, f32 coefficients | common |
| `mhc_pre` | yes | mhc_pre_bf16 | bf16 activation, f32 weights and coefficients | common |
| `mhc_pre_finish` | yes | mhc_pre_finish_bf16 | bf16 activation, f32 partials and coefficients | common |
| `mhc_pre_partial` | yes | mhc_pre_partial_bf16 | bf16 activation, f32 weights and partials | common |
| `mix_rows` | yes | mix_rows_bf16 | bf16 | krea2 |
| `mla_attn` | yes | mla_attn_bf16, mla_attn_matrix_bf16 | bf16 Q/cache/output, f32 softmax and partials; bf16 operands; FP32 probabilities via high/low BF16 | common |
| `mla_project` | yes | mla_project_bf16 | bf16 input, weights and output; fp32 arithmetic | common |
| `moe_gather` | yes | moe_gather_bf16 | bf16 in and out | common, gemma4 |
| `moe_gather_inv` | no | moe_gather_inv_bf16 | bf16 in and out, f32 or bf16 routing weights | common |
| `moe_gemm` | yes | moe_gemm_bf16 | bf16 activation, bf16 weight as the checkpoint stores it ([N, K] row-major, no layout hook), f32 accumulate over the whole of K, bf16 out rounded to nearest-even | common, gemma4 |
| `moe_gemm_q` | yes | moe_gemm_fp8a8, moe_gemm_fp8a8_f32scale, moe_gemm_mxfp4a8, moe_gemm_w4a8 | E2M1 and E8M0 weights, E4M3 activations and f32 scales, bf16 output; E4M3 activation with an f32 scale per 128 of K, E4M3 weight with a bf16 scale per 128x128 tile, bf16 out; E4M3 activation with an f32 scale per 128 of K, symmetric int4 weight (codes -8..7) with a bf16 scale per row per 128 of K, bf16 out; dtype w4a8h is the same plane with a 128-wide Hadamard rotation along K baked into both, and pairs with had_quant_act_fp8; dtype w4nla8h is w4a8h with the codes indexing libquant's w4nl levels, and w4nl64a8h / w4nl32a8h are w4nla8h with an E4M3 scale per row per 64 / 32 of K under a fixed 2^-13; w5nl64a8h is w4nl64a8h with five-bit codes into libquant's w5nl levels, a sign bit plane after each row's nibbles | common, gemma4 |
| `moe_gemm_q_mod4` | yes | moe_gemm_fp8a8_mod4, moe_gemm_w4a8_mod4 | as moe_gemm_fp8a8; as moe_gemm_w4a8 | common |
| `moe_scatter` | yes | moe_scatter_i32 | i32 throughout | common, gemma4 |
| `moe_scatter_inv` | no | moe_scatter_inv_i32 | i32 throughout | common |
| `mtp_enter` | yes | mtp_enter_bf16, mtp_enter_e4m3 | bf16 activations and fc, f32 gains; bf16 activations, E4M3 fc rows with f32 128-column group scales in each row's tail, f32 gains | common |
| `mul` | yes | mul_bf16 | bf16 in and out, fp32 arithmetic | anima, common, flux3, gemma4, krea2, lfm2_bf16, ltx2, minimaxh3, qwenimage21, sdxl |
| `mul_weight` | yes | mul_weight_bf16, mul_weight_f32 | bf16 in and out, a bf16 or f32 weight, fp32 arithmetic; bf16 or f32 in, a bf16 or f32 weight, f32 out, the product rounded once | breeze, common, embgemma2, gemma4, minimaxh3 |
| `ngram_ids` | yes | ngram_ids_i32 | i32 tokens and state, i64 multipliers and per-head vocab sizes and offsets | common |
| `norm_add_norm` | no | norm_add_norm_bf16 | bf16 activations, f32 gains | gemma4 |
| `norm_add_norm_route` | no | norm_add_norm_route_bf16 | bf16 activations, f32 gains; E4M3 codes with an f32 scale a 128 columns | gemma4 |
| `pair_argmax` | yes | pair_argmax_f32 | f32 pairs (int32 id bits, f32 value), i32 idx, f32 val | common |
| `patch_fold` | yes | patch_fold_f32 | bf16 or f32 voxels, f32 patch rows | minimaxh3 |
| `patch_unfold` | yes | patch_unfold_f32 | f32 | minimaxh3 |
| `pix_patch` | yes | pix_patch | bf16 or f32 x and y | ltx2 |
| `pixel_norm` | yes | pixel_norm | bf16 or f32 x and y | ltx2 |
| `ple_conv` | yes | ple_conv_bf16 | bf16 activations, weights and conv state; i32 cu, slots, has_init and num_accepted | common |
| `ple_gate` | yes | ple_gate_bf16 | bf16 activations, F32 norm gains | common |
| `pool_rows` | yes | pool_rows_bf16 | bf16 in and out, f32 sum, two roundings | common |
| `prefetch` | no | prefetch | any | common, gemma4_bf16 |
| `qk_norm_rope` | yes | qk_norm_rope_bf16 | bf16 qkv, bf16 or f32 gains, i32 positions, f32 arithmetic, the norm rounded before the rotation | anima, breeze, common, embgemma2, flux3, gemma4, krea2, ltx2, minimaxh3, qwenimage21 |
| `qk_norm_rope_gate` | no | qk_norm_rope_gate | bf16 in and out; the norm output is rounded to bf16 before the rotation, as the unfused reference does by storing it | common |
| `qk_norm_rope_gate_kv_store` | no | qk_norm_rope_gate_kv_store_bf16, qk_norm_rope_gate_kv_store_fp8, qk_norm_rope_gate_kv_store_fp8v4, qk_norm_rope_gate_kv_store_k6v4 | bf16 in and out, E4M3 K and int4 V with f16 scales, i32 slot mapping; bf16 in and out, bf16 cache, i32 slot mapping; bf16 in and out, fp8-e4m3 cache, i32 slot mapping, scalar k_scale / v_scale descales | common |
| `qkv_norm_rope` | no | qkv_norm_rope_bf16, qkv_norm_rope_h128_bf16 | bf16 q/k/v and gains (or f32 gains), i32 positions; byte-identical to [rmsnorm_p +] rmsnorm x2 + rope x2, each norm taken by its standalone kernel's partition; bf16 q/k/v and gains (or f32 gains), i32 positions; byte-identical to rmsnorm_p + rmsnorm x2 + rope x2, each norm taken by its standalone kernel's partition | gemma3, gemma4_bf16 |
| `qkv_norm_rope_kv_store` | no | qkv_norm_rope_kv_store_bf16, qkv_norm_rope_kv_store_fp8 | bf16 q/k/v and gains (or f32 gains), i32 positions and slots, fp8-e4m3 cache, scalar k_scale / v_scale descales; byte-identical to qkv_norm_rope + kv_store_fp8; bf16 q/k/v, gains, cache; i32 positions and slots; byte-identical to qkv_norm_rope + kv_store_bf16 | common, gemma4_bf16 |
| `qsa_block_key` | yes | qsa_block_key_bf16 | bf16 keys in with an f32 gain; bf16 out, one row a BLOCK. The mean is rounded to bf16 before the norm, which is the reference's order and not the convenient one | common |
| `qsa_score` | yes | qsa_score_bf16 | bf16 queries and block keys, an i32 page-id table, f32 scores; a negative table entry scores -inf and not zero | common, qwen4exp_fp8 |
| `qsa_select` | yes | qsa_select_i32 | f32 scores and an i32 page table in; an i32 [M, topk+1] table and a live count out | common |
| `qsa_tail_store` | yes | qsa_tail_store_bf16 | bf16 keys in, an i32 position and an i32 cu_seqlens; the bf16 tail written in place | common |
| `qsa_work` | yes | qsa_work_bf16 | bf16 keys and a bf16 tail in, an i32 position, cu_seqlens and the block-key table; a bf16 staging plane out with an i32 page and first-token position a block | common |
| `quant_act_fp8` | yes | quant_act_fp8 | bf16 in, E4M3 out in PLAIN ROW-MAJOR order with an f32 scale per (row, 128 columns) | common, gemma3, gemma4 |
| `quant_act_i8` | yes | quant_act_i8 | bf16 in, int8 out with an f32 per-row scale | common, gemma3, gemma4_bf16 |
| `quant_act_i8g` | yes | quant_act_i8g | bf16 in, int8 out in PLAIN ROW-MAJOR order with an f32 scale of amax/127 per (row, 128 columns) | common, gemma3, minimaxh3, qwenimage21 |
| `quant_cols_fp8` | yes | quant_cols_fp8_bf16 | bf16 in, E4M3 out at its own pitch, f32 scale per column | minimaxh3 |
| `randn_lanes` | yes | randn_lanes_bf16, randn_lanes_f32 | bf16; f32 | anima, flux3, krea2, ltx2, minimaxh3, qwenimage21 |
| `rel_sinusoid` | yes | rel_sinusoid_bf16 | bf16 out, f32 libm sin / cos / exp | embgemma2 |
| `relu` | yes | relu_bf16 | bf16 in and out | embgemma2 |
| `resample_nearest` | yes | resample_nearest_bf16 | bf16 | minimaxmusic3 |
| `resize_bilinear` | yes | resize_bilinear | bf16 or f32 voxels, f32 arithmetic | minimaxh3 |
| `rms_mod` | yes | rms_mod_bf16 | bf16 rows, gain and table, fp32 sum of squares | anima, flux3, krea2, ltx2, minimaxh3 |
| `rms_mod_quant_fp8` | yes | rms_mod_quant_fp8_bf16 | bf16 rows, gain and table, E4M3 codes and f32 scales | anima, flux3, krea2, minimaxh3 |
| `rmsnorm` | yes | rmsnorm_bf16 | bf16 y, x bf16 or (with a gain) f32, bf16 or f32 gain, fp32 reduction | anima, breeze, common, embgemma2, flux3, gemma3, gemma4, gemma4_bf16, glm5next, krea2, lfm2_bf16, llama_fp8, ltx2, minimaxh3, minimaxmusic3, qwen35_bf16, qwen35_fp8, qwen3asr_bf16, qwenimage21, unlimitedocr_bf16 |
| `rmsnorm_add` | yes | -- | | -- |
| `rmsnorm_had_quant_i8` | yes | rmsnorm_had_quant_i8 | bf16 in, int8 out with an f32 per-row scale carrying 1/sqrt(had), optional bf16 out | -- |
| `rmsnorm_had_quant_i8g` | no | rmsnorm_had_quant_i8g | bf16 in, int8 out with an f32 scale per (row, 128 columns) and an optional bf16 out that receives the UNROTATED norm output; the codes are taken over the rotated BF16-ROUNDED norm output, byte-identical to rmsnorm + had_quant_act_i8g | common, qwen35_fp8 |
| `rmsnorm_p` | yes | rmsnorm_p_bf16 | bf16 x / y, fp32 reduction | gemma4_bf16, ltx2 |
| `rmsnorm_quant_fp8` | yes | rmsnorm_quant_fp8 | bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; the codes are taken over the BF16-ROUNDED norm output | common, gemma3, gemma4 |
| `rmsnorm_quant_i8` | no | rmsnorm_quant_i8 | bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale, optional bf16 out; every stored intermediate rounded to bf16 as the unfused chain stores it | common, gemma3, gemma4_bf16 |
| `rope` | yes | rope_bf16 | bf16 qkv, i32 positions, fp32 angles through the accurate sincosf | breeze, common, gemma3, gemma4, gemma4_bf16, ltx2 |
| `rope_split` | yes | rope_split | bf16 or f32 x, f32 or i32 positions | ltx2 |
| `rope_table` | yes | rope_table_f32 | f32 or bf16 table, i32 or i64 positions; the angles are rope_bf16's exactly | qwen35_fp8, qwen4exp_fp8 |
| `router_gemm_topk_scatter` | yes | router_gemm_topk_scatter_bf16 | bf16 activation and weights, fp32 accumulate; bf16 logits, gate and weights, i32 ids, sorted slots, offsets and counts out | common, gemma4 |
| `router_sigmoid_topk` | yes | router_sigmoid_topk_f32 | f32 logits, bias and weights; i32 ids | common |
| `router_sigmoid_topk_scatter` | no | router_sigmoid_topk_scatter_f32 | f32 logits, bias and weights; i32 ids, sorted slots, offsets and counts; bf16 gate | common |
| `router_topk` | yes | router_topk_bf16 | bf16 in, bf16 weights + i32 expert ids out | common, gemma4 |
| `router_topk_scatter` | yes | router_topk_scatter_bf16 | bf16 in, bf16 weights + i32 ids, sorted slots, offsets and counts out | common, gemma4 |
| `row_topk` | yes | rowtopk_bf16 | bf16 in, f32 values + i32 columns out | common |
| `row_topk_merge` | yes | rowtopk_merge | f32 pairs in, f32 values + i32 ids out, ties to the lower id | common |
| `rvq_embed` | yes | rvq_embed_bf16 | bf16 tables and rows | breeze, minimaxmusic3 |
| `s2d3d` | yes | s2d3d | bf16 or f32 x and y, i32 geom | ltx2 |
| `s2d_avg_add` | yes | s2d_avg_add_bf16 | bf16 | common, flux3 |
| `sam_attn` | yes | sam_attn_bf16 | bf16 query / key / value / out and rel_pos tables, i32 cu_seqlens, fp32 accumulate | common |
| `sample_argmax` | yes | sample_argmax_f32 | f32 logits, i32 token | -- |
| `sample_chain` | no | sample_chain_f32 | f32 logits, f32 uniforms (two a position), u32 query tokens or absent, {u32 tok, u32 tok_excl, f32 p_query} out | -- |
| `sample_dry` | yes | sample_dry_f32 | f32 logits in place, i32 history, optional u8 breaker plane, per-row params | -- |
| `sample_logprobs` | yes | sample_logprobs_f32 | f32 logits, f32 stats [M, 2 + 2k] with the ids as floats | -- |
| `sample_mask` | yes | sample_mask_f32 | f32 logits in place, u32 bitmask, per-row params | -- |
| `sample_merge_topk` | yes | sample_merge_topk_f32 | u32 (id, logit-bits) pairs in, i32 candidate ids and f32 candidate logits out | -- |
| `sample_minp` | yes | sample_minp_f32 | i32 candidate ids and f32 candidate logits, both in place | -- |
| `sample_ngram_ban` | yes | sample_ngram_ban_f32 | f32 logits in place, i32 history, i32 {n, window} per-row pair | -- |
| `sample_penalties` | yes | sample_penalties_f32 | f32 logits in place, i32 history, per-row params | -- |
| `sample_pick` | yes | sample_pick_f32 | i32 candidate ids, f32 candidate logits, i32 token | -- |
| `sample_temp` | yes | sample_temp_f32 | f32 logits in place, per-row params | -- |
| `sample_topk` | yes | sample_topk_f32 | f32 logits, i32 candidate ids, f32 candidate LOGITS (not probabilities) | -- |
| `sample_topp` | yes | sample_topp_f32 | i32 candidate ids and f32 candidate logits, both in place | -- |
| `sample_typical` | yes | sample_typical_f32 | i32 candidate ids and f32 candidate logits, both in place | -- |
| `sample_xtc` | yes | sample_xtc_f32 | i32 candidate ids and f32 candidate logits, both in place | -- |
| `scale` | yes | scale_bf16 | bf16 in and out, fp32 arithmetic, s f32 or bf16 | anima, breeze, common, embgemma2, flux3, gemma3, gemma4, gemma4_bf16, krea2, lfm2_bf16, ltx2, minimaxh3, minimaxmusic3, qwen35_fp8, qwen3asr_bf16, qwen4exp_fp8, qwenimage21, sdxl |
| `scale_rows` | yes | scale_rows_bf16 | bf16 in and out, fp32 arithmetic | -- |
| `scatter_add_rows` | yes | scatter_add_rows_bf16 | bf16 | qwenimage21 |
| `scatter_rows` | yes | scatter_rows_bf16, scatter_rows_u8 | i32 indices, bf16 rows; i32 indices, u8 rows | breeze, common, embgemma2, flux3, gemma4_bf16, krea2, minimaxmusic3, qwenimage21, unlimitedocr_bf16 |
| `seg_mean` | yes | seg_mean_bf16 | bf16 in and out, f64 sum, one rounding | embgemma2 |
| `seg_sinusoid` | yes | seg_sinusoid_bf16 | bf16 out, i32 cu_seqlens, f32 libm sin / cos / exp | qwen3asr_bf16 |
| `sigmoid` | yes | sigmoid_bf16 | bf16 in and out, fp32 arithmetic | common, embgemma2, krea2, qwen4exp_fp8 |
| `silu` | yes | silu_bf16, silu_f32 | bf16 in and out, fp32 arithmetic; f32 in, f32 out or bf16 rounded once | anima, common, embgemma2, flux3, gemma4_bf16, krea2, ltx2, minimaxh3, minimaxmusic3, qwen4exp_fp8, qwenimage21, sdxl |
| `silu_mul` | yes | silu_mul_bf16 | bf16 in and out, fp32 arithmetic | breeze, common, ltx2, minimaxh3, unlimitedocr_bf16 |
| `snake` | yes | snake_bf16 | bf16 rows, f32 alpha | breeze, minimaxmusic3 |
| `snake_aa` | yes | snake_aa_f32 | f32 rows, filters, alpha and beta | ltx2, minimaxh3 |
| `softmax` | yes | -- | | unlimitedocr_bf16 |
| `stft_logmel` | yes | stft_logmel | bf16 or f32 operands | ltx2 |
| `swiglu_clamped` | yes | swiglu_clamped_bf16 | bf16 in and out, fp32 arithmetic | common |
| `swiglu_clamped_quant_fp8` | no | swiglu_clamped_quant_fp8 | bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; the codes are taken over the BF16-ROUNDED product | common |
| `table_add` | yes | table_add_bf16 | bf16 | krea2, ltx2 |
| `tconv_dw` | yes | tconv_dw_bf16 | bf16 voxels, weight and bias, fp32 accumulate | minimaxh3 |
| `tile_crop` | yes | tile_crop | bf16 or f32 x and y, i32 geom and box | ltx2 |
| `tile_grid` | yes | tile_grid | i32 | ltx2 |
| `tile_stitch` | yes | tile_stitch | bf16 or f32 x, u8 y, i32 geom and first | ltx2 |
| `timestep_embed` | yes | timestep_embed_bf16, timestep_embed_f32 | bf16; f32 t and out, f32 angles | anima, flux3, krea2, ltx2, minimaxh3, qwenimage21, sdxl |
| `to_rgba8` | yes | to_rgba8_bf16 | bf16 | anima, flux3, krea2, qwenimage21, sdxl |
| `vol_index` | yes | vol_index | i32 | ltx2 |
| `vsa_select` | yes | vsa_select_h128_bf16 | bf16 q / k / v / coarse, i32 segs / geom / sel; f32 means, scores and softmax | minimaxh3 |
| `vtile_gather` | yes | vtile_gather | bf16 or f32 rows and registers | minimaxh3 |
| `vtile_stitch` | yes | vtile_stitch | bf16 or f32 tiles and overlap, u8 out | minimaxh3 |
| `win_finish` | yes | win_finish_bf16 | bf16 states | minimaxmusic3 |
| `win_input` | yes | win_input_bf16 | bf16 | minimaxmusic3 |
| `win_prep` | yes | win_prep_bf16 | bf16 states, f32 t | minimaxmusic3 |
+542
View File
@@ -0,0 +1,542 @@
# Intel GPU (SYCL / Level Zero) backend: progress log
Task brief: `radiance-sycl.md` (repo root, not committed). Porting analysis: `docs/SYCL_PORTING.md`
(Phase 1, not written yet). This file is the resume point: a fresh session should be able to continue
from it alone.
## Status
| phase | state |
|---|---|
| 0 environment check | done |
| 1 codebase study, `SYCL_PORTING.md` | done (`docs/SYCL_PORTING.md` §1-§3, Appendix A) |
| 2 design | done: device backend, build integration, core kernels (`device_test_sycl` on the B65) |
| 3 correctness-first kernels | **Milestone A reached 2026-10-23** (`874f8d2`): MiniCPM5-2B bf16 serves on the B65, greedy-identical to the libref host backend; Milestone B next |
| 4 performance | in progress on MiniCPM5-2B bf16: decode 4.2 -> 51.8 tok/s, prefill 17 -> 1576 tok/s (BetterBench quick, `b07da2a`) |
| 5 broaden and finish | not started |
## Open blockers / questions for the user
1. ~~**No `.rad` container for any milestone model is in `/mnt/model-library`.**~~ Resolved for bf16
(2026-10-23): `StillDeadcode/minicpm5-2b-bf16/minicpm5-2b-bf16.rad` (5,501,632,512 bytes) appeared;
copied to `/models/minicpm5-2b-bf16/` and verified with `cmp`. **Still missing: `minicpm5-2b-fp8.rad`**
(Milestone B). Original note:
`StillDeadcode/minicpm5-2b-bf16/` holds only `README.md` and `minicpm5-2b-bf16-dspark.recipe`; there
is no `minicpm5-2b-bf16.rad`, no `minicpm5-2b-fp8.rad`, and no raw `openbmb/MiniCPM5-2B` /
`MiniCPM5-2B-DSpark` checkpoint to convert from. A `find -iname '*.rad'` over the library and
`/models` returns nothing. Milestones A and B cannot be run until the user provides the containers
(or the checkpoints plus permission to run `rad-convert`). Per the brief, nothing is downloaded or
converted without asking.
2. **Bring-up without a real model.** The test suite writes synthetic llama checkpoints and converts
them to `.rad` itself (`tests/tiny_model.h`, `tests/engine_e2e_test.cpp`; `RAD_E2E_KEEP=1` keeps
them): bf16, block-fp8 trunk, fp8 / int8 heads, int4, MXFP4, all on the `llama_dense_fp8` graph
MiniCPM5 uses. Those are test fixtures, not library models, and are what the Intel backend is
brought up and compared against the host backend on until the real containers exist.
Optionally, `HuggingFaceTB/SmolLM2-135M` (real bf16 llama weights, head_dim 64, tied embeddings)
could be converted as a real-weights check; that needs the user's OK, since it is a conversion.
3. ~~**No ROCm on this machine**~~ Resolved: `sudo` needs a password, so the HIP compile check runs
in docker (see "HIP compile check"); it passes.
## Phase 0 results (2026-10-23)
### Toolchain and device
- Compiler: `Intel(R) oneAPI DPC++/C++ Compiler 2026.2.0 (2026.2.0.20261001)`, at `/opt/intel/oneapi`
(not on PATH by default: `. /opt/intel/oneapi/setvars.sh`).
- `sycl-ls`: `[level_zero:gpu][level_zero:0] Intel(R) oneAPI Unified Runtime over Level-Zero V2, Intel(R) Arc(TM) Pro B65 Graphics 20.2.0 [1.17.39395+16]`
(also an OpenCL GPU entry for the same card, NEO 26.31.39395.16, and the OpenCL CPU device).
- `clinfo -l`: Intel OpenCL (EPYC 7282 CPU), Intel OpenCL Graphics (Arc Pro B65).
- `lspci -k`: `01:00.0 Intel Corporation Battlemage G31`, kernel driver `xe`. Linux 7.0.0-38-generic.
- User is in `render` and `video`; `/dev/dri/renderD128` is `root:render 0660`.
- Host: AMD EPYC 7282, 8 visible cores, 30 GiB RAM (a VM; the bochs VGA is the emulated console).
### Device limits (`scripts/sycl/devprobe.cpp`)
| query | value |
|---|---|
| architecture | `intel_gpu_bmg_g31` (alias `intel_gpu_20_2_0`); AOT target `-device bmg-g31` |
| compute units | 160 (20 Xe cores x 8 vector engines) |
| max work-group size | 1024 |
| sub-group sizes | 16, 32 |
| local memory (SLM) per work-group | 131072 B (128 KiB) |
| global memory | 34242297856 B (31.89 GiB) |
| max single allocation | 32530182144 B (30.30 GiB) |
| L2 (global_mem_cache_size) | 18 MiB |
| max clock | 2400 MHz |
| fp16 / fp64 / atomic64 | yes / yes / yes |
| USM device / host / shared / system | yes / yes / yes / yes |
| `ext_intel_matrix` aspect | yes |
### XMX (joint_matrix and ESIMD DPAS)
`matrix_combinations` reports, for sub-group 16: A/B in {u8,s8} -> s32 at M<=8 N16 K32; fp16 and bf16
-> fp32 or 16-bit at M<=8 N16 K16, plus the larger fixed shapes M16N16K16, M1/M32 x N64 x K16/K32;
tf32 -> fp32 at M<=8 N16 K8. No FP8 combination is listed (the query enum has no fp8 member).
Executed on the device, each checked exactly against a host loop:
| op | result |
|---|---|
| joint_matrix bf16 x bf16 -> f32, M8 N16 K16 | exact |
| joint_matrix fp16 x fp16 -> f32, M8 N16 K16 | exact |
| joint_matrix s8 x s8 -> s32, M8 N16 K32 | exact |
| ESIMD `xmx::dpas` bf16 -> f32, M8 N16 K16 (control) | exact |
| ESIMD `xmx::dpas` s8 -> s32, M8 N16 K32 (control) | exact |
| ESIMD `xmx::dpas` **hf8 (E4M3)** -> f32, M8 N16 K32 | **wrong** (values ~1e15..1e24 and inf; expected 31.75) |
| ESIMD `xmx::dpas` **bf8 (E5M2)** -> f32, M8 N16 K32 | **wrong** |
The ESIMD headers declare `hf8`/`bf8`/`e2m1` DPAS argument types, and IGC compiles them for
`bmg-g31` (AOT and JIT) without a diagnostic, but the results are garbage while the bf16 and s8
controls through the identical harness and VNNI packing are exact. **Conclusion: FP8 is not a native
XMX input on this Battlemage part** (the brief's belief holds). The 8-bit float DPAS precisions are
for a later generation; the compiler does not reject them for BMG.
Consequence for the design: fp8 (E4M3) weights are widened in-register before DPAS. E4M3 -> bf16 is
exact for every finite E4M3 value (3 mantissa bits fit in bf16's 7; max 448 and the smallest
subnormal 2^-9 are inside bf16's range), and it keeps the activations bf16, so **bf16 XMX is the
default path for fp8 weights**. (E4M3 -> fp16 is also exact, but the bf16 activations would then have
to be narrowed to fp16, which can overflow.) MXFP4 (e2m1) is the same: widen to bf16 in-register.
int8 (w4a8, int8 trunks) has native s8 DPAS.
Reproduce: `scripts/sycl/probe.sh` (prints both tables' raw output).
### Host baseline (tree at `9eaf10d`, before any change)
`./build.sh --no-hip` builds cleanly (625 targets, GCC, Ninja). Then:
- `ctest -L '^fast$' -j8`: 75/80 pass.
- `ctest --test-dir build -LE 'gpu|oot' -j8`: **82/88 pass, 540 s**. `engine_e2e_test` (33 s) and
`convert_test` pass.
The six failures are pre-existing and environmental; none touches code this task changes. **This
set is the baseline that "passes exactly as before" is measured against:**
| test | cause | evidence |
|---|---|---|
| `images_test` | no FFmpeg dev libraries, so `RAD_WITH_FFMPEG` resolves off and pictures cannot be encoded | `500 ... this build has no media decoder: it was configured without libavformat / libavcodec / libswscale`; `pkg-config libavcodec` fails |
| `videos_test` | same | `400 ... input_reference: the picture could not be read: this build has no media decoder` |
| `glm5next_test` | over its CPU-time budget on this slow VM host | `the binary spent 11.17 s of CPU, over its budget of 10 s (RAD_TEST_CPU_BUDGET)` |
| `gbnf_test_shard2` | same | `10.52 s of CPU, over its budget of 10 s` |
| `quant_ggml_test` | same | `25.38 s of CPU, over its budget of 25 s` |
| `trigger_test` | timing ratio under `-j8` load; passes 3/3 run alone | `trigger_test.cpp:429: CHECK((double)last < (double)first * 1.25)` in `lazy_grammar_waiting_work_does_not_grow_with_the_reply` |
Installing `libavformat-dev libavcodec-dev libswscale-dev` would clear the first two (the user's
call; not needed for this task). After each phase, the same command must show these six and no
others; the CPU-budget and timing tests are compared by cause (re-run alone if they flip).
## Benchmarks
Tool: BetterBench 0.6.1 (`GGZ14/BetterBench` at `f72bb90`), cloned to `~/tools/BetterBench` and
installed editable into its own venv `~/tools/betterbench-venv` (Python 3.14.4). Every flag of the
brief's command (`--quick --decode --prefill --no-update-check --name --out --note --api-key`) is
present in `betterbench run --help`.
```sh
~/tools/betterbench-venv/bin/betterbench run --endpoint http://127.0.0.1:8000/v1 --model <served name> \
--quick --decode --prefill --no-update-check \
--name sycl-<model>-<short commit> --out <run dir>/results.json \
--note backend=sycl --note gpu=arc-pro-b65 --note commit=<short commit>
```
Discord posting: the user added `~/.config/radiance-bench.env` (mode 0600) on 2026-10-23;
`DISCORD_WEBHOOK_URL` loads from it (never printed or logged). The user also asked for
**screenshots of BetterBench's HTML report** to be sent to the webhook with each result. No headless
browser is installed (no chromium/firefox/wkhtmltoimage, no playwright); at the first benchmark,
install one outside the repo (e.g. playwright + chromium in `~/tools/betterbench-venv`) and have
`scripts/bench_report.sh` render the report to PNG and post it as a multipart attachment beside the
summary. `scripts/bench_report.sh` (quick run, parse `results.json` with `jq`, post, check the HTTP
status) is to be written at the first benchmarkable milestone, against a real `results.json`.
All runs are `--quick` (1 warmup, 5 passes): progress tracking, not publishable numbers.
`scripts/sycl/bench_report.sh TAG` runs the brief's command against a live server, summarises with
BetterBench's own report functions, screenshots the HTML report (JPEG, at the user's request) and
posts both to the webhook; `--report RUN_DIR TAG` reports an existing run. The screenshot needs
headless Chromium (Playwright in the BetterBench venv), nine system libraries it lacks here and
fonts (this host has none; the first post had no text) -- all unpacked without root under
`~/tools/chromium-libs` (`apt-get download` + `dpkg -x`, a private `fonts.conf`).
| date | commit | model | backend | flags | prefill tok/s (median / 1% low) | decode tok/s (median / 1% low) | vs previous | report |
|---|---|---|---|---|---|---|---|---|
| 2026-10-23 | `874f8d2` | minicpm5-2b-bf16 | sycl, correctness-first kernels | `--num-speculative-tokens 0 --max-model-len 8192 --max-num-seqs 4` | 17.3 / 17.3 @2000 (8000+ skipped: over the 8192 context) | 4.2 / 3.5 | first run | `~/radiance-bench/runs/20261023-165102-minicpm5-2b-bf16-874f8d2/results.html`, posted with `report.jpg` |
| 2026-10-23 | `a869226` | minicpm5-2b-bf16 | sycl, Phase 4 step 1 (GEMV) | same | 17.5 / 17.4 @2000 | 25.3 / 16.2 | decode +504.5% | `~/radiance-bench/runs/20261023-194856-minicpm5-2b-bf16-a869226/results.html`, posted with `report.jpg` |
| 2026-10-23 | `b07da2a` | minicpm5-2b-bf16 | sycl, Phase 4 steps 2-6 (XMX prefill, split-KV attention, norms, GEMV split) | same | 1575.6 / 1547.1 @2000 | 51.8 / 41.4 | decode +104.7%, prefill 90x | `~/radiance-bench/runs/20261023-221354-minicpm5-2b-bf16-b07da2a/results.html`, posted with `report.jpg` |
## Models
Library (`/mnt/model-library`, read-only), as of 2026-10-23:
| path | what | useful for |
|---|---|---|
| `StillDeadcode/minicpm5-2b-bf16/` | README + recipe only, **no weights** | nothing until the `.rad` is supplied |
| `HuggingFaceTB/SmolLM2-135M/` | bf16 safetensors, llama | possible bring-up stand-in (blocker 2) |
| `Launch80/Swift-1.5-Qwen3.8-27B-Uncensored-Int4-baked/` | 16 GiB int4 safetensors (qwen35, "baked") | possibly a 19-22 GiB-class Milestone B model, if `rad-convert` reads it; unverified |
| `Wrapzii/Swift-1.5-Qwen3.8-27b-GPTQ-Int4-baked-v1-embed-int8/` | 17 GiB GPTQ int4 + int8 embed | same |
| `unsloth/Qwen3.8-27B-GGUF`, other `*-GGUF` dirs | GGUF quantisations | the engine converts some GGUF (`libquant/lq_ggml.cpp`); unverified for these |
| `Qwen/Qwen3-0.6B-GGUF`, `unsloth/Qwen3-8B-GGUF`, `SmolLM3-3B-GGUF`, ... | GGUF | not on the README's model table |
`/models` (196 GiB, 137 GiB free) already holds copies made before this task: `Qwen3.8-27B-Q4_0.gguf`,
`mtp-Qwen3.8-27B-Q4_0.gguf`, and the two Swift 27B directories. They are left as found.
Planned use: Milestone A = `minicpm5-2b-bf16.rad` (blocked, item 1); Milestone B = `minicpm5-2b-fp8.rad`
(blocked) and one of the 27B int4 / MXFP4 containers (to be decided once Phase 1 shows what
`rad-convert` accepts, and with the user's OK for any conversion).
## Decisions
- D1 (Phase 0): FP8 and FP4 weights are widened to bf16 in-register for XMX; int8 uses native s8 DPAS.
Evidence above.
- D2 (Phase 1): no new device-runtime abstraction. `DeviceBackend` (`core/device/device.h:178`)
already is one and HIP/AQL sit behind it; the Intel backend is a fourth vtable,
`core/device/sycl.cpp`. The HIP path is not touched. (`SYCL_PORTING.md` §4.1)
- D3: plugins get the queue through `abi/rad_sycl.h`'s `RadSyclStream` (magic + own version +
`sycl::queue*`), not a `RAD_ABI_VERSION` bump: no existing shape changes. (§4.2)
- D4: kernel library `libxe2/`, AOT for `intel_gpu_bmg_g31`; `code_runs` under SYCL compares a
plugin's `build_target` with the device arch so libr4d rows are never selected on the B65. (§4.3)
- D5: on the SYCL backend the "host-only ops ... Not a hole" placement is fatal unless
`--debug-accept-host-ops`. (§4.4)
- D6 (revised 2026-10-23): ~~`RAD_SYCL=ON` builds everything with `icpx`~~. Tried: `cmake -B build-icpx
-DCMAKE_CXX_COMPILER=icpx -DCMAKE_CXX_FLAGS=-ffp-model=precise -DRAD_WITH_HIP=OFF` fails in libavx:
`avx_gemm_tile.cpp:289: always_inline function '_pdep_u64' requires target feature 'bmi2', but would
be inlined into function 'qb_codes_zp' that is compiled without support` (GCC accepts it, clang does
not), and fixing that means changing libavx. So the **main build stays GCC in every configuration**
and only the SYCL code is built and linked by `icpx`, as shared libraries in a sub-build
(`librad_sycl.so`: the device backend and the core's SYCL kernels, a C entry point and a callback
table for logging and errors; `libxe2.so`: the kernel plugin). Host code in a SYCL build is then the
default build's, byte for byte. HIP + SYCL refused together at configure until a ROCm machine can
test it. (§4.5)
- D7: `advance` and `wtab` get SYCL launchers; `xprefetch` stays off. (§4.6)
- D8: `--tp > 1` refused at startup on the SYCL backend, before the device-count check. (§4.7)
- D9 (2026-10-23): queues are made **without** `enable_profiling` unless `RADIANCE_SYCL_TIMING=1`.
Measured on the idle B65 (`scratchpad` probe `subcost.cpp`, 4000 trivial kernels): in-order +
profiling 24.4 us host time per `single_task`, 22.8 us per `parallel_for`; in-order without
profiling 4.5 / 4.4 us; `ext::oneapi::experimental::nd_launch` 4.0 us either way. At ~550 launches
per MiniCPM5 decode step that is 13 ms vs 2.5 ms. Without timing, `rad_event_elapsed_ms` refuses
and names the variable (`--profile-ops` and `rad-kbench` need it set). libxe2 launches with
`nd_launch`. (An earlier 50 us figure was measured while a -j8 build loaded the host.)
- D10 (2026-10-23): `RAD_MEM_HOST_PINNED` / `_MAPPED` are `posix_memalign` + `prepare_for_device_copy`,
not SYCL `malloc_host`: O_DIRECT into `malloc_host` fails with EFAULT (driver-mapped pages), and
the mover reads the file tier straight into pinned buffers. Measured, 256 MiB: `malloc_host` 28.4 /
28.5 GB/s H2D / D2H, O_DIRECT fails; registered `posix_memalign` 28.4 / 28.4 GB/s, O_DIRECT ok,
kernel read/write ok (system USM); unregistered 21.0 / 18.2 GB/s. The backend keeps a registry
of those ranges, since the runtime does not know them.
- D13 (2026-10-23): fast kernels may change libref's reduction order. They are held to rad-kbench's
per-op tolerances (libr4d's standard) and, end to end, to the KL bound measured above against the
libref host build -- no worse than libavx's distance from libref. Every fast row keeps its exact
twin, selectable with `XE2_EXACT=1`.
- D12 (2026-10-23): every libxe2 op is checked twice: rad-kbench (dense operands, fixture and the
real container) and the engine's op oracle on the operands the engine hands it
(`RADIANCE_OP_ORACLE`), at tolerance ~0 where the kernel reproduces libref's order. Transcendentals
are libref's: double `exp`/`log`/`cos`/`sin` on the device, rounded once to f32 (verified
bit-identical to glibc over MiniCPM5's rope angles and exp's [-104, -20] range).
- D11: the SYCL engine needs the oneAPI environment at run time: the runtime `dlopen`s its Level
Zero adapter, which needs `libumf.so.1` from oneAPI's `umf/` tree (no RUNPATH can reach it). A SYCL
build that sees no GPU now warns (not Info) that it is running on the CPU and names the fix.
## Done in Phase 2 (2026-10-23)
- `abi/rad_sycl.h` (commit `f00e9b7`). The `__host__ __device__` macros needed no SYCL case: their
`#else` (empty) is what SYCL device code wants.
- Build: `RAD_SYCL=OFF|ON|AUTO` (default OFF), `RAD_SYCL_TARGETS` (default `intel_gpu_bmg_g31`),
`build.sh --sycl` (in `build-sycl/`), presets `sycl` (configure, build, test). The icpx sub-build is
`sycl/CMakeLists.txt`, run through ExternalProject; `rad_core` links `librad_sycl.so` with
`RAD_HAVE_SYCL=1`. HIP + SYCL refused at configure. The default build's generated test
definitions are byte-identical apart from CMake's backtrace line numbers.
- `core/device/sycl.cpp` (+ `sycl_host.h/.cpp`: the logger/error-slot callback table), selection in
`dispatch.cpp` ahead of the host fallback; `core/sched/advance_sycl.cpp`,
`core/runtime/wtab_sycl.cpp`; startup refusals for `--tp > 1` and host-only ops on SYCL.
- Tests: host-tier tests hide Level Zero GPUs with `ONEAPI_DEVICE_SELECTOR=!level_zero:*`
(`RAD_TEST_HIDE_ENV`). `device_test_sycl` (label `sycl`, `RAD_TEST_BACKEND=sycl` so a fallback to
the host backend fails, `RADIANCE_SYCL_TIMING=1`): **36 cases pass on the B65, 16579 checks**,
12 skipped (8 elastic memory, not provided; 4 host-backend-only, skipped on AMD cards too). It
runs the SYCL `advance` kernel (`an_advance_reads_the_token_a_copy_issued_before_it_delivers`).
Fixed on the way: memset of pageable memory returns `RAD_E_UNSUPPORTED`; ranged copies refuse
what the other backends refuse; a room check refuses an allocation past the driver's free count;
gates (a spin kernel on a pinned flag).
- SYCL build, `ctest -LE 'gpu|oot'` with the oneAPI environment loaded (card present, hidden):
83/88, the baseline's failures (FFmpeg, CPU budgets); `trigger_test`'s load flake did not occur.
## libxe2 (started 2026-10-23)
`libxe2/` is built by the sycl sub-build with `rad_add_plugin` into `radiance_home/kernels`
(`xe2_common.h`: queue, row views, refusals; `xe2_rows.cpp`: rows with designated initialisers).
Ops so far: `add`.
**The correctness check for every op is `rad-kbench`**: it replays each kernel against libref's
recorded answers on seeded inputs inside guarded allocations (`data/kernels.rkb`, recorded from
qwen3.8-27b; `kernels_moe.rkb`), at the project's per-op tolerances, and with `-m` against a real
container at its geometry. In a SYCL build the `kbench` and `kbench_moe` tests are labelled
`kbench;sycl` (card tier), as they are `kbench;gpu` in a HIP build. Per op:
```sh
. /opt/intel/oneapi/setvars.sh
RADIANCE_SYCL_TIMING=1 RADIANCE_HOME=$PWD/build-sycl/radiance_home build-sycl/bin/rad-kbench --op <op>
RADIANCE_SYCL_TIMING=1 RADIANCE_HOME=$PWD/build-sycl/radiance_home build-sycl/bin/rad-kbench \
-m /models/minicpm5-2b-bf16/minicpm5-2b-bf16.rad --num-speculative-tokens 0 --op <op>
```
`add`: fixture 30/30 and MiniCPM5 20/20, worst rel_l2 0, no writes outside guarded allocations.
`ctest -L '^sycl$'` (device_test_sycl, kbench, kbench_moe): 3/3 on the B65.
In a SYCL build the host tier is `ctest -LE 'gpu|oot|sycl'` (kbench moved to the card tier).
### MiniCPM5-2B bf16, the real container (`--debug-graph`, host backend)
42 layers, n_embd 2048, 16 q / 2 kv heads, head_dim 128 (gqa 8), ffn 6144, vocab 130560, rope theta
5e6 neox, eps 1e-6. With `--num-speculative-tokens 0`: 523 ops, exactly the 13 + 13 of
`SYCL_PORTING.md` §3.1 (gemm_nt at N,K = 2560x2048 qkv, 2048x2048 o, 12288x2048 gate_up,
2048x6144 down; logits 130560x2048). With its DSpark drafter (default, depth 7): 619 ops, adding
`gemm_nt_q` fp8a8 (128x128 blocks) and `w2a8` (the 2-bit head), `gemm_nt_q_gated`, `silu_mul`,
`quant_act_i8`, `row_topk` (N 130560, R 16), `dflash_select`, a non-causal `attn_paged`, and
`rmsnorm` n=128. Milestone A runs with speculation off first; the drafter's ops are Milestone B.
## Milestone A (2026-10-23, commit `874f8d2`)
`minicpm5-2b-bf16.rad` with `--num-speculative-tokens 0` serves on the Arc Pro B65: 26 libxe2 ops
(13 model, 13 sampler), every one resolved to a device row, none placed on the host.
- **Greedy, token for token, against the host backend restricted to libref** (`--kernels libref
--debug-accept-reference-kernels`): `scripts/sycl/greedy_compare.py`, 8 prompts x 64 tokens,
**8/8 identical**; top-5 logprobs over 96 decode steps differ by **exactly 0**.
- Against the default host backend (libavx): 5/8 identical; the three others diverge late (tokens
27, 55, 61) at near-ties (top-2 gaps 0.01-0.07 nats). libavx's reductions are not libref's, and
libxe2 reproduces libref, so this is libavx vs libref, not the card. Measured, not bounded further.
- `/v1/chat/completions` answers coherently, the reasoning split out ("In one sentence, why is the
sky blue?" -> "The sky appears blue because shorter blue wavelengths of sunlight are scattered
more by the atmosphere's molecules than longer red wavelengths.").
- Reproduce:
```sh
. /opt/intel/oneapi/setvars.sh
RADIANCE_HOME=$PWD/build-sycl/radiance_home build-sycl/bin/radiance \
--model /models/minicpm5-2b-bf16/minicpm5-2b-bf16.rad --num-speculative-tokens 0 \
--max-model-len 8192 --max-num-seqs 4 --port 8100 &
RADIANCE_HOME=$PWD/build/radiance_home ROCR_VISIBLE_DEVICES=99 build/bin/radiance \
--model /models/minicpm5-2b-bf16/minicpm5-2b-bf16.rad --kernels libref \
--debug-accept-reference-kernels --num-speculative-tokens 0 --max-model-len 8192 --port 8102 &
python3 -I scripts/sycl/greedy_compare.py http://127.0.0.1:8100 http://127.0.0.1:8102
```
**Two checks, not one.** rad-kbench passed every op, and the engine still found two bugs, because its
operands are not kbench's: `cast` was handed a strided slice of the fused qkv row (refused, loudly),
and `gated_quant_fp8`'s f32 `exp` was inside kbench's tolerance but not libref's double `exp`, which
moved one E4M3 code in some layers and flipped a greedy near-tie later. The engine's op oracle finds
the second kind: it runs libref on the very operands each device kernel was handed. **Every new op
gets both checks** (D12):
```sh
RADIANCE_OP_ORACLE='*' RADIANCE_OP_ORACLE_MAX=600 RADIANCE_OP_ORACLE_TOL=1e-9 \
RADIANCE_HOME=$PWD/build-sycl/radiance_home build-sycl/bin/radiance --model ... --port 8120
# one short request, then: grep -c 'oracle #.* agrees' / grep 'MISMATCH' in the log
```
After the fix: 600/600 issues of a 26-token prefill bit-identical.
Speed (correctness-first kernels: serial-dot GEMM, one work-group a (row, head) attention):
24 tokens in 5.6 s including prefill; BetterBench quick numbers in "Benchmarks".
## Milestone B, part 1: the DSpark drafter (2026-10-23)
libxe2 now serves every op of `minicpm5-2b-bf16.rad` with its drafter: `gemm_nt_q` over fp8a8
(128x128 blocks; libref's `quant_dot` per output), `gemm_nt_q_gated` (fp8a8, gated epilogue; n <= 28672
in local memory, declared as N <= 57344), the `w2a8` vocabulary head (libref's `gemm_zp`; `b_scale`
in libref's joined planes form through the same layout hook, the planes found on the device),
`quant_act_i8`, `silu_mul`, `row_topk`, `dflash_select`. Non-causal attention and head-only rope were
already served.
- rad-kbench: MiniCPM5-2B 191/191 at rel_l2 0 (the head's row is not reached by kbench's cases);
fixture: the gated GEMM at a 27B geometry (N 34816) was refused at first -- its first version held
the whole N-wide row in local memory -- and passes since.
- Engine oracle with speculation on: **1500/1500 issues bit-identical**, the w2a8 head included.
- Greedy, speculation on (DSpark, depth 7) against libref's greedy with it off:
**8/8 prompts identical** (`greedy_compare.py`, 64 tokens each).
- Speed: 2.5-5.4 tok/s with speculation against 4.2 without: verifying 7 drafts costs about as much as
7 tokens in a serial-dot GEMM. Speculation pays once the GEMMs are bandwidth-bound (Phase 4).
## Install and the out-of-tree rebuild (2026-10-23)
A SYCL build installs `librad_sycl.so` to `lib/` and `libxe2.so` to `share/radiance/kernels`, and
its executables carry `INSTALL_RPATH $ORIGIN/../lib` (checked: an installed `radiance` resolves the
backend from the prefix with no environment). `tests/oot_plugins.sh` rebuilds libxe2 out of tree
with icpx when `RAD_OOT_ICPX` is set (the SYCL build's registration sets it) and hides Level Zero
GPUs from its listing and replay. `ctest -R oot_plugins` in build-sycl: **passed** (370 s).
## Phase 4, step 1 (2026-10-23)
Profile (`RADIANCE_SYCL_TIMING=1 --profile-ops`, MiniCPM5 bf16 decode, correctness-first kernels):
232.8 ms/step; `gemm_nt` 79.2% (gate_up, 50 MB of bf16, 810 us a call = 62 GB/s on a ~600 GB/s
card), `rmsnorm_quant_fp8` 13.0% (the serial sum of squares, 360 us a call), `logits_gemm` 3.4%,
the rest under 1.5% each.
- `rmsnorm*`: the squares are formed in parallel into local memory, work-item 0 adds them in index
order -- the same additions, still bit-identical to libref (kbench rel_l2 0).
- `xe2_gemm_nt_gemv`, `xe2_logits_gemm_gemv` (priority 10, `M <= 16`, bf16): a sub-group an output
column, 16-byte coalesced weight loads, a tree reduction. Not libref's order. kbench: fixture
361/361, MiniCPM5 180/180 (worst rel_l2 1.6e-4, tol 8e-3). `XE2_EXACT=1` sends them to the exact
kernels.
- **Decode: 4.2 -> 35.5 tok/s** (128-token greedy completions, speculation off).
- **KL bound (D13)**, `--kld-record` with the libref host build over 12 passages of the repo's docs
(1914 positions), scored with `--max-num-batched-tokens 16` so the GEMV computes every position:
| path | KL mean | median | p99 | p99.9 | max | top-1 | PPL ratio |
|---|---|---|---|---|---|---|---|
| B65, `XE2_EXACT=1` | 0 | 0 | 0 | 0 | 0 | 100% | 1.0000 |
| B65, fast GEMV | 5.9e-4 | 4.1e-4 | 3.5e-3 | 9.4e-3 | 0.045 | 98.54% | 0.9989 |
| host, libavx (reference point) | 5.7e-4 | 4.2e-4 | 3.0e-3 | 6.4e-3 | 0.016 | 98.59% | 1.0004 |
The B65's fast path is as far from libref as the production CPU library is. Greedy against libref:
7/8 prompts identical, the eighth diverging at token 18 on a 0.008-nat near-tie.
## Phase 4, step 2 (2026-10-23): XMX GEMM and one-pass attention
- `xe2_gemm_nt_xmx` / `xe2_logits_gemm_xmx` (priority 5, `M >= 17`, bf16): joint_matrix M8 N16 K16,
use::b loaded column-major straight from the [N, K] weight (probed exact on the card), eight
sub-groups a work-group sharing one 64-column slice; tail rows by the GEMV, odd shapes to the exact
kernel.
- `xe2_attn_paged` (priority 10): one pass, online softmax, keys over eight sub-groups, head_dim over
lanes; the exact kernel underneath.
- rad-kbench: fixture 499/499, MiniCPM5 482/482 (worst rel_l2 1.7e-4); every new row reached.
- KL against the libref reference (same corpus as D13): normal batching (XMX + fast attention)
mean 5.8e-4, p99 3.2e-3, top-1 98.69%, PPL x1.0001; 16-token chunks (GEMV + fast attention)
5.8e-4 / 2.9e-3 / 98.59%. Inside the bound.
- **Prefill 1795 tokens: TTFT 4.57 s = 393 tok/s (was ~17).** Decode 33.2 tok/s over 512 tokens, but
16.2 tok/s right after a 1.8k-token prompt: single-row decode attention runs 16 work-groups (one a
head) on a 160-engine card, and each kv head is read by 8 query heads. Next: split the keys across
work-groups and share a kv head's reads across its query heads.
## Phase 4, step 3 (2026-10-23): split-KV attention
Long-context decode profile (1.8k-token prompt, 64 steps): attn_paged 69.9%, gemm_nt 11.1%,
rmsnorm_quant_fp8 9.3%, gated_quant_fp8 4.1%. `xe2_attn_paged` is now flash-decoding: a work-group a
(row, kv head, key partition) whose sub-groups are the kv head's query heads (each key read once for
all 8), partitions of 32+ keys merged from 64 MiB of scratch; P = 1 for prefill-sized row counts.
A first try at 256-key partitions halved short-context decode (all keys in one partition, each
sub-group walking every key for its head): 32 keys fixed it.
- rad-kbench 138/138 and 132/132 (worst rel_l2 2.9e-4); KL mean 5.8e-4, p99 3.2e-3, top-1 98.5%.
- **Decode after a 1797-token prompt: 16.2 -> 29.8 tok/s**; short-context decode 32.0 tok/s;
1797-token prefill 4.61 s.
## Phase 4, step 4 (2026-10-23): the norm and the quantisers, still exact
`scripts/sycl/profile_decode.sh MODEL PROMPT [STEPS] [flags]` isolates decode: the same request at
1 and 1 + STEPS tokens in two profiled servers, the difference per op divided by STEPS. At a
1.8k-token context, before: 34.8 ms/step of device time -- gemm_nt 9.65, attn_paged 9.51,
rmsnorm_quant_fp8 9.12 (108 us a call for one row), gated_quant_fp8 3.52 (84 us, one work-group a row
and every value computed twice, a double exp each).
- The ordered sum reads its squares eight at a time, adding them in the same order.
- `quant_group` computes a group's values once into registers (up to 128 a group) and writes
out_bf16 itself; `gated_quant_fp8` spreads a row's groups over ceil(groups/16) work-groups.
- Still bit-identical: rad-kbench 208/208 and 206/206 at rel_l2 0.
- After: **26.6 ms/step** -- gemm_nt 9.62, attn_paged 9.50, rmsnorm_quant_fp8 3.75, logits_gemm 1.02,
gated_quant_fp8 0.87.
## Phase 4, step 5 (2026-10-23): attention, lane-per-key with vector loads
- 16 keys a step, one a lane: a lane scores its key in full against q in local memory; one max and
one sum a step; value rows accumulated with each key's weight taken from its lane. Alone: 9.5 ->
8.8 ms/step.
- Partitions split each row's *own* visible span on the device (P = 32), not the context limit.
Alone it was slower (11.5 ms: fewer active work-groups), which showed the real cost.
- bf16 cache rows read 16 bytes at a time (keys for the lane's dot, values for the lane's 8 dims):
**4.67 ms/step**. P = 64: 4.81, P = 128: 7.46 -- kept 32.
- rad-kbench 138/138, 132/132; KL mean 5.7e-4, p99 3.1e-3, top-1 98.6%.
- **Decode 55 tok/s short context, 49.2 tok/s after a 1797-token prompt (was 29.8); that prefill
1.62 s = 1109 tok/s (was 4.61 s).** Device time a 1.8k-context step 23.4 ms (profiled):
gemm_nt 9.7, attn 4.7, rmsnorm_quant_fp8 3.8.
## Phase 4, step 6 (2026-10-23): the decode GEMV, and what GRIMOIRE suggested
Per-shape times from `rad-kbench -m ... --timing-only --op gemm_nt --report FILE` (cold weights),
M = 1, MiniCPM5-2B: gate_up N=12288 K=2048 93.3 us (540 GB/s), down N=2048 K=6144 59.7 (420),
qkv N=2560 K=2048 21.0, o N=2048 K=2048 18.1. A plain read kernel reaches ~600 GB/s with
incompressible data (1042 GB/s on a memset buffer: the card compresses).
- Two columns a sub-group (commit 7a58b31): gemm_nt 9.1 -> 8.5 ms a step at 1.8k.
- **down_proj splits K two ways inside the work-group** (partials added in chunk order through
local memory, deterministic): 59.7 -> 52.2 us. 4/8/16 ways no better; splitting the K=2048 shapes
made them slower (18.1 -> 21.6 us), so only K >= 4096 splits.
- Tried and dropped: four columns a sub-group (10.9 ms a step, fewer sub-groups), K unrolled 2/4/8
loads ahead (9.2 / 9.4 / 12.3 against 8.8 ms).
- rad-kbench 361/361, 350/350; KL (chunk 16) mean 6.0e-4; greedy against libref 7/8, the eighth a
near-tie at token 14 (" and" vs " Neptune", 0.025 nats apart here, 0.048 in libref).
- **Decode 57.3 tok/s short, 51.4 tok/s after a 1797-token prompt.**
`rad_memcpy_ranges_async` read its range list on the host (commit 10455f2); device.h has the kernel
read it, and rad-kbench's timer keeps it on the card, so `--bench` / `--timing-only` crashed. Fixed:
the list is read by a kernel. rad-kbench's timer is slow on this backend (a 4-op `-m` run 7 min:
each unit restores its inputs with a small host copy).
**GRIMOIRE** (github.com/doopeworld/GRIMOIRE, a SYCL engine for the Arc Pro B70) was read on the
user's suggestion. It is GPL-3.0 and radiance is Apache-2.0, so no code comes from it; only measured
ideas were tried:
- wide loads with several in flight, sub-group-contiguous ("vec16x4", 626 GB/s there): our GEMV
already reads 16 B a lane contiguously; more loads in flight lost (above).
- decode split-K scaled with context (their attention went 3650 -> 1197 us a layer): ours already
splits each row's visible keys 32 ways (step 5).
- low-N decode GEMVs underfilling the card: the down_proj split above.
- the decode step as a replayed SYCL command graph: not taken yet. Profiled device time (21.3 ms a
step at short context, inflated by the timing events) already exceeds wall time (17.5 ms), so the
card is not waiting on the host; a graph would only trim launch gaps. Radiance's tape hooks
(`tape_begin` / `tape_play` in device.h) are where it would go.
## Next steps
1. ~~Milestone B, part 2: `minicpm5-2b-fp8.rad`~~ **Dropped by the user (2026-10-23): "instead of the
fp8 use the one you are already using so the bf16".** Milestone B's MiniCPM5 half is the bf16
container with its DSpark drafter, done above.
2. A 19-22 GiB container: none is in the library as `.rad` (the two Swift-1.5 Qwen3.8-27B int4
checkpoints there are safetensors, not containers). Asking the user which to use / for a container.
3. Phase 4 can start now that Milestone A is correct: XMX GEMMs and a split-KV attention, each checked
against the correctness-first kernels and libref with both checks (D12).
## Next steps (previous list, kept for reference)
1. Milestone B: `minicpm5-2b-fp8.rad` (**not in the library; asked**), the DSpark drafter's ops
(fp8a8 GEMMs, `gemm_nt_q_gated`, `w2a8` head, `quant_act_i8`, `row_topk`, `dflash_select`,
`silu_mul`, non-causal attention), then a 19-22 GiB container. The 27B models at correctness-
first speed will be very slow (a serial-dot GEMM over 27B weights), so their end-to-end check may
come after the first XMX GEMM (Phase 4 order adjusted only for the big model, not for
correctness: the fast GEMM is checked against the slow one and libref first).
2. `code_runs` under SYCL from `build_target` (D4); install rules and the `oot` rebuild for
`librad_sycl.so` and libxe2.
## Notifications
`scripts/sycl/notify.sh "msg"` posts to the Discord webhook (user's request, 2026-10-23): used for
blockers, questions and milestones. Tested: posted.
## HIP compile check
2026-10-23, commit `370a906` (the SYCL backend, every core-side change): built in docker,
`rocm/dev-ubuntu-24.04:10.1.0-full` (HIP 7.16, AMD clang 24.0.0git, the Dockerfile's base with its
stock compiler rather than the Dockerfile's patched LLVM), `cmake -DRAD_WITH_HIP=ON
-DRAD_GPU_TARGETS=gfx1201`, g++-14: **785/785 targets, 0 errors**, libr4d included. Later commits add
only libxe2 and sycl/, which a HIP build does not compile. Re-run after any core change:
```sh
git worktree add --detach /tmp/hipsrc HEAD
docker run --rm -v /tmp/hipsrc:/src:ro rocm/dev-ubuntu-24.04:10.1.0-full bash -c '
apt-get update -qq && apt-get install -y -qq --no-install-recommends cmake ninja-build pkg-config g++-14 gawk
export CC=gcc-14 CXX=g++-14 ROCM_PATH=/opt/rocm HIP_PATH=/opt/rocm
cmake -S /src -B /build -G Ninja -DRAD_WITH_HIP=ON -DRAD_GPU_TARGETS=gfx1201 && cmake --build /build -j6'
git worktree remove --force /tmp/hipsrc
```
## Reproduce the current state
```sh
. /opt/intel/oneapi/setvars.sh
./build.sh --sycl # build-sycl/: configure, build, fast tests
ctest --test-dir build-sycl -L '^sycl$' --output-on-failure # the card tests (B65)
ctest --test-dir build-sycl -LE 'gpu|oot' -j8 # host tier in the SYCL build
scripts/sycl/probe.sh # Phase 0 device tables
scripts/sycl/op_inventory.sh # SYCL_PORTING.md Appendix A
# the tiny llama containers and their graphs (Phase 1, SYCL_PORTING.md §3.1):
mkdir -p "$T/tmp" && env RADIANCE_HOME=$PWD/build/radiance_home RAD_TEST_TMPDIR=$T/tmp \
ROCR_VISIBLE_DEVICES=99 RAD_E2E_KEEP=1 build/tests/engine_e2e_test -perf_
# -> $T/tmp/radiance_e2e.*/{llama,llama_int4}/ checkpoints and llama*.rad containers
build/bin/rad-convert $D/llama -o $D/llama_bf16.rad # the bf16 analogue (no recipe)
build/bin/radiance --model $D/llama_bf16.rad --debug-graph
build/bin/radiance --model $D/llama.rad --kv-cache-dtype fp8 --debug-graph
./build.sh --no-hip # host backend + fast tests
ctest --test-dir build -LE 'gpu|oot' # host baseline
```
+38
View File
@@ -0,0 +1,38 @@
# libxe2 -- radiance's kernel library for Intel Xe2 GPUs (Battlemage; the Arc Pro B65), in SYCL.
# docs/SYCL_PORTING.md has the design, docs/SYCL_PROGRESS.md the state.
#
# Links radiance::abi and the SYCL runtime, nothing of radiance's. Built by icpx: in radiance's tree
# through the sycl/ sub-build, or standalone against an installed radiance:
# cmake -S libxe2 -B build -DCMAKE_CXX_COMPILER=icpx -DCMAKE_PREFIX_PATH=<radiance prefix>
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(libxe2 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
message(FATAL_ERROR "libxe2 is SYCL and needs icpx (-DCMAKE_CXX_COMPILER=icpx); this configure "
"has ${CMAKE_CXX_COMPILER_ID}.")
endif()
if(NOT RAD_SYCL_TARGETS)
set(RAD_SYCL_TARGETS "intel_gpu_bmg_g31")
endif()
file(GLOB XE2_SRC CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
rad_add_plugin(libxe2 kernels SOURCES ${XE2_SRC})
# -ffp-contract=off is a correctness flag here as in libref: kernels are checked against it, so
# `a*b + c` rounds twice on both sides. It follows -ffp-model=precise, which would otherwise set
# contraction back on. -foffload-fp32-prec-div and -sqrt make device division and sqrt correctly
# rounded, as libref's are: a quantiser's scale is amax * (1/top), and a 1/top one ulp off moves
# codes that sit exactly on an E4M3 rounding tie, which bf16 inputs hit often.
# Device code is generated at link time (AOT), so every flag that shapes it goes to the link too;
# on the compile line alone it changes nothing on the card.
set(_xe2_sycl -fsycl "-fsycl-targets=${RAD_SYCL_TARGETS}" -ffp-model=precise -ffp-contract=off
-Wno-overriding-option -foffload-fp32-prec-div -foffload-fp32-prec-sqrt)
target_compile_options(libxe2 PRIVATE ${_xe2_sycl} -fvisibility=hidden)
get_filename_component(_xe2_icpx_bin "${CMAKE_CXX_COMPILER}" DIRECTORY)
get_filename_component(_xe2_oneapi_lib "${_xe2_icpx_bin}/../lib" ABSOLUTE)
target_link_options(libxe2 PRIVATE ${_xe2_sycl} "LINKER:-rpath,${_xe2_oneapi_lib}"
"LINKER:--no-undefined")
+266
View File
@@ -0,0 +1,266 @@
/* xe2_attn.cpp -- the paged KV cache: kv_store writes a step's keys and values, attn_paged reads
* them. The layout is libref's (ref_attn.cpp) and libr4d's:
*
* kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K then V inside a slot
*
* read through the cache tensor's own strides when it is rank 4.
*
* attn_paged, correctness first: one work-group a (query row, head), computing libref's arithmetic
* in libref's order, so the result is the reference's:
* pass 1 lanes take keys; each key's dot q . (k * k_descale) is summed over d serially by its
* lane, scaled, and the group takes the max;
* pass 2 keys in chunks of kChunk: lanes compute w_j = exp(s_j - max) (in double, as libref's
* ref_exp) into local memory, lane 0 adds them to the sum in key order, and lane d adds
* w_j * (v_j[d] * v_descale) to acc[d] in key order.
* Scores are recomputed in pass 2 rather than kept: 131072 keys of them do not fit local memory.
* The mask, the zero row for no visible key, ragged batches (cu_seqlens) and sliding windows are
* libref's. The fast kernels (split-KV decode, XMX prefill) are Phase 4's.
*
* kv_store skips a slot past the cache (libref refuses the whole launch after reading every slot
* on the host, which a device launch cannot do without waiting) and a negative slot (libref's
* padding rule). An fp8 cache stores k / k_scale and v / v_scale, as libref.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include <cmath>
namespace xe2 {
namespace {
int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
return t->stride[t->rank - 2];
}
struct KVView {
int64_t sb, sh, so, sd; /* strides: block, kv head, slot offset, element */
};
KVView kv_view(const RadTensor* c, int64_t head_dim, int64_t block_size, int64_t kv_heads) {
KVView v{};
if (c->rank == 4) {
v.sb = c->stride[0]; v.sh = c->stride[1]; v.so = c->stride[2]; v.sd = c->stride[3];
} else {
v.sd = 1;
v.so = 2 * head_dim;
v.sh = block_size * v.so;
v.sb = kv_heads * v.sh;
}
return v;
}
constexpr int kMaxHd = 512;
constexpr int kChunk = 256;
} // namespace
/* ------------------------------------------------------------------ kv_store */
int kv_store(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *K = &a->t[0], *V = &a->t[1], *SM = &a->t[2], *KV = &a->t[3];
const int64_t head_dim = rad_args_geti_or(a, "head_dim", K->rank >= 3 ? K->shape[K->rank - 1] : 0);
const int64_t block_size = rad_args_geti_or(a, "block_size", 0);
const int64_t kv_heads = rad_args_geti_or(a, "n_head_kv", KV->rank == 4 ? KV->shape[1] : 0);
if (head_dim <= 0 || block_size <= 0 || kv_heads <= 0) return RAD_E_SHAPE;
if (KV->rank == 4 && (KV->shape[1] != kv_heads || KV->shape[2] != block_size ||
KV->shape[3] < 2 * head_dim)) return RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(SM);
if (M <= 0 || rad_tensor_numel(K) < M * kv_heads * head_dim) return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(SM)) return refuse("kv_store: slot_mapping not contiguous");
const int64_t n_blocks = KV->rank == 4 ? KV->shape[0] : 0;
const int64_t k_ds = K->rank >= 2 ? K->stride[K->rank - 1] : 1;
const int64_t k_hs = K->rank >= 3 ? K->stride[K->rank - 2] : head_dim * k_ds;
const int64_t k_rs = row_stride(K, kv_heads * head_dim);
const int64_t v_ds = V->rank >= 2 ? V->stride[V->rank - 1] : 1;
const int64_t v_hs = V->rank >= 3 ? V->stride[V->rank - 2] : head_dim * v_ds;
const int64_t v_rs = row_stride(V, kv_heads * head_dim);
const KVView kvv = kv_view(KV, head_dim, block_size, kv_heads);
const bool fp8 = KV->dtype == RAD_F8E4M3 || KV->dtype == RAD_F8E5M2;
const float ks = fp8 ? 1.0f / (float)rad_args_getf_or(a, "k_scale", 1.0) : 1.0f;
const float vs = fp8 ? 1.0f / (float)rad_args_getf_or(a, "v_scale", 1.0) : 1.0f;
const char *kb = (const char*)K->data, *vb = (const char*)V->data, *sb = (const char*)SM->data;
char* cb = (char*)KV->data;
const uint32_t kdt = K->dtype, vdt = V->dtype, sdt = SM->dtype, cdt = KV->dtype;
const int64_t per_tok = kv_heads * head_dim;
const int64_t total = M * per_tok;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t wg = 128;
const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t g = (int64_t)it.get_global_id(0);
if (g >= total) return;
const int64_t t = g / per_tok, h = (g / head_dim) % kv_heads, d = g % head_dim;
const int64_t slot = ld_index(sdt, sb, t);
if (slot < 0) return;
const int64_t blk = slot / block_size, off = slot % block_size;
if (n_blocks > 0 && blk >= n_blocks) return;
const int64_t c = blk * kvv.sb + h * kvv.sh + off * kvv.so;
rad_store_f32(cb, cdt, c + d * kvv.sd,
rad_load_f32(kb, kdt, t * k_rs + h * k_hs + d * k_ds) * ks);
rad_store_f32(cb, cdt, c + (head_dim + d) * kvv.sd,
rad_load_f32(vb, vdt, t * v_rs + h * v_hs + d * v_ds) * vs);
});
});
}
/* ------------------------------------------------------------------ attn_paged */
int attn_paged(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 8) return RAD_E_INVAL;
const RadTensor *Q = &a->t[0], *KV = &a->t[1], *BT = &a->t[2], *SU = &a->t[3], *O = &a->t[7];
const RadTensor* KD = rad_arg_in(a, 4);
const RadTensor* VD = rad_arg_in(a, 5);
const RadTensor* CU = rad_arg_in(a, 6);
if (!Q->data || !KV->data || !BT->data || !SU->data || !O->data) return RAD_E_INVAL;
const int64_t head_dim = rad_args_geti_or(a, "head_dim", Q->rank >= 3 ? Q->shape[Q->rank - 1] : 0);
const int64_t gqa = rad_args_geti_or(a, "gqa", 1);
const int64_t block_size = rad_args_geti_or(a, "block_size", KV->rank == 4 ? KV->shape[2] : 0);
const int causal = (int)rad_args_geti_or(a, "causal", 1);
const int64_t window = rad_args_geti_or(a, "window", 0);
if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE;
if (head_dim > kMaxHd) return refuse("attn_paged: head_dim %lld over %d", (long long)head_dim, kMaxHd);
const int64_t kv_heads = KV->rank == 4 ? KV->shape[1] : 0;
if (kv_heads <= 0) return RAD_E_SHAPE;
const int64_t q_heads = gqa * kv_heads;
if (Q->rank >= 3 && Q->shape[Q->rank - 2] != q_heads) return RAD_E_SHAPE;
const int64_t n_seq = rad_tensor_numel(SU);
const int64_t rows = rad_tensor_numel(Q) / (q_heads * head_dim);
if (n_seq <= 0 || rows <= 0) return RAD_E_SHAPE;
if (!CU && rows % n_seq != 0) return RAD_E_SHAPE;
if (CU && rad_tensor_numel(CU) != n_seq + 1) return RAD_E_SHAPE;
const int64_t q_len_all = CU ? 0 : rows / n_seq;
if (rad_tensor_numel(O) < rows * q_heads * head_dim) return RAD_E_SHAPE;
if (KV->rank == 4 && KV->shape[2] != block_size) return RAD_E_SHAPE;
if (KV->rank == 4 && KV->shape[3] < 2 * head_dim) return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(SU) || (CU && !rad_tensor_is_contiguous(CU)))
return refuse("attn_paged: seqused / cu_seqlens not contiguous");
if ((KD && !rad_tensor_is_contiguous(KD)) || (VD && !rad_tensor_is_contiguous(VD)))
return refuse("attn_paged: descales not contiguous");
const int64_t max_blocks = BT->rank >= 2 ? BT->shape[BT->rank - 1] : rad_tensor_numel(BT) / n_seq;
const int64_t bt_rs = BT->rank >= 2 ? BT->stride[BT->rank - 2] : max_blocks;
const int64_t bt_cs = BT->rank >= 2 ? BT->stride[BT->rank - 1] : 1;
const KVView kvv = kv_view(KV, head_dim, block_size, kv_heads);
const int64_t q_ds = Q->rank >= 2 ? Q->stride[Q->rank - 1] : 1;
const int64_t q_hs = Q->rank >= 3 ? Q->stride[Q->rank - 2] : head_dim * q_ds;
const int64_t q_rs = row_stride(Q, q_heads * head_dim);
const int64_t o_ds = O->rank >= 2 ? O->stride[O->rank - 1] : 1;
const int64_t o_hs = O->rank >= 3 ? O->stride[O->rank - 2] : head_dim * o_ds;
const int64_t o_rs = row_stride(O, q_heads * head_dim);
/* libref's default, 1 / sqrt(head_dim) in f32. */
const float scale_f =
(float)rad_args_getf_or(a, "scale", (double)(1.0f / std::sqrt((float)head_dim)));
const int64_t jcap = max_blocks * block_size;
const char *qb = (const char*)Q->data, *cb = (const char*)KV->data, *btb = (const char*)BT->data;
const char *sub = (const char*)SU->data, *cub = CU ? (const char*)CU->data : nullptr;
const char *kdb = KD ? (const char*)KD->data : nullptr, *vdb = VD ? (const char*)VD->data : nullptr;
char* ob = (char*)O->data;
const uint32_t qdt = Q->dtype, cdt = KV->dtype, btdt = BT->dtype, sudt = SU->dtype;
const uint32_t cudt = CU ? CU->dtype : 0, kddt = KD ? KD->dtype : 0, vddt = VD ? VD->dtype : 0;
const uint32_t odt = O->dtype;
const int64_t total = rows * q_heads;
const size_t wg = (size_t)((head_dim + 15) / 16 * 16) < 64 ? 64 : (size_t)((head_dim + 15) / 16 * 16);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return submit([&] {
q->submit([&](sycl::handler& h) {
sycl::local_accessor<float, 1> qf(sycl::range<1>(kMaxHd), h);
sycl::local_accessor<float, 1> wv(sycl::range<1>(kChunk), h);
sycl::local_accessor<int64_t, 1> kbv(sycl::range<1>(kChunk), h);
h.parallel_for(sycl::nd_range<1>{(size_t)total * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t idx = (int64_t)it.get_group(0);
const int lane = (int)it.get_local_id(0);
const auto grp = it.get_group();
const int64_t hq = idx % q_heads, tok = idx / q_heads;
int64_t s = 0, qlen = q_len_all, i = 0;
if (cub) {
while (s + 1 < n_seq && ld_index(cudt, cub, s + 1) <= tok) ++s;
qlen = ld_index(cudt, cub, s + 1) - ld_index(cudt, cub, s);
i = tok - ld_index(cudt, cub, s);
} else {
s = tok / q_len_all;
i = tok - s * q_len_all;
}
if (qlen <= 0) return; /* uniform across the group */
const int64_t kh = hq / gqa;
const int64_t ctx = ld_index(sudt, sub, s);
const int64_t pos = ctx - qlen + i;
const int64_t qoff = tok * q_rs + hq * q_hs;
const int64_t ooff = tok * o_rs + hq * o_hs;
const float kds = kdb ? rad_load_f32(kdb, kddt, s * kv_heads + kh) : 1.0f;
const float vds = vdb ? rad_load_f32(vdb, vddt, s * kv_heads + kh) : 1.0f;
const int64_t jend = sycl::min(ctx, jcap);
auto key_at = [&](int64_t j) -> int64_t {
if (causal && j > pos) return -1;
if (window > 0) {
const int64_t d = pos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) return -1;
}
const int64_t blk = ld_index(btdt, btb, s * bt_rs + (j / block_size) * bt_cs);
return blk < 0 ? -1 : blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so;
};
auto score = [&](int64_t kb) {
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d)
dot += qf[d] * (rad_load_f32(cb, cdt, kb + d * kvv.sd) * kds);
return dot * scale_f;
};
for (int64_t d = lane; d < head_dim; d += (int64_t)wg)
qf[d] = rad_load_f32(qb, qdt, qoff + d * q_ds);
sycl::group_barrier(grp);
/* Pass 1: the max score. */
float mx = -INFINITY;
for (int64_t j = lane; j < jend; j += (int64_t)wg) {
const int64_t kb = key_at(j);
if (kb >= 0) mx = sycl::fmax(mx, score(kb));
}
mx = sycl::reduce_over_group(grp, mx, sycl::maximum<float>());
if (mx == -INFINITY) {
for (int64_t d = lane; d < head_dim; d += (int64_t)wg)
rad_store_f32(ob, odt, ooff + d * o_ds, 0.0f);
return;
}
/* Pass 2: weights by chunk, the sum and acc[d] in key order. */
float acc = 0.0f; /* acc[lane], lanes past head_dim idle */
float sum = 0.0f; /* lane 0's */
for (int64_t c0 = 0; c0 < jend; c0 += kChunk) {
const int64_t cn = sycl::min((int64_t)kChunk, jend - c0);
for (int64_t jj = lane; jj < cn; jj += (int64_t)wg) {
const int64_t kb = key_at(c0 + jj);
kbv[jj] = kb;
wv[jj] = kb >= 0 ? (float)sycl::exp((double)(score(kb) - mx)) : 0.0f;
}
sycl::group_barrier(grp);
if (lane == 0)
for (int64_t jj = 0; jj < cn; ++jj)
if (kbv[jj] >= 0) sum += wv[jj];
if (lane < head_dim)
for (int64_t jj = 0; jj < cn; ++jj) {
const int64_t kb = kbv[jj];
if (kb < 0) continue;
acc += wv[jj] * (rad_load_f32(cb, cdt, kb + (head_dim + lane) * kvv.sd) * vds);
}
sycl::group_barrier(grp);
}
sum = sycl::group_broadcast(grp, sum, 0);
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
if (lane < head_dim) rad_store_f32(ob, odt, ooff + lane * o_ds, acc * inv);
});
});
});
}
} // namespace xe2
+279
View File
@@ -0,0 +1,279 @@
/* xe2_attn_fast.cpp -- Phase 4's paged attention: split-KV with an online softmax ("flash
* decoding"), a kv head's keys read once for all its query heads.
*
* Pass 1: a work-group a (query row, kv head, key partition). Its sub-groups are the kv head's
* query heads (sub-group s takes heads s, s + 8, ...); each walks the partition's visible keys
* sixteen at a time, one key a lane: the lane scores its key in full against the query in local
* memory (q . (k * k_descale), scaled), one max and one sum over the sub-group update the flash
* state (max m, sum l), and the lanes -- which split head_dim for the value rows -- add each key's
* value row weighted by that key's exp(s - m), taken from its lane. Per key that is no reduction and
* no exp on the lanes that do not own it (the first version reduced and exponentiated once a key on
* every lane, 27% of a 1.8k-context decode step). The eight query heads read the same key and value
* rows, so the bytes come from memory once a work-group.
*
* The partition count P is chosen at launch from the rows: a decode step (one row, a few heads)
* splits each row's visible keys evenly 32 ways, on the device from the row's own context, so the
* whole card works on one token; a prefill step has parallelism in its rows and takes P = 1. With P > 1 each partition's state goes
* to scratch (64 MiB, the `scratch` hook) and pass 2 -- a sub-group a (row, query head) -- merges
* them; with P = 1 pass 1 writes the normalised output itself.
*
* Same mask, window, ragged batches (cu_seqlens), fp8 descales and zero row for no visible key as
* libref's attn_paged and xe2_attn_paged_ref. Not libref's order: held to rad-kbench's attention
* tolerance and the KL bound (D13). XE2_EXACT=1, a head_dim that is not a multiple of 16 up to 256,
* or a rank-3 cache, sends the launch to xe2_attn_paged_ref.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include <cmath>
namespace xe2 {
namespace {
constexpr int kSgs = 8;
constexpr size_t kWg = kSgs * kSub;
constexpr int kMaxPer = 16; /* head_dim / 16, up to head_dim 256 */
constexpr int64_t kScratch = (int64_t)64 << 20; /* pass 1's partial states */
constexpr int64_t kMaxParts = 32; /* a row's visible keys split this many ways at most */
int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
return t->stride[t->rank - 2];
}
} // namespace
int64_t attn_paged_scratch(const RadArgs*) { return kScratch; }
int attn_paged_fast(const RadArgs* a, RadStream st) {
if (exact_only()) return attn_paged(a, st);
if (!a || a->n_t < 8) return RAD_E_INVAL;
const RadTensor *Q = &a->t[0], *KV = &a->t[1], *BT = &a->t[2], *SU = &a->t[3], *O = &a->t[7];
const RadTensor* KD = rad_arg_in(a, 4);
const RadTensor* VD = rad_arg_in(a, 5);
const RadTensor* CU = rad_arg_in(a, 6);
if (!Q->data || !KV->data || !BT->data || !SU->data || !O->data) return RAD_E_INVAL;
const int64_t head_dim = rad_args_geti_or(a, "head_dim", Q->rank >= 3 ? Q->shape[Q->rank - 1] : 0);
if (head_dim <= 0 || head_dim % kSub || head_dim / kSub > kMaxPer || KV->rank != 4)
return attn_paged(a, st);
const int64_t gqa = rad_args_geti_or(a, "gqa", 1);
const int64_t block_size = rad_args_geti_or(a, "block_size", KV->shape[2]);
const int causal = (int)rad_args_geti_or(a, "causal", 1);
const int64_t window = rad_args_geti_or(a, "window", 0);
if (gqa <= 0 || block_size <= 0) return RAD_E_SHAPE;
const int64_t kv_heads = KV->shape[1];
if (kv_heads <= 0) return RAD_E_SHAPE;
const int64_t q_heads = gqa * kv_heads;
if (Q->rank >= 3 && Q->shape[Q->rank - 2] != q_heads) return RAD_E_SHAPE;
const int64_t n_seq = rad_tensor_numel(SU);
const int64_t rows = rad_tensor_numel(Q) / (q_heads * head_dim);
if (n_seq <= 0 || rows <= 0) return RAD_E_SHAPE;
if (!CU && rows % n_seq != 0) return RAD_E_SHAPE;
if (CU && rad_tensor_numel(CU) != n_seq + 1) return RAD_E_SHAPE;
const int64_t q_len_all = CU ? 0 : rows / n_seq;
if (rad_tensor_numel(O) < rows * q_heads * head_dim) return RAD_E_SHAPE;
if (KV->shape[2] != block_size || KV->shape[3] < 2 * head_dim) return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(SU) || (CU && !rad_tensor_is_contiguous(CU)) ||
(KD && !rad_tensor_is_contiguous(KD)) || (VD && !rad_tensor_is_contiguous(VD)))
return attn_paged(a, st);
const int64_t max_blocks = BT->rank >= 2 ? BT->shape[BT->rank - 1] : rad_tensor_numel(BT) / n_seq;
const int64_t bt_rs = BT->rank >= 2 ? BT->stride[BT->rank - 2] : max_blocks;
const int64_t bt_cs = BT->rank >= 2 ? BT->stride[BT->rank - 1] : 1;
const int64_t sb = KV->stride[0], sh = KV->stride[1], so = KV->stride[2], sd = KV->stride[3];
const int64_t q_ds = Q->rank >= 2 ? Q->stride[Q->rank - 1] : 1;
const int64_t q_hs = Q->rank >= 3 ? Q->stride[Q->rank - 2] : head_dim * q_ds;
const int64_t q_rs = row_stride(Q, q_heads * head_dim);
const int64_t o_ds = O->rank >= 2 ? O->stride[O->rank - 1] : 1;
const int64_t o_hs = O->rank >= 3 ? O->stride[O->rank - 2] : head_dim * o_ds;
const int64_t o_rs = row_stride(O, q_heads * head_dim);
const float scale = (float)rad_args_getf_or(a, "scale", (double)(1.0f / std::sqrt((float)head_dim)));
const int64_t jcap = max_blocks * block_size;
const int per = (int)(head_dim / kSub);
/* bf16 cache rows read 16 bytes at a time when every row start is 16-byte aligned. */
const bool vec_kv = KV->dtype == RAD_BF16 && sd == 1 && head_dim % 8 == 0 && sb % 8 == 0 &&
sh % 8 == 0 && so % 8 == 0 && rad_ptr_aligned(KV->data, 16);
/* The partitions: as many as the scratch holds for these rows, at most kMaxParts. Each row's
* own visible span is split evenly on the device, so every partition has keys whatever the
* context limit (splitting the limit instead left most partitions empty at a short context and
* the merge walking all of them). */
const int64_t state = 2 + head_dim; /* floats a partial state: m, l, acc[head_dim] */
int64_t P = 1;
if (a->scratch && a->scratch_bytes > 0) {
const int64_t fit = a->scratch_bytes / (rows * q_heads * state * (int64_t)sizeof(float));
P = sycl::min(fit, kMaxParts);
if (P < 1) P = 1;
}
float* part = (float*)a->scratch;
const char *qb = (const char*)Q->data, *cb = (const char*)KV->data, *btb = (const char*)BT->data;
const char *sub = (const char*)SU->data, *cub = CU ? (const char*)CU->data : nullptr;
const char *kdb = KD ? (const char*)KD->data : nullptr, *vdb = VD ? (const char*)VD->data : nullptr;
char* ob = (char*)O->data;
const uint32_t qdt = Q->dtype, cdt = KV->dtype, btdt = BT->dtype, sudt = SU->dtype;
const uint32_t cudt = CU ? CU->dtype : 0, kddt = KD ? KD->dtype : 0, vddt = VD ? VD->dtype : 0;
const uint32_t odt = O->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
int rc = submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)(rows * kv_heads * P) * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t g = (int64_t)it.get_group(0);
const int64_t p = g % P, kh = (g / P) % kv_heads, tok = g / (P * kv_heads);
float* qloc = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kSgs * kSub * kMaxPer]>(
it.get_group());
const sycl::sub_group sg = it.get_sub_group();
const int s = (int)sg.get_group_linear_id();
const int lane = (int)sg.get_local_linear_id();
int64_t sq = 0, qlen = q_len_all, i = 0;
if (cub) {
while (sq + 1 < n_seq && ld_index(cudt, cub, sq + 1) <= tok) ++sq;
qlen = ld_index(cudt, cub, sq + 1) - ld_index(cudt, cub, sq);
i = tok - ld_index(cudt, cub, sq);
} else {
sq = tok / q_len_all;
i = tok - sq * q_len_all;
}
if (qlen <= 0) return;
const int64_t ctx = ld_index(sudt, sub, sq);
const int64_t pos = ctx - qlen + i;
const float kds = kdb ? rad_load_f32(kdb, kddt, sq * kv_heads + kh) : 1.0f;
const float vds = vdb ? rad_load_f32(vdb, vddt, sq * kv_heads + kh) : 1.0f;
const int64_t jend = sycl::min(ctx, jcap);
int64_t jlo = 0, jhi = causal ? sycl::min(jend, pos + 1) : jend;
if (window > 0) {
jlo = sycl::max((int64_t)0, pos - window + 1);
if (!causal) jhi = sycl::min(jend, pos + window);
}
if (P > 1) {
const int64_t span = sycl::max(jhi - jlo, (int64_t)0);
const int64_t ch = (span + P - 1) / P;
jlo += p * ch;
jhi = sycl::min(jhi, jlo + ch);
}
for (int64_t hl = s; hl < gqa; hl += kSgs) {
const int64_t hq = kh * gqa + hl;
const int64_t qoff = tok * q_rs + hq * q_hs;
float qv[kMaxPer], acc[kMaxPer];
for (int e = 0; e < kMaxPer; ++e) {
qv[e] = e < per ? rad_load_f32(qb, qdt, qoff + (lane * per + e) * q_ds) : 0.0f;
acc[e] = 0.0f;
}
/* The query in local memory, so a lane can score a whole key by itself. */
float* qs = qloc + (size_t)s * kSub * kMaxPer;
for (int e = 0; e < per; ++e) qs[lane * per + e] = qv[e];
sycl::group_barrier(sg);
float m = -INFINITY, l = 0.0f;
/* Sixteen keys a step, one a lane: the lane's own dot, then one max and one sum
* over the sub-group, and the value rows accumulated with each key's weight taken
* from its lane. */
for (int64_t j0 = jlo; j0 < jhi; j0 += kSub) {
const int64_t j = j0 + lane;
int64_t kb = -1;
float sc = -INFINITY;
if (j < jhi) {
const int64_t blk = ld_index(btdt, btb, sq * bt_rs + (j / block_size) * bt_cs);
if (blk >= 0) {
kb = blk * sb + kh * sh + (j % block_size) * so;
float dot = 0.0f;
if (vec_kv) {
/* A bf16 key row, 16 bytes at a time. */
const uint16_t* kr = (const uint16_t*)cb + kb;
for (int64_t d = 0; d < head_dim; d += 8) {
const sycl::vec<uint16_t, 8> kk = *(const sycl::vec<uint16_t, 8>*)(kr + d);
for (int u = 0; u < 8; ++u)
dot += qs[d + u] * (rad_bf16_to_f32(kk[u]) * kds);
}
} else {
for (int64_t d = 0; d < head_dim; ++d)
dot += qs[d] * (rad_load_f32(cb, cdt, kb + d * sd) * kds);
}
sc = dot * scale;
}
}
const float bm = sycl::reduce_over_group(sg, sc, sycl::maximum<float>());
if (bm == -INFINITY) continue; /* uniform: no visible key in this step */
const float mn = sycl::fmax(m, bm);
const float corr = sycl::exp(m - mn);
const float w = kb >= 0 ? sycl::exp(sc - mn) : 0.0f;
l = l * corr + sycl::reduce_over_group(sg, w, sycl::plus<float>());
for (int e = 0; e < per; ++e) acc[e] *= corr;
for (int jj = 0; jj < kSub; ++jj) {
const int64_t kbj = sycl::select_from_group(sg, kb, jj);
if (kbj < 0) continue; /* uniform */
const float wj = sycl::select_from_group(sg, w, jj);
if (vec_kv && per == 8) {
const sycl::vec<uint16_t, 8> vv = *(const sycl::vec<uint16_t, 8>*)(
(const uint16_t*)cb + kbj + head_dim + lane * 8);
for (int e = 0; e < 8; ++e) acc[e] += wj * (rad_bf16_to_f32(vv[e]) * vds);
} else {
for (int e = 0; e < per; ++e)
acc[e] += wj * (rad_load_f32(cb, cdt, kbj + (head_dim + lane * per + e) * sd) * vds);
}
}
m = mn;
}
sycl::group_barrier(sg);
if (P == 1) {
const int64_t ooff = tok * o_rs + hq * o_hs;
const float inv = l > 0.0f ? 1.0f / l : 0.0f; /* no visible key: zero row */
for (int e = 0; e < per; ++e)
rad_store_f32(ob, odt, ooff + (lane * per + e) * o_ds, acc[e] * inv);
} else {
float* ps = part + ((tok * q_heads + hq) * P + p) * state;
if (lane == 0) {
ps[0] = m;
ps[1] = l;
}
for (int e = 0; e < per; ++e) ps[2 + lane * per + e] = acc[e];
}
}
});
});
if (rc < 0 || P == 1) return rc;
/* Pass 2: merge the partitions of each (row, query head). */
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)(rows * q_heads) * kSub, (size_t)kSub},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t g = (int64_t)it.get_group(0);
const int64_t hq = g % q_heads, tok = g / q_heads;
const int lane = (int)it.get_local_id(0);
int64_t sq = 0, qlen = q_len_all;
if (cub) {
while (sq + 1 < n_seq && ld_index(cudt, cub, sq + 1) <= tok) ++sq;
qlen = ld_index(cudt, cub, sq + 1) - ld_index(cudt, cub, sq);
}
if (qlen <= 0) return;
const float* ps = part + (tok * q_heads + hq) * P * state;
float M = -INFINITY;
for (int64_t p = 0; p < P; ++p)
if (ps[p * state + 1] > 0.0f) M = sycl::fmax(M, ps[p * state]);
const int64_t ooff = tok * o_rs + hq * o_hs;
float L = 0.0f, out[kMaxPer];
for (int e = 0; e < kMaxPer; ++e) out[e] = 0.0f;
if (M != -INFINITY)
for (int64_t p = 0; p < P; ++p) {
const float* q0 = ps + p * state;
if (!(q0[1] > 0.0f)) continue; /* an empty partition */
const float f = sycl::exp(q0[0] - M);
L += q0[1] * f;
for (int e = 0; e < per; ++e) out[e] += q0[2 + lane * per + e] * f;
}
const float inv = L > 0.0f ? 1.0f / L : 0.0f;
for (int e = 0; e < per; ++e)
rad_store_f32(ob, odt, ooff + (lane * per + e) * o_ds, out[e] * inv);
});
});
}
} // namespace xe2
+57
View File
@@ -0,0 +1,57 @@
/* xe2_common.cpp -- the shared helpers of xe2_common.h. */
#include "xe2_common.h"
#include <cstdarg>
namespace xe2 {
namespace {
thread_local char t_refusal[512] = "";
}
const char* last_refusal() { return t_refusal; }
int refuse(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
std::vsnprintf(t_refusal, sizeof t_refusal, fmt, ap);
va_end(ap);
std::fprintf(stderr, "libxe2: %s\n", t_refusal);
return RAD_E_UNSUPPORTED;
}
sycl::queue* queue_of(RadStream s) {
sycl::queue* q = rad_sycl_queue(s);
if (!q) refuse("the stream is not a SYCL stream of version %u (another backend?)",
RAD_SYCL_STREAM_VERSION);
return q;
}
int rows_view(const RadTensor* t, int64_t n, Rows* out, const char* what) {
if (!t || !t->data || n <= 0) return refuse("%s: missing operand or n <= 0", what);
out->base = (char*)t->data;
out->dtype = t->dtype;
out->rows = rad_tensor_numel(t) / n;
if (t->rank >= 2 && t->shape[t->rank - 1] == n) {
if (t->stride[t->rank - 1] != 1) return refuse("%s: last-axis stride %lld, not 1", what,
(long long)t->stride[t->rank - 1]);
/* Every leading axis must step by the one below it times its extent, so a row index maps
* to one pitch (libref's rowoff walks them; here they must agree). */
const int64_t pitch = t->stride[t->rank - 2];
int64_t span = pitch;
for (int i = (int)t->rank - 3; i >= 0; --i) {
span *= t->shape[i + 1];
if (t->shape[i] != 1 && t->stride[i] != span)
return refuse("%s: leading axes do not collapse to one row pitch", what);
}
out->pitch = pitch;
return RAD_OK;
}
if (!rad_tensor_is_contiguous(t))
return refuse("%s: read as rows of %lld but neither its last extent nor contiguous", what,
(long long)n);
out->pitch = n;
return RAD_OK;
}
} // namespace xe2
+140
View File
@@ -0,0 +1,140 @@
/* xe2_common.h -- what every libxe2 kernel shares: the queue a launch submits to, row geometry,
* and the dtype conversions.
*
* Correctness first (docs/SYCL_PORTING.md §4.8): the conversions are rad_plugin.h's, the ones
* libref computes with, so a result rounds where the reference's does. Device code is compiled
* with -ffp-contract=off for the same reason (libxe2/CMakeLists.txt). A kernel that cannot serve
* the geometry it is handed returns RAD_E_UNSUPPORTED and names why through xe2_refuse; it never
* hands the work to the host.
*/
#pragma once
#include "rad_abi.h"
#include "rad_plugin.h"
#include "rad_sycl.h"
#include <sycl/sycl.hpp>
#include <cstdint>
#include <cstdio>
#include <cstring>
namespace xe2 {
namespace syclex = sycl::ext::oneapi::experimental;
/* The sub-group every libxe2 kernel is written for: Xe2's native SIMD16. */
constexpr int kSub = 16;
/* Why the last launch on this thread refused, for the engine's error report and the tests. */
const char* last_refusal();
int refuse(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
/* A row-major view of an operand read as rows of `n` elements: the base, and the element distance
* between consecutive rows. A tensor whose last axis is `n` may have padded rows, provided every
* leading axis collapses to one uniform pitch; anything else (`n` not the last extent) must be
* contiguous and is read as rows of `n`. The last axis must have stride 1. */
struct Rows {
char* base = nullptr;
int64_t pitch = 0; /* elements */
int64_t rows = 0;
uint32_t dtype = 0;
};
/* Fills `out` for `t` read as rows of `n`; RAD_E_UNSUPPORTED (with a reason) for a layout the
* kernels do not stride over. `rows` is numel / n, as libref counts them. */
int rows_view(const RadTensor* t, int64_t n, Rows* out, const char* what);
/* The queue behind a launch's stream, or null with a reason (not a SYCL stream). */
sycl::queue* queue_of(RadStream s);
/* Runs `submit`, turning a SYCL exception into RAD_E_DEVICE with its message. */
template <typename F>
int submit(F&& f) {
try {
f();
} catch (const sycl::exception& e) {
return refuse("SYCL: %s", e.what());
}
return RAD_OK;
}
/* A tensor's element addressing for kernels that walk it in logical (row-major) order: libref's
* offlin, copied by value into the kernel. Contiguous costs nothing; a strided view (the q slice of
* a fused qkv row, which `cast` copies out) decomposes the index over its axes. */
struct Lin {
char* base = nullptr;
uint32_t dtype = 0;
uint32_t rank = 0;
bool contig = true;
int64_t shape[RAD_MAX_RANK] = {};
int64_t stride[RAD_MAX_RANK] = {};
static Lin of(const RadTensor* t) {
Lin l;
l.base = (char*)t->data;
l.dtype = t->dtype;
l.rank = t->rank;
int64_t acc = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
l.shape[i] = t->shape[i];
l.stride[i] = t->stride[i];
if (t->shape[i] != 1 && t->stride[i] != acc) l.contig = false;
acc *= t->shape[i];
}
return l;
}
int64_t off(int64_t lin) const {
if (contig || rank == 0) return lin;
int64_t o = 0;
for (int i = (int)rank - 1; i >= 0; --i) {
const int64_t s = shape[i];
if (s <= 0) return 0;
o += (lin % s) * stride[i];
lin /= s;
}
return o;
}
};
/* An index or position element as libref's ld_int reads it. */
inline int64_t ld_index(uint32_t dt, const void* p, int64_t i) {
switch (dt) {
case RAD_I32: return (int64_t)((const int32_t*)p)[i];
case RAD_U32: return (int64_t)((const uint32_t*)p)[i];
case RAD_I64: return ((const int64_t*)p)[i];
case RAD_I16: return (int64_t)((const int16_t*)p)[i];
case RAD_I8: return (int64_t)((const int8_t*)p)[i];
case RAD_U8: return (int64_t)((const uint8_t*)p)[i];
default: return 0;
}
}
/* The top-k selection key (sample_topk, sample_logprobs, row_topk): the value's order-preserving
* bits above the complemented index, so the largest key is the largest value and, among equal
* values, the lowest index -- libref's topk_next. -0 is folded to +0 (libref compares floats);
* NaN is key 0, never selected. */
inline uint64_t sel_key(float v, int64_t i) {
if (sycl::isnan(v)) return 0;
if (v == 0.0f) v = 0.0f;
uint32_t b;
std::memcpy(&b, &v, 4);
const uint32_t ord = (b & 0x80000000u) ? ~b : (b | 0x80000000u);
return ((uint64_t)ord << 32) | (uint64_t)(~(uint32_t)i);
}
inline int64_t key_index(uint64_t k) { return (int64_t)(~(uint32_t)k); }
inline float key_value(uint64_t k) {
const uint32_t ord = (uint32_t)(k >> 32);
const uint32_t b = (ord & 0x80000000u) ? (ord & 0x7fffffffu) : ~ord;
float v;
std::memcpy(&v, &b, 4);
return v;
}
/* Rounds `v` through a store and load of `dt`, as libref's round_dt does. */
inline float round_dt(uint32_t dt, float v) {
uint64_t buf = 0;
rad_store_f32(&buf, dt, 0, v);
return rad_load_f32(&buf, dt, 0);
}
} // namespace xe2
+150
View File
@@ -0,0 +1,150 @@
/* xe2_draft.cpp -- the speculative drafters' selection ops.
*
* row_topk exact per-row top-R, descending, ties to the lower column (ref_moe.cpp): libref's
* topk_next R times, each a work-group reduction of the selection key
* (xe2_common.h), one work-group a row
* dflash_select the block drafter's greedy walk over its candidate lattice (ref_quant.cpp):
* score[l, c] = unary[l, c] + sum_r pred[pid][r] * hp[l][r] * succ[cand[l, c]][r],
* the best candidate (first strict maximum) becoming the next step's predecessor.
* Serial in l by nature, so one work-item a sequence, summing over r in libref's
* order; (pred * hp)[r] is recomputed per term rather than held, the same floats.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include <cmath>
#include <cstring>
namespace xe2 {
namespace {
constexpr size_t kRowWg = 1024;
}
/* ------------------------------------------------------------------ row_topk */
int row_topk(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *IDX = &a->t[1], *VAL = &a->t[2];
const RadTensor* PAIRS = rad_arg_in(a, 3);
const int64_t off = rad_args_geti_or(a, "vocab_off", 0);
const int64_t N = rad_args_geti_or(a, "N", X->rank >= 2 ? X->shape[X->rank - 1] : 0);
const int64_t R = rad_args_geti_or(a, "R", 1);
if (N <= 0 || R <= 0) return RAD_E_SHAPE;
Rows x, iv, vv;
if (int rc = rows_view(X, N, &x, "row_topk x"); rc < 0) return rc;
const int64_t M = x.rows;
if (M <= 0 || rad_tensor_numel(IDX) < M * R || rad_tensor_numel(VAL) < M * R) return RAD_E_SHAPE;
if (PAIRS && (PAIRS->dtype != RAD_F32 || rad_tensor_numel(PAIRS) < M * R * 2)) return RAD_E_SHAPE;
if (PAIRS && !rad_tensor_is_contiguous(PAIRS)) return refuse("row_topk: pairs not contiguous");
if (int rc = rows_view(IDX, R, &iv, "row_topk idx"); rc < 0) return rc;
if (int rc = rows_view(VAL, R, &vv, "row_topk val"); rc < 0) return rc;
float* pairs = PAIRS ? (float*)PAIRS->data : nullptr;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)M * kRowWg, kRowWg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0);
const int lane = (int)it.get_local_id(0);
uint64_t prev = ~(uint64_t)0;
bool more = true; /* uniform across the group */
for (int64_t r = 0; r < R; ++r) {
uint64_t best = 0;
if (more) {
for (int64_t i = lane; i < N; i += (int64_t)kRowWg) {
const uint64_t key = sel_key(rad_load_f32(x.base, x.dtype, m * x.pitch + i), i);
if (key < prev) best = sycl::max(best, key);
}
best = sycl::reduce_over_group(it.get_group(), best, sycl::maximum<uint64_t>());
}
if (lane == 0) {
const bool ok = best != 0;
const int64_t id = ok ? key_index(best) + off : -1;
const float v = ok ? key_value(best) : -INFINITY;
const int64_t io = m * iv.pitch + r;
if (iv.dtype == RAD_I64) ((int64_t*)iv.base)[io] = id;
else ((int32_t*)iv.base)[io] = (int32_t)id;
rad_store_f32(vv.base, vv.dtype, m * vv.pitch + r, v);
if (pairs) {
float* pq = pairs + (m * R + r) * 2;
const int32_t i32 = (int32_t)id;
std::memcpy(pq, &i32, sizeof i32);
pq[1] = v;
}
}
if (best == 0) more = false;
else prev = best;
}
});
});
}
/* ------------------------------------------------------------------ dflash_select */
int dflash_select(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 7) return RAD_E_INVAL;
const RadTensor *CAND = &a->t[0], *UN = &a->t[1], *ANC = &a->t[3];
const RadTensor *PRED = &a->t[4], *SUCC = &a->t[5], *OUT = &a->t[6];
const RadTensor* HP = rad_arg_in(a, 2);
if (!CAND->data || !UN->data || !ANC->data || !PRED->data || !SUCC->data || !OUT->data)
return RAD_E_INVAL;
const int64_t steps = rad_args_geti_or(a, "steps", 0);
const int64_t K = rad_args_geti_or(a, "top_k", 0);
/* libref's band_rows: the rows `cand` holds, unless that exceeds the band. */
int64_t M = 0;
if (steps > 0 && K > 0) {
const int64_t from = rad_tensor_numel(CAND) / (steps * K), band = rad_args_geti_or(a, "M", 0);
M = from <= 0 ? 0 : (band > 0 && from > band) ? 0 : from;
}
const int64_t R = rad_args_geti_or(a, "rank", PRED->rank >= 2 ? PRED->shape[PRED->rank - 1] : 0);
const int64_t nv = rad_args_geti_or(a, "n_vocab", PRED->rank >= 2 ? PRED->shape[PRED->rank - 2] : 0);
const int64_t astr = rad_args_geti_or(a, "anchor_stride", 1);
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0) return RAD_E_SHAPE;
if (rad_tensor_numel(UN) < M * steps * K) return RAD_E_SHAPE;
if (rad_tensor_numel(ANC) < (M - 1) * astr + 1 || rad_tensor_numel(OUT) < M * steps) return RAD_E_SHAPE;
if (rad_tensor_numel(PRED) < nv * R || rad_tensor_numel(SUCC) < nv * R) return RAD_E_SHAPE;
if (HP && rad_tensor_numel(HP) < M * steps * R) return RAD_E_SHAPE;
Rows cand, un, pred, succ, out, hp;
if (int rc = rows_view(CAND, K, &cand, "dflash_select cand"); rc < 0) return rc;
if (int rc = rows_view(UN, K, &un, "dflash_select unary"); rc < 0) return rc;
if (int rc = rows_view(PRED, R, &pred, "dflash_select pred"); rc < 0) return rc;
if (int rc = rows_view(SUCC, R, &succ, "dflash_select succ"); rc < 0) return rc;
if (int rc = rows_view(OUT, steps, &out, "dflash_select tokens"); rc < 0) return rc;
const bool has_hp = HP != nullptr;
if (has_hp)
if (int rc = rows_view(HP, R, &hp, "dflash_select hp"); rc < 0) return rc;
const Lin anc = Lin::of(ANC);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t wg = 16;
const size_t n = (size_t)((M + (int64_t)wg - 1) / (int64_t)wg) * wg;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{n, wg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_global_id(0);
if (m >= M) return;
int64_t pid = ld_index(anc.dtype, anc.base, anc.off(m * astr));
for (int64_t l = 0; l < steps; ++l) {
const int64_t r = m * steps + l;
const bool ok = pid >= 0 && pid < nv;
auto ax = [&](int64_t i) {
return (ok ? rad_load_f32(pred.base, pred.dtype, pid * pred.pitch + i) : 0.0f) *
(has_hp ? rad_load_f32(hp.base, hp.dtype, r * hp.pitch + i) : 1.0f);
};
int64_t best_c = 0;
float best_s = -INFINITY;
for (int64_t c = 0; c < K; ++c) {
const int64_t tok = ld_index(cand.dtype, cand.base, r * cand.pitch + c);
float sc = rad_load_f32(un.base, un.dtype, r * un.pitch + c);
if (tok >= 0 && tok < nv)
for (int64_t i = 0; i < R; ++i)
sc += ax(i) * rad_load_f32(succ.base, succ.dtype, tok * succ.pitch + i);
if (sc > best_s) { best_s = sc; best_c = c; }
}
pid = ld_index(cand.dtype, cand.base, r * cand.pitch + best_c);
const int64_t oo = m * out.pitch + l;
if (out.dtype == RAD_I64) ((int64_t*)out.base)[oo] = pid;
else ((int32_t*)out.base)[oo] = (int32_t)pid;
}
});
});
}
} // namespace xe2
+47
View File
@@ -0,0 +1,47 @@
/* xe2_elementwise.cpp -- elementwise ops, one work-item an element.
*
* add: y = a + b, b broadcast along rows when it holds one row (a bias add), and with `div`,
* y = rd(rd(a + b) / div), rd being y's dtype: libref's elementwise2 (ref_elementwise.cpp).
*/
#include "xe2_common.h"
#include "xe2_ops.h"
namespace xe2 {
int add(const RadArgs* a, RadStream s) {
if (!rad_args_have(a, 3)) return refuse("add: missing operand");
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
const int64_t n = rad_args_geti_or(a, "n", rad_tensor_numel(Y));
const float div = (float)rad_args_getf_or(a, "div", 1.0);
if (!(div != 0.0f) || !sycl::isfinite(div)) return RAD_E_INVAL;
if (n <= 0) return RAD_E_SHAPE;
Rows ya, aa, ba;
if (int rc = rows_view(Y, n, &ya, "add y"); rc < 0) return rc;
const int64_t rows = ya.rows;
if (rows <= 0 || rad_tensor_numel(A) < rows * n) return RAD_E_SHAPE;
const bool bcast = rad_tensor_numel(B) == n && rows > 1;
if (!bcast && rad_tensor_numel(B) < rows * n) return RAD_E_SHAPE;
if (int rc = rows_view(A, n, &aa, "add a"); rc < 0) return rc;
if (int rc = rows_view(B, n, &ba, "add b"); rc < 0) return rc;
if (bcast) ba.pitch = 0;
sycl::queue* q = queue_of(s);
if (!q) return RAD_E_DEVICE;
const int64_t total = rows * n;
const size_t wg = 256;
const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t g = (int64_t)it.get_global_id(0);
if (g >= total) return;
const int64_t r = g / n, i = g % n;
const float u = rad_load_f32(aa.base, aa.dtype, r * aa.pitch + i);
const float v = rad_load_f32(ba.base, ba.dtype, r * ba.pitch + i);
float x = u + v;
if (div != 1.0f) x = round_dt(ya.dtype, x) / div;
rad_store_f32(ya.base, ya.dtype, r * ya.pitch + i, x);
});
});
}
} // namespace xe2
+123
View File
@@ -0,0 +1,123 @@
/* xe2_gather.cpp -- row gathers and the dtype cast.
*
* embed_lookup x[m, :] = wte[tok[m] - vocab_offset, :] * mult
* gather_rows y[i, :] = x[idx[i], :]
* cast y = x in y's dtype; integer to integer bypasses f32, as libref's does
*
* Index checks differ from libref's in one way, by necessity: libref reads every index on the host
* before running and returns RAD_E_INVAL for one past the table, but a launch cannot read device
* memory without waiting for the stream, which a launch must not do. Here such a row is written as
* zeros, the rule libr4d's embed_lookup_bf16 states ("a negative or out-of-range id writes a zero
* row"). A negative index is a zero row in both.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
namespace xe2 {
namespace {
bool is_int(uint32_t dt) { return dt == RAD_I32 || dt == RAD_I64 || dt == RAD_U32 || dt == RAD_I16; }
inline void st_index(uint32_t dt, void* p, int64_t i, int64_t v) {
switch (dt) {
case RAD_I32: ((int32_t*)p)[i] = (int32_t)v; break;
case RAD_U32: ((uint32_t*)p)[i] = (uint32_t)v; break;
case RAD_I64: ((int64_t*)p)[i] = v; break;
case RAD_I16: ((int16_t*)p)[i] = (int16_t)v; break;
default: break;
}
}
constexpr size_t kWg = 256;
} // namespace
/* ------------------------------------------------------------------ embed_lookup */
int embed_lookup(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *TOK = &a->t[0], *WTE = &a->t[1], *X = &a->t[2];
const int64_t n_embd = rad_args_geti_or(a, "n_embd", WTE->rank >= 2 ? WTE->shape[WTE->rank - 1] : 0);
const int64_t n_vocab = rad_args_geti_or(a, "n_vocab", WTE->rank >= 2 ? WTE->shape[WTE->rank - 2] : 0);
const int64_t voff = rad_args_geti_or(a, "vocab_offset", 0);
const float mult = (float)rad_args_getf_or(a, "mult", 1.0);
if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE;
Rows x;
if (int rc = rows_view(X, n_embd, &x, "embed_lookup x"); rc < 0) return rc;
const int64_t M = x.rows;
if (M <= 0 || rad_tensor_numel(TOK) < M || rad_tensor_numel(WTE) < n_vocab * n_embd)
return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(TOK)) return refuse("embed_lookup: token ids not contiguous");
const int64_t ws = WTE->rank >= 2 ? WTE->stride[WTE->rank - 2] : n_embd;
const int64_t wc = WTE->rank >= 2 ? WTE->stride[WTE->rank - 1] : 1;
const char* wb = (const char*)WTE->data;
const uint32_t wdt = WTE->dtype;
const char* tb = (const char*)TOK->data;
const uint32_t tdt = TOK->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)M * kWg, kWg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0);
const int64_t id = ld_index(tdt, tb, m) - voff;
const bool have = id >= 0 && id < n_vocab;
for (int64_t i = (int64_t)it.get_local_id(0); i < n_embd; i += kWg)
rad_store_f32(x.base, x.dtype, m * x.pitch + i,
have ? rad_load_f32(wb, wdt, id * ws + i * wc) * mult : 0.0f);
});
});
}
/* ------------------------------------------------------------------ gather_rows */
int gather_rows(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *IDX = &a->t[1], *Y = &a->t[2];
const int64_t n = rad_args_geti_or(a, "n", Y->rank >= 1 ? Y->shape[Y->rank - 1] : 0);
if (n <= 0) return RAD_E_SHAPE;
Rows x, y;
if (int rc = rows_view(Y, n, &y, "gather_rows y"); rc < 0) return rc;
if (int rc = rows_view(X, n, &x, "gather_rows x"); rc < 0) return rc;
const int64_t M = y.rows, src_rows = x.rows;
if (M <= 0 || src_rows <= 0 || rad_tensor_numel(IDX) < M) return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(IDX)) return refuse("gather_rows: idx not contiguous");
const char* ib = (const char*)IDX->data;
const uint32_t idt = IDX->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)M * kWg, kWg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0);
const int64_t r = ld_index(idt, ib, m);
const bool have = r >= 0 && r < src_rows;
for (int64_t i = (int64_t)it.get_local_id(0); i < n; i += kWg)
rad_store_f32(y.base, y.dtype, m * y.pitch + i,
have ? rad_load_f32(x.base, x.dtype, r * x.pitch + i) : 0.0f);
});
});
}
/* ------------------------------------------------------------------ cast */
int cast(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t nel = rad_tensor_numel(Y);
if (nel <= 0 || rad_tensor_numel(X) < nel) return RAD_E_SHAPE;
const bool int_pair = is_int(X->dtype) && is_int(Y->dtype);
/* Either side may be a strided view: the graph casts q out of the fused qkv row, 2048 of
* every 2560 elements. Elements are walked in logical order through libref's offlin. */
const Lin x = Lin::of(X), y = Lin::of(Y);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t groups = (size_t)((nel + (int64_t)kWg - 1) / (int64_t)kWg);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * kWg, kWg}, [=](sycl::nd_item<1> it) {
const int64_t i = (int64_t)it.get_global_id(0);
if (i >= nel) return;
const int64_t xo = x.off(i), yo = y.off(i);
if (int_pair) st_index(y.dtype, y.base, yo, ld_index(x.dtype, x.base, xo));
else rad_store_f32(y.base, y.dtype, yo, rad_load_f32(x.base, x.dtype, xo));
});
});
}
} // namespace xe2
+78
View File
@@ -0,0 +1,78 @@
/* xe2_gemm.cpp -- the unquantised GEMMs: gemm_nt (Y = A B^T) and logits_gemm, its lm_head twin.
*
* Correctness first (docs/SYCL_PORTING.md §4.8, Phase 3): one work-item an output, accumulating
* a * b in f32 over ascending k from zero, no fused multiply-add, then one store: libref's
* gemm_plain exactly. It reads each weight row once per output row, so it is slow; the XMX kernels
* of Phase 4 are checked against it and against libref.
*
* A is read through its row and column strides (an activation may be a slice of a wider arena
* buffer); B is the weight, [N, K]. A joined head (codes with a scale plane) and a non-float
* weight are refused: those are gemm_nt_q's.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
namespace xe2 {
namespace {
/* libref's row_stride: fold trailing axes until they span `cols`. */
int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
return t->stride[t->rank - 2];
}
bool is_float(uint32_t dt) {
return dt == RAD_F32 || dt == RAD_F16 || dt == RAD_BF16 || dt == RAD_F8E4M3 || dt == RAD_F8E5M2;
}
int gemm_plain(const RadArgs* a, RadStream st, const char* nkey, const char* kkey, const char* op) {
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
const int64_t K = rad_args_geti_or(a, kkey, B->rank >= 2 ? B->shape[B->rank - 1] : 0);
const int64_t N = rad_args_geti_or(a, nkey, B->rank >= 2 ? B->shape[B->rank - 2] : 0);
if (K <= 0 || N <= 0) return RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(Y) / N;
if (M <= 0) return RAD_E_SHAPE;
if (!is_float(B->dtype) || !is_float(A->dtype))
return refuse("%s: dtype pair %u x %u is not served (a quantised weight is gemm_nt_q's)", op,
A->dtype, B->dtype);
if (rad_tensor_numel(A) < M * K || rad_tensor_numel(B) < N * K) return RAD_E_SHAPE;
const int64_t ars = row_stride(A, K), acs = A->rank >= 2 ? A->stride[A->rank - 1] : 1;
const int64_t brs = row_stride(B, K), bcs = B->rank >= 2 ? B->stride[B->rank - 1] : 1;
const int64_t yrs = row_stride(Y, N), ycs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
const char *ab = (const char*)A->data, *bb = (const char*)B->data;
char* yb = (char*)Y->data;
const uint32_t adt = A->dtype, bdt = B->dtype, ydt = Y->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t wn = 64;
const size_t nn = (size_t)((N + (int64_t)wn - 1) / (int64_t)wn) * wn;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<2>{{(size_t)M, nn}, {1, wn}},
[=](sycl::nd_item<2> it) {
const int64_t m = (int64_t)it.get_global_id(0), n = (int64_t)it.get_global_id(1);
if (n >= N) return;
float acc = 0.0f;
for (int64_t k = 0; k < K; ++k)
acc += rad_load_f32(ab, adt, m * ars + k * acs) * rad_load_f32(bb, bdt, n * brs + k * bcs);
rad_store_f32(yb, ydt, m * yrs + n * ycs, acc);
});
});
}
} // namespace
int gemm_nt(const RadArgs* a, RadStream s) { return gemm_plain(a, s, "N", "K", "gemm_nt"); }
int logits_gemm(const RadArgs* a, RadStream s) {
return gemm_plain(a, s, "n_vocab", "n_embd", "logits_gemm");
}
} // namespace xe2
+363
View File
@@ -0,0 +1,363 @@
/* xe2_gemm_q.cpp -- the block-scaled GEMMs: gemm_nt_q over fp8 codes, and gemm_nt_q_gated, the
* same product with the gated fp8 quantiser in its epilogue. Correctness first, like xe2_gemm.cpp:
* libref's quant_dot (ref_gemm.h) per output, in its order --
*
* per weight group g: sub = sum over ascending k in g of a[k] * b[k] (codes decoded to f32)
* acc = acc + (sub * sa) * sb
*
* -- with the scale streams read as libref's make_scales reads them: a rank-2 stream states its own
* grid, and a stream with fewer rows than its operand is a block grid (DeepSeek-style 128x128 fp8,
* `[ceil(N/128)][ceil(K/128)]`), its block the power of two grid_block finds. The scale grids are
* worked out on the host per launch and handed to the kernel as values.
*
* Served: the byte-coded pairs fp8a8, fp8a8f32 and fp8a16 (E4M3 weights against E4M3 or bf16
* activations). The zero-point grids (w2a8, w4*_asym), mxfp4 and the parts form are not here; their
* rows are not declared, so they cannot be selected.
*
* gemm_nt_q_gated: one work-group a row. Each work-item takes output columns i of the gated half,
* forms the gate and up products (columns i and n + i) and libref's epilogue on them -- both rounded
* to bf16, the gate (silu or sigmoid, exp in double), the product narrowed to bf16 -- into local
* memory; then the E4M3 (or int8) group quantiser over those n values. Byte-identical to gemm_nt_q
* followed by gated_quant_fp8, as libref's is. Local memory holds n floats, so n <= 28672 (a
* 27B model's gate_up has n = 17408).
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include <cstring>
namespace xe2 {
namespace {
int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
return t->stride[t->rank - 2];
}
/* libref's grid_block. */
int64_t grid_block(int64_t ext, int64_t blocks) {
if (ext <= 0) return 1;
if (blocks <= 1) return ext;
const int64_t lo = (ext + blocks - 1) / blocks;
int64_t b = 1;
while (b < lo) b <<= 1;
return (ext + b - 1) / b == blocks ? b : lo;
}
/* libref's Scales, by value. */
struct Scales {
const char* p = nullptr;
uint32_t dt = RAD_F32;
int64_t rs = 0, cs = 0, group = 0, rblk = 1;
float grp(int64_t row, int64_t g) const {
const int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs;
return rad_load_f32(p, dt, i);
}
float at(int64_t row, int64_t k) const { return grp(row, group > 0 ? k / group : 0); }
};
/* libref's make_scales (no mxfp4 here, so never e8m0). */
Scales make_scales(const RadTensor* s, int64_t rows, int64_t K) {
Scales q;
if (!s || !s->data || rows <= 0 || rad_tensor_numel(s) <= 0) {
q.group = K;
return q;
}
q.p = (const char*)s->data;
q.dt = s->dtype;
int64_t groups = 0;
if (s->rank >= 2) {
const int64_t srows = s->shape[s->rank - 2];
q.rblk = srows >= rows ? 1 : grid_block(rows, srows);
groups = s->shape[s->rank - 1];
q.rs = s->stride[s->rank - 2];
q.cs = s->stride[s->rank - 1];
} else {
const int64_t nel = rad_tensor_numel(s);
if (nel >= rows) {
groups = nel / rows;
q.rs = groups;
} else {
groups = 1;
q.rblk = grid_block(rows, nel);
q.rs = 1;
}
q.cs = 1;
}
q.group = grid_block(K, groups);
return q;
}
struct Mat {
const char* p;
uint32_t dt;
int64_t rs, cs;
};
/* libref's quant_dot. */
inline float quant_dot(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB, int64_t m,
int64_t n, int64_t K) {
const int64_t g = SB.group > 0 ? SB.group : K;
const int64_t ngrp = (K + g - 1) / g;
const bool coarse_a = !SA.p || SA.group >= g;
const int64_t a0 = m * A.rs, b0 = n * B.rs;
float acc = 0.0f;
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < K) ? k0 + g : K;
const float sb = SB.p ? SB.grp(n, gi) : 1.0f;
float sub = 0.0f;
if (coarse_a) {
for (int64_t k = k0; k < k1; ++k)
sub += rad_load_f32(A.p, A.dt, a0 + k * A.cs) * rad_load_f32(B.p, B.dt, b0 + k * B.cs);
acc += sub * (SA.p ? SA.at(m, k0) : 1.0f) * sb;
} else {
for (int64_t k = k0; k < k1; ++k)
sub += rad_load_f32(A.p, A.dt, a0 + k * A.cs) * SA.at(m, k) *
rad_load_f32(B.p, B.dt, b0 + k * B.cs);
acc += sub * sb;
}
}
return acc;
}
bool byte_float(uint32_t dt) {
return dt == RAD_F8E4M3 || dt == RAD_F8E5M2 || dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32;
}
/* The shared front of both ops: operands, extents and the scale grids. */
struct QArgs {
Mat A, B;
Scales SA, SB;
int64_t M = 0, N = 0, K = 0;
};
int q_args(const RadArgs* a, const RadTensor* A, const RadTensor* AS, const RadTensor* B,
const RadTensor* BS, int64_t M, QArgs* out, const char* op) {
const int64_t K = rad_args_geti_or(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0);
const int64_t N = rad_args_geti_or(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0);
if (K <= 0 || N <= 0) return RAD_E_SHAPE;
if (!byte_float(A->dtype) || !byte_float(B->dtype))
return refuse("%s: dtype pair %u x %u is not served (fp8 or bf16 codes only)", op,
A->dtype, B->dtype);
out->K = K;
out->N = N;
out->M = M;
if (M <= 0 || rad_tensor_numel(A) < M * K || rad_tensor_numel(B) < N * K) return RAD_E_SHAPE;
out->A = Mat{ (const char*)A->data, A->dtype, row_stride(A, K),
A->rank >= 2 ? A->stride[A->rank - 1] : 1 };
out->B = Mat{ (const char*)B->data, B->dtype, row_stride(B, K),
B->rank >= 2 ? B->stride[B->rank - 1] : 1 };
out->SA = make_scales(AS, M, K);
out->SB = make_scales(BS, N, K);
const int64_t gp = rad_args_geti_or(a, "group", 0);
if (gp > 0 && out->SB.p && out->SB.group != gp) return RAD_E_SHAPE;
return RAD_OK;
}
} // namespace
/* ------------------------------------------------------------------ gemm_nt_q */
int gemm_nt_q(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 5 || !a->t[0].data || !a->t[2].data || !a->t[4].data) return RAD_E_INVAL;
if (rad_arg_in(a, 5) || rad_arg_in(a, 6))
return refuse("gemm_nt_q: a_sum / b_ref belong to the zero-point and mxfp4 grids, not served");
if (rad_args_geti_or(a, "pb1", 0) > 0 || rad_args_geti_or(a, "pb2", 0) > 0)
return refuse("gemm_nt_q: the parts form is not served");
const RadTensor *Y = &a->t[4], *B = &a->t[2];
const int64_t N = rad_args_geti_or(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0);
if (N <= 0) return RAD_E_SHAPE;
QArgs g;
if (int rc = q_args(a, &a->t[0], rad_arg_in(a, 1), B, rad_arg_in(a, 3), rad_tensor_numel(Y) / N,
&g, "gemm_nt_q");
rc < 0)
return rc;
const int64_t yrs = row_stride(Y, N), ycs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
char* yb = (char*)Y->data;
const uint32_t ydt = Y->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t wn = 64;
const size_t nn = (size_t)((g.N + (int64_t)wn - 1) / (int64_t)wn) * wn;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<2>{{(size_t)g.M, nn}, {1, wn}}, [=](sycl::nd_item<2> it) {
const int64_t m = (int64_t)it.get_global_id(0), n = (int64_t)it.get_global_id(1);
if (n >= g.N) return;
rad_store_f32(yb, ydt, m * yrs + n * ycs, quant_dot(g.A, g.B, g.SA, g.SB, m, n, g.K));
});
});
}
/* ------------------------------------------------------------------ gemm_nt_q_gated */
namespace {
constexpr size_t kGatedWg = 512;
constexpr int64_t kGatedMaxN = 2 * 28672; /* n gated values in local memory: 112 KiB of f32 */
}
int gemm_nt_q_gated(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 6) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[2], *Q = &a->t[4], *S = &a->t[5];
const RadTensor* O = rad_arg_in(a, 6);
if (!A->data || !B->data || !Q->data || !S->data) return RAD_E_INVAL;
const int64_t N = rad_args_geti_or(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0);
if (N <= 0 || (N & 1)) return RAD_E_SHAPE;
if (N > kGatedMaxN) return refuse("gemm_nt_q_gated: N %lld over %lld", (long long)N, (long long)kGatedMaxN);
const int64_t n = N / 2;
const char* act_s = rad_args_gets_or(a, "act", nullptr);
const int act = !act_s ? -1 : !std::strcmp(act_s, "silu") ? 0 : !std::strcmp(act_s, "sigmoid") ? 1 : -1;
if (act != 0 && act != 1) return RAD_E_INVAL;
int64_t gq = rad_args_geti_or(a, "group", 0);
if (gq <= 0 || gq > n) gq = n;
const int64_t ngrp = (n + gq - 1) / gq;
const int64_t M = rad_tensor_numel(Q) / n;
QArgs g;
if (int rc = q_args(a, A, rad_arg_in(a, 1), B, rad_arg_in(a, 3), M, &g, "gemm_nt_q_gated"); rc < 0)
return rc;
if (rad_tensor_numel(S) < M * ngrp) return RAD_E_SHAPE;
Rows qv, sv, ob;
if (int rc = rows_view(Q, n, &qv, "gemm_nt_q_gated q"); rc < 0) return rc;
if (int rc = rows_view(S, ngrp, &sv, "gemm_nt_q_gated scale"); rc < 0) return rc;
const bool has_ob = O != nullptr;
if (has_ob) {
if (rad_tensor_numel(O) < M * n) return RAD_E_SHAPE;
if (int rc = rows_view(O, n, &ob, "gemm_nt_q_gated out_bf16"); rc < 0) return rc;
}
const float top = Q->dtype == RAD_I8 ? 127.0f : 448.0f;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
constexpr int kSubs = (int)(kGatedWg / kSub);
return submit([&] {
q->submit([&](sycl::handler& h) {
sycl::local_accessor<float, 1> gv(sycl::range<1>((size_t)n), h);
h.parallel_for(sycl::nd_range<1>{(size_t)M * kGatedWg, kGatedWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t m = (int64_t)it.get_group(0);
const int t = (int)it.get_local_id(0);
for (int64_t i = t; i < n; i += (int64_t)kGatedWg) {
const float gt = round_dt(RAD_BF16, quant_dot(g.A, g.B, g.SA, g.SB, m, i, g.K));
const float up = round_dt(RAD_BF16, quant_dot(g.A, g.B, g.SA, g.SB, m, n + i, g.K));
const float sg = 1.0f / (1.0f + (float)sycl::exp((double)-gt));
gv[i] = rad_bf16_to_f32(rad_f32_to_bf16((act == 0 ? gt * sg : sg) * up));
}
sycl::group_barrier(it.get_group());
auto v = [&](int64_t i) { return gv[i]; };
if (has_ob)
for (int64_t i = t; i < n; i += (int64_t)kGatedWg)
rad_store_f32(ob.base, ob.dtype, m * ob.pitch + i, v(i));
const sycl::sub_group sg = it.get_sub_group();
const int sgi = (int)sg.get_group_linear_id();
const int lane = (int)sg.get_local_linear_id();
for (int64_t gi = sgi; gi < ngrp; gi += kSubs) {
const int64_t k0 = gi * gq, len = sycl::min(gq, n - k0);
float amax = 0.0f;
for (int64_t i = lane; i < len; i += kSub) amax = sycl::fmax(amax, sycl::fabs(v(k0 + i)));
amax = sycl::reduce_over_group(sg, amax, sycl::maximum<float>());
const float sc = amax > 0.0f ? amax * (1.0f / top) : 1.0f;
const float inv = 1.0f / sc;
for (int64_t i = lane; i < len; i += kSub) {
float c = v(k0 + i) * inv;
if (c > top) c = top;
if (c < -top) c = -top;
rad_store_f32(qv.base, qv.dtype, m * qv.pitch + k0 + i, c);
}
if (lane == 0) rad_store_f32(sv.base, sv.dtype, m * sv.pitch + gi, sc);
}
});
});
});
}
/* ------------------------------------------------------------------ silu_mul */
/* y[i] = silu(gate[i]) * up[i] over a packed [M, 2n] gate_up (ref_elementwise.cpp), exp in double. */
int silu_mul(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *GU = &a->t[0], *Y = &a->t[1];
const int64_t n = rad_args_geti_or(a, "n", rad_tensor_numel(Y));
if (n <= 0) return RAD_E_SHAPE;
Rows y, gu;
if (int rc = rows_view(Y, n, &y, "silu_mul y"); rc < 0) return rc;
const int64_t rows = y.rows;
if (rows <= 0 || rad_tensor_numel(GU) < rows * 2 * n) return RAD_E_SHAPE;
if (int rc = rows_view(GU, 2 * n, &gu, "silu_mul gate_up"); rc < 0) return rc;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const int64_t total = rows * n;
const size_t wg = 256, groups = (size_t)((total + 255) / 256);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t g = (int64_t)it.get_global_id(0);
if (g >= total) return;
const int64_t r = g / n, i = g % n;
const float x = rad_load_f32(gu.base, gu.dtype, r * gu.pitch + i);
const float up = rad_load_f32(gu.base, gu.dtype, r * gu.pitch + n + i);
const float sg = 1.0f / (1.0f + (float)sycl::exp((double)-x));
rad_store_f32(y.base, y.dtype, r * y.pitch + i, x * sg * up);
});
});
}
/* ------------------------------------------------------------------ quant_act_i8 */
/* libref's quant_act_i8: one scale a row, max(amax, 1e-8) / 127; codes x * (1 / scale) stored RNE
* and saturated, at the step position i8_step_pos(i) (bits 2 and 3 of the column swapped, the
* order libr4d's int8 WMMA reads an A fragment); `asum` (optional) the code sums per `group`
* columns, group-major [n/group][Mpad], Mpad = ceil(M/16)*16, rows past M untouched. */
int quant_act_i8(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Q = &a->t[1], *S = &a->t[2];
const RadTensor* AS = rad_arg_in(a, 3);
const int64_t n = rad_args_geti_or(a, "n", 0);
if (n <= 0 || n % 16) return RAD_E_SHAPE;
if (Q->dtype != RAD_I8) return RAD_E_DTYPE;
if (Q->rank && Q->stride[Q->rank - 1] != 1) return RAD_E_STRIDE;
Rows x, qv, sv;
if (int rc = rows_view(X, n, &x, "quant_act_i8 x"); rc < 0) return rc;
const int64_t rows = x.rows;
if (rows <= 0 || rad_tensor_numel(Q) < rows * n || rad_tensor_numel(S) < rows) return RAD_E_SHAPE;
if (int rc = rows_view(Q, n, &qv, "quant_act_i8 q"); rc < 0) return rc;
if (int rc = rows_view(S, 1, &sv, "quant_act_i8 scale"); rc < 0) return rc;
const int64_t gsz = AS ? rad_args_geti_or(a, "group", 0) : 0;
const int64_t mpad = (rows + 15) / 16 * 16;
if (AS && (gsz <= 0 || n % gsz || rad_tensor_numel(AS) < n / gsz * mpad)) return RAD_E_SHAPE;
const bool has_as = AS != nullptr;
char* asb = AS ? (char*)AS->data : nullptr;
const uint32_t asdt = AS ? AS->dtype : 0;
if (AS && !rad_tensor_is_contiguous(AS)) return refuse("quant_act_i8: asum not contiguous");
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t wg = 256;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)rows * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t r = (int64_t)it.get_group(0);
const int t = (int)it.get_local_id(0);
float amax = 0.0f;
for (int64_t i = t; i < n; i += (int64_t)wg)
amax = sycl::fmax(amax, sycl::fabs(rad_load_f32(x.base, x.dtype, r * x.pitch + i)));
amax = sycl::reduce_over_group(it.get_group(), amax, sycl::maximum<float>());
const float scale = sycl::fmax(amax, 1e-8f) / 127.0f;
const float inv = 1.0f / scale;
int8_t* qr = (int8_t*)qv.base + r * qv.pitch;
for (int64_t i = t; i < n; i += (int64_t)wg) {
const int64_t pos = (i & ~(int64_t)12) | ((i & 4) << 1) | ((i & 8) >> 1);
rad_store_f32(qr, RAD_I8, pos, rad_load_f32(x.base, x.dtype, r * x.pitch + i) * inv);
}
if (t == 0) rad_store_f32(sv.base, sv.dtype, r * sv.pitch, scale);
if (!has_as) return;
sycl::group_barrier(it.get_group());
for (int64_t gi = t; gi < n / gsz; gi += (int64_t)wg) {
int64_t sum = 0;
for (int64_t i = gi * gsz; i < (gi + 1) * gsz; ++i)
sum += qr[(i & ~(int64_t)12) | ((i & 4) << 1) | ((i & 8) >> 1)];
rad_store_f32(asb, asdt, gi * mpad + r, (float)sum);
}
});
});
}
} // namespace xe2
+153
View File
@@ -0,0 +1,153 @@
/* xe2_gemm_xmx.cpp -- the bf16 GEMM for prefill-sized M on Xe2's XMX engines (joint_matrix,
* M8 x N16 x K16, bf16 in, f32 accumulate; verified exact on the B65 in Phase 0).
*
* The weight is [N, K] row-major, which is B = W^T column-major: use::b is loaded column-major
* straight from it (checked on the card: scripts/sycl's probe pattern, exact). A sub-group owns an
* 8-row tile and 64 columns (four accumulators); the eight sub-groups of a work-group own eight
* different row tiles of the same 64 columns, so a B tile one of them loads is in cache for the
* others and the weight streams from memory once per 64 rows rather than once per 8. Each
* accumulator goes through local memory to the output, so Y may be bf16 or f32 at any row stride.
*
* Rows past the last whole 8-row tile (at most 7) go to the decode GEMV, and a launch whose
* operands the tiles cannot read -- N not a multiple of 64, K not a multiple of 16, unaligned or
* strided rows, a non-bf16 operand -- to the correctness-first kernel. Not libref's summation
* order (XMX accumulates K in blocks of 16): held to rad-kbench's gemm tolerance and the KL bound
* (docs/SYCL_PROGRESS.md D13). XE2_EXACT=1 sends every launch to the exact kernel.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
namespace xe2 {
namespace {
namespace jm = sycl::ext::oneapi::experimental::matrix;
using bf16 = sycl::ext::oneapi::bfloat16;
constexpr int kTm = 8, kTn = 16, kTk = 16;
constexpr int kTiles = 4; /* accumulators a sub-group: 64 columns */
constexpr int kSgs = 8; /* sub-groups a work-group: 64 rows */
constexpr size_t kWg = kSgs * kSub;
int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
return t->stride[t->rank - 2];
}
/* The launch's operands with the first `rows` rows dropped: the tail the GEMV takes. */
RadArgs tail_args(const RadArgs* a, RadTensor* t, int64_t rows, int64_t ars, int64_t yrs) {
RadArgs b = *a;
for (int i = 0; i < a->n_t && i < 3; ++i) t[i] = a->t[i];
t[0].data = (char*)a->t[0].data + rows * ars * 2;
t[2].data = (char*)a->t[2].data + rows * yrs * (int64_t)((rad_dtype_bits(a->t[2].dtype) + 7) / 8);
for (int i : { 0, 2 }) {
if (t[i].rank >= 2) {
/* Leading axes collapse to rows; the tail is a [rows', cols] view. */
const int64_t cols = t[i].shape[t[i].rank - 1];
const int64_t total = rad_tensor_numel(&a->t[i]) / cols;
const int64_t stride = i == 0 ? ars : yrs;
const int64_t cs = t[i].stride[t[i].rank - 1];
t[i].rank = 2;
t[i].shape[0] = total - rows;
t[i].shape[1] = cols;
t[i].stride[0] = stride;
t[i].stride[1] = cs;
}
}
b.t = t;
return b;
}
int xmx(const RadArgs* a, RadStream st, const char* nkey, const char* kkey,
int (*exact)(const RadArgs*, RadStream), int (*skinny)(const RadArgs*, RadStream)) {
if (exact_only()) return exact(a, st);
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
const int64_t K = rad_args_geti_or(a, kkey, B->rank >= 2 ? B->shape[B->rank - 1] : 0);
const int64_t N = rad_args_geti_or(a, nkey, B->rank >= 2 ? B->shape[B->rank - 2] : 0);
if (K <= 0 || N <= 0) return RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(Y) / N;
if (M <= 0 || rad_tensor_numel(A) < M * K || rad_tensor_numel(B) < N * K) return RAD_E_SHAPE;
const int64_t ars = row_stride(A, K), brs = row_stride(B, K);
const int64_t yrs = row_stride(Y, N), ycs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
const bool ok = A->dtype == RAD_BF16 && B->dtype == RAD_BF16 &&
(Y->dtype == RAD_BF16 || Y->dtype == RAD_F32) && N % (kTn * kTiles) == 0 &&
K % kTk == 0 && ars % 8 == 0 && brs % 8 == 0 &&
(A->rank < 2 || A->stride[A->rank - 1] == 1) &&
(B->rank < 2 || B->stride[B->rank - 1] == 1) && rad_ptr_aligned(A->data, 16) &&
rad_ptr_aligned(B->data, 16);
const int64_t M8 = M / kTm * kTm;
if (!ok || M8 == 0) return exact(a, st);
const bf16* ab = (const bf16*)A->data;
const bf16* bb = (const bf16*)B->data;
char* yb = (char*)Y->data;
const uint32_t ydt = Y->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t gm = (size_t)((M8 + kTm * kSgs - 1) / (kTm * kSgs));
const size_t gn = (size_t)(N / (kTn * kTiles));
int rc = submit([&] {
q->submit([&](sycl::handler& h) {
sycl::local_accessor<float, 1> stage(sycl::range<1>((size_t)kSgs * kTm * kTn), h);
h.parallel_for(sycl::nd_range<2>{{gm, gn * kWg}, {1, kWg}},
[=](sycl::nd_item<2> it) [[sycl::reqd_sub_group_size(kSub)]] {
const sycl::sub_group sg = it.get_sub_group();
const int s = (int)sg.get_group_linear_id();
const int64_t m0 = ((int64_t)it.get_group(0) * kSgs + s) * kTm;
const int64_t n0 = (int64_t)it.get_group(1) * kTn * kTiles;
if (m0 >= M8) return; /* uniform across the sub-group */
auto ga = sycl::address_space_cast<sycl::access::address_space::global_space,
sycl::access::decorated::no>(ab + m0 * ars);
jm::joint_matrix<sycl::sub_group, bf16, jm::use::a, kTm, kTk, jm::layout::row_major> ma;
jm::joint_matrix<sycl::sub_group, bf16, jm::use::b, kTk, kTn, jm::layout::col_major> mb;
jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, kTm, kTn> mc[kTiles];
for (int t = 0; t < kTiles; ++t) jm::joint_matrix_fill(sg, mc[t], 0.0f);
for (int64_t k = 0; k < K; k += kTk) {
jm::joint_matrix_load(sg, ma, ga + k, (size_t)ars);
for (int t = 0; t < kTiles; ++t) {
auto gb = sycl::address_space_cast<sycl::access::address_space::global_space,
sycl::access::decorated::no>(
bb + (n0 + t * kTn) * brs + k);
jm::joint_matrix_load(sg, mb, gb, (size_t)brs);
jm::joint_matrix_mad(sg, mc[t], ma, mb, mc[t]);
}
}
float* mine = &stage[(size_t)s * kTm * kTn];
auto ls = sycl::address_space_cast<sycl::access::address_space::local_space,
sycl::access::decorated::no>(mine);
const int lane = (int)sg.get_local_linear_id();
for (int t = 0; t < kTiles; ++t) {
jm::joint_matrix_store(sg, mc[t], ls, kTn, jm::layout::row_major);
sycl::group_barrier(sg);
for (int e = lane; e < kTm * kTn; e += kSub) {
const int64_t r = e / kTn, c = e % kTn;
rad_store_f32(yb, ydt, (m0 + r) * yrs + (n0 + t * kTn + c) * ycs, mine[e]);
}
sycl::group_barrier(sg);
}
});
});
});
if (rc < 0 || M8 == M) return rc;
RadTensor t[3];
const RadArgs b = tail_args(a, t, M8, ars, yrs);
return skinny(&b, st);
}
} // namespace
int gemm_nt_xmx(const RadArgs* a, RadStream s) {
return xmx(a, s, "N", "K", gemm_nt, gemm_nt_gemv);
}
int logits_gemm_xmx(const RadArgs* a, RadStream s) {
return xmx(a, s, "n_vocab", "n_embd", logits_gemm, logits_gemm_gemv);
}
} // namespace xe2
+209
View File
@@ -0,0 +1,209 @@
/* xe2_gemm_zp.cpp -- gemm_nt_q over the zero-point grids whose activation is quant_act_i8's
* (w2a8, w4a8_asym): the DSpark drafter's 2-bit vocabulary head. Correctness first: libref's
* gemm_zp (ref_gemm.cpp) per output --
*
* per group g of K: is = sum over ascending k of a[k] * code[n][k] (exact integers)
* sub = (float)is - (float)zero[n][g] * a_sum[g][m]
* acc = acc + (sub * a_scale[m]) * scale[n][g]
*
* -- with `a` read back from quant_act_i8's step order into column order, as libref does.
*
* `b_scale` reaches the kernel in libref's joined form (abi/rad_planes.h): a header, an entry per
* plane, then the "scale" and "zero" planes. The layout hook below is libref's
* (ref_layout_gemm_q), so both libraries ask for the same stored bytes and the builder can resolve
* either for a band. The header lives in device memory, so the kernel finds its planes itself: a
* launch must not read device memory from the host.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include "rad_planes.h"
#include <cstring>
namespace xe2 {
namespace {
struct ZpGrid {
const char* name;
uint32_t codes;
bool i8_row; /* the activation is quant_act_i8's (served here) */
};
const ZpGrid* zp_grid(const char* dtype) {
static const ZpGrid kGrids[] = {
{ "w2a8", RAD_U2, true }, { "w4a8_asym", RAD_U4, true },
{ "w4a16_asym", RAD_U4, false }, { "w5a16", RAD_U5, false },
{ "w4a8i8_asym", RAD_U4, false }, { "w5a8i8", RAD_U5, false },
};
if (!dtype) return nullptr;
for (const ZpGrid& g : kGrids)
if (std::strcmp(g.name, dtype) == 0) return &g;
return nullptr;
}
bool zero_dt(uint32_t dt) { return dt == RAD_U8 || dt == RAD_U2 || dt == RAD_U4 || dt == RAD_U5; }
bool sel_roles(const RadEncoding* enc, const int* sel, int n, const char* r0, const char* r1) {
if (!enc || !sel || n != 2) return false;
for (int i = 0; i < 2; ++i)
if (sel[i] < 0 || sel[i] >= enc->n_planes) return false;
return std::strncmp(enc->plane[sel[0]].role, r0, RAD_ENC_STR) == 0 &&
std::strncmp(enc->plane[sel[1]].role, r1, RAD_ENC_STR) == 0;
}
/* One plane of the joined operand, found on the device. */
struct DPlane {
const char* p = nullptr;
uint32_t dt = 0;
int64_t row_bytes = 0;
float at(int64_t i, int64_t j) const { return rad_load_f32(p + i * row_bytes, dt, j); }
};
inline bool role_is(const char* role, const char* want) {
for (int i = 0; i < RAD_ENC_STR; ++i) {
if (role[i] != want[i]) return false;
if (!want[i]) return true;
}
return true;
}
inline DPlane find_plane(const char* base, const char* role) {
DPlane v;
const RadPlanesHeader* h = (const RadPlanesHeader*)base;
if (h->magic != RAD_PLANES_MAGIC) return v;
const RadPlanesEntry* e = (const RadPlanesEntry*)(base + sizeof(RadPlanesHeader));
for (int i = 0; i < h->n_planes && i < RAD_ENC_MAX_PLANES; ++i)
if (role_is(e[i].role, role)) {
v.p = base + e[i].offset;
v.dt = e[i].dtype;
v.row_bytes = e[i].row_bytes;
return v;
}
return v;
}
int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
return t->stride[t->rank - 2];
}
} // namespace
/* ------------------------------------------------------------------ the layout hooks */
/* libref's ref_layout_gemm_q, line for line: `b_scale` (operand 3) joined as "scale" and "zero",
* one each per (row, `group` of K), over codes of the grid's width. */
int gemm_zp_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out) {
if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
const ZpGrid* zg = zp_grid(rad_param_gets(p, n_p, "dtype", nullptr));
const long long group = rad_param_geti(p, n_p, "group", 0);
if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
if (!sel_roles(enc, sel, n, "scale", "zero") || enc->n_planes < 3) return RAD_E_DTYPE;
const RadEncPlane& c = enc->plane[0];
const RadEncPlane& s = enc->plane[sel[0]];
const RadEncPlane& z = enc->plane[sel[1]];
if (std::strncmp(c.role, "codes", RAD_ENC_STR) != 0 || c.dtype != zg->codes ||
c.block[0] != 1 || c.block[1] != 1)
return RAD_E_DTYPE;
if (s.kind != RAD_PLANE_TILED || s.dtype != RAD_F16 || s.block[0] != 1 || s.block[1] != group ||
z.kind != RAD_PLANE_TILED || !zero_dt(z.dtype) || z.block[0] != 1 || z.block[1] != group)
return RAD_E_DTYPE;
return rad_planes_layout(enc, sel, planes, n, out);
}
int gemm_zp_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, void* dst, int64_t dst_bytes) {
RadLayout lay{};
const int st = gemm_zp_layout(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes);
}
int gemm_zp_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes, const RadTensor* planes,
int n) {
RadLayout lay{};
const int st = gemm_zp_layout(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n);
}
/* ------------------------------------------------------------------ the launch */
int gemm_nt_q_zp(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 5 || !a->t[0].data || !a->t[2].data || !a->t[4].data) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[4];
const RadTensor* AS = rad_arg_in(a, 1);
const RadTensor* BS = rad_arg_in(a, 3);
const RadTensor* ASUM = rad_arg_in(a, 5);
if (rad_arg_in(a, 6)) return refuse("gemm_nt_q (zero-point): b_ref is mxfp4's");
const ZpGrid* zg = zp_grid(rad_args_gets_or(a, "dtype", nullptr));
if (!zg || !zg->i8_row)
return refuse("gemm_nt_q (zero-point): dtype '%s' is not served (w2a8, w4a8_asym are)",
rad_args_gets_or(a, "dtype", ""));
if (rad_args_geti_or(a, "pb1", 0) > 0 || rad_args_geti_or(a, "pb2", 0) > 0) return RAD_E_UNSUPPORTED;
const int64_t K = rad_args_geti_or(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0);
const int64_t N = rad_args_geti_or(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0);
const int64_t group = rad_args_geti_or(a, "group", 0);
if (K <= 0 || N <= 0) return RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(Y) / N;
if (M <= 0 || rad_tensor_numel(A) < M * K || rad_tensor_numel(B) < N * K) return RAD_E_SHAPE;
if (!BS) return RAD_E_INVAL;
if (B->dtype != zg->codes) return RAD_E_DTYPE;
if (group <= 0 || K % group || K % 16) return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(B)) return RAD_E_STRIDE;
if (A->dtype != RAD_I8) return RAD_E_DTYPE;
if (A->rank && A->stride[A->rank - 1] != 1) return RAD_E_STRIDE;
const int64_t G = K / group, mpad = (M + 15) / 16 * 16;
if (!AS || rad_tensor_numel(AS) < M) return RAD_E_INVAL;
if (!ASUM || rad_tensor_numel(ASUM) < G * mpad) return RAD_E_INVAL;
const int64_t brow = rad_dtype_bytes(B->dtype, K);
const int cbits = rad_dtype_bits(B->dtype);
const int64_t ars = row_stride(A, K);
const int64_t sa_rs = row_stride(AS, 1);
const int64_t asum_s = ASUM->rank ? ASUM->stride[ASUM->rank - 1] : 1;
const int64_t ys_r = row_stride(Y, N), ys_c = Y->rank ? Y->stride[Y->rank - 1] : 1;
const char *ab = (const char*)A->data, *bb = (const char*)B->data, *bsb = (const char*)BS->data;
const char *sab = (const char*)AS->data, *sumb = (const char*)ASUM->data;
const uint32_t sadt = AS->dtype, sumdt = ASUM->dtype, ydt = Y->dtype;
char* yb = (char*)Y->data;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t wn = 64;
const size_t nn = (size_t)((N + (int64_t)wn - 1) / (int64_t)wn) * wn;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<2>{{(size_t)M, nn}, {1, wn}}, [=](sycl::nd_item<2> it) {
const int64_t m = (int64_t)it.get_global_id(0), n = (int64_t)it.get_global_id(1);
if (n >= N) return;
const DPlane sc = find_plane(bsb, "scale"), zp = find_plane(bsb, "zero");
if (!sc.p || !zp.p) return; /* not a joined b_scale: the layout hook guarantees one */
const uint8_t* crow = (const uint8_t*)bb + n * brow;
const int8_t* ar = (const int8_t*)ab + m * ars;
const float sa = rad_load_f32(sab, sadt, m * sa_rs);
float acc = 0.0f;
for (int64_t g = 0; g < G; ++g) {
const float sb = sc.at(n, g);
const int32_t z = (int32_t)zp.at(n, g);
int64_t is = 0;
for (int64_t k = g * group; k < (g + 1) * group; ++k) {
const int64_t pos = (k & ~(int64_t)12) | ((k & 4) << 1) | ((k & 8) >> 1);
is += (int64_t)ar[pos] * (int32_t)rad_load_bits(crow, cbits, k);
}
const float sub = (float)is - (float)z * rad_load_f32(sumb, sumdt, (g * mpad + m) * asum_s);
acc += sub * sa * sb;
}
rad_store_f32(yb, ydt, m * ys_r + n * ys_c, acc);
});
});
}
} // namespace xe2
+213
View File
@@ -0,0 +1,213 @@
/* xe2_gemv.cpp -- Phase 4's first fast kernel: the skinny bf16 GEMM a decode step is made of
* (gemm_nt and logits_gemm at M <= 16), bandwidth-bound by construction.
*
* At decode (M = 1) one 16-lane sub-group takes two output columns: each lane reads 8 bf16 of each
* weight row at a time (16-byte loads, the sub-group 256 contiguous bytes a row), multiplies them
* against the same 8 columns of the activation, and keeps a partial sum a column; the sub-group then
* reduces and lane 0 stores. Measured on the B65 at a 1.8k context: one column 9.1 ms a step of
* gemm_nt, two 8.5 (~465 GB/s of the card's ~600), four 10.9 (fewer sub-groups, more registers).
* For 2 <= M <= 16, one column a sub-group with a partial sum a row. A weight byte is read once per step whatever M is, so the cost is the weight's
* bytes over the card's bandwidth.
*
* Not libref's order: each lane sums its own strided slice and the slices are reduced as a tree, so
* the result differs from the reference's ascending sum in the last bits. It is checked against
* libref at rad-kbench's gemm tolerance, the standard libr4d's split-K WMMA GEMMs are held to, and
* by the engine oracle at that tolerance. XE2_EXACT=1 sends every launch to the correctness-first
* kernel instead (xe2_gemm.cpp), for bisecting a difference.
*
* Takes: bf16 activation and weight, rows 16-byte aligned with K a multiple of 8 and a unit column
* stride; anything else falls back to the correctness-first kernel, which serves every layout.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include <cstdlib>
namespace xe2 {
bool exact_only() {
static const bool on = [] {
const char* e = std::getenv("XE2_EXACT");
return e && e[0] == '1';
}();
return on;
}
namespace {
constexpr int kMaxM = 16;
constexpr int kCols = 2; /* output columns a sub-group at decode: two weight rows in flight */
constexpr size_t kWg = 256; /* 16 sub-groups */
constexpr int64_t kFill = 8192; /* sub-groups that fill the B65 (it runs ~10k threads) */
int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
return t->stride[t->rank - 2];
}
inline float bf(uint16_t h) { return rad_bf16_to_f32(h); }
/* Whether the fast kernel can read this launch's operands; otherwise the exact one runs. */
bool gemv_ok(const RadTensor* A, const RadTensor* B, const RadTensor* Y, int64_t M, int64_t K,
int64_t ars, int64_t brs) {
if (A->dtype != RAD_BF16 || B->dtype != RAD_BF16) return false;
if (Y->dtype != RAD_BF16 && Y->dtype != RAD_F32) return false;
if (M < 1 || M > kMaxM || K % 8) return false;
if ((A->rank >= 2 && A->stride[A->rank - 1] != 1) || (B->rank >= 2 && B->stride[B->rank - 1] != 1))
return false;
if (ars % 8 || brs % 8) return false;
return rad_ptr_aligned(A->data, 16) && rad_ptr_aligned(B->data, 16);
}
/* The kernel: NC output columns a sub-group, up to MM activation rows. */
template <int NC, int MM>
int launch(sycl::queue& q, const uint16_t* ab, const uint16_t* bb, char* yb, uint32_t ydt, int64_t N,
int64_t K, int64_t ars, int64_t brs, int64_t yrs, int64_t ycs, int mm) {
const int64_t per_wg = 16 * NC;
const size_t groups = (size_t)((N + per_wg - 1) / per_wg);
return submit([&] {
syclex::nd_launch(q, sycl::nd_range<1>{groups * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const sycl::sub_group sg = it.get_sub_group();
const int64_t n0 = ((int64_t)it.get_group(0) * 16 + (int64_t)sg.get_group_linear_id()) * NC;
if (n0 >= N) return; /* uniform across the sub-group */
const int nc = (int)sycl::min((int64_t)NC, N - n0);
const int lane = (int)sg.get_local_linear_id();
float acc[NC][MM];
for (int c = 0; c < NC; ++c)
for (int r = 0; r < MM; ++r) acc[c][r] = 0.0f;
for (int64_t k = (int64_t)lane * 8; k < K; k += 8 * kSub) {
float wf[NC][8];
for (int c = 0; c < NC; ++c) {
if (c >= nc) break;
const sycl::vec<uint16_t, 8> w = *(const sycl::vec<uint16_t, 8>*)(bb + (n0 + c) * brs + k);
for (int j = 0; j < 8; ++j) wf[c][j] = bf(w[j]);
}
for (int r = 0; r < MM; ++r) {
if (r >= mm) break;
const sycl::vec<uint16_t, 8> x = *(const sycl::vec<uint16_t, 8>*)(ab + r * ars + k);
float xf[8];
for (int j = 0; j < 8; ++j) xf[j] = bf(x[j]);
for (int c = 0; c < NC; ++c) {
if (c >= nc) break;
float s = 0.0f;
for (int j = 0; j < 8; ++j) s += xf[j] * wf[c][j];
acc[c][r] += s;
}
}
}
for (int c = 0; c < NC; ++c) {
if (c >= nc) break;
for (int r = 0; r < MM; ++r) {
if (r >= mm) break;
const float v = sycl::reduce_over_group(sg, acc[c][r], sycl::plus<float>());
if (lane == 0) rad_store_f32(yb, ydt, r * yrs + (n0 + c) * ycs, v);
}
}
});
});
}
/* Decode (M = 1) with K split S ways inside a work-group: sub-group g takes columns
* (group * 16/S + g / S) * NC + c and the K chunk g % S (whole 128-element steps), its lanes reduce
* their partials, and the chunk partials are added in chunk order through local memory -- the same
* order every launch. Without the split a decode GEMV is N / NC sub-groups, which for N = 2048 is a
* tenth of the card's threads; at a long K each of them then walks K alone. */
template <int NC>
int launch_split(sycl::queue& q, const uint16_t* ab, const uint16_t* bb, char* yb, uint32_t ydt,
int64_t N, int64_t K, int64_t brs, int64_t ycs, int S) {
const int cg = 16 / S; /* column groups a work-group */
const int64_t per_wg = (int64_t)cg * NC;
const size_t groups = (size_t)((N + per_wg - 1) / per_wg);
const int64_t steps = (K + 8 * kSub - 1) / (8 * kSub);
const int64_t chunk = (steps + S - 1) / S * (8 * kSub); /* K elements a split */
return submit([&] {
q.submit([&](sycl::handler& h) {
sycl::local_accessor<float, 1> part(sycl::range<1>((size_t)16 * NC), h);
h.parallel_for(sycl::nd_range<1>{groups * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const sycl::sub_group sg = it.get_sub_group();
const int g = (int)sg.get_group_linear_id();
const int sp = g % S;
const int64_t n0 = ((int64_t)it.get_group(0) * cg + g / S) * NC;
const int nc = (int)sycl::max((int64_t)0, sycl::min((int64_t)NC, N - n0));
const int lane = (int)sg.get_local_linear_id();
float acc[NC];
for (int c = 0; c < NC; ++c) acc[c] = 0.0f;
const int64_t klo = sp * chunk, khi = sycl::min(K, klo + chunk);
using V8 = sycl::vec<uint16_t, 8>;
for (int64_t k = klo + (int64_t)lane * 8; k < khi; k += 8 * kSub) {
const V8 x = *(const V8*)(ab + k);
float xf[8];
for (int j = 0; j < 8; ++j) xf[j] = bf(x[j]);
for (int c = 0; c < NC; ++c) {
if (c >= nc) break;
const V8 w = *(const V8*)(bb + (n0 + c) * brs + k);
float s = 0.0f;
for (int j = 0; j < 8; ++j) s += xf[j] * bf(w[j]);
acc[c] += s;
}
}
for (int c = 0; c < NC; ++c) {
const float v = sycl::reduce_over_group(sg, acc[c], sycl::plus<float>());
if (lane == 0) part[g * NC + c] = v;
}
sycl::group_barrier(it.get_group());
if (sp == 0 && lane < nc) {
float y = 0.0f;
for (int t = 0; t < S; ++t) y += part[(g + t) * NC + lane];
rad_store_f32(yb, ydt, (n0 + lane) * ycs, y);
}
});
});
});
}
int gemv(const RadArgs* a, RadStream st, const char* nkey, const char* kkey, int (*exact)(const RadArgs*, RadStream)) {
if (exact_only()) return exact(a, st);
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
const int64_t K = rad_args_geti_or(a, kkey, B->rank >= 2 ? B->shape[B->rank - 1] : 0);
const int64_t N = rad_args_geti_or(a, nkey, B->rank >= 2 ? B->shape[B->rank - 2] : 0);
if (K <= 0 || N <= 0) return RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(Y) / N;
if (M <= 0 || rad_tensor_numel(A) < M * K || rad_tensor_numel(B) < N * K) return RAD_E_SHAPE;
const int64_t ars = row_stride(A, K), brs = row_stride(B, K);
if (!gemv_ok(A, B, Y, M, K, ars, brs)) return exact(a, st);
const int64_t yrs = row_stride(Y, N), ycs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
const uint16_t* ab = (const uint16_t*)A->data;
const uint16_t* bb = (const uint16_t*)B->data;
char* yb = (char*)Y->data;
const uint32_t ydt = Y->dtype;
const int mm = (int)M;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
/* Decode (M = 1) takes the lean form with kCols columns a sub-group; M up to 16 one column a
* sub-group with a partial sum a row. Sizing the accumulators by the band keeps them in
* registers (four columns at sixteen rows spilled and ran slower than one). */
if (mm == 1) {
/* A long K on too few sub-groups to fill the card splits two ways. Measured on the B65
* (MiniCPM5-2B, cold weights): down_proj N=2048 K=6144 59.7 -> 52.2 us; 4, 8 or 16 ways no
* better; the K=2048 shapes slower split (18.1 -> 21.6 us at N=2048), so they keep one. */
const int64_t sgs = (N + kCols - 1) / kCols;
const int S = (K >= 4096 && sgs < kFill) ? 2 : 1;
if (S > 1) return launch_split<kCols>(*q, ab, bb, yb, ydt, N, K, brs, ycs, S);
return launch<kCols, 1>(*q, ab, bb, yb, ydt, N, K, ars, brs, yrs, ycs, 1);
}
return launch<1, kMaxM>(*q, ab, bb, yb, ydt, N, K, ars, brs, yrs, ycs, mm);
}
} // namespace
int gemm_nt_gemv(const RadArgs* a, RadStream s) { return gemv(a, s, "N", "K", gemm_nt); }
int logits_gemm_gemv(const RadArgs* a, RadStream s) {
return gemv(a, s, "n_vocab", "n_embd", logits_gemm);
}
} // namespace xe2
+340
View File
@@ -0,0 +1,340 @@
/* xe2_norm.cpp -- the RMS norms and the block-scaled fp8 activation quantisers.
*
* One work-group a row. The sum of squares is libref's: f32, in ascending index order, by one
* work-item and broadcast to the group. A tree reduction rounds differently, and on MiniCPM5-2B's
* real weights that difference moved enough normed values across a bf16 tie, and from there the
* E4M3 codes, to fail rmsnorm_quant_fp8's tolerance at M=1 (rel 7.7e-3 against 4e-3). The serial
* sum is n multiply-adds, small beside the row's loads; a faster ordered form is Phase 4's.
* A quantisation group belongs to one sub-group, whose lanes stride over it for the amax and the
* codes.
*
* The arithmetic is libref's, step for step (ref_elementwise.cpp, ref_quant.cpp):
* rmsnorm y = ((x * s) * (w + wadd)) * mult, s = 1 / sqrt(mean(x^2) + eps)
* quant_act_fp8 per group: scale = amax * (1/448) (1 for an all-zero group),
* code = clamp(x * (1/scale), +-448), stored RNE
* rmsnorm_quant_fp8 the residual sum is stored first and read back (so the norm sees the
* narrowed sum), the normed row is narrowed to bf16, and the codes are
* taken over those bf16 values; an int8 `q` takes amax / 127 instead
* gated_quant_fp8 silu(gate) * up or sigmoid(gate) * up over a packed [M, 2n] gate_up,
* narrowed to bf16, then quantised as above
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include <cstring>
namespace xe2 {
namespace {
constexpr size_t kWg = 256; /* work-items a row */
/* sigmoid exactly as libref's act_sigmoid: exp in double, rounded once to f32 (ref_exp). An f32
* exp is within an ulp, inside rad-kbench's tolerance, but an ulp in silu now and then moves the
* bf16 narrowing and then an E4M3 code; the engine-level oracle (RADIANCE_OP_ORACLE) caught one
* such code in some of MiniCPM5-2B's 42 layers, enough to flip a greedy near-tie later. */
inline float sigmoidf(float x) { return 1.0f / (1.0f + (float)sycl::exp((double)-x)); }
/* The sum of src(i)^2 over i < n in ascending order, f32, as libref sums it, returned to every
* work-item of the group. The squares are formed in parallel into local memory a chunk at a time
* and work-item 0 adds them in index order: the same additions as a serial loop, bit for bit, but
* reading local memory instead of waiting on one global load after another (that serial walk was
* 13% of a MiniCPM5 decode step, 360 us a call). */
constexpr int64_t kSqChunk = 2048;
template <class F>
inline float ordered_sumsq(const sycl::nd_item<1>& it, const F& src, int64_t n) {
auto grp = it.get_group();
float* sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kSqChunk]>(grp);
const int64_t t = (int64_t)it.get_local_id(0), wg = (int64_t)it.get_local_range(0);
float ss = 0.0f;
for (int64_t c0 = 0; c0 < n; c0 += kSqChunk) {
const int64_t cn = sycl::min(kSqChunk, n - c0);
for (int64_t i = t; i < cn; i += wg) {
const float v = src(c0 + i);
sq[i] = v * v;
}
sycl::group_barrier(grp);
if (t == 0) {
/* Eight independent loads a step, then the eight adds in index order: the same sum,
* without waiting on one local-memory load per addition. */
int64_t i = 0;
for (; i + 8 <= cn; i += 8) {
float b[8];
for (int j = 0; j < 8; ++j) b[j] = sq[i + j];
for (int j = 0; j < 8; ++j) ss += b[j];
}
for (; i < cn; ++i) ss += sq[i];
}
sycl::group_barrier(grp);
}
return sycl::group_broadcast(grp, ss, 0);
}
/* One group's codes and scale, by the sub-group `sg` over values v(k0 + i), i < len; with
* `obase`, each value is also stored there (out_bf16). A group of up to kCached * 16 values is
* computed once into registers, so the amax pass and the codes read the same floats without
* evaluating v twice (for gated_quant_fp8 that is a double exp an element); a wider group
* evaluates v in each pass, which gives the same floats. Returns the scale (the same in every
* lane). */
constexpr int kCached = 8;
template <class V>
inline float quant_group(const sycl::sub_group& sg, const V& v, int64_t k0, int64_t len, float top,
char* qbase, uint32_t qdt, int64_t qoff, char* obase = nullptr,
uint32_t odt = 0, int64_t ooff = 0) {
const int lane = (int)sg.get_local_linear_id();
auto code = [&](int64_t i, float x, float inv) {
float c = x * inv;
if (c > top) c = top;
if (c < -top) c = -top;
rad_store_f32(qbase, qdt, qoff + k0 + i, c);
if (obase) rad_store_f32(obase, odt, ooff + k0 + i, x);
};
float amax = 0.0f;
if (len <= (int64_t)kCached * kSub) {
float c[kCached];
for (int j = 0; j < kCached; ++j) {
const int64_t i = lane + (int64_t)j * kSub;
c[j] = i < len ? v(k0 + i) : 0.0f;
amax = sycl::fmax(amax, sycl::fabs(c[j]));
}
amax = sycl::reduce_over_group(sg, amax, sycl::maximum<float>());
const float sc = amax > 0.0f ? amax * (1.0f / top) : 1.0f;
const float inv = 1.0f / sc;
for (int j = 0; j < kCached; ++j) {
const int64_t i = lane + (int64_t)j * kSub;
if (i < len) code(i, c[j], inv);
}
return sc;
}
for (int64_t i = lane; i < len; i += kSub) amax = sycl::fmax(amax, sycl::fabs(v(k0 + i)));
amax = sycl::reduce_over_group(sg, amax, sycl::maximum<float>());
const float sc = amax > 0.0f ? amax * (1.0f / top) : 1.0f;
const float inv = 1.0f / sc;
for (int64_t i = lane; i < len; i += kSub) code(i, v(k0 + i), inv);
return sc;
}
/* The scale plane, one value a group, rows of `ngrp`. */
int scale_view(const RadTensor* s, int64_t rows, int64_t ngrp, Rows* out, const char* what) {
if (rad_tensor_numel(s) < rows * ngrp) return RAD_E_SHAPE;
return rows_view(s, ngrp, out, what);
}
/* The gain, read as one row of n, or absent. */
struct Gain {
const char* base = nullptr;
uint32_t dtype = 0;
int64_t stride = 1;
};
int gain_view(const RadTensor* w, int64_t n, Gain* out, const char* what) {
if (!w) return RAD_OK;
if (rad_tensor_numel(w) < n) return RAD_E_SHAPE;
out->base = (const char*)w->data;
out->dtype = w->dtype;
out->stride = w->rank ? w->stride[w->rank - 1] : 1;
(void)what;
return RAD_OK;
}
} // namespace
/* ------------------------------------------------------------------ rmsnorm */
int rmsnorm(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor* w = rad_arg_in(a, 1);
const float wadd = (float)rad_args_getf_or(a, "wadd", 0.0);
if (!w && wadd != 0.0f) return RAD_E_INVAL;
const int64_t n = rad_args_geti_or(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0);
const float eps = (float)rad_args_getf_or(a, "eps", 1e-6);
const float mult = (float)rad_args_getf_or(a, "mult", 1.0);
if (n <= 0) return RAD_E_SHAPE;
Rows x, y;
Gain g;
if (int rc = rows_view(&a->t[0], n, &x, "rmsnorm x"); rc < 0) return rc;
if (int rc = rows_view(&a->t[2], n, &y, "rmsnorm y"); rc < 0) return rc;
if (int rc = gain_view(w, n, &g, "rmsnorm w"); rc < 0) return rc;
const int64_t rows = x.rows;
if (rows <= 0 || y.rows < rows) return RAD_E_SHAPE;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)rows * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t r = (int64_t)it.get_group(0);
const int t = (int)it.get_local_id(0);
const float ss = ordered_sumsq(
it, [&](int64_t i) { return rad_load_f32(x.base, x.dtype, r * x.pitch + i); }, n);
const float s = 1.0f / sycl::sqrt(ss / (float)n + eps);
for (int64_t i = t; i < n; i += kWg) {
const float gw = g.base ? rad_load_f32(g.base, g.dtype, i * g.stride) + wadd : 1.0f;
const float v = rad_load_f32(x.base, x.dtype, r * x.pitch + i);
rad_store_f32(y.base, y.dtype, r * y.pitch + i, v * s * gw * mult);
}
});
});
}
/* ------------------------------------------------------------------ quant_act_fp8 */
int quant_act_fp8(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const int64_t n = rad_args_geti_or(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
int64_t g = rad_args_geti_or(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
Rows x, qv, sv;
if (int rc = rows_view(&a->t[0], n, &x, "quant_act_fp8 x"); rc < 0) return rc;
const int64_t rows = x.rows;
if (rows <= 0 || rad_tensor_numel(&a->t[1]) < rows * n) return RAD_E_SHAPE;
if (int rc = rows_view(&a->t[1], n, &qv, "quant_act_fp8 q"); rc < 0) return rc;
if (int rc = scale_view(&a->t[2], rows, ngrp, &sv, "quant_act_fp8 scale"); rc < 0) return rc;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
constexpr int kSubs = (int)(kWg / kSub);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)rows * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t r = (int64_t)it.get_group(0);
const sycl::sub_group sg = it.get_sub_group();
const int sgi = (int)sg.get_group_linear_id();
auto v = [&](int64_t i) { return rad_load_f32(x.base, x.dtype, r * x.pitch + i); };
for (int64_t gi = sgi; gi < ngrp; gi += kSubs) {
const int64_t k0 = gi * g, len = sycl::min(g, n - k0);
const float sc = quant_group(sg, v, k0, len, 448.0f, qv.base, qv.dtype, r * qv.pitch);
if (sg.get_local_linear_id() == 0)
rad_store_f32(sv.base, sv.dtype, r * sv.pitch + gi, sc);
}
});
});
}
/* ------------------------------------------------------------------ rmsnorm_quant_fp8 */
int rmsnorm_quant_fp8(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 5) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *W = &a->t[2], *Q = &a->t[3], *S = &a->t[4];
const RadTensor* R = rad_arg_in(a, 1);
const RadTensor* O = rad_arg_in(a, 5);
if (!X->data || !W->data || !Q->data || !S->data) return RAD_E_INVAL;
const int64_t n = rad_args_geti_or(a, "n", W->rank ? W->shape[W->rank - 1] : 0);
const float eps = (float)rad_args_getf_or(a, "eps", 1e-6);
const float wadd = (float)rad_args_getf_or(a, "wadd", 0.0);
if (n <= 0) return RAD_E_SHAPE;
int64_t g = rad_args_geti_or(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
Rows x, qv, sv, res, ob;
Gain gw;
if (int rc = rows_view(X, n, &x, "rmsnorm_quant_fp8 x"); rc < 0) return rc;
const int64_t rows = x.rows;
if (rows <= 0 || rad_tensor_numel(Q) < rows * n) return RAD_E_SHAPE;
if (int rc = rows_view(Q, n, &qv, "rmsnorm_quant_fp8 q"); rc < 0) return rc;
if (int rc = scale_view(S, rows, ngrp, &sv, "rmsnorm_quant_fp8 scale"); rc < 0) return rc;
if (int rc = gain_view(W, n, &gw, "rmsnorm_quant_fp8 w"); rc < 0) return rc;
const bool has_res = R != nullptr, has_ob = O != nullptr;
if (has_res) {
if (rad_tensor_numel(R) < rows * n) return RAD_E_SHAPE;
if (int rc = rows_view(R, n, &res, "rmsnorm_quant_fp8 residual"); rc < 0) return rc;
}
if (has_ob) {
if (rad_tensor_numel(O) < rows * n) return RAD_E_SHAPE;
if (int rc = rows_view(O, n, &ob, "rmsnorm_quant_fp8 out_bf16"); rc < 0) return rc;
}
const float top = Q->dtype == RAD_I8 ? 127.0f : 448.0f;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
constexpr int kSubs = (int)(kWg / kSub);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)rows * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t r = (int64_t)it.get_group(0);
const int t = (int)it.get_local_id(0);
/* The residual sum, stored first; the rest reads it back narrowed. Other work-items
* read these elements below, hence the barrier. */
if (has_res) {
for (int64_t i = t; i < n; i += kWg) {
const float s = rad_load_f32(x.base, x.dtype, r * x.pitch + i) +
rad_load_f32(res.base, res.dtype, r * res.pitch + i);
rad_store_f32(res.base, res.dtype, r * res.pitch + i, s);
}
sycl::group_barrier(it.get_group());
}
auto src = [&](int64_t i) {
return has_res ? rad_load_f32(res.base, res.dtype, r * res.pitch + i)
: rad_load_f32(x.base, x.dtype, r * x.pitch + i);
};
const float ss = ordered_sumsq(it, src, n);
const float rs = 1.0f / sycl::sqrt(ss / (float)n + eps);
/* The normed value narrowed to bf16, as the unfused pair would write it. */
auto v = [&](int64_t i) {
const float w = rad_load_f32(gw.base, gw.dtype, i * gw.stride) + wadd;
return rad_bf16_to_f32(rad_f32_to_bf16(src(i) * rs * w));
};
const sycl::sub_group sg = it.get_sub_group();
const int sgi = (int)sg.get_group_linear_id();
for (int64_t gi = sgi; gi < ngrp; gi += kSubs) {
const int64_t k0 = gi * g, len = sycl::min(g, n - k0);
const float sc = quant_group(sg, v, k0, len, top, qv.base, qv.dtype, r * qv.pitch,
has_ob ? ob.base : nullptr, ob.dtype, r * ob.pitch);
if (sg.get_local_linear_id() == 0)
rad_store_f32(sv.base, sv.dtype, r * sv.pitch + gi, sc);
}
});
});
}
/* ------------------------------------------------------------------ gated_quant_fp8 */
int gated_quant_fp8(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *GU = &a->t[0], *Q = &a->t[1], *S = &a->t[2];
const RadTensor* O = rad_arg_in(a, 3);
const int64_t n = rad_args_geti_or(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const char* act_s = rad_args_gets_or(a, "act", nullptr);
int act = (int)rad_args_geti_or(a, "mode", 0);
if (act_s) act = !std::strcmp(act_s, "silu") ? 0 : !std::strcmp(act_s, "sigmoid") ? 1 : -1;
if (act != 0 && act != 1) return RAD_E_INVAL;
int64_t g = rad_args_geti_or(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
Rows gu, qv, sv, ob;
if (int rc = rows_view(GU, 2 * n, &gu, "gated_quant_fp8 gate_up"); rc < 0) return rc;
const int64_t rows = gu.rows;
if (rows <= 0 || rad_tensor_numel(Q) < rows * n) return RAD_E_SHAPE;
if (int rc = rows_view(Q, n, &qv, "gated_quant_fp8 q"); rc < 0) return rc;
if (int rc = scale_view(S, rows, ngrp, &sv, "gated_quant_fp8 scale"); rc < 0) return rc;
const bool has_ob = O != nullptr;
if (has_ob) {
if (rad_tensor_numel(O) < rows * n) return RAD_E_SHAPE;
if (int rc = rows_view(O, n, &ob, "gated_quant_fp8 out_bf16"); rc < 0) return rc;
}
const float top = Q->dtype == RAD_I8 ? 127.0f : 448.0f;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
/* The groups are independent, so a row spreads over ceil(ngrp / 16) work-groups, one group a
* sub-group: at decode (one row of 48 groups) three work-groups share the row, not one. */
constexpr int kSubs = (int)(kWg / kSub);
const int64_t per_row = (ngrp + kSubs - 1) / kSubs;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)(rows * per_row) * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t r = (int64_t)it.get_group(0) / per_row;
const sycl::sub_group sg = it.get_sub_group();
const int64_t gi = ((int64_t)it.get_group(0) % per_row) * kSubs + (int64_t)sg.get_group_linear_id();
if (gi >= ngrp) return; /* uniform across the sub-group */
auto v = [&](int64_t i) {
const float gt = rad_load_f32(gu.base, gu.dtype, r * gu.pitch + i);
const float up = rad_load_f32(gu.base, gu.dtype, r * gu.pitch + n + i);
const float sgm = sigmoidf(gt);
return rad_bf16_to_f32(rad_f32_to_bf16((act == 0 ? gt * sgm : sgm) * up));
};
const int64_t k0 = gi * g, len = sycl::min(g, n - k0);
const float sc = quant_group(sg, v, k0, len, top, qv.base, qv.dtype, r * qv.pitch,
has_ob ? ob.base : nullptr, ob.dtype, r * ob.pitch);
if (sg.get_local_linear_id() == 0) rad_store_f32(sv.base, sv.dtype, r * sv.pitch + gi, sc);
});
});
}
} // namespace xe2
+65
View File
@@ -0,0 +1,65 @@
/* xe2_ops.h -- every libxe2 launch, by op. The rows that select them are in xe2_rows.cpp. */
#pragma once
#include "rad_abi.h"
namespace xe2 {
int add(const RadArgs* a, RadStream s);
int rmsnorm(const RadArgs* a, RadStream s);
int rmsnorm_quant_fp8(const RadArgs* a, RadStream s);
int quant_act_fp8(const RadArgs* a, RadStream s);
int gated_quant_fp8(const RadArgs* a, RadStream s);
int rope(const RadArgs* a, RadStream s);
int embed_lookup(const RadArgs* a, RadStream s);
int gather_rows(const RadArgs* a, RadStream s);
int cast(const RadArgs* a, RadStream s);
int gemm_nt(const RadArgs* a, RadStream s);
int logits_gemm(const RadArgs* a, RadStream s);
int kv_store(const RadArgs* a, RadStream s);
int attn_paged(const RadArgs* a, RadStream s);
int sample_penalties(const RadArgs* a, RadStream s);
int sample_dry(const RadArgs* a, RadStream s);
int sample_ngram_ban(const RadArgs* a, RadStream s);
int sample_temp(const RadArgs* a, RadStream s);
int sample_mask(const RadArgs* a, RadStream s);
int sample_topk(const RadArgs* a, RadStream s);
int sample_topp(const RadArgs* a, RadStream s);
int sample_minp(const RadArgs* a, RadStream s);
int sample_typical(const RadArgs* a, RadStream s);
int sample_xtc(const RadArgs* a, RadStream s);
int sample_pick(const RadArgs* a, RadStream s);
int sample_argmax(const RadArgs* a, RadStream s);
int sample_logprobs(const RadArgs* a, RadStream s);
int gemm_nt_q(const RadArgs* a, RadStream s);
int gemm_nt_q_gated(const RadArgs* a, RadStream s);
int silu_mul(const RadArgs* a, RadStream s);
int quant_act_i8(const RadArgs* a, RadStream s);
int row_topk(const RadArgs* a, RadStream s);
int dflash_select(const RadArgs* a, RadStream s);
int gemm_nt_q_zp(const RadArgs* a, RadStream s);
/* Phase 4's fast kernels (xe2_gemv.cpp). XE2_EXACT=1 sends them to the correctness-first ones. */
bool exact_only();
int gemm_nt_gemv(const RadArgs* a, RadStream s);
int logits_gemm_gemv(const RadArgs* a, RadStream s);
int gemm_nt_xmx(const RadArgs* a, RadStream s);
int logits_gemm_xmx(const RadArgs* a, RadStream s);
int attn_paged_fast(const RadArgs* a, RadStream s);
int64_t attn_paged_scratch(const RadArgs* a);
int gemm_zp_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out);
int gemm_zp_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, void* dst, int64_t dst_bytes);
int gemm_zp_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes, const RadTensor* planes,
int n);
} // namespace xe2
+130
View File
@@ -0,0 +1,130 @@
/* xe2_rope.cpp -- rotary position embedding over a packed qkv row, in place.
*
* The frequency ladder is computed on the host per launch, exactly as libref's rope_freqs does
* (theta^(2i/den) through a double pow, then YaRN or llama3 scaling from rad_yarn.h), and handed to
* the kernel as a table: at most 64 floats for MiniCPM5's head_dim 128. The card computes the
* angle pos * inv in f32 and its cosine and sine in double, rounded to f32, as libref's
* ref_cos/ref_sin are: positions reach 131072, where f32 range reduction is at its weakest.
*
* Modes: neox (i with i + rot/2) and gptj (2i with 2i+1), one position component per token. The
* multi-component modes (mrope, imrope, axial) are refused at launch with their name; their rows
* are not declared either (the `mode` constraint in xe2_rows.cpp).
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include "rad_yarn.h"
#include <cmath>
#include <cstring>
namespace xe2 {
namespace {
constexpr int kMaxHalf = 128; /* head_dim up to 256 */
struct Freqs {
float inv[kMaxHalf];
};
/* libref's row_stride: fold trailing axes until they span `cols`; the next axis out carries the
* row. */
int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
return t->stride[t->rank - 2];
}
} // namespace
int rope(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *QKV = &a->t[0], *POS = &a->t[1];
const int64_t head_dim = rad_args_geti_or(a, "head_dim", 0);
const int64_t n_head = rad_args_geti_or(a, "n_head", 0);
const int64_t n_head_kv = rad_args_geti_or(a, "n_head_kv", 0);
const float theta = (float)rad_args_getf_or(a, "theta", 10000.0);
const float rscale = (float)rad_args_getf_or(a, "scale", 1.0);
const char* mode_s = rad_args_gets_or(a, "mode", "");
int mode = -1;
if (!std::strcmp(mode_s, "neox")) mode = 0;
else if (!std::strcmp(mode_s, "gptj")) mode = 1;
else return refuse("rope: mode '%s' is not served (neox and gptj are)", mode_s);
int64_t rot = rad_args_geti_or(a, "rotary_dim", head_dim);
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
int64_t den = rot;
if (const char* lad = rad_args_gets_or(a, "ladder", nullptr)) {
if (!std::strcmp(lad, "head")) den = head_dim;
else if (std::strcmp(lad, "rotary")) return RAD_E_UNSUPPORTED;
}
if (rad_args_gets_or(a, "sections", nullptr) || POS->rank >= 2)
return refuse("rope: multi-component positions are not served");
const int64_t M = rad_tensor_numel(POS);
const int64_t nfreq = rot / 2;
if (den == head_dim && rot < head_dim && mode == 0) rot = head_dim;
const int64_t half = rot / 2;
if (half > kMaxHalf) return refuse("rope: rotary_dim %lld over %d", (long long)rot, 2 * kMaxHalf);
/* The ladder, as libref builds it. */
Freqs f{};
for (int64_t i = 0; i < half; ++i)
f.inv[i] = 1.0f / (float)std::pow((double)theta, (double)((float)(2 * i) / (float)den));
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn)) return RAD_E_INVAL;
if (yarn.factor != 0.0f) {
if (rscale != 1.0f) return RAD_E_UNSUPPORTED;
for (int64_t i = 0; i < half; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
}
const RadLlama3 l3 = rad_llama3_args(a);
if (!rad_llama3_valid(l3) || (l3.factor != 0.0f && yarn.factor != 0.0f)) return RAD_E_INVAL;
if (l3.factor != 0.0f)
for (int64_t i = 0; i < half; ++i) f.inv[i] = l3.frequency(f.inv[i]);
for (int64_t i = nfreq; i < half; ++i) f.inv[i] = 0.0f;
const float magnitude = yarn.magnitude;
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
if (M <= 0 || rad_tensor_numel(QKV) < M * stride_row) return RAD_E_SHAPE;
const int64_t rs = row_stride(QKV, stride_row);
const int64_t ds = QKV->rank ? QKV->stride[QKV->rank - 1] : 1;
char* base = (char*)QKV->data;
const uint32_t dt = QKV->dtype;
const char* pbase = (const char*)POS->data;
const uint32_t pdt = POS->dtype;
const bool pflt = pdt == RAD_F32 || pdt == RAD_BF16 || pdt == RAD_F16;
const bool pcontig = rad_tensor_is_contiguous(POS);
if (!pcontig) return refuse("rope: positions are not contiguous");
const float div = rscale != 0.0f ? rscale : 1.0f;
const int64_t heads = n_head + n_head_kv;
const int64_t total = M * heads * half;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t wg = 128;
const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t g = (int64_t)it.get_global_id(0);
if (g >= total) return;
const int64_t i = g % half, h = (g / half) % heads, m = g / (half * heads);
const float p = (pflt ? rad_load_f32(pbase, pdt, m) : (float)ld_index(pdt, pbase, m)) / div;
const float ang = p * f.inv[i];
const float c = (float)sycl::cos((double)ang) * magnitude;
const float s = (float)sycl::sin((double)ang) * magnitude;
const int64_t i0 = mode == 1 ? 2 * i : i;
const int64_t i1 = mode == 1 ? 2 * i + 1 : i + half;
const int64_t hb = m * rs + h * head_dim * ds;
const float x0 = rad_load_f32(base, dt, hb + i0 * ds);
const float x1 = rad_load_f32(base, dt, hb + i1 * ds);
rad_store_f32(base, dt, hb + i0 * ds, x0 * c - x1 * s);
rad_store_f32(base, dt, hb + i1 * ds, x0 * s + x1 * c);
});
});
}
} // namespace xe2
+262
View File
@@ -0,0 +1,262 @@
/* xe2_rows.cpp -- libxe2's plugin exports: identity and the kernel rows the engine selects from.
*
* libxe2 is radiance's kernel library for Intel Xe2 GPUs (the Arc Pro B65, Battlemage G31) through
* SYCL. It defines no op schemas of its own: every op it serves is in the conventional vocabulary,
* whose schemas libref fixes (docs/OPS.md). All rows are device-domain; an op libxe2 lacks has no
* row here, and on the SYCL backend the engine stops at startup naming it (docs/SYCL_PORTING.md
* §4.4).
*/
#include "rad_abi.h"
#include "xe2_ops.h"
namespace {
const RadConstraint cRopeModes[] = { RAD_CIN("mode", "neox gptj") };
/* The GEMMs here read float weights only; a quantised dtype key is gemm_nt_q's. */
const RadConstraint cFloatDtype[] = { RAD_CIN("dtype", "bf16 f16 fp16 f32 fp32") };
/* The decode band of the skinny bf16 GEMV (xe2_gemv.cpp). */
const RadConstraint cGemvBf16[] = { RAD_CIN("dtype", "bf16"), RAD_CLE("M", 16) };
/* The prefill band of the bf16 XMX GEMM (xe2_gemm_xmx.cpp). */
const RadConstraint cXmxBf16[] = { RAD_CIN("dtype", "bf16"), RAD_CGE("M", 17) };
/* The block-scaled pairs xe2_gemm_q.cpp serves; the zero-point grids (w2a8, w4*_asym) and mxfp4 are
* other rows. */
const RadConstraint cFp8Dtype[] = { RAD_CIN("dtype", "fp8a8 fp8a8f32 fp8a16") };
const RadConstraint cFp8Gated[] = { RAD_CIN("dtype", "fp8a8 fp8a8f32 fp8a16"), RAD_CLE("N", 57344) };
/* The zero-point grids over quant_act_i8's activation (xe2_gemm_zp.cpp). */
const RadConstraint cZpI8Dtype[] = { RAD_CIN("dtype", "w2a8 w4a8_asym") };
/* Rows by field name (C++20 designated initialisers must follow declaration order, so the compiler
* checks it), unlike a positional table where a shifted field can still compile. */
const RadKernelInfo kKernels[] = {
{ .name = "xe2_add", .op = "add", .family = "elem",
.computes = "elementwise sum, b broadcast along rows when it is one row; optional div",
.shape = "any n and row count; rows may be padded, the last axis dense",
.dtypes = "any float dtype in and out (bf16, f16, f32, fp8), f32 arithmetic, rounded as libref",
.domain = RAD_DOMAIN_DEVICE, .priority = 0,
.launch = xe2::add },
{ .name = "xe2_rmsnorm", .op = "rmsnorm", .family = "norm",
.computes = "RMS norm, one work-group a row, f32 work-group reduction",
.shape = "any n; rows may be padded",
.dtypes = "float x, gain and y (bf16 in the recipes), f32 arithmetic",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::rmsnorm },
{ .name = "xe2_rmsnorm_quant_fp8", .op = "rmsnorm_quant_fp8", .family = "norm",
.computes = "residual add (optional), RMS norm, bf16 narrowing, E4M3 codes and an f32 scale "
"per group; int8 codes at amax/127 for an int8 q",
.shape = "any n and group; one sub-group a quantisation group",
.dtypes = "bf16 in, E4M3 (or i8) codes, f32 scales, optional bf16 out",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::rmsnorm_quant_fp8 },
{ .name = "xe2_quant_act_fp8", .op = "quant_act_fp8", .family = "quant",
.computes = "E4M3 codes and an f32 scale amax/448 per group",
.shape = "any n and group",
.dtypes = "float in, E4M3 codes, f32 scales",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::quant_act_fp8 },
{ .name = "xe2_gated_quant_fp8", .op = "gated_quant_fp8", .family = "quant",
.computes = "silu(gate)*up or sigmoid(gate)*up over packed gate_up, bf16 narrowing, E4M3 "
"codes and an f32 scale per group",
.shape = "any n and group",
.dtypes = "bf16 gate_up, E4M3 (or i8) codes, f32 scales, optional bf16 out",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::gated_quant_fp8 },
{ .name = "xe2_rope", .op = "rope", .family = "rope",
.computes = "rotary embedding in place over q and k heads; frequency ladder (YaRN, llama3) "
"on the host as libref builds it, cos/sin in double",
.shape = "neox or gptj, one position component a token, rotary_dim <= 256",
.dtypes = "bf16 qkv (any float), integer or float positions",
.domain = RAD_DOMAIN_DEVICE, .constraints = cRopeModes, .n_constraints = 1,
.launch = xe2::rope },
{ .name = "xe2_embed_lookup", .op = "embed_lookup", .family = "vocab",
.computes = "embedding gather times mult; an id outside the table writes a zero row",
.shape = "any n_embd and n_vocab, vocab_offset",
.dtypes = "integer ids, float table and output",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::embed_lookup },
{ .name = "xe2_gather_rows", .op = "gather_rows", .family = "elem",
.computes = "row gather; a negative or out-of-range index writes a zero row",
.shape = "any n",
.dtypes = "integer indices, float rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::gather_rows },
{ .name = "xe2_cast", .op = "cast", .family = "elem",
.computes = "dtype conversion; integer to integer exact",
.shape = "any strides (libref's offlin order)",
.dtypes = "any float or integer pair",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::cast },
{ .name = "xe2_gemm_nt_gemv", .op = "gemm_nt", .family = "gemm",
.computes = "skinny Y = A B^T for decode: a sub-group an output column, 16-byte coalesced "
"weight loads, a tree reduction (not libref's order; checked at the gemm "
"tolerance). XE2_EXACT=1 runs xe2_gemm_nt_ref instead",
.shape = "M <= 16; bf16 rows 16-byte aligned, K a multiple of 8 (else the exact kernel)",
.dtypes = "bf16 A and W, bf16 or f32 Y, f32 accumulate",
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .constraints = cGemvBf16, .n_constraints = 2,
.launch = xe2::gemm_nt_gemv },
{ .name = "xe2_logits_gemm_gemv", .op = "logits_gemm", .family = "gemm",
.computes = "logits at decode, as xe2_gemm_nt_gemv", .shape = "M <= 16",
.dtypes = "bf16 x and head, f32 logits",
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .constraints = cGemvBf16, .n_constraints = 2,
.launch = xe2::logits_gemm_gemv },
{ .name = "xe2_gemm_nt_xmx", .op = "gemm_nt", .family = "gemm",
.computes = "Y = A B^T on XMX (joint_matrix M8 N16 K16), B read column-major from the "
"[N, K] weight; tail rows by the GEMV. XE2_EXACT=1 runs xe2_gemm_nt_ref instead",
.shape = "M >= 17; N a multiple of 64, K of 16, bf16 rows 16-byte aligned (else the exact "
"kernel)",
.dtypes = "bf16 A and W, bf16 or f32 Y, f32 accumulate",
.domain = RAD_DOMAIN_DEVICE, .priority = 5, .constraints = cXmxBf16, .n_constraints = 2,
.launch = xe2::gemm_nt_xmx },
{ .name = "xe2_logits_gemm_xmx", .op = "logits_gemm", .family = "gemm",
.computes = "logits at prefill sizes, as xe2_gemm_nt_xmx", .shape = "M >= 17",
.dtypes = "bf16 x and head, f32 logits",
.domain = RAD_DOMAIN_DEVICE, .priority = 5, .constraints = cXmxBf16, .n_constraints = 2,
.launch = xe2::logits_gemm_xmx },
{ .name = "xe2_gemm_nt_ref", .op = "gemm_nt", .family = "gemm",
.computes = "Y = A B^T, one work-item an output, f32 over ascending k (libref's order); the "
"correctness-first form, not the fast one",
.shape = "any M, N, K; strided A",
.dtypes = "float A and W (bf16 in the recipes), float Y",
.domain = RAD_DOMAIN_DEVICE, .constraints = cFloatDtype, .n_constraints = 1,
.launch = xe2::gemm_nt },
{ .name = "xe2_logits_gemm_ref", .op = "logits_gemm", .family = "gemm",
.computes = "logits = x lm_head^T, as xe2_gemm_nt_ref",
.shape = "any M, n_vocab, n_embd",
.dtypes = "float x and head, f32 logits",
.domain = RAD_DOMAIN_DEVICE, .constraints = cFloatDtype, .n_constraints = 1,
.launch = xe2::logits_gemm },
{ .name = "xe2_kv_store", .op = "kv_store", .family = "attn",
.computes = "this step's K and V into the paged cache at slot_mapping; fp8 stores k/k_scale",
.shape = "any head_dim, kv heads and block size; a negative or out-of-range slot is skipped",
.dtypes = "bf16 k and v, bf16 or E4M3 cache",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::kv_store },
{ .name = "xe2_attn_paged", .op = "attn_paged", .family = "attn",
.computes = "split-KV paged attention with an online softmax: a work-group a (row, kv head, "
"key partition), its sub-groups the kv head's query heads, partitions merged from "
"scratch (not libref's order). XE2_EXACT=1 runs xe2_attn_paged_ref instead",
.shape = "head_dim a multiple of 16 up to 256 (else the exact kernel); any gqa, causal or "
"not, sliding window, ragged batches",
.dtypes = "bf16 query, bf16 or E4M3 cache with per-(seq, head) descales, bf16 out",
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = xe2::attn_paged_fast,
.scratch = xe2::attn_paged_scratch },
{ .name = "xe2_attn_paged_ref", .op = "attn_paged", .family = "attn",
.computes = "paged attention, one work-group a (row, head), libref's order: serial dots, "
"keys summed in order; the correctness-first form",
.shape = "head_dim <= 512, any gqa, causal or not, sliding window, ragged batches",
.dtypes = "bf16 query, bf16 or E4M3 cache with per-(seq, head) descales, bf16 out",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::attn_paged },
{ .name = "xe2_sample_penalties", .op = "sample_penalties", .family = "sample",
.computes = "repetition, frequency and presence penalties over the row's history", .shape = "one work-item a row",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_penalties },
{ .name = "xe2_sample_dry", .op = "sample_dry", .family = "sample",
.computes = "DRY penalty over the row's history", .shape = "one work-item a row; quadratic in the window, as libref",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_dry },
{ .name = "xe2_sample_ngram_ban", .op = "sample_ngram_ban", .family = "sample",
.computes = "windowed no-repeat-ngram ban, optional whitelist", .shape = "one work-item a row",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_ngram_ban },
{ .name = "xe2_sample_temp", .op = "sample_temp", .family = "sample",
.computes = "logits divided by the row's temperature", .shape = "one work-item an element",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_temp },
{ .name = "xe2_sample_mask", .op = "sample_mask", .family = "sample",
.computes = "grammar bitmask: a cleared bit sets -inf", .shape = "one work-item an element",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_mask },
{ .name = "xe2_sample_topk", .op = "sample_topk", .family = "sample",
.computes = "the row's top_k candidates, descending, ties to the lower id", .shape = "one work-group a row, k reduction rounds",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_topk },
{ .name = "xe2_sample_topp", .op = "sample_topp", .family = "sample",
.computes = "top-p over the candidate set", .shape = "one work-item a row",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_topp },
{ .name = "xe2_sample_minp", .op = "sample_minp", .family = "sample",
.computes = "min-p over the candidate set", .shape = "one work-item a row",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_minp },
{ .name = "xe2_sample_typical", .op = "sample_typical", .family = "sample",
.computes = "locally typical sampling over the candidate set", .shape = "one work-item a row",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_typical },
{ .name = "xe2_sample_xtc", .op = "sample_xtc", .family = "sample",
.computes = "exclude top choices, seeded coin", .shape = "one work-item a row",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_xtc },
{ .name = "xe2_sample_pick", .op = "sample_pick", .family = "sample",
.computes = "inverse-CDF draw over the candidates, seeded per row", .shape = "one work-item a row",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_pick },
{ .name = "xe2_sample_argmax", .op = "sample_argmax", .family = "sample",
.computes = "greedy token, ties to the lower id", .shape = "one work-group a row",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_argmax },
{ .name = "xe2_sample_logprobs", .op = "sample_logprobs", .family = "sample",
.computes = "max, double normaliser and the top k (id, logit) pairs", .shape = "one work-group a row",
.dtypes = "f32 logits and candidates, RadSampleParams rows",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_logprobs },
{ .name = "xe2_gemm_nt_q_fp8_ref", .op = "gemm_nt_q", .family = "gemm",
.computes = "Y = A B^T over E4M3 codes with group and block scales, libref's quant_dot per "
"output; the correctness-first form",
.shape = "any M, N, K; 128x128 block or per-row group scale grids",
.dtypes = "fp8a8, fp8a8f32, fp8a16: E4M3 weights, E4M3 or bf16 activations",
.domain = RAD_DOMAIN_DEVICE, .constraints = cFp8Dtype, .n_constraints = 1,
.launch = xe2::gemm_nt_q },
{ .name = "xe2_gemm_nt_q_gated_fp8_ref", .op = "gemm_nt_q_gated", .family = "gemm",
.computes = "gemm_nt_q over a gate_up plane with gated_quant_fp8 in the epilogue, one "
"work-group a row",
.shape = "N <= 57344 (n gated values in local memory)",
.dtypes = "fp8a8, fp8a8f32, fp8a16; E4M3 (or i8) codes and f32 scales out",
.domain = RAD_DOMAIN_DEVICE, .constraints = cFp8Gated, .n_constraints = 2,
.launch = xe2::gemm_nt_q_gated },
{ .name = "xe2_silu_mul", .op = "silu_mul", .family = "elem",
.computes = "silu(gate) * up over a packed gate_up", .shape = "any n",
.dtypes = "bf16 (any float)", .domain = RAD_DOMAIN_DEVICE, .launch = xe2::silu_mul },
{ .name = "xe2_quant_act_i8", .op = "quant_act_i8", .family = "quant",
.computes = "int8 codes with one scale a row, in the int8 WMMA step order; optional group sums",
.shape = "n a multiple of 16", .dtypes = "float in, i8 codes, f32 scale",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::quant_act_i8 },
{ .name = "xe2_row_topk", .op = "row_topk", .family = "sample",
.computes = "exact per-row top-R, descending, ties to the lower column; one work-group a row",
.shape = "any N and R", .dtypes = "float x, integer ids and float values out",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::row_topk },
{ .name = "xe2_dflash_select", .op = "dflash_select", .family = "draft",
.computes = "the block drafter's greedy walk over its candidate lattice, one work-item a "
"sequence",
.shape = "any steps, top_k and rank", .dtypes = "integer candidates, float scores and factors",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::dflash_select },
{ .name = "xe2_gemm_nt_q_zp_ref", .op = "gemm_nt_q", .family = "gemm",
.computes = "Y = A B^T over an unsigned zero-point grid against quant_act_i8's activation, "
"libref's gemm_zp per output; the correctness-first form",
.shape = "any M, N; K a multiple of 16 and of group",
.dtypes = "w2a8, w4a8_asym: u2/u4 codes, f16 scale and unsigned zero per (row, group), i8 "
"activation in step order with row scale and group sums",
.domain = RAD_DOMAIN_DEVICE, .constraints = cZpI8Dtype, .n_constraints = 1,
.launch = xe2::gemm_nt_q_zp, .layout = xe2::gemm_zp_layout,
.relayout = xe2::gemm_zp_relayout, .unrelayout = xe2::gemm_zp_unrelayout },
};
const RadPluginInfo kInfo = {
RAD_PLUGIN_KERNEL, "libxe2", "0.1",
"Intel Xe2 (Battlemage) kernels in SYCL, checked against libref",
"intel_gpu_bmg_g31",
};
} // namespace
extern "C" {
__attribute__((visibility("default"))) uint32_t rad_plugin_abi_version(void) {
return RAD_ABI_VERSION;
}
__attribute__((visibility("default"))) const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
__attribute__((visibility("default"))) int rad_kernel_schema_count(void) { return 0; }
__attribute__((visibility("default"))) const RadOpSchema* rad_kernel_schema_at(int) { return nullptr; }
__attribute__((visibility("default"))) int rad_kernel_count(void) {
return (int)(sizeof kKernels / sizeof kKernels[0]);
}
__attribute__((visibility("default"))) const RadKernelInfo* rad_kernel_at(int i) {
return i >= 0 && i < rad_kernel_count() ? &kKernels[i] : nullptr;
}
} // extern "C"
+684
View File
@@ -0,0 +1,684 @@
/* xe2_sample.cpp -- the sampler ops: libref's arithmetic (ref_sample.cpp), on the card.
*
* Every scalar is per row, read from the `params` operand of RadSampleParams (abi/rad_sample.h).
* Three shapes of kernel, correctness first:
*
* one work-item a row the stages whose arithmetic is a serial walk: penalties, DRY and the
* n-gram ban over the row's history, the narrowing stages (top-p, min-p,
* typical, XTC) and the pick over at most a thousand candidates. These
* are libref's loops, unchanged, so their sums run in libref's order.
* one work-item an element temperature and the grammar mask.
* one work-group a row the full-vocabulary scans (argmax, top-k, logprobs), as reductions
* over a 64-bit key: the value's order-preserving bits above the
* complemented index, so the maximum key is the largest value and, among
* equal values, the lowest index -- libref's tie rule ("ties to the lower
* token id"). -0 is folded to +0 first, since libref compares floats and
* -0 == +0. A NaN logit is never selected (libref's scans would take one
* only by accident of order).
*
* Top-k selects its k candidates in k rounds, each a group reduction over the keys below the
* previous pick: libref's topk_next, k times. A greedy row takes none, so the greedy path costs one
* round trip of the row.
*
* logprobs' normaliser is a double sum, as libref's, here by a group reduction; the f32 it rounds to
* is the reference's but for a double-rounding tie.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include "rad_sample.h"
#include <cfloat>
#include <cmath>
#include <cstring>
namespace xe2 {
namespace {
constexpr size_t kRowWg = 1024; /* work-items a row for the full-vocabulary scans */
/* The params operand, checked once (libref's param_rows). */
int param_rows(const RadTensor* t, int64_t M, const RadSampleParams** out) {
if (!t || !t->data) return RAD_E_INVAL;
if (t->dtype != RAD_U32 && t->dtype != RAD_I32 && t->dtype != RAD_F32) return RAD_E_DTYPE;
if (rad_tensor_numel(t) * 4 < M * (int64_t)sizeof(RadSampleParams)) return RAD_E_SHAPE;
*out = (const RadSampleParams*)t->data;
return RAD_OK;
}
/* A logits row: the vocabulary width from the parameter or the last extent; M = numel / width. */
int logits_rows(const RadArgs* a, const RadTensor* lg, int64_t* n_vocab, Rows* out, const char* op) {
*n_vocab = rad_args_geti_or(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (*n_vocab <= 0) return RAD_E_SHAPE;
if (int rc = rows_view(lg, *n_vocab, out, op); rc < 0) return rc;
return out->rows > 0 ? RAD_OK : RAD_E_SHAPE;
}
/* The history plane, [M, hmax] with rows of its own. */
int hist_rows(const RadTensor* h, int64_t M, Rows* out, const char* op) {
const int64_t hmax = rad_tensor_numel(h) / M;
if (hmax <= 0) return RAD_E_SHAPE;
return rows_view(h, hmax, out, op);
}
/* libref's hist_window. */
inline bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_t hmax, int64_t* ho_out,
int64_t* hl_out) {
if (last_n == 0) return false;
int64_t hl = sp.hist_len;
int64_t ho = sp.hist_off < 0 ? 0 : sp.hist_off;
if (ho > hmax) ho = hmax;
if (hl > hmax - ho) hl = hmax - ho;
if (last_n > 0 && hl > last_n) {
ho += hl - last_n;
hl = last_n;
}
*ho_out = ho;
*hl_out = hl;
return hl > 0;
}
inline float ref_exp(float x) { return (float)sycl::exp((double)x); }
inline float ref_log(float x) { return (float)sycl::log((double)x); }
/* A candidate plane row: cand_idx (integer) and cand_val (float), rows of n_cand. */
struct Cands {
Rows idx, val;
int64_t n_cand = 0;
};
int cand_rows(const RadTensor* ci, const RadTensor* cv, int64_t n_cand, int64_t M, Cands* out,
const char* op) {
out->n_cand = n_cand;
if (rad_tensor_numel(ci) < M * n_cand || rad_tensor_numel(cv) < M * n_cand) return RAD_E_SHAPE;
if (int rc = rows_view(ci, n_cand, &out->idx, op); rc < 0) return rc;
return rows_view(cv, n_cand, &out->val, op);
}
/* One work-item a row over M rows. */
template <class F>
int per_row(sycl::queue* q, int64_t M, F&& body) {
const size_t wg = 16;
const size_t n = (size_t)((M + (int64_t)wg - 1) / (int64_t)wg) * wg;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{n, wg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_global_id(0);
if (m < M) body(m);
});
});
}
} // namespace
/* ------------------------------------------------------------------ sample_penalties */
int sample_penalties(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
int64_t n_vocab = 0;
Rows lg, hist;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_penalties"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
if (int rc = hist_rows(&a->t[2], M, &hist, "sample_penalties history"); rc < 0) return rc;
const int64_t hmax = rad_tensor_numel(&a->t[2]) / M;
const int64_t voff = rad_args_geti_or(a, "vocab_off", 0);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return per_row(q, M, [=](int64_t m) {
const RadSampleParams& sp = P[m];
if (!(sp.flags & RAD_SP_PENALTY)) return;
const float rep = sp.rep_penalty, freq = sp.freq_penalty, pres = sp.pres_penalty;
if (rep == 1.0f && freq == 0.0f && pres == 0.0f) return;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, sp.penalty_last_n, hmax, &ho, &hl)) return;
const int64_t hb = m * hist.pitch + ho;
auto tok_at = [&](int64_t i) { return ld_index(hist.dtype, hist.base, hb + i); };
for (int64_t i = 0; i < hl; ++i) {
const int64_t tok = tok_at(i);
const int64_t col = tok - voff;
if (tok < 0 || col < 0 || col >= n_vocab) continue;
bool first = true;
int64_t count = 0;
for (int64_t j = 0; j < hl; ++j) {
if (tok_at(j) != tok) continue;
if (j < i) { first = false; break; }
++count;
}
if (!first) continue;
const int64_t off = m * lg.pitch + col;
float v = rad_load_f32(lg.base, lg.dtype, off);
v = v > 0.0f ? v / rep : v * rep;
v -= (float)count * freq;
v -= pres;
rad_store_f32(lg.base, lg.dtype, off, v);
}
});
}
/* ------------------------------------------------------------------ sample_dry */
int sample_dry(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor* BRK = rad_arg_in(a, 3);
int64_t n_vocab = 0;
Rows lg, hist, brk;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_dry"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
if (int rc = hist_rows(&a->t[2], M, &hist, "sample_dry history"); rc < 0) return rc;
const int64_t hmax = rad_tensor_numel(&a->t[2]) / M;
const bool has_brk = BRK != nullptr;
if (has_brk) {
if (rad_tensor_numel(BRK) < M * hmax) return RAD_E_SHAPE;
if (int rc = rows_view(BRK, hmax, &brk, "sample_dry breakers"); rc < 0) return rc;
}
const int64_t voff = rad_args_geti_or(a, "vocab_off", 0);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return per_row(q, M, [=](int64_t m) {
const RadSampleParams& sp = P[m];
if (!(sp.flags & RAD_SP_DRY) || !(sp.dry_multiplier > 0.0f)) return;
const int64_t allowed = sp.dry_allowed_length > 0 ? sp.dry_allowed_length : 2;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, sp.dry_penalty_last_n, hmax, &ho, &hl)) return;
if (hl <= allowed) return;
const int64_t cap = sp.dry_rep_limit > 0 && sp.dry_rep_limit < hl ? sp.dry_rep_limit : hl;
if (cap < allowed) return;
const int64_t hb = m * hist.pitch + ho;
const int64_t bb = has_brk ? m * brk.pitch + ho : 0;
auto tok_at = [&](int64_t i) { return ld_index(hist.dtype, hist.base, hb + i); };
auto exempt = [&](int64_t i) { return has_brk && ld_index(brk.dtype, brk.base, bb + i) != 0; };
/* The repeat length a continuation j + 1 would extend, or -1 when it does not count:
* libref's loop body, so the per-token maximum below is the same map libref builds. */
auto rep_len = [&](int64_t j) -> int64_t {
const int64_t lim = j + 1 < cap ? j + 1 : cap;
int64_t n = 0;
while (n < lim && tok_at(j - n) == tok_at(hl - 1 - n)) ++n;
if (n < allowed || exempt(j + 1)) return -1;
const int64_t next = tok_at(j + 1);
const int64_t col = next - voff;
if (next < 0 || col < 0 || col >= n_vocab) return -1;
return n;
};
const float base = sp.dry_base > 0.0f ? sp.dry_base : 1.75f;
for (int64_t j = 0; j + 1 < hl; ++j) {
const int64_t n = rep_len(j);
if (n < 0) continue;
const int64_t next = tok_at(j + 1);
/* Each token once, at its first qualifying position, with its longest repeat. */
bool first = true;
int64_t L = n;
for (int64_t j2 = 0; j2 + 1 < hl; ++j2) {
if (j2 == j || tok_at(j2 + 1) != next) continue;
const int64_t n2 = rep_len(j2);
if (n2 < 0) continue;
if (j2 < j) { first = false; break; }
if (n2 > L) L = n2;
}
if (!first) continue;
float pen = sp.dry_multiplier;
if (base != 1.0f) {
const float lim = FLT_MAX / base;
for (int64_t i = 0; i < L - allowed; ++i) {
if (pen > lim) break;
pen *= base;
}
}
const int64_t off = m * lg.pitch + (next - voff);
rad_store_f32(lg.base, lg.dtype, off, rad_load_f32(lg.base, lg.dtype, off) - pen);
}
});
}
/* ------------------------------------------------------------------ sample_ngram_ban */
int sample_ngram_ban(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor* NG = &a->t[3];
const RadTensor* WL = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr;
int64_t n_vocab = 0;
Rows lg, hist, ng, wl;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_ngram_ban"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
if (int rc = hist_rows(&a->t[2], M, &hist, "sample_ngram_ban history"); rc < 0) return rc;
const int64_t hmax = rad_tensor_numel(&a->t[2]) / M;
if (rad_tensor_numel(NG) < 2 * M) return RAD_E_SHAPE;
if (int rc = rows_view(NG, 2, &ng, "sample_ngram_ban ngram"); rc < 0) return rc;
const int64_t wwords = (n_vocab + 31) / 32;
const bool has_wl = WL != nullptr;
if (has_wl) {
if (WL->dtype != RAD_I32 && WL->dtype != RAD_U32) return RAD_E_DTYPE;
if (rad_tensor_numel(WL) < M * wwords) return RAD_E_SHAPE;
if (int rc = rows_view(WL, wwords, &wl, "sample_ngram_ban whitelist"); rc < 0) return rc;
}
const int64_t voff = rad_args_geti_or(a, "vocab_off", 0);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return per_row(q, M, [=](int64_t m) {
const RadSampleParams& sp = P[m];
const int64_t n = ld_index(ng.dtype, ng.base, m * ng.pitch);
const int64_t win_req = ld_index(ng.dtype, ng.base, m * ng.pitch + 1);
if (n <= 0) return;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, -1, hmax, &ho, &hl)) return;
if (hl < n) return;
const int64_t win = win_req > 0 && win_req < hl ? win_req : hl;
const int64_t search_start = hl - win, search_end = hl - n + 1;
if (search_end <= search_start) return;
const int64_t hb = m * hist.pitch + ho;
auto tok_at = [&](int64_t i) { return ld_index(hist.dtype, hist.base, hb + i); };
auto exempt = [&](int64_t col) {
if (!has_wl) return false;
const uint32_t word = (uint32_t)ld_index(wl.dtype, wl.base, m * wl.pitch + col / 32);
return ((word >> (uint32_t)(col % 32)) & 1u) != 0u;
};
const int64_t plen = n - 1, p0 = hl - plen;
for (int64_t idx = search_start; idx < search_end; ++idx) {
bool match = true;
for (int64_t j = 0; j < plen; ++j)
if (tok_at(idx + j) != tok_at(p0 + j)) { match = false; break; }
if (!match) continue;
const int64_t tok = tok_at(idx + plen);
const int64_t col = tok - voff;
if (tok < 0 || col < 0 || col >= n_vocab || exempt(col)) continue;
rad_store_f32(lg.base, lg.dtype, m * lg.pitch + col, -INFINITY);
}
});
}
/* ------------------------------------------------------------------ sample_temp, sample_mask */
int sample_temp(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
int64_t n_vocab = 0;
Rows lg;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_temp"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const int64_t total = M * n_vocab;
const size_t wg = 256, groups = (size_t)((total + 255) / 256);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t g = (int64_t)it.get_global_id(0);
if (g >= total) return;
const int64_t m = g / n_vocab, i = g % n_vocab;
const float t = P[m].temp;
if (!(t > 0.0f) || t == 1.0f) return;
const float inv = 1.0f / t;
const int64_t off = m * lg.pitch + i;
rad_store_f32(lg.base, lg.dtype, off, rad_load_f32(lg.base, lg.dtype, off) * inv);
});
});
}
int sample_mask(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
int64_t n_vocab = 0;
Rows lg, bm;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_mask"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
const int64_t words = (n_vocab + 31) / 32;
const int64_t mask_rows = rad_tensor_numel(&a->t[2]) / words;
if (mask_rows <= 0) return RAD_E_SHAPE;
if (int rc = rows_view(&a->t[2], words, &bm, "sample_mask bitmask"); rc < 0) return rc;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const int64_t total = M * n_vocab;
const size_t wg = 256, groups = (size_t)((total + 255) / 256);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t g = (int64_t)it.get_global_id(0);
if (g >= total) return;
const int64_t m = g / n_vocab, i = g % n_vocab;
const RadSampleParams& sp = P[m];
if (!(sp.flags & RAD_SP_MASK)) return;
const int64_t row = sp.mask_row;
if (row < 0 || row >= mask_rows) return;
const uint32_t word = (uint32_t)ld_index(bm.dtype, bm.base, row * bm.pitch + i / 32);
if (!((word >> (i % 32)) & 1u))
rad_store_f32(lg.base, lg.dtype, m * lg.pitch + i, -INFINITY);
});
});
}
/* ------------------------------------------------------------------ sample_argmax */
int sample_argmax(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor* TOK = &a->t[2];
int64_t n_vocab = 0;
Rows lg;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_argmax"); rc < 0) return rc;
const int64_t M = lg.rows;
if (rad_tensor_numel(TOK) < M) return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(TOK)) return refuse("sample_argmax: token not contiguous");
char* tb = (char*)TOK->data;
const uint32_t tdt = TOK->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)M * kRowWg, kRowWg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0);
uint64_t best = 0;
for (int64_t i = (int64_t)it.get_local_id(0); i < n_vocab; i += (int64_t)kRowWg)
best = sycl::max(best, sel_key(rad_load_f32(lg.base, lg.dtype, m * lg.pitch + i), i));
best = sycl::reduce_over_group(it.get_group(), best, sycl::maximum<uint64_t>());
if (it.get_local_id(0) == 0) {
/* All NaN: libref takes index 0 (its first element always seeds the scan). */
const int64_t bi = best ? key_index(best) : 0;
if (tdt == RAD_I64) ((int64_t*)tb)[m] = bi;
else ((int32_t*)tb)[m] = (int32_t)bi;
}
});
});
}
/* ------------------------------------------------------------------ sample_topk */
int sample_topk(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *CI = &a->t[2], *CV = &a->t[3];
const RadTensor* PP = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr;
int64_t n_vocab = 0;
Rows lg, pp;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_topk"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
const int64_t n_cand = CI->rank >= 2 ? CI->shape[CI->rank - 1] : rad_tensor_numel(CI) / M;
if (n_cand <= 0) return RAD_E_SHAPE;
Cands c;
if (int rc = cand_rows(CI, CV, n_cand, M, &c, "sample_topk"); rc < 0) return rc;
const bool has_pp = PP != nullptr;
if (has_pp) {
if (rad_tensor_numel(PP) < M * 2 * n_cand) return RAD_E_SHAPE;
if (int rc = rows_view(PP, 2 * n_cand, &pp, "sample_topk pairs"); rc < 0) return rc;
}
const int64_t voff = rad_args_geti_or(a, "vocab_off", 0);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)M * kRowWg, kRowWg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0);
const int lane = (int)it.get_local_id(0);
int64_t k = P[m].top_k;
if (k <= 0 || k > n_cand) k = n_cand;
if (P[m].flags & RAD_SP_GREEDY) k = 0;
/* prev starts above every key, so the first round takes the maximum; `more` is uniform
* across the group, so every work-item reaches the same reductions. */
uint64_t prev = ~(uint64_t)0;
bool more = true;
for (int64_t r = 0; r < n_cand; ++r) {
uint64_t best = 0;
if (r < k && more) {
for (int64_t i = lane; i < n_vocab; i += (int64_t)kRowWg) {
const uint64_t key = sel_key(rad_load_f32(lg.base, lg.dtype, m * lg.pitch + i), i);
if (key < prev) best = sycl::max(best, key);
}
best = sycl::reduce_over_group(it.get_group(), best, sycl::maximum<uint64_t>());
}
if (lane == 0) {
const bool ok = best != 0;
const int64_t pi = ok ? key_index(best) : -1;
const float pv = ok ? key_value(best) : -INFINITY;
const int64_t io = m * c.idx.pitch + r;
if (c.idx.dtype == RAD_I64) ((int64_t*)c.idx.base)[io] = pi;
else ((int32_t*)c.idx.base)[io] = (int32_t)pi;
rad_store_f32(c.val.base, c.val.dtype, m * c.val.pitch + r, pv);
if (has_pp) {
uint32_t bits;
std::memcpy(&bits, &pv, 4);
uint32_t* pr = (uint32_t*)pp.base + m * pp.pitch + 2 * r;
pr[0] = ok ? (uint32_t)(pi + voff) : 0xffffffffu;
pr[1] = bits;
}
}
if (best == 0) more = false;
else prev = best;
}
});
});
}
/* ------------------------------------------------------------------ the narrowing stages */
namespace {
enum Narrow { NR_TOPP, NR_MINP, NR_TYPICAL, NR_XTC };
int narrow(const RadArgs* a, RadStream st, Narrow which, const char* op) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *CI = &a->t[0], *CV = &a->t[1];
const int64_t n_cand = rad_args_geti_or(a, "n_cand", CI->rank >= 2 ? CI->shape[CI->rank - 1] : 0);
if (n_cand <= 0) return RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(CI) / n_cand;
if (M <= 0) return RAD_E_SHAPE;
Cands c;
if (int rc = cand_rows(CI, CV, n_cand, M, &c, op); rc < 0) return rc;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[2], M, &P); rc < 0) return rc;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return per_row(q, M, [=](int64_t m) {
const RadSampleParams& sp = P[m];
if (sp.flags & RAD_SP_GREEDY) return;
const int64_t ib = m * c.idx.pitch, vb = m * c.val.pitch;
auto drop = [&](int64_t i) {
if (c.idx.dtype == RAD_I64) ((int64_t*)c.idx.base)[ib + i] = -1;
else ((int32_t*)c.idx.base)[ib + i] = -1;
rad_store_f32(c.val.base, c.val.dtype, vb + i, -INFINITY);
};
auto live = [&](int64_t i) { return ld_index(c.idx.dtype, c.idx.base, ib + i) >= 0; };
auto val = [&](int64_t i) { return rad_load_f32(c.val.base, c.val.dtype, vb + i); };
float mx = -INFINITY;
for (int64_t i = 0; i < n_cand; ++i)
if (live(i)) { const float v = val(i); if (v > mx) mx = v; }
if (mx == -INFINITY) return;
if (which == NR_MINP) {
const float p = sp.min_p;
if (!(p > 0.0f)) return;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
const float v = val(i);
if (v == mx) continue;
if (ref_exp(v - mx) < p) drop(i);
}
return;
}
float sum = 0.0f;
for (int64_t i = 0; i < n_cand; ++i)
if (live(i)) sum += ref_exp(val(i) - mx);
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
if (which == NR_TOPP) {
const float p = sp.top_p;
if (!(p < 1.0f) || !(p > 0.0f)) return;
float cum = 0.0f;
bool done = false;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
if (done) { drop(i); continue; }
cum += ref_exp(val(i) - mx) * inv;
if (cum >= p) done = true;
}
return;
}
if (which == NR_TYPICAL) {
const float p = sp.typical_p;
if (!(p < 1.0f) || !(p > 0.0f)) return;
/* libref keeps q[] and d[]; here they are recomputed from the candidates, which give
* the same floats, since the plane is not written until the drops at the end. */
auto qp = [&](int64_t i) { return live(i) ? ref_exp(val(i) - mx) * inv : 0.0f; };
float H = 0.0f;
for (int64_t i = 0; i < n_cand; ++i) {
const float qi = qp(i);
if (qi > 0.0f) H -= qi * ref_log(qi);
}
auto dist = [&](float qi) { return sycl::fabs(-ref_log(qi) - H); };
float cut = 0.0f;
bool have_cut = false;
for (int64_t cc = 0; cc < n_cand; ++cc) {
const float qc = qp(cc);
if (!(qc > 0.0f)) continue;
const float dc = dist(qc);
float mass = 0.0f;
for (int64_t i = 0; i < n_cand; ++i) {
const float qi = qp(i);
if (qi > 0.0f && dist(qi) <= dc) mass += qi;
}
if (mass >= p && (!have_cut || dc < cut)) {
cut = dc;
have_cut = true;
}
}
if (!have_cut) return;
/* libref decides from a snapshot of q[]; dropping in order is the same, since a
* decision reads only mx, inv, H, cut and the candidate's own entry, which no other
* candidate's drop changes. */
for (int64_t i = 0; i < n_cand; ++i) {
const float qi = qp(i);
if (live(i) && (!(qi > 0.0f) || dist(qi) > cut)) drop(i);
}
return;
}
/* XTC */
if (!(sp.xtc_probability > 0.0f) || !(sp.xtc_threshold > 0.0f)) return;
if (rad_sample_uniform01(sp.seed ^ RAD_SAMPLE_KEY_XTC, sp.pos) >= sp.xtc_probability) return;
int64_t last_above = -1, n_above = 0;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
if (ref_exp(val(i) - mx) * inv >= sp.xtc_threshold) {
last_above = i;
++n_above;
}
}
if (n_above < 2) return;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i) || i == last_above) continue;
if (ref_exp(val(i) - mx) * inv >= sp.xtc_threshold) drop(i);
}
});
}
} // namespace
int sample_topp(const RadArgs* a, RadStream s) { return narrow(a, s, NR_TOPP, "sample_topp"); }
int sample_minp(const RadArgs* a, RadStream s) { return narrow(a, s, NR_MINP, "sample_minp"); }
int sample_typical(const RadArgs* a, RadStream s) { return narrow(a, s, NR_TYPICAL, "sample_typical"); }
int sample_xtc(const RadArgs* a, RadStream s) { return narrow(a, s, NR_XTC, "sample_xtc"); }
/* ------------------------------------------------------------------ sample_pick */
int sample_pick(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *CI = &a->t[0], *CV = &a->t[1], *TOK = &a->t[3];
const int64_t n_cand = rad_args_geti_or(a, "n_cand", CI->rank >= 2 ? CI->shape[CI->rank - 1] : 0);
if (n_cand <= 0) return RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(CI) / n_cand;
if (M <= 0 || rad_tensor_numel(TOK) < M) return RAD_E_SHAPE;
Cands c;
if (int rc = cand_rows(CI, CV, n_cand, M, &c, "sample_pick"); rc < 0) return rc;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[2], M, &P); rc < 0) return rc;
if (!rad_tensor_is_contiguous(TOK)) return refuse("sample_pick: token not contiguous");
char* tb = (char*)TOK->data;
const uint32_t tdt = TOK->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return per_row(q, M, [=](int64_t m) {
if (P[m].flags & RAD_SP_GREEDY) return;
const int64_t ib = m * c.idx.pitch, vb = m * c.val.pitch;
auto id_at = [&](int64_t i) { return ld_index(c.idx.dtype, c.idx.base, ib + i); };
auto val = [&](int64_t i) { return rad_load_f32(c.val.base, c.val.dtype, vb + i); };
auto put = [&](int64_t v) {
if (tdt == RAD_I64) ((int64_t*)tb)[m] = v;
else ((int32_t*)tb)[m] = (int32_t)v;
};
float mx = -INFINITY;
for (int64_t i = 0; i < n_cand; ++i) {
if (id_at(i) < 0) continue;
const float v = val(i);
if (v > mx) mx = v;
}
if (mx == -INFINITY) { put(-1); return; }
float sum = 0.0f;
for (int64_t i = 0; i < n_cand; ++i)
if (id_at(i) >= 0) sum += ref_exp(val(i) - mx);
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
const float u = rad_sample_uniform01(P[m].seed ^ RAD_SAMPLE_KEY_PICK, P[m].pos);
float cum = 0.0f;
int64_t chosen = -1, last = -1;
for (int64_t i = 0; i < n_cand; ++i) {
const int64_t id = id_at(i);
if (id < 0) continue;
const float v = val(i);
if (v > -INFINITY) last = id;
cum += ref_exp(v - mx) * inv;
if (u < cum) { chosen = id; break; }
}
put(chosen >= 0 ? chosen : last);
});
}
/* ------------------------------------------------------------------ sample_logprobs */
int sample_logprobs(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor* ST = &a->t[2];
int64_t n_vocab = 0;
Rows lg, so;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_logprobs"); rc < 0) return rc;
const int64_t k = rad_args_geti_or(a, "k", 0);
const int64_t voff = rad_args_geti_or(a, "vocab_off", 0);
if (k <= 0) return RAD_E_SHAPE;
const int64_t M = lg.rows;
const int64_t w = 2 + 2 * k;
if (rad_tensor_numel(ST) < M * w) return RAD_E_SHAPE;
if (int rc = rows_view(ST, w, &so, "sample_logprobs stats"); rc < 0) return rc;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)M * kRowWg, kRowWg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0);
if (!(P[m].flags & RAD_SP_LOGPROBS)) return; /* uniform across the group */
const int lane = (int)it.get_local_id(0);
const auto grp = it.get_group();
auto ld = [&](int64_t i) { return rad_load_f32(lg.base, lg.dtype, m * lg.pitch + i); };
float mx = -INFINITY;
for (int64_t i = lane; i < n_vocab; i += (int64_t)kRowWg) mx = sycl::fmax(mx, ld(i));
mx = sycl::reduce_over_group(grp, mx, sycl::maximum<float>());
double sum = 0.0;
for (int64_t i = lane; i < n_vocab; i += (int64_t)kRowWg)
sum += sycl::exp((double)ld(i) - (double)mx);
sum = sycl::reduce_over_group(grp, sum, sycl::plus<double>());
const int64_t sb = m * so.pitch;
if (lane == 0) {
rad_store_f32(so.base, so.dtype, sb, mx);
rad_store_f32(so.base, so.dtype, sb + 1, (float)sum);
}
uint64_t prev = ~(uint64_t)0;
for (int64_t j = 0; j < k; ++j) {
uint64_t best = 0;
if (prev != 0) {
for (int64_t i = lane; i < n_vocab; i += (int64_t)kRowWg) {
const uint64_t key = sel_key(ld(i), i);
if (key < prev) best = sycl::max(best, key);
}
best = sycl::reduce_over_group(grp, best, sycl::maximum<uint64_t>());
}
if (lane == 0) {
const bool have = best != 0;
rad_store_f32(so.base, so.dtype, sb + 2 + 2 * j,
have ? (float)(key_index(best) + voff) : -1.0f);
rad_store_f32(so.base, so.dtype, sb + 3 + 2 * j,
have ? key_value(best) : -INFINITY);
}
prev = best;
}
});
});
}
} // namespace xe2
+10
View File
@@ -55,3 +55,13 @@ output. `mcagent.sh` and `mcdecl.sh` start their own MiniCPM5-2B server through
| `mcstream.sh` | Tool-call replies streamed, asserting on raw SSE fragments rather than the assembled message. Streamed content cannot be retracted, so a repair applied at the end is not a fix. |
| `mcagent.sh` | What speculation is worth on an agentic workload: `/v1/chat/completions` with tools, a constrained decode. Speculation on and off alternate across restarts because the speculation depth is a server-level setting. |
| `mcdecl.sh` | How often the drafter proposes, by context length. `draft_acceptance_ratio` is conditional on having drafted, so it can look healthy while tokens per step collapse; blocks per step separates the two. |
## The Intel (SYCL) backend
Tools for the port in `docs/SYCL_PORTING.md`; its log is `docs/SYCL_PROGRESS.md`. They need oneAPI
(`. /opt/intel/oneapi/setvars.sh`) only where they compile device code.
| | |
|---|---|
| `sycl/probe.sh` | The card's limits, sub-group sizes and `joint_matrix` combinations, and whether XMX executes E4M3 / E5M2 DPAS, each checked against a host loop with bf16 and s8 DPAS as controls in the same harness (on the Arc Pro B65 fp8 DPAS compiles and returns garbage). |
| `sycl/op_inventory.sh` | The op vocabulary as a markdown table: libref's schemas, libr4d's kernels and dtypes per op (its rows read from source by `sycl/r4d_rows.py`, since a build without HIP has no `libr4d.so`), and which architectures name each op. |
+129
View File
@@ -0,0 +1,129 @@
#!/bin/sh
# bench_report.sh -- a BetterBench quick run against a live radiance server, its summary and a
# screenshot of its HTML report posted to the Discord webhook (docs/SYCL_PROGRESS.md, Benchmarks).
#
# Usage:
# scripts/sycl/bench_report.sh TAG [ENDPOINT] [SERVED_MODEL]
# runs `betterbench run --quick --decode --prefill` (the brief's command) into
# $RUNS/<date>-<TAG>-<commit>/, then reports it
# scripts/sycl/bench_report.sh --report RUN_DIR TAG
# reports an existing run (results.json and results.html in RUN_DIR) without running
#
# TAG the model and configuration, e.g. minicpm5-2b-bf16; runs with the same TAG are
# compared (the delta is against the newest earlier run of that TAG)
# ENDPOINT default http://127.0.0.1:8100/v1; SERVED_MODEL default: the server's first model
# BB BetterBench's venv (default ~/tools/betterbench-venv)
# RUNS where runs are kept (default ~/radiance-bench/runs)
# CHROMIUM_LIBS libraries headless Chromium lacks on this host, unpacked without root
# (default ~/tools/chromium-libs/root/usr/lib/x86_64-linux-gnu)
# CHROMIUM_FONTS a fontconfig file naming fonts for it (default ~/tools/chromium-libs/fonts.conf):
# this host has no fonts, and without them the report renders with no text
#
# Quick runs are 1 warmup and 5 passes: for tracking progress, not for publishing, and labelled so.
# The numbers are BetterBench's own (report.combined_score for decode, report.prefill_rows for
# prefill), so they are the ones its HTML report shows. The Discord message is built with jq and
# stays under 2000 characters; the webhook URL comes from ~/.config/radiance-bench.env and is never
# printed. A failed post is reported and the script exits 2; no webhook configured exits 0 after
# saying so (the run itself is kept either way).
set -eu
here=$(cd "$(dirname "$0")" && pwd)
root=$(cd "$here/../.." && pwd)
BB=${BB:-$HOME/tools/betterbench-venv}
RUNS=${RUNS:-$HOME/radiance-bench/runs}
CHROMIUM_LIBS=${CHROMIUM_LIBS:-$HOME/tools/chromium-libs/root/usr/lib/x86_64-linux-gnu}
CHROMIUM_FONTS=${CHROMIUM_FONTS:-$HOME/tools/chromium-libs/fonts.conf}
commit=$(git -C "$root" rev-parse --short HEAD)
if [ "${1:-}" = "--report" ]; then
run=${2:?--report RUN_DIR TAG}
tag=${3:?--report RUN_DIR TAG}
else
tag=${1:?usage: bench_report.sh TAG [ENDPOINT] [SERVED_MODEL]}
endpoint=${2:-http://127.0.0.1:8100/v1}
model=${3:-$(curl -sf "$endpoint/models" | jq -r '.data[0].id')}
run=$RUNS/$(date +%Y%m%d-%H%M%S)-$tag-$commit
mkdir -p "$run"
"$BB/bin/betterbench" run --endpoint "$endpoint" --model "$model" \
--quick --decode --prefill --no-update-check \
--name "sycl-$tag-$commit" --out "$run/results.json" \
--note backend=sycl --note gpu=arc-pro-b65 --note commit="$commit" > "$run/betterbench.log" 2>&1
fi
[ -f "$run/results.json" ] || { echo "bench_report.sh: no $run/results.json" >&2; exit 1; }
# The previous run of the same tag, for the delta.
# Directories start with their date, so string order is time order: the newest one before this.
prev=$(ls -d "$RUNS"/*-"$tag"-* 2>/dev/null | sort | awk -v r="$run" '$0 < r' | tail -n 1 || true)
[ -n "$prev" ] && [ -f "$prev/results.json" ] || prev=
# The summary, from BetterBench's own report functions.
"$BB/bin/python" -I - "$run/results.json" ${prev:+"$prev/results.json"} > "$run/summary.json" <<'EOF'
import json, sys
from betterbench import report
def summ(path):
r = json.load(open(path))
comb = report.combined_score(r) or {}
pre = [d for d in report.prefill_rows(r) if not d.get("skipped")]
deep = pre[-1] if pre else {}
return {"decode_med": comb.get("decode"), "decode_low1": comb.get("itl_low1"),
"prefill_med": deep.get("pp_med"), "prefill_low1": deep.get("pp_low1"),
"prefill_depth": deep.get("target_depth"),
"prefill": [{"depth": d["target_depth"], "med": d["pp_med"], "low1": d["pp_low1"]} for d in pre]}
out = {"now": summ(sys.argv[1])}
if len(sys.argv) > 2:
out["prev"] = summ(sys.argv[2])
print(json.dumps(out))
EOF
# The report's screenshot, the whole page, as JPEG (the user's choice of format).
html=$run/results.html
img=$run/report.jpg
if [ -f "$html" ]; then
LD_LIBRARY_PATH=$CHROMIUM_LIBS${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} FONTCONFIG_FILE=$CHROMIUM_FONTS \
"$BB/bin/python" -I - "$html" "$img" <<'EOF'
import sys
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
b = p.chromium.launch()
pg = b.new_page(viewport={"width": 1400, "height": 900}, device_scale_factor=1)
pg.goto("file://" + sys.argv[1])
pg.wait_for_timeout(1500)
pg.screenshot(path=sys.argv[2], full_page=True, type="jpeg", quality=88)
b.close()
EOF
fi
# The message.
jq -n --arg tag "$tag" --arg commit "$commit" --slurpfile s "$run/summary.json" '
def f(x): if x == null then "-" else (x * 10 | round / 10 | tostring) end;
def d(a; b): if a == null or b == null or b == 0 then "" else
" (" + (if a >= b then "+" else "" end) + (((a - b) / b * 1000 | round) / 10 | tostring) + "%)" end;
$s[0] as $x | $x.now as $n | ($x.prev // {}) as $p |
{content: ("**radiance-sycl** quick BetterBench run (1 warmup + 5 passes; for tracking, not publishing)\n" +
"model `" + $tag + "` | commit `" + $commit + "` | GPU Arc Pro B65 (SYCL)\n" +
"decode tok/s: median " + f($n.decode_med) + d($n.decode_med; $p.decode_med) +
", 1% low " + f($n.decode_low1) + d($n.decode_low1; $p.decode_low1) + "\n" +
"prefill tok/s @" + ($n.prefill_depth | tostring) + ": median " + f($n.prefill_med) +
d($n.prefill_med; $p.prefill_med) + ", 1% low " + f($n.prefill_low1) +
d($n.prefill_low1; $p.prefill_low1) + "\n" +
(if $x.prev then "delta vs the previous " + $tag + " run" else "first run of this model" end))[0:1990]}' \
> "$run/payload.json"
cat "$run/payload.json" | jq -r .content
echo "run: $run"
[ -r "$HOME/.config/radiance-bench.env" ] && . "$HOME/.config/radiance-bench.env"
if [ -z "${DISCORD_WEBHOOK_URL:-}" ]; then
echo "bench_report.sh: no DISCORD_WEBHOOK_URL; not posted" >&2
exit 0
fi
if [ -f "$img" ]; then
code=$(curl -sS -o "$run/post.out" -w '%{http_code}' -F "payload_json=<$run/payload.json" \
-F "files[0]=@$img;type=image/jpeg" "$DISCORD_WEBHOOK_URL") || code=000
else
code=$(curl -sS -o "$run/post.out" -w '%{http_code}' -H 'Content-Type: application/json' \
-d @"$run/payload.json" "$DISCORD_WEBHOOK_URL") || code=000
fi
case "$code" in
2??) echo "posted to Discord (HTTP $code)" ;;
*) echo "bench_report.sh: the webhook answered HTTP $code: $(head -c 300 "$run/post.out")" >&2; exit 2 ;;
esac
+111
View File
@@ -0,0 +1,111 @@
// Phase 0 device probe: limits, aspects, sub-groups, joint_matrix combinations, and a
// numerical check of which XMX element types actually execute on the device.
#include <sycl/sycl.hpp>
#include <cmath>
#include <cstdio>
#include <vector>
namespace syclex = sycl::ext::oneapi::experimental;
namespace jm = sycl::ext::oneapi::experimental::matrix;
static const char *mt(jm::matrix_type t) {
switch (t) {
case jm::matrix_type::bf16: return "bf16";
case jm::matrix_type::fp16: return "fp16";
case jm::matrix_type::tf32: return "tf32";
case jm::matrix_type::fp32: return "fp32";
case jm::matrix_type::fp64: return "fp64";
case jm::matrix_type::sint8: return "s8";
case jm::matrix_type::uint8: return "u8";
case jm::matrix_type::sint32: return "s32";
case jm::matrix_type::uint32: return "u32";
default: return "other";
}
}
// One sub-group computes C[M x N] = A[M x K] * B[K x N] with joint_matrix, compared with a host loop.
template <typename Ta, typename Tc, size_t M, size_t N, size_t K>
static double jm_test(sycl::queue &q, const char *name) {
std::vector<Ta> a(M * K), b(K * N);
std::vector<Tc> c(M * N, 0);
std::vector<double> ref(M * N, 0);
for (size_t i = 0; i < M * K; i++) a[i] = Ta(float(int(i * 7 % 11) - 5) * 0.25f);
for (size_t i = 0; i < K * N; i++) b[i] = Ta(float(int(i * 5 % 13) - 6) * 0.5f);
for (size_t m = 0; m < M; m++)
for (size_t n = 0; n < N; n++)
for (size_t k = 0; k < K; k++) ref[m * N + n] += double(float(a[m * K + k])) * double(float(b[k * N + n]));
Ta *da = sycl::malloc_device<Ta>(M * K, q), *db = sycl::malloc_device<Ta>(K * N, q);
Tc *dc = sycl::malloc_device<Tc>(M * N, q);
q.memcpy(da, a.data(), sizeof(Ta) * M * K);
q.memcpy(db, b.data(), sizeof(Ta) * K * N);
q.memset(dc, 0, sizeof(Tc) * M * N).wait();
try {
q.parallel_for(sycl::nd_range<1>{16, 16}, [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(16)]] {
auto sg = it.get_sub_group();
jm::joint_matrix<sycl::sub_group, Ta, jm::use::a, M, K, jm::layout::row_major> ma;
jm::joint_matrix<sycl::sub_group, Ta, jm::use::b, K, N, jm::layout::row_major> mb;
jm::joint_matrix<sycl::sub_group, Tc, jm::use::accumulator, M, N> mc;
jm::joint_matrix_fill(sg, mc, Tc(0));
auto pa = sycl::address_space_cast<sycl::access::address_space::global_space, sycl::access::decorated::no>(da);
auto pb = sycl::address_space_cast<sycl::access::address_space::global_space, sycl::access::decorated::no>(db);
auto pc = sycl::address_space_cast<sycl::access::address_space::global_space, sycl::access::decorated::no>(dc);
jm::joint_matrix_load(sg, ma, pa, K);
jm::joint_matrix_load(sg, mb, pb, N);
jm::joint_matrix_mad(sg, mc, ma, mb, mc);
jm::joint_matrix_store(sg, mc, pc, N, jm::layout::row_major);
}).wait_and_throw();
} catch (sycl::exception &e) {
printf(" jm %-28s FAILED: %s\n", name, e.what());
return -1;
}
q.memcpy(c.data(), dc, sizeof(Tc) * M * N).wait();
double maxerr = 0;
for (size_t i = 0; i < M * N; i++) maxerr = std::fmax(maxerr, std::fabs(double(c[i]) - ref[i]));
printf(" jm %-28s M%zu N%zu K%zu max|err|=%g\n", name, M, N, K, maxerr);
sycl::free(da, q); sycl::free(db, q); sycl::free(dc, q);
return maxerr;
}
int main() {
sycl::queue q{sycl::gpu_selector_v, sycl::property::queue::in_order{}};
auto d = q.get_device();
printf("device: %s\n", d.get_info<sycl::info::device::name>().c_str());
printf("backend: %s driver: %s\n",
d.get_backend() == sycl::backend::ext_oneapi_level_zero ? "level_zero" : "other",
d.get_info<sycl::info::device::driver_version>().c_str());
printf("max_compute_units: %u\n", d.get_info<sycl::info::device::max_compute_units>());
printf("max_work_group_size: %zu\n", d.get_info<sycl::info::device::max_work_group_size>());
printf("sub_group_sizes:");
for (auto s : d.get_info<sycl::info::device::sub_group_sizes>()) printf(" %zu", s);
printf("\nlocal_mem_size: %llu\n", (unsigned long long)d.get_info<sycl::info::device::local_mem_size>());
printf("global_mem_size: %llu (%.2f GiB)\n", (unsigned long long)d.get_info<sycl::info::device::global_mem_size>(),
d.get_info<sycl::info::device::global_mem_size>() / 1073741824.0);
printf("max_mem_alloc_size: %llu (%.2f GiB)\n", (unsigned long long)d.get_info<sycl::info::device::max_mem_alloc_size>(),
d.get_info<sycl::info::device::max_mem_alloc_size>() / 1073741824.0);
printf("max_clock_frequency: %u MHz\n", d.get_info<sycl::info::device::max_clock_frequency>());
printf("global_mem_cache_size: %llu\n", (unsigned long long)d.get_info<sycl::info::device::global_mem_cache_size>());
printf("aspects: fp16=%d fp64=%d usm_device=%d usm_host=%d usm_shared=%d usm_system=%d atomic64=%d intel_matrix=%d\n",
d.has(sycl::aspect::fp16), d.has(sycl::aspect::fp64), d.has(sycl::aspect::usm_device_allocations),
d.has(sycl::aspect::usm_host_allocations), d.has(sycl::aspect::usm_shared_allocations),
d.has(sycl::aspect::usm_system_allocations), d.has(sycl::aspect::atomic64),
d.has(sycl::aspect::ext_intel_matrix));
try {
auto arch = d.get_info<syclex::info::device::architecture>();
printf("architecture enum: %d (bmg_g31=%d)\n", int(arch), int(syclex::architecture::intel_gpu_bmg_g31));
} catch (...) { printf("architecture: query failed\n"); }
printf("matrix_combinations:\n");
try {
auto combos = d.get_info<syclex::info::device::matrix_combinations>();
for (auto &c : combos)
printf(" A=%s B=%s C=%s D=%s M=%zu N=%zu K=%zu (max M %zu N %zu K %zu)\n", mt(c.atype), mt(c.btype),
mt(c.ctype), mt(c.dtype), c.msize, c.nsize, c.ksize, c.max_msize, c.max_nsize, c.max_ksize);
if (combos.empty()) printf(" (none)\n");
} catch (sycl::exception &e) { printf(" query failed: %s\n", e.what()); }
printf("joint_matrix execution checks:\n");
jm_test<sycl::ext::oneapi::bfloat16, float, 8, 16, 16>(q, "bf16 x bf16 -> f32");
jm_test<sycl::half, float, 8, 16, 16>(q, "fp16 x fp16 -> f32");
jm_test<int8_t, int32_t, 8, 16, 32>(q, "s8 x s8 -> s32");
return 0;
}
+128
View File
@@ -0,0 +1,128 @@
// Does Xe2 (BMG) XMX execute FP8 DPAS? One ESIMD work-item does C[8x16] = A[8x32] * B[32x16]
// with A and B as E4M3 (hf8) or E5M2 (bf8) bytes, checked against a host reference. A bf16
// DPAS of the same values (K=16, two halves) runs first as a control.
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/esimd.hpp>
#include <cmath>
#include <cstdio>
#include <vector>
using namespace sycl::ext::intel::esimd;
namespace xmx = sycl::ext::intel::esimd::xmx;
constexpr int M = 8, N = 16, K = 32;
static uint8_t enc(float v, int ebits) { // exact values only
int mbits = 7 - ebits, bias = (1 << (ebits - 1)) - 1;
if (v == 0) return 0;
uint8_t s = v < 0 ? 0x80 : 0;
float a = std::fabs(v);
int e = int(std::floor(std::log2(a)));
int m = int(std::lround((a / std::ldexp(1.f, e) - 1.f) * (1 << mbits)));
return s | uint8_t((e + bias) << mbits) | uint8_t(m);
}
template <xmx::dpas_argument_type P>
static void run(sycl::queue &q, const char *name, int ebits) {
std::vector<float> af(M * K), bf(K * N);
const float vals[] = {-2, -1.5f, -1, -0.5f, 0, 0.5f, 1, 1.5f, 2};
for (int i = 0; i < M * K; i++) af[i] = vals[(i * 7 + 3) % 9];
for (int i = 0; i < K * N; i++) bf[i] = vals[(i * 5 + 1) % 9];
std::vector<uint8_t> a8(M * K), b8(K * N);
for (int i = 0; i < M * K; i++) a8[i] = enc(af[i], ebits);
for (int k = 0; k < K; k++) // VNNI: [K/4][N][4]
for (int n = 0; n < N; n++) b8[(k / 4) * N * 4 + n * 4 + (k % 4)] = enc(bf[k * N + n], ebits);
std::vector<double> ref(M * N, 0);
for (int m = 0; m < M; m++)
for (int n = 0; n < N; n++)
for (int k = 0; k < K; k++) ref[m * N + n] += af[m * K + k] * bf[k * N + n];
uint8_t *da = sycl::malloc_device<uint8_t>(M * K, q), *db = sycl::malloc_device<uint8_t>(K * N, q);
float *dc = sycl::malloc_device<float>(M * N, q);
q.memcpy(da, a8.data(), M * K).wait();
q.memcpy(db, b8.data(), K * N).wait();
try {
q.parallel_for(sycl::range<1>{1}, [=](sycl::id<1>) SYCL_ESIMD_KERNEL {
simd<uint8_t, M * K> A = block_load<uint8_t, M * K>(da);
simd<uint8_t, K * N> B = block_load<uint8_t, K * N>(db);
simd<float, M * N> C = 0;
C = xmx::dpas<8, M, float, float, uint8_t, uint8_t, P, P>(C, B, A);
block_store<float, M * N>(dc, C);
}).wait_and_throw();
} catch (sycl::exception &e) {
printf("%-6s DPAS FAILED: %s\n", name, e.what());
return;
}
std::vector<float> c(M * N);
q.memcpy(c.data(), dc, sizeof(float) * M * N).wait();
double err = 0;
for (int i = 0; i < M * N; i++) err = std::fmax(err, std::fabs(c[i] - ref[i]));
printf("%-6s DPAS M8 N16 K32 -> f32: max|err| = %g (c[0]=%g ref=%g)\n", name, err, c[0], ref[0]);
sycl::free(da, q); sycl::free(db, q); sycl::free(dc, q);
}
// Controls with the same harness: bf16 (K=16, VNNI pairs) -> f32 and s8 (K=32) -> s32.
static void ctl_bf16(sycl::queue &q) {
using bf = sycl::ext::oneapi::bfloat16;
constexpr int KB = 16;
const float vals[] = {-2, -1.5f, -1, -0.5f, 0, 0.5f, 1, 1.5f, 2};
std::vector<bf> a(M * KB), b(KB * N);
std::vector<double> ref(M * N, 0);
for (int i = 0; i < M * KB; i++) a[i] = vals[(i * 7 + 3) % 9];
std::vector<float> bfv(KB * N);
for (int i = 0; i < KB * N; i++) bfv[i] = vals[(i * 5 + 1) % 9];
for (int k = 0; k < KB; k++)
for (int n = 0; n < N; n++) b[(k / 2) * N * 2 + n * 2 + (k % 2)] = bfv[k * N + n];
for (int m = 0; m < M; m++) for (int n = 0; n < N; n++) for (int k = 0; k < KB; k++)
ref[m * N + n] += float(a[m * KB + k]) * bfv[k * N + n];
bf *da = sycl::malloc_device<bf>(M * KB, q), *db = sycl::malloc_device<bf>(KB * N, q);
float *dc = sycl::malloc_device<float>(M * N, q);
q.memcpy(da, a.data(), sizeof(bf) * M * KB).wait();
q.memcpy(db, b.data(), sizeof(bf) * KB * N).wait();
q.parallel_for(sycl::range<1>{1}, [=](sycl::id<1>) SYCL_ESIMD_KERNEL {
simd<bf, M * KB> A = block_load<bf, M * KB>(da);
simd<bf, KB * N> B = block_load<bf, KB * N>(db);
simd<float, M * N> C = 0;
C = xmx::dpas<8, M, float, float, bf, bf>(C, B, A);
block_store<float, M * N>(dc, C);
}).wait();
std::vector<float> c(M * N);
q.memcpy(c.data(), dc, sizeof(float) * M * N).wait();
double err = 0;
for (int i = 0; i < M * N; i++) err = std::fmax(err, std::fabs(c[i] - ref[i]));
printf("bf16 DPAS M8 N16 K16 -> f32: max|err| = %g (c[0]=%g ref=%g)\n", err, c[0], ref[0]);
}
static void ctl_s8(sycl::queue &q) {
std::vector<int8_t> a(M * K), b(K * N);
std::vector<int> bv(K * N); std::vector<long> ref(M * N, 0);
for (int i = 0; i < M * K; i++) a[i] = int8_t((i * 7 + 3) % 9 - 4);
for (int i = 0; i < K * N; i++) bv[i] = (i * 5 + 1) % 9 - 4;
for (int k = 0; k < K; k++) for (int n = 0; n < N; n++) b[(k / 4) * N * 4 + n * 4 + (k % 4)] = int8_t(bv[k * N + n]);
for (int m = 0; m < M; m++) for (int n = 0; n < N; n++) for (int k = 0; k < K; k++) ref[m * N + n] += a[m * K + k] * bv[k * N + n];
int8_t *da = sycl::malloc_device<int8_t>(M * K, q), *db = sycl::malloc_device<int8_t>(K * N, q);
int *dc = sycl::malloc_device<int>(M * N, q);
q.memcpy(da, a.data(), M * K).wait();
q.memcpy(db, b.data(), K * N).wait();
q.parallel_for(sycl::range<1>{1}, [=](sycl::id<1>) SYCL_ESIMD_KERNEL {
simd<int8_t, M * K> A = block_load<int8_t, M * K>(da);
simd<int8_t, K * N> B = block_load<int8_t, K * N>(db);
simd<int, M * N> C = 0;
C = xmx::dpas<8, M, int, int, int8_t, int8_t>(C, B, A);
block_store<int, M * N>(dc, C);
}).wait();
std::vector<int> c(M * N);
q.memcpy(c.data(), dc, sizeof(int) * M * N).wait();
long err = 0;
for (int i = 0; i < M * N; i++) err = std::max(err, std::labs(c[i] - ref[i]));
printf("s8 DPAS M8 N16 K32 -> s32: max|err| = %ld (c[0]=%d ref=%ld)\n", err, c[0], ref[0]);
}
int main() {
sycl::queue q{sycl::gpu_selector_v};
printf("device: %s\n", q.get_device().get_info<sycl::info::device::name>().c_str());
run<xmx::dpas_argument_type::hf8>(q, "e4m3", 4);
run<xmx::dpas_argument_type::bf8>(q, "e5m2", 5);
ctl_bf16(q);
ctl_s8(q);
return 0;
}
+70
View File
@@ -0,0 +1,70 @@
"""greedy_compare.py URL_A URL_B [--max-tokens N] -- greedy decoding on two radiance servers,
token for token.
Milestone A's check (docs/SYCL_PROGRESS.md): the Intel (SYCL) backend and the host backend serve the
same container; at temperature 0 their outputs must agree. Each prompt goes to both servers through
/v1/completions with logprobs, so the comparison is on token ids as the servers report them (the
`tokens` field) and their text, and the first divergence is reported with both sides' top
candidates at that step: a near-tie that flips is told apart from a broken kernel by the logit gap.
Exit status 0 when every prompt agrees, 1 otherwise. Standard library only.
"""
import argparse
import json
import sys
import urllib.request
PROMPTS = [
"The capital of France is",
"def fibonacci(n):\n ",
"Q: What is 17 times 23?\nA:",
"Once upon a time, in a village by the sea,",
"The three primary colors are",
"Translate to German: 'The weather is nice today.'\nGerman:",
"<|im_start|>user\nWrite one sentence about the ocean.<|im_end|>\n<|im_start|>assistant\n",
"List the planets of the solar system in order from the sun:",
]
def complete(url, prompt, max_tokens):
body = json.dumps({"prompt": prompt, "max_tokens": max_tokens, "temperature": 0,
"logprobs": 5}).encode()
req = urllib.request.Request(url.rstrip("/") + "/v1/completions", data=body,
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=3600) as r:
out = json.load(r)
ch = out["choices"][0]
lp = ch.get("logprobs") or {}
return ch.get("text", ""), lp.get("tokens") or [], lp.get("top_logprobs") or []
def main():
ap = argparse.ArgumentParser()
ap.add_argument("a")
ap.add_argument("b")
ap.add_argument("--max-tokens", type=int, default=64)
args = ap.parse_args()
bad = 0
for p in PROMPTS:
ta, toks_a, top_a = complete(args.a, p, args.max_tokens)
tb, toks_b, top_b = complete(args.b, p, args.max_tokens)
same = ta == tb and toks_a == toks_b
n = min(len(toks_a), len(toks_b))
first = next((i for i in range(n) if toks_a[i] != toks_b[i]), None)
if first is None and len(toks_a) != len(toks_b):
first = n
print(f"{'SAME' if same else 'DIFF'} {len(toks_a):3d} tok {p[:48]!r}")
print(f" A: {ta[:160]!r}")
if not same:
bad += 1
print(f" B: {tb[:160]!r}")
print(f" first divergence at token {first}")
if first is not None and first < len(top_a) and first < len(top_b):
print(f" A top: {json.dumps(top_a[first])}")
print(f" B top: {json.dumps(top_b[first])}")
print(f"{len(PROMPTS) - bad}/{len(PROMPTS)} prompts identical")
return 0 if bad == 0 else 1
if __name__ == "__main__":
sys.exit(main())
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# notify.sh -- post a short message to the Discord webhook in ~/.config/radiance-bench.env
# (DISCORD_WEBHOOK_URL), for anything in the SYCL port that needs the user's attention: a blocker,
# a question, a finished milestone. The URL is a secret: it is read from the file, never printed.
#
# Usage: scripts/sycl/notify.sh "message" (cut to Discord's 2000 characters)
# Exit status: 0 posted, 1 no webhook configured, 2 the post failed (HTTP status printed).
set -e
msg=${1:?usage: notify.sh "message"}
env_file=${RAD_BENCH_ENV:-$HOME/.config/radiance-bench.env}
[ -r "$env_file" ] && . "$env_file"
if [ -z "$DISCORD_WEBHOOK_URL" ]; then
echo "notify.sh: no DISCORD_WEBHOOK_URL (looked in $env_file); not posted" >&2
exit 1
fi
payload=$(printf '%s' "$msg" | jq -Rs '{content: (.[0:2000])}')
code=$(printf '%s' "$payload" | curl -sS -o /dev/null -w '%{http_code}' \
-H 'Content-Type: application/json' --data-binary @- "$DISCORD_WEBHOOK_URL") || code=000
case "$code" in
2??) exit 0 ;;
*) echo "notify.sh: the webhook answered HTTP $code" >&2; exit 2 ;;
esac
+37
View File
@@ -0,0 +1,37 @@
#!/bin/sh
# op_inventory.sh -- the op vocabulary as a markdown table, for docs/SYCL_PORTING.md.
#
# One row per op that libref or libr4d declares: whether libref has it (the oracle), the libr4d
# kernels that implement it (from the kKernels rows in libr4d/r4d_rows.cpp, read as source because a
# build without HIP has no libr4d.so), the dtypes those rows state, and the architecture plugins
# whose source names the op. "Architectures naming it" is a grep, so it over-counts an op a plugin
# names only conditionally; --debug-graph on a real container is the exact answer for one model.
#
# Usage: scripts/sycl/op_inventory.sh [BUILD_DIR] (default build/)
set -e
root=$(cd "$(dirname "$0")/../.." && pwd)
build=${1:-$root/build}
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
RADIANCE_HOME=$build/radiance_home "$build/bin/rad-schemas" "$build/radiance_home/kernels/libref.so" |
awk '/^ [a-z0-9_]+$/ {print $1}' | sort -u > "$tmp/libref"
python3 -I "$root/scripts/sycl/r4d_rows.py" "$root/libr4d/r4d_rows.cpp" | sort > "$tmp/r4d"
cut -f1 "$tmp/r4d" | sort -u > "$tmp/r4d_ops"
sort -u "$tmp/libref" "$tmp/r4d_ops" > "$tmp/all"
echo "| op | libref | libr4d kernels | libr4d dtypes (first three rows' prose) | architectures naming it |"
echo "|---|---|---|---|---|"
while read -r op; do
ref=no; grep -qx "$op" "$tmp/libref" && ref=yes
kern=$(awk -F'\t' -v o="$op" '$1 == o {print $2}' "$tmp/r4d" | tr '\n' ' ' | sed 's/ $//; s/ /, /g')
dts=$(awk -F'\t' -v o="$op" '$1 == o && $3 != "" {print $3}' "$tmp/r4d" | sort -u | head -3 |
tr '\n' ';' | sed 's/;$//; s/;/; /g; s/|/\\|/g')
archs=$(grep -rlw --include=*.cpp --include=*.h -e "\"$op\"" "$root/arch" 2>/dev/null |
sed "s#$root/arch/##; s#/.*##" | sort -u | tr '\n' ' ' | sed 's/ $//; s/ /, /g')
[ -z "$kern" ] && kern="--"
[ -z "$archs" ] && archs="--"
echo "| \`$op\` | $ref | $kern | $dts | $archs |"
done < "$tmp/all"
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
# probe.sh -- Phase 0 device checks for the Intel (SYCL / Level Zero) backend; see docs/SYCL_PROGRESS.md.
# devprobe: limits, aspects, sub-group sizes, joint_matrix combinations and three joint_matrix runs
# dpas_fp8: whether XMX executes E4M3 / E5M2 DPAS, against bf16 and s8 DPAS controls in the same harness
# Usage: scripts/sycl/probe.sh [OUTDIR] (needs oneAPI; sources setvars.sh if icpx is not on PATH)
set -e
here=$(cd "$(dirname "$0")" && pwd)
out=${1:-${TMPDIR:-/tmp}/rad-sycl-probe}
mkdir -p "$out"
command -v icpx >/dev/null || . /opt/intel/oneapi/setvars.sh >/dev/null
icpx -fsycl -O2 "$here/devprobe.cpp" -o "$out/devprobe"
icpx -fsycl -O2 -fsycl-targets=spir64_gen -Xs "-device bmg-g31" "$here/dpas_fp8.cpp" -o "$out/dpas_fp8"
"$out/devprobe"
"$out/dpas_fp8"
+58
View File
@@ -0,0 +1,58 @@
#!/bin/sh
# profile_decode.sh -- per-op device time of decode steps alone, on the SYCL backend.
#
# --profile-ops reports every op over a whole run, so a prompt's prefill and the decode steps after
# it are mixed. This runs the same request twice in two fresh servers -- one generating 1 token, one
# generating 1 + STEPS -- and prints the difference per op type, divided by STEPS: the device time a
# decode step spends in each op at the prompt's context length. The numbers carry --profile-ops'
# synchronisations, so compare them with each other, not with unprofiled tok/s.
#
# Usage: scripts/sycl/profile_decode.sh MODEL PROMPT_FILE [STEPS] [extra radiance flags...]
# PROMPT_FILE plain text, sent as one /v1/completions prompt
# STEPS decode steps measured (default 128)
# Needs the oneAPI environment (it sources setvars.sh if icpx is not on PATH) and build-sycl/.
set -eu
model=${1:?usage: profile_decode.sh MODEL PROMPT_FILE [STEPS] [flags...]}
prompt=${2:?usage: profile_decode.sh MODEL PROMPT_FILE [STEPS] [flags...]}
steps=${3:-128}
[ $# -ge 3 ] && shift 3 || shift $#
root=$(cd "$(dirname "$0")/../.." && pwd)
if ! command -v icpx >/dev/null; then set +u; . /opt/intel/oneapi/setvars.sh >/dev/null; set -u; fi
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
port=${PORT:-8139}
run() { # run TOKENS FLAGS... -> $work/TOKENS.tsv: op, total ms, calls
tok=$1; shift
RADIANCE_SYCL_TIMING=1 RADIANCE_HOME="$root/build-sycl/radiance_home" \
"$root/build-sycl/bin/radiance" --model "$model" --profile-ops --max-num-seqs 1 \
--host 127.0.0.1 --port "$port" "$@" > "$work/$tok.log" 2>&1 &
pid=$!
i=0
until grep -q 'server: listening' "$work/$tok.log"; do
i=$((i + 1)); [ $i -lt 600 ] || { echo "the server did not start" >&2; kill $pid; exit 1; }
kill -0 $pid 2>/dev/null || { tail -5 "$work/$tok.log" >&2; exit 1; }
sleep 1
done
python3 -I -c 'import json,sys; print(json.dumps({"prompt": open(sys.argv[1]).read(),
"max_tokens": int(sys.argv[2]), "temperature": 0}))' "$prompt" "$tok" > "$work/req.json"
curl -sf -m 3600 "http://127.0.0.1:$port/v1/completions" -H 'Content-Type: application/json' \
-d @"$work/req.json" > /dev/null
kill -INT $pid
wait $pid 2>/dev/null || true
n=$(grep -n -E 'calls +total ms' "$work/$tok.log" | tail -1 | cut -d: -f1)
awk -v from="$n" 'NR > from && $4 == "dev" { t[$7] += $2; c[$7] += $1 }
END { for (o in t) print o, t[o], c[o] }' \
"$work/$tok.log" | sort > "$work/$tok.tsv"
}
run 1 "$@"
run $((steps + 1)) "$@"
join "$work/1.tsv" "$work/$((steps + 1)).tsv" | awk -v n="$steps" '
{ d = $4 - $2; T += d; a[$1] = d; k[$1] = ($5 - $3) / n }
END {
for (o in a)
printf "%8.3f ms/step %5.1f%% %5.1f calls/step %7.1f us/call %s\n", a[o] / n,
100 * a[o] / T, k[o], (k[o] > 0 ? 1000 * a[o] / n / k[o] : 0), o
printf "%8.3f ms/step of device time over %d decode steps\n", T / n, n
}' | sort -rn
+44
View File
@@ -0,0 +1,44 @@
"""r4d_rows.py ROWS_CPP -- the kKernels rows of libr4d/r4d_rows.cpp as TSV: op, kernel, dtypes, domain.
Read as source because a build without HIP has no libr4d.so to ask. A row is
{ "kernel", "op", "family", "computes", "shape", "dtypes", RAD_DOMAIN_..., ... }; adjacent string
literals are joined as the C compiler joins them, so a dtypes string split over lines stays whole.
"""
import re
import sys
src = open(sys.argv[1], encoding="utf-8").read()
start = src.index("static const RadKernelInfo kKernels[] = {")
body = src[start:]
# Comments out, so prose in them cannot look like a row.
body = re.sub(r"/\*.*?\*/", " ", body, flags=re.S)
body = re.sub(r"//[^\n]*", " ", body)
body = body.replace("\\\n", "\n") # macro line continuations
lit = r'"(?:[^"\\]|\\.)*"'
# Between literals a row may splice in a macro: R4D_XSTR(X), a stringised #PARAM, or a name such as
# KVDOC. Each is kept as <NAME>, so a template row's kernel reads attn_window_h<HD>_gqa<G>_<KVN>.
mac = r"R4D_XSTR\(\s*\w+\s*\)|#\w+|\b(?!RAD_DOMAIN_)[A-Z][A-Z0-9_]*\b"
row_re = re.compile(r"\{\s*((?:(?:" + lit + "|" + mac + r")\s*,?\s*)+?)(RAD_DOMAIN_[A-Z]+)")
for m in row_re.finditer(body):
if not m.group(1).lstrip().startswith('"'):
continue
# Split the run into arguments at commas; join adjacent literals and macros within one.
args, cur = [], []
for tok in re.finditer(lit + "|" + mac + r"|,", m.group(1)):
t = tok.group(0)
if t == ",":
args.append("".join(cur))
cur = []
elif t.startswith('"'):
cur.append(re.sub(r"\\(.)", r"\1", t[1:-1]))
else:
name = re.sub(r"^R4D_XSTR\(\s*|\s*\)$|^#", "", t)
cur.append(f"<{name}>")
if cur:
args.append("".join(cur))
if len(args) < 6:
continue
kern, op, dtypes = args[0], args[1], " ".join(args[5].split())
print(f"{op}\t{kern}\t{dtypes}\t{m.group(2)[len('RAD_DOMAIN_'):].lower()}")
+68
View File
@@ -0,0 +1,68 @@
# The parts of radiance compiled by icpx: the SYCL device backend (librad_sycl.so) and, later, the
# Intel kernel library. The main project builds this directory through ExternalProject with icpx
# as the C++ compiler (top-level CMakeLists.txt, RAD_SYCL), so the engine and every host plugin
# stay on the main project's compiler (docs/SYCL_PORTING.md §4.5, docs/SYCL_PROGRESS.md D6).
cmake_minimum_required(VERSION 3.21)
project(radiance_sycl LANGUAGES CXX)
if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
message(FATAL_ERROR "sycl/ is built by icpx (IntelLLVM); this configure has "
"${CMAKE_CXX_COMPILER_ID} at ${CMAKE_CXX_COMPILER}.")
endif()
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE RelWithDebInfo)
endif()
set(RAD_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/.." CACHE PATH "the radiance checkout")
set(RAD_SYCL_TARGETS "intel_gpu_bmg_g31" CACHE STRING "AOT targets for SYCL device code")
# The same warnings as the main build. icpx defaults to -fp-model=fast; host code here is precise
# as the main build's is, and device code keeps the main build's -ffp-contract=off discipline in
# the kernels themselves.
add_compile_options(-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers
-ffp-model=precise)
set(RAD_SYCL_FLAGS -fsycl "-fsycl-targets=${RAD_SYCL_TARGETS}" -foffload-fp32-prec-div
-foffload-fp32-prec-sqrt)
# The oneAPI runtime libraries sit beside the compiler; record their directory so the engine runs
# without setvars.sh in its environment.
get_filename_component(_icpx_bin "${CMAKE_CXX_COMPILER}" DIRECTORY)
get_filename_component(RAD_ONEAPI_LIBDIR "${_icpx_bin}/../lib" ABSOLUTE)
# ---------------------------------------------------------------- the device backend
# The backend, and the core's own kernels under it (the step's advance, the weight-table patches),
# each the SYCL twin of a .hip the AMD build compiles. The engine calls the kernels' launchers by
# the same names on either backend.
add_library(rad_sycl SHARED
${RAD_SOURCE_DIR}/core/device/sycl.cpp
${RAD_SOURCE_DIR}/core/device/sycl_host.cpp
${RAD_SOURCE_DIR}/core/sched/advance_sycl.cpp
${RAD_SOURCE_DIR}/core/runtime/wtab_sycl.cpp)
target_include_directories(rad_sycl PRIVATE
${RAD_SOURCE_DIR}/core/device ${RAD_SOURCE_DIR}/core ${RAD_SOURCE_DIR}/abi
${RAD_SOURCE_DIR}/vendor)
target_compile_definitions(rad_sycl PRIVATE RAD_HAVE_SYCL=1)
target_compile_options(rad_sycl PRIVATE ${RAD_SYCL_FLAGS} -fvisibility=hidden)
target_link_options(rad_sycl PRIVATE ${RAD_SYCL_FLAGS} "LINKER:-rpath,${RAD_ONEAPI_LIBDIR}"
"LINKER:--no-undefined")
set_target_properties(rad_sycl PROPERTIES OUTPUT_NAME rad_sycl)
# ---------------------------------------------------------------- the kernel library
# libxe2 is a plugin like any other: built by rad_add_plugin against the ABI headers alone, into
# the main build's $RADIANCE_HOME (RAD_PLUGIN_OUT, passed down by the main project). The variables
# cmake/RadAddPlugin.cmake expects describe a build with no HIP; libxe2 adds its SYCL flags itself.
set(RAD_PLUGIN_OUT "${CMAKE_BINARY_DIR}/radiance_home" CACHE PATH "the build tree's $RADIANCE_HOME")
set(RAD_HIP_FOUND OFF)
set(RAD_GPU_TARGETS "")
set(RAD_HIP_RUNTIME "")
# The sub-build installs nothing; the main project installs what it needs from here.
set(RAD_PLUGIN_INSTALL OFF)
add_library(rad_abi INTERFACE)
add_library(radiance::abi ALIAS rad_abi)
target_include_directories(rad_abi INTERFACE ${RAD_SOURCE_DIR}/abi)
include(GNUInstallDirs)
include(${RAD_SOURCE_DIR}/cmake/RadAddPlugin.cmake)
add_subdirectory(${RAD_SOURCE_DIR}/libxe2 ${CMAKE_BINARY_DIR}/libxe2)
+39 -8
View File
@@ -80,7 +80,8 @@ set(RAD_TEST_SHARDS_gbnf_test 4)
#
# ROCR_VISIBLE_DEVICES=99 hides every card, so a unit test runs on the host backend on every
# machine: the same code everywhere, and nothing touches a card a server is using. The _card
# entries below run the device tests on a card.
# entries below run the device tests on a card. A SYCL build hides its cards the same way with
# ONEAPI_DEVICE_SELECTOR (the backend uses Level Zero devices only).
#
# RAD_TEST_STRICT=1: a plugin or fixture this build makes is never legitimately absent, so a test
# that cannot find one fails rather than skips. RAD_TEST_TMPDIR puts radtest::tmpdir() in the build
@@ -109,7 +110,11 @@ set(RAD_TEST_OMP_ENV "OMP_WAIT_POLICY=passive" "OMP_NUM_THREADS=${RAD_TEST_OMP_T
set(RAD_TEST_CARD_ENV "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home" ${RAD_TEST_OMP_ENV}
"RAD_TEST_STRICT=1" "RAD_TEST_TMPDIR=${CMAKE_BINARY_DIR}/tmp"
${RAD_TEST_SAN_ENV})
set(RAD_TEST_ENV ${RAD_TEST_CARD_ENV} "ROCR_VISIBLE_DEVICES=99")
set(RAD_TEST_HIDE_ENV "ROCR_VISIBLE_DEVICES=99")
if(RAD_SYCL_FOUND)
list(APPEND RAD_TEST_HIDE_ENV "ONEAPI_DEVICE_SELECTOR=!level_zero:*")
endif()
set(RAD_TEST_ENV ${RAD_TEST_CARD_ENV} ${RAD_TEST_HIDE_ENV})
# Binaries that need more CPU than the default budget, and what costs it. Lower an entry when its
# cost comes down, so the tripwire stays tight.
@@ -244,6 +249,21 @@ if(RAD_HIP_FOUND)
endforeach()
endif()
# The same on an Intel GPU through the SYCL backend, labelled sycl. The oneAPI environment must be
# loaded (the runtime finds its Level Zero adapter through it), and RAD_TEST_BACKEND=sycl makes a
# run that fell back to the host backend fail instead of passing on the CPU. RADIANCE_SYCL_TIMING=1
# turns event timing on, which the backend leaves off by default (core/device/sycl.cpp), so the
# whole device contract is under test.
if(RAD_SYCL_FOUND)
foreach(n device_test)
add_test(NAME ${n}_sycl COMMAND ${n} -perf_)
set_tests_properties(${n}_sycl PROPERTIES
LABELS sycl
TIMEOUT ${RAD_TEST_TIMEOUT}
ENVIRONMENT "${RAD_TEST_CARD_ENV};RAD_TEST_BACKEND=sycl;RADIANCE_SYCL_TIMING=1")
endforeach()
endif()
# ================================================================== whole models on the CPU
#
# engine_e2e_test runs the radiance binary on tiny synthetic checkpoints (tests/tiny_model.h) on
@@ -362,7 +382,7 @@ if(TARGET libavx AND TARGET rad-avx-check)
add_test(NAME avx_check
COMMAND rad-avx-check --ref ${RAD_PLUGIN_OUT}/kernels/libref.so
--avx ${RAD_PLUGIN_OUT}/kernels/libavx.so)
set(env ${RAD_TEST_OMP_ENV} "ROCR_VISIBLE_DEVICES=99" ${RAD_TEST_SAN_ENV})
set(env ${RAD_TEST_OMP_ENV} ${RAD_TEST_HIDE_ENV} ${RAD_TEST_SAN_ENV})
set_tests_properties(avx_check PROPERTIES TIMEOUT ${RAD_TEST_TIMEOUT} ENVIRONMENT "${env}")
endif()
@@ -376,7 +396,7 @@ if(TARGET rad-avx-check AND TARGET libref)
COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/avx_check_general.sh
$<TARGET_FILE:rad-avx-check> ${RAD_PLUGIN_OUT}/kernels/libref.so
$<TARGET_FILE:avx_subset_plugin>)
set(env ${RAD_TEST_OMP_ENV} "ROCR_VISIBLE_DEVICES=99" ${RAD_TEST_SAN_ENV})
set(env ${RAD_TEST_OMP_ENV} ${RAD_TEST_HIDE_ENV} ${RAD_TEST_SAN_ENV})
set_tests_properties(avx_check_general PROPERTIES TIMEOUT ${RAD_TEST_TIMEOUT} ENVIRONMENT "${env}")
endif()
@@ -534,7 +554,7 @@ add_test(NAME ops_doc
set_tests_properties(ops_doc PROPERTIES
SKIP_RETURN_CODE 77
TIMEOUT ${RAD_TEST_TIMEOUT}
ENVIRONMENT "ROCR_VISIBLE_DEVICES=99")
ENVIRONMENT "${RAD_TEST_HIDE_ENV}")
# tools/rad-export. Its standard-library checks always run; the merge arithmetic runs where torch
# and safetensors import, and the PEFT comparison where peft and transformers do too.
@@ -561,11 +581,16 @@ add_test(NAME oot_plugins
COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/oot_plugins.sh
${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/oot ${RAD_OOT_HIP})
# RESOURCE_LOCK kbench_memory: its replay holds operands in host memory as the kbench entries do.
# A SYCL build passes its icpx so libxe2 is rebuilt out of tree too.
set(RAD_OOT_ENV "CMAKE_GENERATOR=${CMAKE_GENERATOR}" ${RAD_TEST_OMP_ENV})
if(RAD_SYCL_FOUND)
list(APPEND RAD_OOT_ENV "RAD_OOT_ICPX=${RAD_ICPX}")
endif()
set_tests_properties(oot_plugins PROPERTIES
LABELS "oot"
TIMEOUT 3600
RESOURCE_LOCK kbench_memory
ENVIRONMENT "CMAKE_GENERATOR=${CMAKE_GENERATOR};${RAD_TEST_OMP_ENV}")
ENVIRONMENT "${RAD_OOT_ENV}")
# ================================================================== the kernel library, as a test
#
@@ -583,6 +608,11 @@ set(RAD_KBENCH_LABELS "kbench")
if(RAD_HIP_FOUND AND TARGET libr4d)
set(RAD_KBENCH_LABELS "kbench;gpu")
endif()
# A SYCL build's replay runs libxe2 on the Intel card, so it is a card test there (label sycl; load
# the oneAPI environment first).
if(RAD_SYCL_FOUND)
set(RAD_KBENCH_LABELS "kbench;sycl")
endif()
set(RAD_KBENCH_ROWS ${CMAKE_SOURCE_DIR}/data/kbench_rows)
if(TARGET rad-kbench AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels.rkb)
add_test(NAME kbench
@@ -616,8 +646,9 @@ endif()
# The M2XFP4 rows over the 27B-trunk fixture set (see the root CMakeLists): the four max-tok
# passes replayed together, covering the m2xfp4a8 decode row's whole M ladder. Scoped to
# libref:libr4d: the m2 arm of the other host library is that library's own to bring up.
if(TARGET rad-kbench AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels_m2xfp4_m128.rkb)
# libref:libr4d: the m2 arm of the other host library is that library's own to bring up. It needs
# libr4d, so only a HIP build has it (a CPU-only or SYCL build has no libr4d to load).
if(RAD_HIP_FOUND AND TARGET rad-kbench AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels_m2xfp4_m128.rkb)
add_test(NAME kbench_m2xfp4
COMMAND rad-kbench --home ${RAD_PLUGIN_OUT} --kernels libref:libr4d --max-cases 1
--no-ref --strict --coverage ${RAD_KBENCH_ROWS}
+1
View File
@@ -15,6 +15,7 @@
#include "rad_quant.h"
#include "rad_runtime.h"
#include "rad_sample.h"
#include "rad_sycl.h"
#include "rad_types.h"
#include "rad_yarn.h"
+6
View File
@@ -642,6 +642,12 @@ ABI_FIELD(RadSampleParams, hist_len)
ABI_FIELD(RadSampleParams, mask_row)
ABI_FIELD(RadSampleParams, flags)
ABI_FIELD(RadSampleParams, dry_rep_limit)
ABI_STRUCT(RadSyclStream)
ABI_FIELD(RadSyclStream, magic)
ABI_FIELD(RadSyclStream, version)
ABI_FIELD(RadSyclStream, queue)
ABI_FIELD(RadSyclStream, device)
ABI_FIELD(RadSyclStream, reserved)
ABI_STRUCT(RadTensor)
ABI_FIELD(RadTensor, data)
ABI_FIELD(RadTensor, dtype)
+1
View File
@@ -26,6 +26,7 @@
#include "rad_quant.h"
#include "rad_runtime.h"
#include "rad_sample.h"
#include "rad_sycl.h"
#include "rad_types.h"
#include "rad_yarn.h"
+15
View File
@@ -93,6 +93,21 @@ std::string temp_path(const char* tag) {
/* ------------------------------------------------------------------ identity */
/* RAD_TEST_BACKEND names the backend a run is registered for (the sycl-labelled entries set it).
* A run that fell back to another backend, typically the host one for want of a driver
* environment, fails here instead of passing every case on the CPU. */
TEST(the_backend_is_the_one_the_run_names) {
const char* want = std::getenv("RAD_TEST_BACKEND");
if (!want || !*want) return;
if (std::strcmp(rad::device_backend_name(), want) != 0)
fprintf(stderr, " RAD_TEST_BACKEND=%s but the %s backend is running: %s\n", want,
rad::device_backend_name(),
std::strcmp(want, "sycl") == 0
? "load the oneAPI environment (. /opt/intel/oneapi/setvars.sh)"
: "is the device visible?");
CHECK_EQ(std::string(rad::device_backend_name()), std::string(want));
}
TEST(backend_reports_itself) {
const char* name = rad::device_backend_name();
CHECK(name && *name);
+26 -5
View File
@@ -24,6 +24,11 @@
# tree's device code. A replay of a device library needs a card, and this test must not touch
# one a server is using; the same instructions mean the tree's own GPU suite (ctest -L gpu)
# has already checked what the out-of-tree build produced.
#
# The SYCL kernel library (libxe2) is built out of tree when RAD_OOT_ICPX names the icpx it was
# built with (a SYCL build's test registration passes it) and takes part in checks 1-3 then;
# without it, it is left out of them like libr4d without a HIP compiler. Check 4 never runs it:
# it needs an Intel card, which this test must not touch.
set -eu
B=$1; S=$2; W=$3
HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}
@@ -57,14 +62,24 @@ for d in libr4d; do
[ -f "$S/$d/CMakeLists.txt" ] && [ -f "$B/radiance_home/kernels/$d.so" ] && devlibs="$devlibs $d"
done
[ -n "$HIPC" ] && dirs="$dirs $devlibs"
is_dev() { case " $devlibs " in *" $1 "*) return 0 ;; esac; return 1; }
ICPX=${RAD_OOT_ICPX:-}
sycllibs=""
for d in libxe2; do
[ -f "$S/$d/CMakeLists.txt" ] && [ -f "$B/radiance_home/kernels/$d.so" ] && sycllibs="$sycllibs $d"
done
[ -n "$ICPX" ] && dirs="$dirs $sycllibs"
is_dev() { case " $devlibs $sycllibs " in *" $1 "*) return 0 ;; esac; return 1; }
is_sycl() { case " $sycllibs " in *" $1 "*) return 0 ;; esac; return 1; }
for d in $dirs; do
n=$(basename "$d")
say "building $d against the installed package"
extra=""
is_dev "$n" && extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT
-DRAD_HIP_VOPD_REPEATABLE=$VOPD"
if is_sycl "$n"; then
extra="-DCMAKE_CXX_COMPILER=$ICPX"
elif is_dev "$n"; then
extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT -DRAD_HIP_VOPD_REPEATABLE=$VOPD"
fi
# shellcheck disable=SC2086
run "$W/logs/$n.configure.log" cmake -S "$S/$d" -B "$W/b/$n" -G "$GEN" \
-DCMAKE_PREFIX_PATH="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra
@@ -82,6 +97,9 @@ want=$(sets "$B/radiance_home")
if [ -z "$HIPC" ]; then
for d in $devlibs; do want=$(printf '%s\n' "$want" | grep -v "^kernels/$d\.so\$" || true); done
fi
if [ -z "$ICPX" ]; then
for d in $sycllibs; do want=$(printf '%s\n' "$want" | grep -v "^kernels/$d\.so\$" || true); done
fi
have=$(sets "$H")
if [ "$want" != "$have" ]; then
say "in-tree:"; say "$want"; say "out of tree:"; say "$have"
@@ -102,13 +120,16 @@ say "2. same schemas"
# 3. The same registration, from each home alone. No card: the test must not depend on one, and
# must not touch one a server is using.
listing() {
HIP_VISIBLE_DEVICES=-1 "$P/bin/rad-info" --plugins --home "$1" 2>/dev/null |
HIP_VISIBLE_DEVICES=-1 ONEAPI_DEVICE_SELECTOR="!level_zero:*" "$P/bin/rad-info" --plugins --home "$1" 2>/dev/null |
grep -v '^plugins on' | grep -v '^ /'
}
tree_list=$(listing "$B/radiance_home")
if [ -z "$HIPC" ]; then
for d in $devlibs; do tree_list=$(printf '%s\n' "$tree_list" | grep -v " $d " || true); done
fi
if [ -z "$ICPX" ]; then
for d in $sycllibs; do tree_list=$(printf '%s\n' "$tree_list" | grep -v " $d " || true); done
fi
oot_list=$(listing "$H")
# The in-tree list numbers a device library's position when it is left out above; compare without the order
# column and check the order separately by name.
@@ -129,7 +150,7 @@ for so in "$H"/kernels/*.so; do
is_dev "$(basename "$so" .so)" || ln -s "$so" "$HH/kernels/"
done
# A fixed --max-bytes, so which cases run does not depend on the memory free at the start.
run "$W/logs/kbench.log" env HIP_VISIBLE_DEVICES=-1 RADIANCE_HOME="$HH" \
run "$W/logs/kbench.log" env HIP_VISIBLE_DEVICES=-1 ONEAPI_DEVICE_SELECTOR="!level_zero:*" RADIANCE_HOME="$HH" \
"$P/bin/rad-kbench" --fixture "$P/share/radiance/kernels.rkb" --max-cases 1 \
--max-bytes 2048 --op rmsnorm --op quant_act_fp8 --op silu_mul
grep -E "passed|failed" "$W/logs/kbench.log" | tail -3