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/libhalo/halo_ple_gate_bf16.hip
Deadcode 9ed3ef7a7b radiance 1.15.0
New models and formats:
- IQR for Qwen3.8-27B: weights on the int8 grid under GPTQ, a trellis down each GPTQ column
  (IQR-V2), and IQR-V3, a computed trellis code under one scale a row, kept at its codes' width in
  VRAM and decoded in the GEMM; 15 IQR-V3 recipes from ~2 to ~7 bits a weight
  (data/recipes/q38-27b-*-v3.recipe, docs/IQR.md)
- libhalo: a kernel library for Strix Halo (gfx1151), preferred there over libr3d
- Nemotron 3.5 Embed 1B and 8B (nemotron35_embed): text and image embeddings through a Pixtral
  tower, on the card and on the CPU
- Nemotron 3.5 Rerank 8B
- /v1/systemone: Cloudflare's clef and clef-flash, Convai Innovations' Laya and Mica beside
  LiquidAI d1; scored steps read the candidates' logits from the head table with no lm_head pass
- LFM2's 8-bit trunk: block-fp8 or int8 linears with the fused producers, and the d1-3B recipe
- DeepSeek-V4.1's reply format with DSML tool calls and typed argument tags

Weights on the drive:
- The file tier reads only the experts the pass routes rows to; the draft head's weights stay in
  the host pool
- A hot VRAM cache for routed experts read off the drive, reads deposited straight into free host
  pool slots, and copyless evictions; the file tier's counters are now ssd_*
- GLM-5 Next shards its routed experts by expert, not by width, so they can live on the drive
- The stall watch counts drive reads as progress, and the DMA lane's room check reads the lane's
  own completion fence

Quantisation tooling:
- --calib-corpus, --calib-dir and --calib-layers record each linear's input Hessian; beside
  --kld-record the reference's own run records them
