Archived
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.
602 lines
32 KiB
Plaintext
602 lines
32 KiB
Plaintext
/* Derived from libr4d/r4d_qk_norm_rope_gate.hip by the libhalo rename transform (2026-10-26),
|
|
* then ported to gfx1151; see libhalo/README.md. */
|
|
// halo_qk_norm_rope_gate.hip -- halo_qk_norm_rope_gate: the whole gated-attention QKV preamble in one
|
|
// pass: split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE, and the gate copy.
|
|
//
|
|
// vLLM's equivalent fusion, `fused_qk_rmsnorm_rope_gate`, is gated on `is_cuda()`, and its Triton
|
|
// kernel does not compile on gfx1201 (Triton's AMD backend fails in
|
|
// `TritonAMDGPUCanonicalizePointers`). The unfused ROCm path is four kernels per attention layer
|
|
// (split, two GemmaRMSNorms, RoPE and gate chunk): 64 dispatches a decode step over 16 layers for
|
|
// ~6.3 us of work.
|
|
//
|
|
// Bit-identity: the reference stores the normed value as bf16 and RoPEs what it reads back, so the
|
|
// norm output is rounded to bf16 before the rotation. Skipping the round trip would be more
|
|
// accurate and a different function; vLLM's kernel has `.to(INPUT_DTYPE).to(tl.float32)` for the
|
|
// same reason.
|
|
//
|
|
// `wadd` is added to every gain: Qwen3NextRMSNorm is GemmaRMSNorm, `x_hat * (1 + w)` over a
|
|
// zero-centred gamma in fp32. This takes the stored gain and the offset and adds them in fp32 after
|
|
// the load, which matches vLLM's `weight.float() + 1.0` without a per-layer fp32 copy.
|
|
//
|
|
#include "halo.h"
|
|
#include "halo_args.h"
|
|
#include "halo_emit.h"
|
|
#include "halo_common.h"
|
|
#include "halo_fp8_wmma.h" // halo_fp8::cvt_pk_fp8_f32 (no fp8-conversion-insts on gfx1151)
|
|
#include "rad_yarn.h"
|
|
#include <hip/hip_bf16.h>
|
|
#include <cstdint>
|
|
#include <cmath>
|
|
|
|
// One block per (token, head) and one element per lane, required for bit-equality.
|
|
//
|
|
// Eight consecutive elements per lane with one wave per head (no LDS, rotary partner one shuffle
|
|
// away) computes a different function. halo_rmsnorm_bf16's width decides which columns a thread
|
|
// folds into the sum of squares, and a last-bit difference in the norm becomes a few percent where
|
|
// a rotated element's two products nearly cancel, enough to change the engine's text within a few
|
|
// dozen steps.
|
|
//
|
|
// The reference's fold is easy to reproduce: `rmsnorm_bf16` runs
|
|
// `for (i = threadIdx.x; i < n; i += THR)`, `halo_act_threads` never returns fewer than 256 threads,
|
|
// and every head_dim here is at most 256, so it always folds exactly one element per thread. Lanes
|
|
// past the head add exact zeros, so `block_sum` over 8 or 32 wave partials gives the same number.
|
|
// Hence one element a lane, 256 threads, `block_sum` in ascending wave order.
|
|
//
|
|
// Cost: at rot 64 the rotary partner is in another wave. The lane re-derives it instead of an LDS
|
|
// exchange: it loads the partner's input (an L1-hot read) and norms it with the block's `inv`.
|
|
/* The paged cache the KV form writes: kv_store's operands and parameters in one argument, to stay
|
|
* inside the emitter's parameter budget. Only the E4M3 form reads the descales. */
|
|
struct QkKvStore {
|
|
const __hip_bfloat16* v;
|
|
const int32_t* slot;
|
|
void* cache;
|
|
int v_pitch, block_size, n_blocks;
|
|
float k_inv, v_inv;
|
|
int row; /* fp8_v4 / k6_v4: a token's bytes in a page, 25 or 22 * HD / 16 */
|
|
/* QK_KV_STREAMED only: the group's host mirror and per-layer residency map, as
|
|
* kv_store_streamed takes them (libhalo/halo_model_bf16.hip). `blocks` is the mirror's block
|
|
* count (the id space) while `n_blocks` stays the ring depth. */
|
|
const int32_t* res;
|
|
void* host;
|
|
int blocks;
|
|
};
|
|
|
|
/* The cache forms KV selects. The two streamed forms are the same store into two planes, E4M3
|
|
* and bf16. */
|
|
enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2, QK_KV_F8V4 = 3, QK_KV_K6V4 = 4,
|
|
QK_KV_STREAMED = 5, QK_KV_STREAMED_BF16 = 6 };
|
|
|
|
/* KV folds kv_store in: a k head's block, holding the token's rotated k one element per lane, also
|
|
* writes that element and the head's v element into the cache at the token's slot, as E4M3 with
|
|
* kv_store_fp8's arithmetic or as bf16 like kv_store_bf16 (see the store at the end). */
|
|
template <int HD, int KV = QK_KV_NONE>
|
|
__global__ __launch_bounds__(256) void halo_qk_norm_rope_gate_kernel(
|
|
const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K,
|
|
__hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO,
|
|
__hip_bfloat16* __restrict__ GO,
|
|
const void* __restrict__ WQ, const void* __restrict__ WK,
|
|
const void* __restrict__ CS, const void* __restrict__ POS, long cs_rows,
|
|
int nq, int nkv, int rot, float eps, float wadd,
|
|
int qg_pitch, int k_pitch, int cs_f32, int pos_i64, int w_f32, QkKvStore kvs) {
|
|
constexpr int THR = 256;
|
|
__shared__ float lds[THR / 32];
|
|
const int tok = blockIdx.x, h = blockIdx.y;
|
|
const int t = threadIdx.x;
|
|
const long p = pos_i64 ? ((const long*)POS)[tok] : (long)((const int*)POS)[tok];
|
|
const int half = rot >> 1;
|
|
const bool isk = h >= nq;
|
|
const int lh = isk ? h - nq : h;
|
|
const __hip_bfloat16* in = isk ? (K + (size_t)tok * k_pitch + (size_t)lh * HD)
|
|
: (QG + (size_t)tok * qg_pitch + (size_t)lh * 2 * HD);
|
|
// The gain is f32 in this engine's plugins and bf16 in vLLM's; its width follows the operand.
|
|
const void* w = isk ? WK : WQ;
|
|
__hip_bfloat16* out = isk ? (KO + ((size_t)tok * nkv + lh) * HD)
|
|
: (QO + ((size_t)tok * nq + lh) * HD);
|
|
const float* csf = (const float*)CS;
|
|
const __hip_bfloat16* csb = (const __hip_bfloat16*)CS;
|
|
|
|
// Spelled once so this lane's element and its rotary partner cannot use different widths.
|
|
auto gain = [&](int i) -> float {
|
|
return w_f32 ? ((const float*)w)[i] : __bfloat162float(((const __hip_bfloat16*)w)[i]);
|
|
};
|
|
// Rounded to bf16 before the rotation; see the bit-identity note at the top of this file.
|
|
auto normed = [&](float v, float g, float inv) -> float {
|
|
return __bfloat162float(__float2bfloat16(v * inv * (g + wadd)));
|
|
};
|
|
|
|
// Everything the rotation reads is loaded before the reduction, so it is in flight during the
|
|
// sum of squares: this lane's element and gain, its partner's, and its cos and sin. Indices are
|
|
// clamped instead of guarding the loads (a lane past the head reads its last element; a lane past
|
|
// the rotary range reads its own element and table column 0, which exists since rot >= 2), and
|
|
// the values are used only where the guards below allow.
|
|
const int tc = t < HD ? t : HD - 1;
|
|
const bool rl = t < rot, first = t < half;
|
|
const int pt = rl ? (first ? t + half : t - half) : tc;
|
|
const int ci = rl ? (first ? t : t - half) : 0;
|
|
// The table row is clamped: a padded row (negative) or a position past the table's height has no
|
|
// row rope_table wrote, and must not read outside the plane.
|
|
const size_t co = (size_t)(p < 0 ? 0 : (p < cs_rows ? p : cs_rows - 1)) * rot;
|
|
const float vt = __bfloat162float(in[tc]), gt = gain(tc);
|
|
const float vp = __bfloat162float(in[pt]), gp = gain(pt);
|
|
const float c = cs_f32 ? csf[co + ci] : __bfloat162float(csb[co + ci]);
|
|
const float s = cs_f32 ? csf[co + half + ci] : __bfloat162float(csb[co + half + ci]);
|
|
|
|
float ss = 0.0f;
|
|
if (t < HD) ss = vt * vt;
|
|
// rmsnorm_bf16's block_sum, transcribed: the wave butterfly, then the wave partials summed in
|
|
// ascending order. Any other order breaks the bit-equality above. The barrier orders only the LDS
|
|
// partials, so the loads above stay in flight across it.
|
|
ss = halo_wave_sum(ss);
|
|
if ((t & 31) == 0) lds[t >> 5] = ss;
|
|
lds_barrier();
|
|
float sum = 0.0f;
|
|
#pragma unroll
|
|
for (int wv = 0; wv < THR / 32; ++wv) sum += lds[wv];
|
|
const float inv = rsqrtf(sum / (float)HD + eps);
|
|
|
|
float res = 0.0f;
|
|
if (t < HD) {
|
|
res = normed(vt, gt, inv);
|
|
if (rl) {
|
|
const float xp = normed(vp, gp, inv);
|
|
res = first ? (res * c - xp * s) : (xp * s + res * c);
|
|
}
|
|
}
|
|
// Every lane must read its input before any lane writes back: the engine rotates `k` in place,
|
|
// and a lane's partner is a memory read, so without this barrier it may already be overwritten.
|
|
// The failure is a ~1% scatter of wrong elements that looks like rounding; halo_selftest's
|
|
// byte-equality row catches it.
|
|
__syncthreads();
|
|
if (t < HD) {
|
|
out[t] = __float2bfloat16(res);
|
|
// `gate_out` is optional: a caller that reads the gate straight from the interleaved projection
|
|
// (the fp8 block, via gate_quant_fp8) passes none.
|
|
if (!isk && GO) GO[((size_t)tok * nq + lh) * HD + t] = in[HD + t];
|
|
}
|
|
// The cache write kv_store would make next, from the same bytes: the rotated k as just stored
|
|
// and the v row as the projection left it. The E4M3 form scales by the inverse descale, clamps
|
|
// (v_cvt_pk_fp8_f32 returns NaN out of range) and converts each element on its own, so one
|
|
// element a lane gives the same byte. The bf16 form stores the values as kv_store_bf16 does.
|
|
// Layout [n_blocks, kv_heads, block_size, 2*head_dim], k then v; a negative or out-of-range slot
|
|
// stores nothing.
|
|
if constexpr (KV != QK_KV_NONE) {
|
|
if (isk && t < HD) {
|
|
const int32_t sl = kvs.slot[tok];
|
|
/* A streamed group's cache is the ring and its truth is the host mirror: the token goes to
|
|
* the mirror's block row ALWAYS and to the ring slot only where the residency map says the
|
|
* block is resident, exactly as kv_store_streamed writes it (libref/ref_attn.cpp states why
|
|
* the test belongs in the writer). The block id bounds the mirror, the map bounds the ring,
|
|
* and a slot names a ring block only through `res`. */
|
|
if constexpr (KV == QK_KV_STREAMED || KV == QK_KV_STREAMED_BF16) {
|
|
if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.blocks) {
|
|
const uint32_t blk = (uint32_t)sl / (uint32_t)kvs.block_size;
|
|
const uint32_t off = (uint32_t)sl % (uint32_t)kvs.block_size;
|
|
/* One element of each plane. The mirror and the ring are byte planes of the same paged
|
|
* layout and `block_bytes` is their pitch, so a bf16 element is two bytes at twice the
|
|
* fp8 offset. */
|
|
const size_t EB = KV == QK_KV_STREAMED_BF16 ? 2 : 1;
|
|
const size_t rowb = (size_t)(2 * HD) * EB;
|
|
const size_t at = ((size_t)blk * nkv * kvs.block_size + off) * rowb +
|
|
(size_t)lh * kvs.block_size * rowb;
|
|
const __hip_bfloat16 kb = __float2bfloat16(res);
|
|
const __hip_bfloat16 vb = kvs.v[(size_t)tok * kvs.v_pitch + (size_t)lh * HD + t];
|
|
const int32_t rs = kvs.res[blk];
|
|
unsigned char* const m = (unsigned char*)kvs.host + at;
|
|
unsigned char* const c =
|
|
(rs >= 0 && (uint32_t)rs < (uint32_t)kvs.n_blocks)
|
|
? (unsigned char*)kvs.cache +
|
|
(((size_t)rs * nkv * kvs.block_size + off) * rowb +
|
|
(size_t)lh * kvs.block_size * rowb)
|
|
: nullptr;
|
|
if constexpr (KV == QK_KV_STREAMED_BF16) {
|
|
/* kv_store_bf16 writes the values themselves: no descales. */
|
|
*(__hip_bfloat16*)(m + EB * t) = kb;
|
|
*(__hip_bfloat16*)(m + EB * (HD + t)) = vb;
|
|
if (c) {
|
|
*(__hip_bfloat16*)(c + EB * t) = kb;
|
|
*(__hip_bfloat16*)(c + EB * (HD + t)) = vb;
|
|
}
|
|
} else {
|
|
const float kf = __bfloat162float(kb) * kvs.k_inv;
|
|
const float vf = __bfloat162float(vb) * kvs.v_inv;
|
|
const int pk = halo_fp8::cvt_pk_fp8_f32(fminf(fmaxf(kf, -448.0f), 448.0f), 0.0f,
|
|
0, false);
|
|
const int pv = halo_fp8::cvt_pk_fp8_f32(fminf(fmaxf(vf, -448.0f), 448.0f), 0.0f,
|
|
0, false);
|
|
m[t] = (unsigned char)(pk & 0xFF);
|
|
m[HD + t] = (unsigned char)(pv & 0xFF);
|
|
if (c) {
|
|
c[t] = (unsigned char)(pk & 0xFF);
|
|
c[HD + t] = (unsigned char)(pv & 0xFF);
|
|
}
|
|
}
|
|
}
|
|
} else if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.n_blocks) {
|
|
const uint32_t blk = (uint32_t)sl / (uint32_t)kvs.block_size;
|
|
const uint32_t off = (uint32_t)sl % (uint32_t)kvs.block_size;
|
|
const size_t rowb = (KV == QK_KV_F8V4 || KV == QK_KV_K6V4) ? (size_t)kvs.row : (size_t)(2 * HD);
|
|
const size_t at = ((size_t)blk * nkv * kvs.block_size + off) * rowb +
|
|
(size_t)lh * kvs.block_size * rowb;
|
|
const __hip_bfloat16 kb = __float2bfloat16(res);
|
|
const __hip_bfloat16 vb = kvs.v[(size_t)tok * kvs.v_pitch + (size_t)lh * HD + t];
|
|
if constexpr (KV == QK_KV_BF16) {
|
|
__hip_bfloat16* c = (__hip_bfloat16*)kvs.cache + at;
|
|
c[t] = kb;
|
|
c[HD + t] = vb;
|
|
} else if constexpr (KV == QK_KV_F8V4 || KV == QK_KV_K6V4) {
|
|
// fp8_v4: K as the E4M3 form writes it. k6_v4: K as int6 in groups of 32 (one wave)
|
|
// with an f16 scale, absmax / 31, in kv_store_k6v4's layout. V as int4 in groups of 32
|
|
// with an f16 scale, absmax / 7. The even lane of a pair writes the pair's nibble byte.
|
|
unsigned char* c = (unsigned char*)kvs.cache + at;
|
|
const float kf = __bfloat162float(kb) * kvs.k_inv;
|
|
constexpr int voff = KV == QK_KV_K6V4 ? HD * 3 / 4 : HD;
|
|
constexpr int vsoff = KV == QK_KV_K6V4 ? HD * 21 / 16 : HD * 3 / 2;
|
|
if constexpr (KV == QK_KV_K6V4) {
|
|
float kmax = fabsf(kf);
|
|
for (int m = 16; m >= 1; m >>= 1) kmax = fmaxf(kmax, __shfl_xor(kmax, m, 32));
|
|
const __fp16 k16 = (__fp16)fminf(kmax / 31.0f, 2112.0f); // finite codes, as kv_store_k6v4
|
|
const float ksc = (float)k16;
|
|
const float r = ksc > 0.0f ? rintf(kf / ksc) : 0.0f;
|
|
const int q = ((int)fminf(fmaxf(r, -31.0f), 31.0f)) & 0x3F;
|
|
const int qn = __shfl_xor(q & 15, 1, 32);
|
|
if ((t & 1) == 0) c[t / 2] = (unsigned char)((q & 15) | (qn << 4));
|
|
// High bits: a pair's four into bits 0-3 at its even lane, then the pair eight dims on
|
|
// into bits 4-7; lane 2j of a 16-dim chunk writes byte j.
|
|
const int h01 = (q >> 4) | (__shfl_xor(q >> 4, 1, 32) << 2);
|
|
const int hb = h01 | (__shfl_xor(h01, 8, 32) << 4);
|
|
if ((t & 1) == 0 && (t & 15) < 8) c[HD / 2 + (t / 16) * 4 + (t & 7) / 2] = (unsigned char)hb;
|
|
if ((t & 31) == 0) *(uint16_t*)(c + HD * 5 / 4 + (t / 32) * 2) = __builtin_bit_cast(uint16_t, k16);
|
|
} else {
|
|
const int pk = halo_fp8::cvt_pk_fp8_f32(fminf(fmaxf(kf, -448.0f), 448.0f), 0.0f,
|
|
0, false);
|
|
c[t] = (unsigned char)(pk & 0xFF);
|
|
}
|
|
const float vf = __bfloat162float(vb) * kvs.v_inv;
|
|
float amax = fabsf(vf);
|
|
for (int m = 16; m >= 1; m >>= 1) amax = fmaxf(amax, __shfl_xor(amax, m, 32));
|
|
const __fp16 s16 = (__fp16)fminf(amax / 7.0f, 8188.0f); // finite codes, as kv_store_fp8v4
|
|
const float sc = (float)s16;
|
|
const float r = sc > 0.0f ? rintf(vf / sc) : 0.0f;
|
|
const int q = ((int)fminf(fmaxf(r, -7.0f), 7.0f)) & 0xF;
|
|
const int qn = __shfl_xor(q, 1, 32);
|
|
if ((t & 1) == 0) c[voff + t / 2] = (unsigned char)(q | (qn << 4));
|
|
if ((t & 31) == 0) *(uint16_t*)(c + vsoff + (t / 32) * 2) = __builtin_bit_cast(uint16_t, s16);
|
|
} else {
|
|
unsigned char* c = (unsigned char*)kvs.cache + at;
|
|
const float kf = __bfloat162float(kb) * kvs.k_inv;
|
|
const float vf = __bfloat162float(vb) * kvs.v_inv;
|
|
const int pk = halo_fp8::cvt_pk_fp8_f32(fminf(fmaxf(kf, -448.0f), 448.0f), 0.0f,
|
|
0, false);
|
|
const int pv = halo_fp8::cvt_pk_fp8_f32(fminf(fmaxf(vf, -448.0f), 448.0f), 0.0f,
|
|
0, false);
|
|
c[t] = (unsigned char)(pk & 0xFF);
|
|
c[HD + t] = (unsigned char)(pv & 0xFF);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// ============================================================ the cos/sin table
|
|
//
|
|
// The fused kernel reads a precomputed table instead of theta, and this fills it: one launch per
|
|
// step for every attention layer, instead of a rope launch per layer (~7 us of dispatch for ~1 us
|
|
// of work at head_dim 256).
|
|
//
|
|
// Each position is written at its own row, so the table has a row per nameable position and only
|
|
// the rows a step touches are filled (kilobytes at decode, not the whole ~6 MB table). Rows nothing
|
|
// addresses are never read.
|
|
//
|
|
// The arithmetic is halo_model_bf16.hip's rope_kernel line for line, which makes the fusion
|
|
// bit-identical: `1.0f / powf(theta, 2i/den)` with `den` the ladder's width (`rot` for `rotary`,
|
|
// `head_dim` for `head`), the position divided by `rscale` in f32, `sincosf`, and the products
|
|
// consumed in f32 by the caller. Changing any of it changes the model's output.
|
|
__global__ __launch_bounds__(64) void halo_qk_rope_table_kernel(
|
|
const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, int den, float theta,
|
|
float rscale, int cs_f32, int pos_i64, RadYarn yarn) {
|
|
const int m = blockIdx.x;
|
|
const long pp = pos_i64 ? ((const long*)POS)[m] : (long)((const int*)POS)[m];
|
|
// A padded row addresses no table row, and a position at or past the table's height writes
|
|
// nothing (it would land in whatever the arena placed after the plane). libref and libavx skip
|
|
// the same rows.
|
|
if (pp < 0 || pp >= rows) return;
|
|
const int half = rot >> 1;
|
|
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
|
|
const size_t o = (size_t)pp * rot;
|
|
for (int i = threadIdx.x; i < half; i += (int)blockDim.x) {
|
|
const float inv = yarn.frequency(1.0f / powf(theta, (float)(2 * i) / (float)den), i);
|
|
float c, s;
|
|
sincosf(p * inv, &s, &c);
|
|
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
|
|
if (cs_f32) {
|
|
((float*)CS)[o + i] = c;
|
|
((float*)CS)[o + half + i] = s;
|
|
} else {
|
|
((__hip_bfloat16*)CS)[o + i] = __float2bfloat16(c);
|
|
((__hip_bfloat16*)CS)[o + half + i] = __float2bfloat16(s);
|
|
}
|
|
}
|
|
}
|
|
|
|
// The two launches, as the plugin ABI's RadLaunchFn. See the note at the head of
|
|
// halo_quant_act_i8.hip on the argument list and status return.
|
|
enum { QK_QGATE = 0, QK_K, QK_COSSIN, QK_POS, QK_WQ, QK_WK, QK_QOUT, QK_KOUT, QK_GOUT,
|
|
QK_V, QK_SLOT, QK_CACHE, QK_RES, QK_HOST };
|
|
|
|
/* The body of both forms; KVF is the kv_store fold and `kvs` its cache, already checked. */
|
|
template <int KVF>
|
|
static int qk_body(const RadArgs* args, RadStream stream, const QkKvStore& kvs) {
|
|
const RadTensor* qg = halo_opt(args, QK_QGATE);
|
|
const RadTensor* k = halo_opt(args, QK_K);
|
|
const RadTensor* cs = halo_opt(args, QK_COSSIN);
|
|
const RadTensor* po = halo_opt(args, QK_POS);
|
|
const RadTensor* wq = halo_opt(args, QK_WQ);
|
|
const RadTensor* wk = halo_opt(args, QK_WK);
|
|
const RadTensor* qo = halo_opt(args, QK_QOUT);
|
|
const RadTensor* ko = halo_opt(args, QK_KOUT);
|
|
const RadTensor* go = halo_opt(args, QK_GOUT);
|
|
// The k-only form: `n_head` 0 means there is no [q|gate] projection to split (each head is a
|
|
// plain `head_dim` run), so `q_gate`, `q_w` and `q_out` are absent and every head is served off
|
|
// `k`. The kernel needs nothing for it: `isk` is `h >= nq`, so at nq 0 every block takes the k
|
|
// path and the absent operands (null via halo_p / halo_wp) are never dereferenced.
|
|
if (!k || !cs || !po || !wk || !ko) return HALO_NO(RAD_E_INVAL);
|
|
if (!halo_contig(cs) || !halo_contig(po) || !halo_contig(wk)) return HALO_NO(RAD_E_STRIDE);
|
|
if (!halo_contig(ko)) return HALO_NO(RAD_E_STRIDE);
|
|
if (go && !halo_contig(go)) return HALO_NO(RAD_E_STRIDE);
|
|
|
|
const long long hd = halo_geti_or(args, "head_dim", 0);
|
|
const long long nq = halo_geti_or(args, "n_head", 0);
|
|
const long long nkv = halo_geti_or(args, "n_head_kv", 0);
|
|
const long long rot = halo_geti_or(args, "rot", 0);
|
|
if (nq < 0 || nkv < 1) return HALO_NO(RAD_E_SHAPE);
|
|
if (nq >= 1 && (!qg || !wq || !qo)) return HALO_NO(RAD_E_INVAL);
|
|
if (qg && (!halo_contig(wq) || !halo_contig(qo))) return HALO_NO(RAD_E_STRIDE);
|
|
|
|
const long long qg_pitch = qg ? halo_row_pitch(qg) : 0;
|
|
const long long k_pitch = halo_row_pitch(k);
|
|
if (qg_pitch < 0 || k_pitch < 0) return HALO_NO(RAD_E_STRIDE);
|
|
|
|
// The row count is the operand's; which operand carries it depends on the form.
|
|
const long long M = qg ? qg->shape[0] : k->shape[0];
|
|
if (M < 1) return HALO_NO(RAD_E_SHAPE);
|
|
if (hd != 64 && hd != 128 && hd != 256) return HALO_NO(RAD_E_SHAPE); // the compiled set
|
|
if (rot < 2 || (rot & 1) || rot > hd) return HALO_NO(RAD_E_SHAPE);
|
|
const long long cs_rows = halo_numel(cs) / rot;
|
|
if (cs_rows < 1 || halo_numel(cs) % rot) return HALO_NO(RAD_E_SHAPE);
|
|
|
|
const float eps = (float)halo_getf(args, "eps", 1e-6);
|
|
const float wadd = (float)halo_getf(args, "wadd", 0.0);
|
|
// The width flags come from the operands: a cos/sin table in f32 and positions in int64 are what
|
|
// the tensors say they are.
|
|
const int cs_f32 = (cs->dtype == RAD_F32) ? 1 : 0;
|
|
const int pos_i64 = (po->dtype == RAD_I64) ? 1 : 0;
|
|
// The norm gain's width is the operand's too (f32 in every architecture plugin here, bf16 in
|
|
// vLLM). One flag serves both gains, so they must agree.
|
|
if (wq && wq->dtype != wk->dtype) return HALO_NO(RAD_E_DTYPE);
|
|
if (wk->dtype != RAD_F32 && wk->dtype != RAD_BF16) return HALO_NO(RAD_E_DTYPE);
|
|
const int w_f32 = (wk->dtype == RAD_F32) ? 1 : 0;
|
|
|
|
const int nh = (int)(nq + nkv);
|
|
// One block per (token, head), 256 threads, one element per lane. The width is fixed at 256, not
|
|
// fitted to the head count, so the sum of squares matches halo_rmsnorm_bf16 (see the kernel).
|
|
#define HALO_QKG_L(H) emit_rc = HALO_EMIT(stream, (halo_qk_norm_rope_gate_kernel<H, KVF>), \
|
|
dim3((int)M, nh), dim3(256), 0, (const __hip_bfloat16*)halo_p(qg), \
|
|
(const __hip_bfloat16*)halo_p(k), (__hip_bfloat16*)halo_wp(qo), (__hip_bfloat16*)halo_wp(ko), \
|
|
(__hip_bfloat16*)halo_wp(go), halo_p(wq), halo_p(wk), halo_p(cs), halo_p(po), (long)cs_rows, \
|
|
(int)nq, (int)nkv, (int)rot, eps, wadd, (int)qg_pitch, (int)k_pitch, cs_f32, pos_i64, w_f32, \
|
|
kvs)
|
|
int emit_rc = RAD_OK;
|
|
switch (hd) {
|
|
case 64: HALO_QKG_L(64); break;
|
|
case 128: HALO_QKG_L(128); break;
|
|
default: HALO_QKG_L(256); break;
|
|
}
|
|
#undef HALO_QKG_L
|
|
return emit_rc;
|
|
}
|
|
|
|
extern "C" int halo_rad_qk_norm_rope_gate(const RadArgs* args, RadStream stream) {
|
|
return qk_body<QK_KV_NONE>(args, stream, QkKvStore{});
|
|
}
|
|
|
|
/* The prologue with the KV store folded in: qk_norm_rope_gate's operands, then kv_store's `v`,
|
|
* `slot_mapping` and `kv_cache`, and its parameters. The cache is E4M3 or bf16 as `kv_dtype`
|
|
* names, checked as kv_store checks it, one slot per prologue row. The k kv_store would read is the
|
|
* prologue's own output, so it is not a separate operand. */
|
|
extern "C" int halo_rad_qk_norm_rope_gate_kv_store(const RadArgs* args, RadStream stream) {
|
|
const RadTensor* k = halo_opt(args, QK_K);
|
|
const RadTensor* qg = halo_opt(args, QK_QGATE);
|
|
const RadTensor* v = halo_opt(args, QK_V);
|
|
const RadTensor* sm = halo_opt(args, QK_SLOT);
|
|
const RadTensor* kv = halo_opt(args, QK_CACHE);
|
|
if (!k || !v || !sm || !kv) return HALO_NO(RAD_E_INVAL);
|
|
const char* kvd = halo_gets(args, "kv_dtype");
|
|
const uint32_t want = kvd ? rad_dtype_parse(kvd) : (uint32_t)RAD_DT_INVALID;
|
|
if (v->dtype != RAD_BF16 || sm->dtype != RAD_I32 || kv->dtype != want ||
|
|
(kv->dtype != RAD_F8E4M3 && kv->dtype != RAD_BF16))
|
|
return HALO_NO(RAD_E_DTYPE);
|
|
if (!halo_contig(sm) || !halo_contig(kv)) return HALO_NO(RAD_E_STRIDE);
|
|
|
|
const long long hd = halo_geti_or(args, "head_dim", 0);
|
|
const long long nkv = halo_geti_or(args, "n_head_kv", 0);
|
|
const long long bs = halo_geti_or(args, "block_size", 0);
|
|
if (hd <= 0 || nkv <= 0 || bs <= 0) return HALO_NO(RAD_E_SHAPE);
|
|
if (kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || kv->shape[3] != 2 * hd)
|
|
return HALO_NO(RAD_E_SHAPE);
|
|
const long long M = qg ? qg->shape[0] : k->shape[0];
|
|
long long Mv = 0;
|
|
const long long v_ld = halo_rows_pitch(v, nkv * hd, &Mv);
|
|
if (v_ld < 0) return HALO_NO(RAD_E_STRIDE);
|
|
if (Mv < M || halo_numel(sm) != M) return HALO_NO(RAD_E_SHAPE);
|
|
|
|
const double ks = halo_getf(args, "k_scale", 1.0);
|
|
const double vs = halo_getf(args, "v_scale", 1.0);
|
|
if (!(ks > 0.0) || !(vs > 0.0)) return HALO_NO(RAD_E_INVAL);
|
|
|
|
QkKvStore kvs{};
|
|
kvs.v = (const __hip_bfloat16*)halo_p(v);
|
|
kvs.slot = (const int32_t*)halo_p(sm);
|
|
kvs.cache = halo_wp(kv);
|
|
kvs.v_pitch = (int)v_ld;
|
|
kvs.block_size = (int)bs;
|
|
kvs.n_blocks = (int)kv->shape[0];
|
|
kvs.k_inv = 1.0f / (float)ks;
|
|
kvs.v_inv = 1.0f / (float)vs;
|
|
return kv->dtype == RAD_BF16 ? qk_body<QK_KV_BF16>(args, stream, kvs)
|
|
: qk_body<QK_KV_FP8>(args, stream, kvs);
|
|
}
|
|
|
|
/* The prologue with the streamed store folded in (docs/OPS.md "kv_store_streamed"): each token's
|
|
* rotated k and its v go to the mirror's block row always and to `kv_cache[res[block]]` only where
|
|
* the block is resident, one launch where qk_norm_rope_gate + kv_store_streamed were two. The bytes
|
|
* are the pair's: `k_out`'s bf16 value is what the conversion reads, and both planes share one
|
|
* layout. E4M3, or bf16 storing the values themselves. */
|
|
extern "C" int halo_rad_qk_norm_rope_gate_kv_store_streamed(const RadArgs* args, RadStream stream) {
|
|
const RadTensor* k = halo_opt(args, QK_K);
|
|
const RadTensor* qg = halo_opt(args, QK_QGATE);
|
|
const RadTensor* v = halo_opt(args, QK_V);
|
|
const RadTensor* sm = halo_opt(args, QK_SLOT);
|
|
const RadTensor* kv = halo_opt(args, QK_CACHE);
|
|
const RadTensor* res = halo_opt(args, QK_RES);
|
|
const RadTensor* ho = halo_opt(args, QK_HOST);
|
|
if (!k || !v || !sm || !kv || !res || !ho) return HALO_NO(RAD_E_INVAL);
|
|
const char* kvd = halo_gets(args, "kv_dtype");
|
|
const uint32_t want = kvd ? rad_dtype_parse(kvd) : (uint32_t)RAD_DT_INVALID;
|
|
if (v->dtype != RAD_BF16 || sm->dtype != RAD_I32 || kv->dtype != want ||
|
|
(kv->dtype != RAD_F8E4M3 && kv->dtype != RAD_BF16) || res->dtype != RAD_I32 ||
|
|
ho->dtype != RAD_U8)
|
|
return HALO_NO(RAD_E_DTYPE);
|
|
if (!halo_contig(sm) || !halo_contig(kv) || !halo_contig(res) || !halo_contig(ho) ||
|
|
ho->rank != 2)
|
|
return HALO_NO(RAD_E_STRIDE);
|
|
|
|
const long long hd = halo_geti_or(args, "head_dim", 0);
|
|
const long long nkv = halo_geti_or(args, "n_head_kv", 0);
|
|
const long long bs = halo_geti_or(args, "block_size", 0);
|
|
if (hd <= 0 || nkv <= 0 || bs <= 0) return HALO_NO(RAD_E_SHAPE);
|
|
if (kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || kv->shape[3] != 2 * hd)
|
|
return HALO_NO(RAD_E_SHAPE);
|
|
const long long M = qg ? qg->shape[0] : k->shape[0];
|
|
long long Mv = 0;
|
|
const long long v_ld = halo_rows_pitch(v, nkv * hd, &Mv);
|
|
if (v_ld < 0) return HALO_NO(RAD_E_STRIDE);
|
|
if (Mv < M || halo_numel(sm) != M) return HALO_NO(RAD_E_SHAPE);
|
|
|
|
/* One block of one layer: the mirror's row pitch and the ring's slot pitch are the same bytes,
|
|
* so the store addresses both with one row arithmetic. */
|
|
const long long row = nkv * bs * 2 * hd * (kv->dtype == RAD_BF16 ? 2 : 1);
|
|
const long long blocks = ho->shape[0], slots = kv->shape[0];
|
|
if (blocks <= 0 || slots <= 0 || row <= 0) return HALO_NO(RAD_E_SHAPE);
|
|
if (ho->shape[1] != row || ho->stride[0] != row) return HALO_NO(RAD_E_STRIDE);
|
|
if (halo_numel(res) < blocks) return HALO_NO(RAD_E_SHAPE);
|
|
|
|
const double ks = halo_getf(args, "k_scale", 1.0);
|
|
const double vs = halo_getf(args, "v_scale", 1.0);
|
|
if (!(ks > 0.0) || !(vs > 0.0)) return HALO_NO(RAD_E_INVAL);
|
|
|
|
QkKvStore kvs{};
|
|
kvs.v = (const __hip_bfloat16*)halo_p(v);
|
|
kvs.slot = (const int32_t*)halo_p(sm);
|
|
kvs.cache = halo_wp(kv);
|
|
kvs.v_pitch = (int)v_ld;
|
|
kvs.block_size = (int)bs;
|
|
kvs.n_blocks = (int)slots;
|
|
kvs.k_inv = 1.0f / (float)ks;
|
|
kvs.v_inv = 1.0f / (float)vs;
|
|
kvs.res = (const int32_t*)halo_p(res);
|
|
kvs.host = halo_wp(ho);
|
|
kvs.blocks = (int)blocks;
|
|
return kv->dtype == RAD_BF16 ? qk_body<QK_KV_STREAMED_BF16>(args, stream, kvs)
|
|
: qk_body<QK_KV_STREAMED>(args, stream, kvs);
|
|
}
|
|
|
|
/* The fp8_v4 and k6_v4 forms: the same operands, the cache [n_blocks, kv_heads, block_size,
|
|
* 25 or 22 * HD / 16] E4M3-typed bytes (fp8_v4: E4M3 K; k6_v4: int6 K; both int4 V, f16 scales). */
|
|
static int qk_kv_q4(const RadArgs* args, RadStream stream, int k6) {
|
|
const long long r16 = k6 ? 22 : 25;
|
|
const RadTensor* k = halo_opt(args, QK_K);
|
|
const RadTensor* qg = halo_opt(args, QK_QGATE);
|
|
const RadTensor* v = halo_opt(args, QK_V);
|
|
const RadTensor* sm = halo_opt(args, QK_SLOT);
|
|
const RadTensor* kv = halo_opt(args, QK_CACHE);
|
|
if (!k || !v || !sm || !kv) return HALO_NO(RAD_E_INVAL);
|
|
if (v->dtype != RAD_BF16 || sm->dtype != RAD_I32 || kv->dtype != RAD_F8E4M3)
|
|
return HALO_NO(RAD_E_DTYPE);
|
|
if (!halo_contig(sm) || !halo_contig(kv)) return HALO_NO(RAD_E_STRIDE);
|
|
const long long hd = halo_geti_or(args, "head_dim", 0);
|
|
const long long nkv = halo_geti_or(args, "n_head_kv", 0);
|
|
const long long bs = halo_geti_or(args, "block_size", 0);
|
|
if (hd <= 0 || nkv <= 0 || bs <= 0 || hd % 32) return HALO_NO(RAD_E_SHAPE);
|
|
if (kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || kv->shape[3] != hd * r16 / 16)
|
|
return HALO_NO(RAD_E_SHAPE);
|
|
const long long M = qg ? qg->shape[0] : k->shape[0];
|
|
long long Mv = 0;
|
|
const long long v_ld = halo_rows_pitch(v, nkv * hd, &Mv);
|
|
if (v_ld < 0) return HALO_NO(RAD_E_STRIDE);
|
|
if (Mv < M || halo_numel(sm) != M) return HALO_NO(RAD_E_SHAPE);
|
|
const double ks = halo_getf(args, "k_scale", 1.0);
|
|
const double vs = halo_getf(args, "v_scale", 1.0);
|
|
if (!(ks > 0.0) || !(vs > 0.0)) return HALO_NO(RAD_E_INVAL);
|
|
QkKvStore kvs{};
|
|
kvs.v = (const __hip_bfloat16*)halo_p(v);
|
|
kvs.slot = (const int32_t*)halo_p(sm);
|
|
kvs.cache = halo_wp(kv);
|
|
kvs.v_pitch = (int)v_ld;
|
|
kvs.block_size = (int)bs;
|
|
kvs.n_blocks = (int)kv->shape[0];
|
|
kvs.k_inv = 1.0f / (float)ks;
|
|
kvs.v_inv = 1.0f / (float)vs;
|
|
kvs.row = (int)(hd * r16 / 16);
|
|
return k6 ? qk_body<QK_KV_K6V4>(args, stream, kvs) : qk_body<QK_KV_F8V4>(args, stream, kvs);
|
|
}
|
|
extern "C" int halo_rad_qk_norm_rope_gate_kv_store_fp8v4(const RadArgs* args, RadStream stream) {
|
|
return qk_kv_q4(args, stream, 0);
|
|
}
|
|
extern "C" int halo_rad_qk_norm_rope_gate_kv_store_k6v4(const RadArgs* args, RadStream stream) {
|
|
return qk_kv_q4(args, stream, 1);
|
|
}
|
|
|
|
// The cos/sin plane the fused prologue reads: one launch a step, against `rope`'s one per layer.
|
|
// `qk_norm_rope_gate` takes a table, not a theta, so this row is what makes it usable.
|
|
//
|
|
// Only the rows `positions` names are written, each at its own row of a [rows, rot] plane whose
|
|
// height is the operand's. A row nothing addresses keeps its contents, which is correct because
|
|
// nothing reads it.
|
|
extern "C" int halo_rad_rope_table(const RadArgs* args, RadStream stream) {
|
|
const RadTensor* po = halo_opt(args, 0);
|
|
const RadTensor* cs = halo_opt(args, 1);
|
|
if (!po || !cs) return HALO_NO(RAD_E_INVAL);
|
|
if (!halo_contig(po) || !halo_contig(cs)) return HALO_NO(RAD_E_STRIDE);
|
|
if (cs->dtype != RAD_F32 && cs->dtype != RAD_BF16) return HALO_NO(RAD_E_DTYPE);
|
|
if (po->dtype != RAD_I32 && po->dtype != RAD_I64) return HALO_NO(RAD_E_DTYPE);
|
|
|
|
// The row count is the operand's: `M` is declared as a band ceiling, but the call carries a
|
|
// step's rows.
|
|
const long long M = halo_numel(po);
|
|
const long long rot = halo_geti_or(args, "rot", 0);
|
|
if (M < 1 || rot < 2 || (rot & 1)) return HALO_NO(RAD_E_SHAPE);
|
|
if (halo_numel(cs) % rot) return HALO_NO(RAD_E_SHAPE);
|
|
|
|
/* `ladder`: `rotary` (default) measures the base ladder in `rot`; `head` in `head_dim`, the
|
|
* proportional variant. `rope_table` has no head_dim by default, so `head` needs the parameter. */
|
|
const long long head_dim = halo_geti_or(args, "head_dim", 0);
|
|
const char* lad = halo_gets(args, "ladder");
|
|
long long den = rot;
|
|
if (lad) {
|
|
if (!std::strcmp(lad, "head")) {
|
|
if (head_dim <= 0) return HALO_NO(RAD_E_SHAPE);
|
|
den = head_dim;
|
|
} else if (std::strcmp(lad, "rotary")) {
|
|
return HALO_NO(RAD_E_UNSUPPORTED);
|
|
}
|
|
}
|
|
|
|
const float theta = (float)halo_getf(args, "theta", 10000.0);
|
|
const float rscale = (float)halo_getf(args, "scale", 1.0);
|
|
const RadYarn yarn = rad_yarn_args(args);
|
|
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return HALO_NO(RAD_E_INVAL);
|
|
return HALO_EMIT(stream, halo_qk_rope_table_kernel, dim3((int)M), dim3(64), 0,
|
|
halo_p(po), halo_wp(cs), (long)(halo_numel(cs) / rot), (int)rot, (int)den, theta,
|
|
rscale, cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn);
|
|
}
|