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_sample_ngram_f32.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

217 lines
10 KiB
Plaintext

/* Derived from libr4d/r4d_sample_ngram_f32.hip by the libhalo rename transform (2026-10-26),
* then ported to gfx1151; see libhalo/README.md. */
// halo_sample_ngram_f32 -- the windowed no-repeat-ngram ban (`sample_ngram_ban`).
//
// Unlimited-OCR's generation_config asks for SlidingWindowNoRepeatNgramProcessor(n=35,
// window=128): a token that would complete an n-gram the last `window` tokens of the sequence
// already contain is banned, by setting its logit to -infinity. modeling_unlimitedocr.py:353-383
// is the reference, which SGLang ships as DeepseekOCRNoRepeatNGramLogitProcessor. A model that
// loops at the n-gram level (OCR layout rows repeat) otherwise repeats a phrase until the context
// ends.
//
// The reference's rule, with the row's history `s[0, hl)` oldest first (the committed tokens,
// including the one just emitted, plus this step's earlier drafts at a speculative verify):
//
// search_start = max(0, hl - w) with w from the row's {n, window} pair, w <= 0 whole span
// search_end = hl - n + 1
// for idx in [search_start, search_end):
// if s[idx .. idx + n - 2] == s[hl - n + 1 .. hl - 1): ban s[idx + n - 1]
//
// and at n = 1 the prefix is empty, so every token in the window is banned. The window bounds the
// n-gram's START, not its end, exactly as the reference slices `sequence[search_start:search_end]`
// -- which is why an n-gram that spans the window boundary is still searched.
//
// Exactness. Nothing here rounds: the kernel compares int32 history ids and stores the constant
// -infinity, so its answer is libref's ref_sample_ngram_ban by construction, not by tolerance. The
// only ordering freedom is that two threads may store -infinity to the same column, and the store
// is idempotent.
//
// Ids are global and the logits row is this rank's vocabulary shard: a token's column is its id
// less `vocab_off`, and a token outside the shard is another rank's to mask (it is not a column
// here at all).
//
// The optional `whitelist` plane is the reference's whitelist (modeling_unlimitedocr.py:359,379):
// word w bit b of the row's own plane row covers column 32w + b, and a SET bit removes that token
// from the banned set -- it is never written. Absent, nothing is exempt, and the kernel's answer
// is the one before the whitelist existed.
//
// The scan is O(w * n) a row over a history of at most max_hist tokens, so one block a row with
// the positions dealt out across the block's threads; the n-1-token prefix is staged in LDS once
// when it fits (n <= 256), which is every request the model card asks for (35).
#include "halo.h"
#include "halo_args.h"
#include "halo_common.h"
#include <cfloat>
// The params row is the engine's wire format, included rather than restated (abi/rad_sample.h).
#include "rad_sample.h"
namespace {
constexpr uint32_t kThreads = 256;
// The prefix staged in LDS, one int32 a token: 1 KiB. A longer n falls back to reading the
// history plane, which is correct but repeats the prefix's loads per position.
constexpr uint32_t kMaxPrefix = 256;
using SP = RadSampleParams;
__global__ __launch_bounds__(kThreads) void ngram_ban_kernel(
float* __restrict__ lg, const SP* __restrict__ sp, const int32_t* __restrict__ hist,
const int32_t* __restrict__ ng, const uint32_t* __restrict__ wl, uint32_t wl_words,
uint32_t n_vocab, uint32_t lg_ld, uint32_t hmax, int32_t voff) {
__shared__ int32_t pf[kMaxPrefix];
__shared__ int64_t s_start, s_end, s_plen, s_p0;
const uint32_t m = blockIdx.x;
const SP p = sp[m];
// The row's {n-gram length, window} pair (a separate plane, so the params row keeps the wire
// format every sampler op shares).
const int32_t ngram = ng[2 * m];
const int32_t win_req = ng[2 * m + 1];
// Every test before the barrier reads the row's own planes, so the block leaves together.
if (ngram <= 0) return;
// The whole staged span of the row (hist_off/hist_len both come from the engine; a negative
// hist_off is 0), clamped to the plane.
int32_t hl = p.hist_len;
int32_t ho = p.hist_off < 0 ? 0 : p.hist_off;
if (ho > (int32_t)hmax) ho = (int32_t)hmax;
if (hl > (int32_t)hmax - ho) hl = (int32_t)hmax - ho;
if (threadIdx.x == 0) {
int64_t start = 0, end = 0, plen = 0, p0 = 0;
if (hl >= ngram) {
// w <= 0 is the un-windowed processor: the whole staged history.
const int64_t win = win_req > 0 && win_req < hl ? win_req : hl;
start = hl - win;
end = (int64_t)hl - ngram + 1;
plen = (int64_t)ngram - 1;
p0 = (int64_t)hl - plen;
if (end <= start) end = start; /* nothing to search */
}
s_start = start;
s_end = end;
s_plen = plen;
s_p0 = p0;
}
__syncthreads();
const int64_t start = s_start, end = s_end, plen = s_plen, p0 = s_p0;
if (end <= start) return;
const int32_t* __restrict__ h = hist + (size_t)m * hmax + ho;
float* __restrict__ row = lg + (size_t)m * lg_ld;
// The row's own whitelist words (a SET bit exempts the column, the reference's
// `banned.difference_update(self.whitelist)`), read at the position loop below.
const uint32_t* __restrict__ w = wl ? wl + (size_t)m * wl_words : nullptr;
// The prefix: LDS when it fits, otherwise each position reads it from the plane.
const bool in_lds = plen <= (int64_t)kMaxPrefix;
if (in_lds) {
for (int64_t j = threadIdx.x; j < plen; j += (int64_t)kThreads) pf[j] = h[p0 + j];
__syncthreads();
}
auto prefix_at = [&](int64_t j) -> int32_t {
return in_lds ? pf[j] : h[p0 + j];
};
for (int64_t idx = start + (int64_t)threadIdx.x; idx < end; idx += (int64_t)kThreads) {
bool match = true;
for (int64_t j = 0; j < plen; ++j) {
if (h[idx + j] != prefix_at(j)) { match = false; break; }
}
if (!match) continue;
const int32_t tok = h[idx + plen];
const int64_t col = (int64_t)tok - voff;
if (tok < 0 || col < 0 || col >= (int64_t)n_vocab) continue;
if (wl && ((w[col >> 5] >> (uint32_t)(col & 31)) & 1u) != 0u) continue;
// Two positions may ban one token; the store is idempotent and the value is constant.
row[col] = -INFINITY;
}
}
int halo_sample_ngram_ban_f32(long lg, long params, long hist, long ng, long wl, int wl_words,
int M, int n_vocab, int hmax, int lg_ld, int vocab_off, long stream) {
if (!lg || !params || !hist || !ng) return HALO_NO(RAD_E_INVAL);
if (M <= 0 || n_vocab <= 0 || hmax <= 0) return HALO_NO(RAD_E_SHAPE);
if (wl && wl_words <= 0) return HALO_NO(RAD_E_SHAPE);
if (!lg_ld) lg_ld = n_vocab;
hipLaunchKernelGGL(ngram_ban_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(float*)lg, (const SP*)params, (const int32_t*)hist, (const int32_t*)ng,
(const uint32_t*)wl, (uint32_t)(wl ? wl_words : 0),
(uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hmax, (int32_t)vocab_off);
return hipGetLastError() == hipSuccess ? RAD_OK : HALO_NO(RAD_E_DEVICE);
}
} // namespace
// ================================================================================ entry point
//
// The shim checks what the kernel assumes: f32 logits, an i32 history contiguous in both rows and
// columns (the kernel walks it as one int32 a token), a params plane of whole RadSampleParams rows
// and the row pitches. `M` is the step's staged row count, never the band's upper bound.
#define HALO_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return HALO_NO(_s); } while (0)
static inline int dt_f32(const RadTensor* t) {
return (t && t->dtype == RAD_F32) ? RAD_OK : RAD_E_DTYPE;
}
static inline int dt_i32(const RadTensor* t) {
return (t && (t->dtype == RAD_I32 || t->dtype == RAD_U32)) ? RAD_OK : RAD_E_DTYPE;
}
static int params_ok(const RadTensor* t, long long M) {
if (!t || !t->data) return HALO_NO(RAD_E_INVAL);
if (t->dtype != RAD_U32 && t->dtype != RAD_I32 && t->dtype != RAD_F32) return HALO_NO(RAD_E_DTYPE);
if (!halo_contig(t)) return HALO_NO(RAD_E_STRIDE);
if (halo_numel(t) * 4 < M * (long long)sizeof(RadSampleParams)) return HALO_NO(RAD_E_SHAPE);
return RAD_OK;
}
extern "C" int halo_rad_sample_ngram_ban(const RadArgs* a, RadStream s) {
enum { V_LOGITS = 0, V_PARAMS, V_HIST, V_NGRAM, V_WL };
const RadTensor* lg = halo_opt(a, V_LOGITS);
if (!lg) return HALO_NO(RAD_E_INVAL);
HALO_NEED(dt_f32(lg));
const long long nv = halo_geti_or(a, "n_vocab", halo_dim(lg, (int)lg->rank - 1));
if (nv <= 0) return HALO_NO(RAD_E_SHAPE);
long long M = 0;
const long long ld = halo_rows_pitch(lg, nv, &M);
if (ld < 0) return HALO_NO(RAD_E_STRIDE);
if (M <= 0) return HALO_NO(RAD_E_SHAPE);
const RadTensor* pr = halo_opt(a, V_PARAMS);
const RadTensor* h = halo_opt(a, V_HIST);
const RadTensor* ng = halo_opt(a, V_NGRAM);
HALO_NEED(params_ok(pr, M));
if (!h || !ng) return HALO_NO(RAD_E_INVAL);
HALO_NEED(dt_i32(h));
HALO_NEED(dt_i32(ng));
if (!halo_contig(h) || !halo_contig(ng)) return HALO_NO(RAD_E_STRIDE);
const long long hmax = halo_numel(h) / M;
if (hmax <= 0) return HALO_NO(RAD_E_SHAPE);
/* One {n, window} pair a row, at least M of them. */
if (halo_numel(ng) < 2 * M) return HALO_NO(RAD_E_SHAPE);
/* The optional whitelist bitmask: contiguous words of 32 columns, M rows of them. */
const RadTensor* wl = halo_opt(a, V_WL);
const long long wwords = (nv + 31) / 32;
long long wl_addr = 0;
if (wl) {
HALO_NEED(dt_i32(wl));
if (!halo_contig(wl)) return HALO_NO(RAD_E_STRIDE);
if (halo_numel(wl) < M * wwords) return HALO_NO(RAD_E_SHAPE);
wl_addr = halo_addr(wl);
}
const long long voff = halo_geti_or(a, "vocab_off", 0);
return halo_sample_ngram_ban_f32(halo_addr(lg), halo_addr(pr), halo_addr(h), halo_addr(ng),
wl_addr, (int)wwords,
(int)M, (int)nv, (int)hmax, (int)ld, (int)voff,
(long)(uintptr_t)s);
}