This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/libxe2/xe2_common.h
T
pascallinxweilerandClaude Opus 5.5 07cdc546a3 libxe2: fast decode kernels for Qwen3.8-27B-PARO-M2XFP4 -- 0.1 -> 12.1 tok/s on the B65
- m2xfp4 GEMV (M <= 16): e2m1 decoded to fp16 by bits alone ((mag << 9) | sign << 15 is exactly
  e2m1 * 2^-14; the card keeps fp16 subnormals), K permuted (u, u + 4) inside each 8 so a code
  pair is one shift and mask, the activation as fp16(a * a_scale / R * 2^14) in that order, half2
  subgroup and group sums, f32 across groups; four columns a sub-group at decode. The scalar
  form was ALU-bound (~10 ops a weight, 80 ms a token); this one runs at 415-525 GB/s on the
  27B's shapes in a standalone probe. rad-kbench against libref on the container: rel_l2 ~5e-5 to
  ~3e-3, tolerance 4e-2.
- m2xfp4 prefill (M >= 17): the weight decoded to bf16 (exact) and the activation to
  bf16(e4m3 * scale), then the bf16 XMX GEMM per part.
- givens_dense_quant: a sub-group an output, the rotation row read coalesced, libref's double sum
  as a float pair (two-product and two-sum, ~48 bits); the double form stays for XE2_EXACT=1.
  146 -> 5.4 ms a token.
- the joined fp8 head (logits_gemm, M <= 16): E4M3 to fp16 by bits ((b & 0x7F) << 7 is E4M3 *
  2^-8), bytes (0, 2), (1, 3) as half pairs; an i8 head or a narrow scale block element by element.
  43 -> 3.9 ms.
- gated delta net, still bit-identical to libref: the decode step split over 16-column blocks
  (384 work-groups, not 48) with the gated norm in a second kernel and the anchor replay its own
  launch (block 0 rewrites the factors other blocks read); the chunked scan and the kkt solve
  work-group parallel; persistent staging (workspace slots) instead of a malloc and a wait a call.
- rmsnorm_quant_fp8: the row in local memory, loads issued before stores, the ordered sum fed by
  sub-group broadcasts -- still libref's chain (a probe puts that chain's floor at ~32 us for 5120).
- round_dt converts the float dtypes directly.

rad-kbench: 1410/1410 on the fixture; the 27B container's M <= 32 bands 77/77. Decode (greedy, no
speculation) 12.1 tok/s, coherent text; with the DFlash2 drafter 5.3 tok/s and the same text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-24 03:22:48 +02:00

167 lines
6.3 KiB
C++

/* 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);
/* A device workspace of at least `floats` floats for `q`, kept between launches and grown on
* demand (libref's ws_get, for kernels whose work-items each need a scratch block). The queue is
* in-order, so consecutive launches can share it; growing waits for the queue first. `slot` picks
* one of a few independent buffers, for an op that needs two at once. Null with a reason when the
* allocation fails. */
float* workspace(sycl::queue& q, size_t floats, int slot = 0);
/* 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;
}
/* Stores an integer index in an integer dtype (the counterpart of ld_index). */
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;
}
}
/* Rounds `v` through a store and load of `dt`, as libref's round_dt does. The float dtypes the
* kernels meet are converted directly: a round trip through a stack buffer can land in private
* (scratch) memory on the card, a global-memory round trip an element. */
inline float round_dt(uint32_t dt, float v) {
switch (dt) {
case RAD_F32: return v;
case RAD_BF16: return rad_bf16_to_f32(rad_f32_to_bf16(v));
case RAD_F16: return rad_f16_to_f32(rad_f32_to_f16(v));
default: break;
}
uint64_t buf = 0;
rad_store_f32(&buf, dt, 0, v);
return rad_load_f32(&buf, dt, 0);
}
} // namespace xe2