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_qsa_block_key_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

230 lines
11 KiB
Plaintext

/* Derived from libr4d/r4d_qsa_block_key_bf16.hip by the libhalo rename transform (2026-10-26),
* then ported to gfx1151; see libhalo/README.md. */
// The QSA indexer's compressed key: one 128-dim vector per four tokens of key history.
//
// Qwen3.8-Flash-Next's full-attention layers use a small MQA indexer that scores 4-token blocks of
// the key history; attention reads only the best 512, so its cost is constant past 2051 tokens.
// This kernel builds the block keys those scores use (docs/QSA.md has the decomposition).
//
// The reference (`Qwen4ExpTextQSAIndexer`) recomputes every block key per query. A block key does
// not depend on the query and is fixed once its four tokens exist, so it is computed once, when
// the fourth token arrives, and cached (64 bytes per token per layer instead of a pass over the
// history every step).
//
// Arithmetic, in the reference's order and rounding:
//
// pooled = mean over the block's `ratio` raw keys, accumulated in f32 and rounded to bf16
// normed = RMSNorm(pooled) over `n`, gain (wadd + w)
// out = rope(normed) at the position of the block's first token
//
// The mean is rounded to bf16 before the norm, as in the reference
// (`key_groups.float().mean(dim=1).to(raw_keys.dtype)`); carrying f32 would give systematically
// different values.
//
// The rotation matches halo_qk_norm_rope_gate: `1/powf(theta, 2i/rot)`, position divided by
// `rscale` in f32, `sincosf`, neox pairing at stride `rot/2`. sincos is computed rather than read
// from that kernel's table, which holds only this step's positions (a block completing at decode
// starts three positions back).
//
// Returns a RAD status rather than throwing, for the reason given in halo_gemm_fp8a8.hip.
#include "halo.h"
#include "halo_args.h"
#include "rad_yarn.h"
#include "halo_emit.h"
#include "halo_common.h" // halo_wave_sum
#include <hip/hip_runtime.h>
#include <hip/hip_bf16.h>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
namespace {
constexpr int kMaxN = 256; // the index head dim; 128 on this model, bounded for the LDS
/* Position component read by frequency `i` for multi-component rotaries: mode 2 is contiguous
* sections, 3 Qwen3-VL's interleaved ones (as in halo_model_bf16.hip's rope). */
__device__ __forceinline__ int qbk_comp(int mode, int i, int s0, int s1, int s2) {
if (mode == 3) {
if (i % 3 == 1 && i < 3 * s1) return 1;
if (i % 3 == 2 && i < 3 * s2) return 2;
return 0;
}
return i < s0 ? 0 : (i < s0 + s1 ? 1 : 2);
}
__global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel(
const uint16_t* __restrict__ k, const float* __restrict__ w,
const int32_t* __restrict__ page, const int32_t* __restrict__ bpos,
uint16_t* __restrict__ out,
int n, int ratio, int rot, float eps, float wadd, float theta, float rscale,
long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc, RadYarn yarn) {
__shared__ float sh[kMaxN];
__shared__ float red[kMaxN / 32];
const int b = blockIdx.x;
const int t = threadIdx.x;
/* Mean in f32 over the block's rows, rounded to bf16 once. */
float acc = 0.0f;
if (t < n) {
const size_t base = (size_t)b * ratio;
for (int j = 0; j < ratio; ++j)
acc += __bfloat162float(((const __hip_bfloat16*)k)[(base + j) * k_ld + t]);
acc = __bfloat162float(__float2bfloat16(acc / (float)ratio));
}
/* RMSNorm over n: a block reduction, since n (128) spans several waves. */
float ss = t < n ? acc * acc : 0.0f;
ss = halo_wave_sum(ss);
if ((t & 31) == 0) red[t >> 5] = ss;
__syncthreads();
float sum = 0.0f;
const int nw = (blockDim.x + 31) / 32;
for (int i = 0; i < nw; ++i) sum += red[i];
const float inv = rsqrtf(sum / (float)n + eps);
/* f32 through the norm and rotation, rounded once at the store, matching
* halo_qk_norm_rope_gate for the model's own K. */
if (t < n) sh[t] = acc * inv * (wadd + w[t]);
__syncthreads();
if (t >= n) return;
float res = sh[t];
if (t < rot) {
const int half = rot >> 1;
const bool first = t < half;
const int pt = first ? t + half : t - half;
const int ci = first ? t : t - half;
/* The block's position: from the work list (bpos) when given, so one launch serves blocks
* of different sequences (decode); otherwise the pos0 + b*ratio tiling (a prefill chunk's
* contiguous run). With `mc` the list holds a block's three components side by side,
* blocks `bstep` apart, and each frequency reads its section's component. */
const int comp = mc ? qbk_comp(mode, ci, s0, s1, s2) : 0;
const long long bp = bpos ? (long long)bpos[(size_t)b * bstep + comp]
: (pos0 + (long long)b * ratio);
const float p = (float)bp / (rscale != 0.0f ? rscale : 1.0f);
const float iv = yarn.frequency(1.0f / powf(theta, (float)(2 * ci) / (float)rot), ci);
float s, c;
sincosf(p * iv, &s, &c);
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
const float xp = sh[pt];
res = first ? (res * c - xp * s) : (xp * s + res * c);
}
/* With `page`, block b is written to its page of the paged block-key store (docs/QSA.md);
* a negative entry (no page) is skipped. Without it the write is contiguous. */
long long orow = b;
if (page) {
const int32_t p = page[b];
if (p < 0) return;
orow = p;
}
((__hip_bfloat16*)out)[(size_t)orow * o_ld + t] = __float2bfloat16(res);
}
} // namespace
// k [M*ratio][n] bf16, `k_ld` elements a row (0 = n)
// w [n] f32
// out [M][n] bf16, `o_ld` elements a row (0 = n)
//
// Without `bpos`, `pos0` is the position of the first block's first token and block i starts at
// `pos0 + i * ratio`.
static int halo_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, long out, int M,
int n, int ratio, int rot, float eps, float wadd,
float theta, float rscale, long long pos0, int k_ld,
int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc,
RadStream stream, RadYarn yarn) {
if (!k || !w || !out || (pos0 < 0 && !bpos)) return HALO_NO(RAD_E_INVAL);
if (M <= 0 || n <= 0 || n > kMaxN || ratio <= 0) return HALO_NO(RAD_E_SHAPE);
if (rot < 0 || rot > n || (rot & 1)) return HALO_NO(RAD_E_SHAPE);
if (!k_ld) k_ld = n;
if (!o_ld) o_ld = n;
/* n threads rounded up to whole waves for the block reduction (extra threads contribute 0). */
const int thr = ((n + 31) / 32) * 32;
return HALO_EMIT(stream, qsa_block_key_kernel, dim3((unsigned)M), dim3((unsigned)thr), 0,
(const uint16_t*)k, (const float*)w, (const int32_t*)page,
(const int32_t*)bpos, (uint16_t*)out, n, ratio, rot, eps, wadd, theta, rscale,
pos0, k_ld, o_ld, mode, s0, s1, s2, bstep, mc, yarn);
}
// ============================================================== the plugin ABI entry point
enum { QBK_K = 0, QBK_W = 1, QBK_PAGE = 2, QBK_POS = 3, QBK_OUT = 4 };
extern "C" int halo_rad_qsa_block_key(const RadArgs* a, RadStream stream) {
const RadTensor* k = halo_opt(a, QBK_K);
const RadTensor* w = halo_opt(a, QBK_W);
const RadTensor* pg = halo_opt(a, QBK_PAGE); /* optional: absent is a contiguous write */
const RadTensor* bp = halo_opt(a, QBK_POS); /* optional: absent is the pos0 tiling */
const RadTensor* o = halo_opt(a, QBK_OUT);
if (!k || !w || !o) return HALO_NO(RAD_E_INVAL);
/* The destination may be a rank-4 KV cache: the block-key store is a KV group with kv_heads 1,
* block_size = ratio and head_dim n/(2*ratio), so a page holds exactly n values (docs/QSA.md).
* It is checked as [pages, n] by the product of the inner dims, not the rank. */
if (k->rank != 2) return HALO_NO(RAD_E_SHAPE);
if (o->rank < 2) return HALO_NO(RAD_E_SHAPE);
const long long n = halo_geti_or(a, "n", 0);
const long long ratio = halo_geti_or(a, "ratio", 0);
const long long rot = halo_geti_or(a, "rotary_dim", 0);
const long long pos0 = halo_geti_or(a, "pos0", -1);
if (n <= 0 || ratio <= 0 || (pos0 < 0 && !bp)) return HALO_NO(RAD_E_INVAL);
/* block_size sizes the block-key KV group and must equal the compress ratio, so a page holds
* exactly one block. */
const long long bs = halo_geti_or(a, "block_size", ratio);
if (bs != ratio) return HALO_NO(RAD_E_SHAPE);
/* With a page list, M is the number of blocks completing this step, not the store's height
* (the whole pool). */
const long long M = pg ? halo_numel(pg) : o->shape[0];
const long long ow = o->shape[0] > 0 ? halo_numel(o) / o->shape[0] : 0;
if (M < 1 || ow != n) return HALO_NO(RAD_E_SHAPE);
if (pg && o->shape[0] < 1) return HALO_NO(RAD_E_SHAPE);
/* `pos` is one position per block, or a rank-2 [>= M, 1 or 3] column slice with a block's
* components side by side and blocks a row pitch apart (qsa_work's output). */
int bstep = 1;
if (bp && bp->rank == 2) {
if (bp->shape[0] < M || bp->stride[1] != 1 || bp->stride[0] < bp->shape[1])
return HALO_NO(RAD_E_SHAPE);
bstep = (int)bp->stride[0];
} else if (bp && halo_numel(bp) < M) {
return HALO_NO(RAD_E_SHAPE);
}
/* Multi-component rotary: mode mrope or imrope with `sections` and three columns of `pos`
* (qsa_work's output with its `rope` operand). A single column is read as NeoX in any mode. */
const char* mode_s = halo_gets(a, "mode");
int mode = 0, sec[3] = { 0, 0, 0 }, n_sec = 0, mc = 0;
if (mode_s && !std::strcmp(mode_s, "mrope")) mode = 2;
else if (mode_s && !std::strcmp(mode_s, "imrope")) mode = 3;
else if (mode_s && std::strcmp(mode_s, "neox")) return HALO_NO(RAD_E_SCHEMA);
for (const char* v = halo_gets(a, "sections"); v && *v;) {
char* e = nullptr;
const long x = std::strtol(v, &e, 10);
if (e == v) break;
if (x <= 0 || n_sec >= 3) return HALO_NO(RAD_E_SHAPE);
sec[n_sec++] = (int)x;
v = e;
}
if (mode && n_sec > 0 && bp && bp->rank == 2 && bp->shape[1] >= 3) mc = 1;
/* The key operand must be exactly M * ratio rows; a wrong height would silently pool rows
* from neighbouring blocks. */
if (k->shape[0] != M * ratio || k->shape[1] != n) return HALO_NO(RAD_E_SHAPE);
if (halo_numel(w) < n) return HALO_NO(RAD_E_SHAPE);
const long long kp = halo_row_pitch(k), op = halo_row_pitch(o);
if (kp < 0 || op < 0) return HALO_NO(RAD_E_STRIDE);
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn) ||
(yarn.factor != 0.0f && (rot <= 0 || halo_getf(a, "scale", 1.0) != 1.0)))
return HALO_NO(RAD_E_INVAL);
return halo_qsa_block_key_bf16_emit(
halo_addr(k), halo_addr(w), halo_addr(pg), halo_addr(bp), halo_addr(o),
(int)M, (int)n, (int)ratio, (int)rot,
(float)halo_getf(a, "eps", 1e-6), (float)halo_getf(a, "wadd", 1.0),
(float)halo_getf(a, "theta", 10000.0), (float)halo_getf(a, "scale", 1.0),
pos0, (int)kp, (int)op, mode, sec[0], sec[1], sec[2], bstep, mc, stream, yarn);
}