Archived
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
This commit is contained in:
1 parent
874f8d28b1
commit
43d84111c2
13 files changed
+1076
-36
No files matched your search
@@ -343,6 +343,12 @@ if(RAD_SYCL_FOUND)
|
||||
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)
|
||||
|
||||
+2
-2
@@ -39,10 +39,10 @@ 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. The rpath finds it in the build tree.
|
||||
# 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)
|
||||
target_link_options(rad_core INTERFACE "LINKER:-rpath,${RAD_SYCL_BINARY_DIR}")
|
||||
endif()
|
||||
|
||||
if(RAD_HIP_FOUND)
|
||||
|
||||
+100
-10
@@ -10,8 +10,8 @@ from it alone.
|
||||
|---|---|
|
||||
| 0 environment check | done |
|
||||
| 1 codebase study, `SYCL_PORTING.md` | done (`docs/SYCL_PORTING.md` §1-§3, Appendix A) |
|
||||
| 2 design | written (`docs/SYCL_PORTING.md` §4); device backend, build integration and core kernels done and passing `device_test` on the B65; `libxe2` skeleton next |
|
||||
| 3 correctness-first kernels | not started |
|
||||
| 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 | not started |
|
||||
| 5 broaden and finish | not started |
|
||||
|
||||
@@ -147,11 +147,17 @@ install one outside the repo (e.g. playwright + chromium in `~/tools/betterbench
|
||||
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`.
|
||||
|
||||
Runs: none yet. Nothing is benchmarked before Milestone A passes its correctness checks. All runs
|
||||
are `--quick` (1 warmup, 5 passes): progress tracking, not publishable numbers.
|
||||
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` |
|
||||
|
||||
## Models
|
||||
|
||||
@@ -211,6 +217,11 @@ Planned use: Milestone A = `minicpm5-2b-bf16.rad` (blocked, item 1); Milestone B
|
||||
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.
|
||||
- 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.
|
||||
@@ -272,14 +283,93 @@ In a SYCL build the host tier is `ctest -LE 'gpu|oot|sycl'` (kbench moved to the
|
||||
`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).
|
||||
|
||||
## Next steps
|
||||
|
||||
1. Phase 3, Milestone A's 13 + 13 ops in libxe2, each passing `rad-kbench` (fixture and MiniCPM5),
|
||||
correctness-first kernels. Order: elementwise/norm/rope/cast/embed/gather, sampler, gemm_nt and
|
||||
logits_gemm, kv_store and attn_paged.
|
||||
2. Then serve MiniCPM5 on the B65 with `--num-speculative-tokens 0` and compare greedy output with
|
||||
the host backend.
|
||||
3. `code_runs` under SYCL from `build_target` (D4); install rules and the `oot` rebuild for
|
||||
1. Milestone B, part 2: `minicpm5-2b-fp8.rad` (**not in the library; asked by webhook**). Its fp8 trunk
|
||||
uses the ops part 1 added (fp8a8 GEMMs), so it should need no new kernel.
|
||||
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
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace xe2 {
|
||||
|
||||
@@ -108,6 +109,27 @@ inline int64_t ld_index(uint32_t dt, const void* p, int64_t i) {
|
||||
}
|
||||
}
|
||||
|
||||
/* 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;
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -36,4 +36,21 @@ 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);
|
||||
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
|
||||
@@ -14,6 +14,12 @@ 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 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. */
|
||||
@@ -149,6 +155,46 @@ const RadKernelInfo kKernels[] = {
|
||||
.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 = {
|
||||
|
||||
@@ -82,24 +82,6 @@ inline bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_t hmax,
|
||||
inline float ref_exp(float x) { return (float)sycl::exp((double)x); }
|
||||
inline float ref_log(float x) { return (float)sycl::log((double)x); }
|
||||
|
||||
/* The selection key: larger value first, then lower index. 0 is no candidate (NaN). */
|
||||
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;
|
||||
}
|
||||
|
||||
/* A candidate plane row: cand_idx (integer) and cand_val (float), rows of n_cand. */
|
||||
struct Cands {
|
||||
Rows idx, val;
|
||||
|
||||
Executable
+129
@@ -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
|
||||
@@ -577,11 +577,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
|
||||
#
|
||||
|
||||
+26
-5
@@ -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
|
||||
|
||||
Reference in new issue
Block a user