- --kld-top N records a sparse KL reference (the N most likely tokens and the tail's mass)
- GPTQ in a third of the time with the same codes, trellis GPTQ on the card, vector codebooks
  with coordinate descent, and rad-convert --reuse repeated, each container supplying what the
  earlier ones lack

Speculation:
- Prompt lookup alone (--spec-ngram K, --spec-ngram-min/-max): each sequence keeps an index of its
  n-grams, and a proposal is verified only when its measured step cost says it pays;
  --draft-window adaptive follows it

Speed:
- IQR decode: the narrow tile splits K for four times the int8 tile's waves and folds each 128-K
  block once; at 8 tokens down and the output projections run in 0.61-0.82x and 0.70-0.92x FP8's
  time (2-6 bits); IQ6R-S-V3 with its DFlash2 drafter steps in 26.3 ms at TP2, against 29.4 ms
  before and FP8's 27.3
- Qwen MXFP4 feed-forward: the gated fold up to 16 rows, not 8
- libr4d: the gated prefill fold, the short-prompt split row, and the rows forms of rmsnorm and
  rope; KLATE again for the head-256 gqa6 paged prefill; gram_accum on the matrix cores

Features:
- /health, /v1/health and /ping answer 503 with "status": "stuck" once the device has advanced
  nothing for a minute or a queue has faulted, so a supervisor can restart a wedged server (#356)
- --image-gen-max-pixels and --image-gen-max-refs size an image generator's buffers (#344)
- The startup report lists only the options not at their default, with a count; -v lists all
  (#250)
- --preempt-wait-ms bounds how long a preempted prefill waits for its whole-recompute room
- --placement layer_offload spills dense layers so one --max-model-len sequence fits
- Startup refuses amdgpu with CWSR off and says how to fix it;
  --proceed-with-incompatible-configuration starts anyway under an UNSUPPORTED banner

Fixes:
- The n-gram read-ahead hands each row to the reader once and reads only as far ahead as the row
  cache holds, and pauses while decode reads: about one drive read a row instead of two (#355)
- A file-tier window reads each of its runs once, not once a run per run
- The decode split law's verify floor is bounded by the batch's workgroups: max_seqs 256 no longer
  declares 64x the scratch (#342)
- A prefetch DMA list's mark stays out of the signal pool until the engine has read it, and a
  prefill stage copies only the blocks its own tables name (#343)
- The split-KV row sum is read with fetch-inactive (#328)
- LFM2 on the host backend: libref and libavx serve the row-form ops it declares (#348)
- The preempted-prefill gate skips a KV group that holds no blocks (#352)
- Every request entry point bounded, gated and sanitised (JSON depth, invalid UTF-8, control bytes
  in the log, the dashboard's CSP, cross-origin browsers on the loopback-only routes); a prompt id
  outside the vocabulary refused at admission; --api-key "" refused at startup
- The telemetry the HTTP thread reads is atomic
- An RMS norm row no longer depends on how many rows its launch carries; prefill attention's
  rescale is decided by live rows only
- A --kld-record prefill chunk that finishes no sequence gets its logits on a tied-head model
- A kernel's lazily made counter block is zeroed outside the lock other ranks take (a TP2 first-step
  hang)

Changes: Plugin ABI 32. Every plugin exports a layout fingerprint of the ABI structs and the loader
refuses a plugin without it or with another (#302), so out-of-tree plugins must be rebuilt.
Appended: RadBuildCtx calib_* and gen_max_*, RadArchProbe gen_max_*, RadBatch score_only and
plugin_words, RadDeviceProps::unified, RadChatFormat arg_json_value_prefix.
2026-10-30 22:01:01 +01:00

184 lines
8.6 KiB
Plaintext

/* Derived from libr4d/r4d_ple_gate_bf16.hip by the libhalo rename transform (2026-10-26),
* then ported to gfx1151; see libhalo/README.md. */
// halo_ple_gate_bf16.hip -- Per-Layer Embedding's dot-product gate.
//
// K[c] = grouped_rmsnorm(k)[c] * (w_key + wadd) k is key_proj(embedding)
// Q[c] = grouped_rmsnorm(q)[c] * (w_query + wadd) q is the incoming hc stream
// s[c] = sum_d K[c][d] * Q[c][d] / sqrt(n)
// s[c] = sign(s[c]) * sqrt(max(|s[c]|, gate_eps)) <- the signed square root
// gv[c] = sigmoid(s[c]) * v v is value_proj(embedding), one row
// gvn = grouped_rmsnorm(gv) * (w_conv + wadd)
//
// libref/ref_ple.cpp is the oracle and docs/OPS.md the contract. The sign comes from the original
// value, not the clamped magnitude: torch's sign(0) is 0, so an exactly-zero dot (as a quantised
// activation row produces) stays zero instead of becoming sqrt(gate_eps).
//
// One workgroup per (row, stream): every reduction (two norms, the dot, the gate's rms) is over
// one stream's `n`, and a workgroup is the widest unit that reduces without a second launch. At
// decode that is four workgroups, which is fine: the op moves 107 KB a row and is latency bound
// well before occupancy matters.
//
// Each thread keeps its n/threads elements of k and q in registers across the norm and the dot,
// and `gv` from its store to its rms, so nothing is read twice. `gv` is narrowed to bf16 before
// its rms, because the reference norms the bf16 tensor it wrote; keeping the f32 value would give
// a different number.
//
// Invariant: gv[c] is a scalar times one shared v row and norm_conv's rms is per stream, so the
// gate cancels out of `gvn`. This holds only in exact arithmetic (gv is narrowed first), so it is a
// property to check a fused kernel against, never one to fold.
#include "halo.h"
#include "halo_args.h"
#include "halo_common.h"
#include <cstdint>
namespace {
enum { kPgThreads = 256 };
/* A value narrowed to bf16 and read back, as the reference's `.type_as(x)` after every norm. */
__device__ __forceinline__ float pg_narrow(float v) {
return bf16_to_f32(f32_to_bf16(v));
}
/* expf, not __expf: this gate is compared against libref's std::exp with a tolerance meant for
* summation order. */
__device__ __forceinline__ float pg_sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); }
/* A workgroup-wide sum through LDS. The trailing barrier lets the next call reuse the array. */
__device__ __forceinline__ float pg_reduce(float v, float* lds) {
const uint32_t t = threadIdx.x;
lds[t] = v;
__syncthreads();
for (uint32_t w = kPgThreads / 2; w > 0; w >>= 1) {
if (t < w) lds[t] += lds[t + w];
__syncthreads();
}
const float r = lds[0];
__syncthreads();
return r;
}
__global__ __launch_bounds__(kPgThreads) void ple_gate_kernel(
const uint16_t* __restrict__ k, const uint16_t* __restrict__ q,
const uint16_t* __restrict__ v, const float* __restrict__ wk,
const float* __restrict__ wq, const float* __restrict__ wc,
uint16_t* __restrict__ gv, uint16_t* __restrict__ gvn,
uint32_t n, uint32_t hc, uint32_t k_ld, uint32_t q_ld, uint32_t v_ld,
uint32_t g_ld, uint32_t gn_ld, float eps, float wadd, float geps, uint32_t per_thread) {
__shared__ float lds[kPgThreads];
/* At most 16 elements per thread: n <= 16 * kPgThreads = 4096, which the row constrains. */
float mine_k[16], mine_q[16], mine_gv[16];
const uint32_t row = blockIdx.x / hc;
const uint32_t c = blockIdx.x % hc;
const uint32_t t = threadIdx.x;
const uint32_t base = c * n; /* this stream's first column of the wide row */
/* ---- the two norms, from values each thread then keeps ------------------------------------ */
float sk = 0.0f, sq = 0.0f;
for (uint32_t i = 0; i < per_thread; ++i) {
const uint32_t d = i * kPgThreads + t;
if (d >= n) break;
const float kv = bf16_to_f32(k[(size_t)row * k_ld + base + d]);
const float qv = bf16_to_f32(q[(size_t)row * q_ld + base + d]);
mine_k[i] = kv;
mine_q[i] = qv;
sk += kv * kv;
sq += qv * qv;
}
const float rk = rsqrtf(pg_reduce(sk, lds) / (float)n + eps);
const float rq = rsqrtf(pg_reduce(sq, lds) / (float)n + eps);
/* ---- the dot between them, over the NARROWED normed values -------------------------------- */
float dot = 0.0f;
for (uint32_t i = 0; i < per_thread; ++i) {
const uint32_t d = i * kPgThreads + t;
if (d >= n) break;
const float kk = pg_narrow(mine_k[i] * rk * (wk[base + d] + wadd));
const float qq = pg_narrow(mine_q[i] * rq * (wq[base + d] + wadd));
dot += kk * qq;
}
float s = pg_reduce(dot, lds) * rsqrtf((float)n);
/* The signed square root in the reference's order: clamp the magnitude, take the root, take the
* sign from the original. */
const float mag = sqrtf(fabsf(s) < geps ? geps : fabsf(s));
s = s > 0.0f ? mag : (s < 0.0f ? -mag : 0.0f);
const float gate = pg_sigmoid(s);
/* ---- the gated value, narrowed, and its own rms from the narrowed bytes ------------------- */
float sg = 0.0f;
for (uint32_t i = 0; i < per_thread; ++i) {
const uint32_t d = i * kPgThreads + t;
if (d >= n) break;
const float x = pg_narrow(gate * bf16_to_f32(v[(size_t)row * v_ld + d]));
mine_gv[i] = x;
gv[(size_t)row * g_ld + base + d] = f32_to_bf16(x);
sg += x * x;
}
const float rg = rsqrtf(pg_reduce(sg, lds) / (float)n + eps);
for (uint32_t i = 0; i < per_thread; ++i) {
const uint32_t d = i * kPgThreads + t;
if (d >= n) break;
gvn[(size_t)row * gn_ld + base + d] =
f32_to_bf16(pg_narrow(mine_gv[i] * rg * (wc[base + d] + wadd)));
}
}
enum { PG_K = 0, PG_Q, PG_V, PG_WK, PG_WQ, PG_WC, PG_GV, PG_GVN };
} // namespace
extern "C" int halo_rad_ple_gate(const RadArgs* a, RadStream s) {
const RadTensor* k = halo_opt(a, PG_K);
const RadTensor* q = halo_opt(a, PG_Q);
const RadTensor* v = halo_opt(a, PG_V);
const RadTensor* wk = halo_opt(a, PG_WK);
const RadTensor* wq = halo_opt(a, PG_WQ);
const RadTensor* wc = halo_opt(a, PG_WC);
const RadTensor* gv = halo_opt(a, PG_GV);
const RadTensor* gvn = halo_opt(a, PG_GVN);
if (!k || !q || !v || !wk || !wq || !wc || !gv || !gvn) return HALO_NO(RAD_E_INVAL);
if (k->dtype != RAD_BF16 || q->dtype != RAD_BF16 || v->dtype != RAD_BF16 ||
gv->dtype != RAD_BF16 || gvn->dtype != RAD_BF16) return HALO_NO(RAD_E_DTYPE);
if (wk->dtype != RAD_F32 || wq->dtype != RAD_F32 || wc->dtype != RAD_F32)
return HALO_NO(RAD_E_DTYPE);
const long long n = halo_geti_or(a, "n", 0);
const long long hc = halo_geti_or(a, "hc", 0);
if (n <= 0 || hc <= 0) return HALO_NO(RAD_E_SHAPE);
const long long hn = hc * n;
const long long per_thread = (n + kPgThreads - 1) / kPgThreads;
if (per_thread > 16) return HALO_NO(RAD_E_UNSUPPORTED);
const float eps = (float)halo_getf(a, "eps", 1e-6);
const float wadd = (float)halo_getf(a, "wadd", 0.0);
const float geps = (float)halo_getf(a, "gate_eps", 1e-6);
long long T = 0, tq = 0, tv = 0, tg = 0, tn = 0;
const long long k_ld = halo_rows_pitch(k, hn, &T);
const long long q_ld = halo_rows_pitch(q, hn, &tq);
const long long v_ld = halo_rows_pitch(v, n, &tv);
const long long g_ld = halo_rows_pitch(gv, hn, &tg);
const long long gn_ld = halo_rows_pitch(gvn, hn, &tn);
if (k_ld < 0 || q_ld < 0 || v_ld < 0 || g_ld < 0 || gn_ld < 0) return HALO_NO(RAD_E_STRIDE);
/* The row count comes from the operands, and they must agree: `M` is ranged, so the arg holds
* the band's upper bound and a grid sized by it would run off the arena. */
if (T <= 0 || tq != T || tv != T || tg != T || tn != T) return HALO_NO(RAD_E_SHAPE);
if (halo_numel(wk) < hn || halo_numel(wq) < hn || halo_numel(wc) < hn)
return HALO_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(ple_gate_kernel, dim3((uint32_t)(T * hc)), dim3(kPgThreads), 0,
(hipStream_t)s,
(const uint16_t*)halo_addr(k), (const uint16_t*)halo_addr(q),
(const uint16_t*)halo_addr(v), (const float*)halo_addr(wk),
(const float*)halo_addr(wq), (const float*)halo_addr(wc),
(uint16_t*)halo_addr(gv), (uint16_t*)halo_addr(gvn),
(uint32_t)n, (uint32_t)hc, (uint32_t)k_ld, (uint32_t)q_ld, (uint32_t)v_ld,
(uint32_t)g_ld, (uint32_t)gn_ld, eps, wadd, geps, (uint32_t)per_thread);
return hipGetLastError() == hipSuccess ? RAD_OK : HALO_NO(RAD_E_DEVICE);
}