Extend YaRN to Qwen4 attention and compressed index keys

This commit is contained in:
hazyumps authored and StillDeadcode committed 2026-10-07 11:09:27 +02:00
1 parent 2af7fa4022
commit 59d36ae928
8 files changed
+112 -11

No files matched your search

+2 -2
View File
@@ -269,7 +269,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
/* UNDER M-RoPE a block key rotates at its first token's three components, which qsa_work /* UNDER M-RoPE a block key rotates at its first token's three components, which qsa_work
* writes into a [work, 3] `bpos` when it is handed the step's rotary planes. */ * writes into a [work, 3] `bpos` when it is handed the step's rotary planes. */
op_bkey = g.rope_mc op_bkey = g.rope_mc
? RAD_OP(b, "qsa_block_key", ? decl_rotary(b, g, "qsa_block_key",
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim), RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot), RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
RAD_INT("block_size", c.ratio), RAD_INT("block_size", c.ratio),
@@ -278,7 +278,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode), RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode),
RAD_STR("sections", g.rope_sections)), RAD_STR("sections", g.rope_sections)),
RAD_WEIGHTS(w_kn)) RAD_WEIGHTS(w_kn))
: RAD_OP(b, "qsa_block_key", : decl_rotary(b, g, "qsa_block_key",
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim), RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot), RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
RAD_INT("block_size", c.ratio), RAD_INT("block_size", c.ratio),
+2 -1
View File
@@ -364,6 +364,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_INVAL; return RAD_E_INVAL;
} }
} }
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
/* THERE IS NO BRING-UP SLICE, and the rule is worth stating: if a model ever arrives too large /* THERE IS NO BRING-UP SLICE, and the rule is worth stating: if a model ever arrives too large
* for the target device, the answer is a converter flag that writes a NAMED partial container * for the target device, the answer is a converter flag that writes a NAMED partial container
* -- not an environment variable that makes a full one silently mean something else. A slice * -- not an environment variable that makes a full one silently mean something else. A slice
@@ -1000,7 +1001,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* one step; the symptom is fluent output with one arm of the model reading the other's * one step; the symptom is fluent output with one arm of the model reading the other's
* leftovers, which nothing downstream flags. * leftovers, which nothing downstream flags.
*/ */
m.op_rope_cs = rw(b, RAD_OP(b, "rope_table", m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)), RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)),
RAD_INT("rot", m.n_rot), RAD_F64("theta", g.theta), RAD_INT("rot", m.n_rot), RAD_F64("theta", g.theta),
RAD_F64("scale", g.rope_scale), RAD_STR("dtype", "f32")), RAD_F64("scale", g.rope_scale), RAD_STR("dtype", "f32")),
+1 -1
View File
@@ -1165,7 +1165,7 @@ hands it unsorted runs gets a wrong order, not a slow one.
| op | params | operands | | op | params | operands |
|---|---|---| |---|---|---|
| `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt | `k`, `w`w, `page`?, `pos`? → `out` | | `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `k`, `w`w, `page`?, `pos`? → `out` |
| `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` | | `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` |
| `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` | | `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` |
| `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` | | `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` |
+17 -2
View File
@@ -1,16 +1,31 @@
# Static YaRN for Qwen dense FP8 and DFlash2 # Static YaRN for Qwen architectures
Increasing `--max-model-len` reserves a larger serving window; it does not change Increasing `--max-model-len` reserves a larger serving window; it does not change
the model's rotary embeddings. A Qwen checkpoint trained at 262144 positions can the model's rotary embeddings. A Qwen checkpoint trained at 262144 positions can
explicitly request static YaRN for a 524288-token deployment. Whether that extension explicitly request static YaRN for a 524288-token deployment. Whether that extension
preserves useful accuracy must be measured on the model and workload. preserves useful accuracy must be measured on the model and workload.
The Qwen dense FP8 architecture reads the target's `text_config.rope_parameters`, The Qwen architectures read the target's `text_config.rope_parameters`,
then `rope_parameters`, then their legacy `rope_scaling` spellings, in that order. then `rope_parameters`, then their legacy `rope_scaling` spellings, in that order.
The first object with `rope_type` (or legacy `type`) is authoritative. The DFlash2 The first object with `rope_type` (or legacy `type`) is authoritative. The DFlash2
drafter reads its own `draft.rope_parameters` / `draft.rope_scaling`; it does not drafter reads its own `draft.rope_parameters` / `draft.rope_scaling`; it does not
inherit the target's scaling. The vision tower keeps its original axial rotations. inherit the target's scaling. The vision tower keeps its original axial rotations.
## Coverage
| Architecture | Rotary paths | Validation so far |
| --- | --- | --- |
| `qwen35_fp8` | Target direct/table; independent DFlash2 | Qwen3.8-27B FP8: text/tool/image checks, 499997-token retrieval and two concurrent 255981-token retrievals, TP4/BF16 KV |
| `qwen35_bf16` | Target direct rotary | Architecture declaration and shared numerical tests; no end-to-end BF16 model run yet |
| `qwen35moe_fp8` | Shared Qwen35 target and MTP geometry | Shares implementation; model qualification pending |
| `qwen4exp_fp8` | Attention, indexer, compressed block keys and shared MTP geometry | Architecture declarations and compressed-key GPU numerical checks; model qualification pending |
Radiance 1.2.0 also serves the published Qwen3.8-27B MXFP4 container through the
Qwen35 FP8 architecture's encoding dispatch. Its model qualification is pending.
Synthetic retrieval is evidence for those requests, not a general accuracy benchmark
or a capacity guarantee for other model sizes. Original-context quality should be
checked alongside extended-context quality when deploying static YaRN.
## Metadata ## Metadata
| Key within the rotary object | Meaning | | Key within the rotary object | Meaning |
+11 -5
View File
@@ -31,6 +31,7 @@
#include "r4d.h" #include "r4d.h"
#include "r4d_args.h" #include "r4d_args.h"
#include "rad_yarn.h"
#include "r4d_emit.h" #include "r4d_emit.h"
#include "r4d_common.h" // r4d_wave_sum #include "r4d_common.h" // r4d_wave_sum
@@ -61,7 +62,7 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel(
const int32_t* __restrict__ page, const int32_t* __restrict__ bpos, const int32_t* __restrict__ page, const int32_t* __restrict__ bpos,
uint16_t* __restrict__ out, uint16_t* __restrict__ out,
int n, int ratio, int rot, float eps, float wadd, float theta, float rscale, 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) { 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 sh[kMaxN];
__shared__ float red[kMaxN / 32]; __shared__ float red[kMaxN / 32];
@@ -114,9 +115,10 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel(
const long long bp = bpos ? (long long)bpos[(size_t)b * bstep + comp] const long long bp = bpos ? (long long)bpos[(size_t)b * bstep + comp]
: (pos0 + (long long)b * ratio); : (pos0 + (long long)b * ratio);
const float p = (float)bp / (rscale != 0.0f ? rscale : 1.0f); const float p = (float)bp / (rscale != 0.0f ? rscale : 1.0f);
const float iv = 1.0f / powf(theta, (float)(2 * ci) / (float)rot); const float iv = yarn.frequency(1.0f / powf(theta, (float)(2 * ci) / (float)rot), ci);
float s, c; float s, c;
sincosf(p * iv, &s, &c); sincosf(p * iv, &s, &c);
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
const float xp = sh[pt]; const float xp = sh[pt];
res = first ? (res * c - xp * s) : (xp * s + res * c); res = first ? (res * c - xp * s) : (xp * s + res * c);
} }
@@ -148,7 +150,7 @@ static int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, lon
int n, int ratio, int rot, float eps, float wadd, int n, int ratio, int rot, float eps, float wadd,
float theta, float rscale, long long pos0, int k_ld, 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, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc,
const R4dSink& sk) { const R4dSink& sk, RadYarn yarn = {}) {
int emit_rc = RAD_OK; int emit_rc = RAD_OK;
if (!k || !w || !out) return -1; if (!k || !w || !out) return -1;
if (M <= 0 || n <= 0 || n > kMaxN || ratio <= 0) return -2; if (M <= 0 || n <= 0 || n > kMaxN || ratio <= 0) return -2;
@@ -162,7 +164,7 @@ static int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, lon
emit_rc = R4D_EMIT(sk, qsa_block_key_kernel, dim3((unsigned)M), dim3((unsigned)thr), 0, (const uint16_t*)k, (const float*)w, emit_rc = R4D_EMIT(sk, 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, (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, n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, s0, s1,
s2, bstep, mc); s2, bstep, mc, yarn);
return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4; return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4;
} }
@@ -244,12 +246,16 @@ static int r4d_rad_qsa_block_key_body(const RadArgs* a, const R4dSink& sk) {
if (r4d_numel(w) < n) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(w) < n) return R4D_NO(RAD_E_SHAPE);
const long long kp = r4d_row_pitch(k), op = r4d_row_pitch(o); const long long kp = r4d_row_pitch(k), op = r4d_row_pitch(o);
if (kp < 0 || op < 0) return R4D_NO(RAD_E_STRIDE); if (kp < 0 || op < 0) return R4D_NO(RAD_E_STRIDE);
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn) ||
(yarn.factor != 0.0f && (rot <= 0 || r4d_getf(a, "scale", 1.0) != 1.0)))
return R4D_NO(RAD_E_INVAL);
const int e = r4d_qsa_block_key_bf16_emit( const int e = r4d_qsa_block_key_bf16_emit(
r4d_addr(k), r4d_addr(w), r4d_addr(pg), r4d_addr(bp), r4d_addr(o), r4d_addr(k), r4d_addr(w), r4d_addr(pg), r4d_addr(bp), r4d_addr(o),
(int)M, (int)n, (int)ratio, (int)rot, (int)M, (int)n, (int)ratio, (int)rot,
(float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 1.0), (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 1.0),
(float)r4d_getf(a, "theta", 10000.0), (float)r4d_getf(a, "scale", 1.0), (float)r4d_getf(a, "theta", 10000.0), (float)r4d_getf(a, "scale", 1.0),
pos0, (int)kp, (int)op, mode, sec[0], sec[1], sec[2], bstep, mc, sk); pos0, (int)kp, (int)op, mode, sec[0], sec[1], sec[2], bstep, mc, sk, yarn);
return e == 0 ? RAD_OK : RAD_E_SHAPE; return e == 0 ? RAD_OK : RAD_E_SHAPE;
} }
+4
View File
@@ -1100,6 +1100,10 @@ static const RadParamSpec pQsaBlockKey[] = {
* its `sections`, read against a [3, M] component-major `pos` list. Absent is NeoX. */ * its `sections`, read against a [3, M] component-major `pos` list. Absent is NeoX. */
{ "mode", RAD_P_STR, RAD_OPTIONAL }, { "mode", RAD_P_STR, RAD_OPTIONAL },
{ "sections", RAD_P_STR, RAD_OPTIONAL }, { "sections", RAD_P_STR, RAD_OPTIONAL },
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
}; };
static const RadOperandSpec oQsaBlockKey[] = { static const RadOperandSpec oQsaBlockKey[] = {
{ "k", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 },
+46
View File
@@ -8658,6 +8658,51 @@ static void qsa_score_rows_case(const Plugin& pl) {
* block's worth of angle, which is the mistake a reader makes when they take the position of the * block's worth of angle, which is the mistake a reader makes when they take the position of the
* block's LAST token instead of its first, and it is invisible in magnitude: the vectors stay the * block's LAST token instead of its first, and it is invisible in magnitude: the vectors stay the
* same length and point somewhere else. rel_l2 is what sees it. */ * same length and point somewhere else. rel_l2 is what sees it. */
static void qsa_block_key_yarn_case(const Plugin& pl) {
const char* what = "qsa_block_key YaRN vs independent ROCm vectors through 524287";
const RadKernelInfo* r = find(pl, "qsa_block_key_bf16");
if (!r) { ok(what, false, "row absent"); return; }
const std::string here = __FILE__;
std::ifstream input(here.substr(0, here.find_last_of('/')) + "/../tests/data/yarn_reference_rocm.json");
if (!input) { ok(what, false, "fixture absent"); return; }
const auto fixture = nlohmann::json::parse(input);
const auto positions = fixture["positions"].get<std::vector<int32_t>>();
const auto& c = fixture["cases"][0];
const int64_t M = positions.size(), n = 128, ratio = 4;
/* Identical unit keys make the block mean exactly one. Unit gain and eps=0
* make the norm exactly one too, isolating the compressed-key rotation. */
std::vector<uint16_t> keys(M * ratio * n, h_to_bf16(1.0f));
std::vector<float> gains(n, 1.0f);
void* dk = dalloc(keys.size()*2), *dw = dalloc(gains.size()*4);
void* dp = dalloc(M*4), *dout = dalloc(M*n*2);
st_memcpy(dk, keys.data(), keys.size()*2, hipMemcpyHostToDevice);
st_memcpy(dw, gains.data(), gains.size()*4, hipMemcpyHostToDevice);
st_memcpy(dp, positions.data(), M*4, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {T(dk, RAD_BF16, {M*ratio,n}), T(dw, RAD_F32, {n}),
T(nullptr, RAD_I32, {M}), T(dp, RAD_I32, {M}), T(dout, RAD_BF16, {M,n})};
std::vector<RadParam> ps = {PI("M",M), PI("n",n), PI("ratio",ratio), PI("rotary_dim",64),
PF("eps",0), PF("theta",1e7), PF("scale",1), PF("wadd",0), PS("dtype","bf16"),
PF("yarn_factor",2), PF("yarn_low",14), PF("yarn_high",22), PF("yarn_magnitude",1.069314718)};
RadArgs a{}; a.t=ts.data(); a.n_t=ts.size(); a.p=ps.data(); a.n_p=ps.size();
bool passed = r->launch(&a,nullptr) == RAD_OK;
st_stream_sync(nullptr);
std::vector<uint16_t> got(M*n);
st_memcpy(got.data(),dout,got.size()*2,hipMemcpyDeviceToHost);
double worst=0;
for (int64_t m=0;m<M;++m) for (int i=0;i<n;++i) {
double expected=1;
if (i<64) {
const int j=i%32;
const double cosine=c["cos"][m][j], sine=c["sin"][m][j];
expected=i<32 ? cosine-sine : cosine+sine;
}
const double actual=h_bf16(got[m*n+i]);
passed = passed && std::isfinite(actual);
worst=std::max(worst,std::abs(actual-expected));
}
ok(what,passed && worst<=0.008,"worst absolute BF16 error "+std::to_string(worst));
}
static void qsa_block_key_case(const Plugin& pl) { static void qsa_block_key_case(const Plugin& pl) {
const char* what = "qsa_block_key vs an f64 evaluation of the same formula"; const char* what = "qsa_block_key vs an f64 evaluation of the same formula";
const RadKernelInfo* r = find(pl, "qsa_block_key_bf16"); const RadKernelInfo* r = find(pl, "qsa_block_key_bf16");
@@ -11057,6 +11102,7 @@ static void device_phase(const Plugin& pl) {
if (sel("qsa_block_key_bf16")) { if (sel("qsa_block_key_bf16")) {
if (!g_case) std::printf("\nthe QSA compressed key, against the formula it implements\n"); if (!g_case) std::printf("\nthe QSA compressed key, against the formula it implements\n");
qsa_block_key_case(pl); qsa_block_key_case(pl);
qsa_block_key_yarn_case(pl);
} }
if (sel("moe_gemm_w4a8")) { if (sel("moe_gemm_w4a8")) {
+29
View File
@@ -1572,6 +1572,35 @@ RadModelMeta qwen4exp_meta() {
* convert and at load. Asked about a model whose recipe made them int4-rotated, E4M3 rows and u2, * convert and at load. Asked about a model whose recipe made them int4-rotated, E4M3 rows and u2,
* it declares the rotated expert kernels, the E4M3 mix and the 2-bit head; asked about one with * it declares the rotated expert kernels, the E4M3 mix and the 2-bit head; asked about one with
* nothing behind it, the fp8 experts and the bf16 mix. */ * nothing behind it, the fp8 experts and the bf16 mix. */
TEST(qwen4exp_yarn_reaches_attention_indexer_and_compressed_keys) {
RadModelMeta meta = qwen4exp_meta();
std::vector<const char*> keys(meta.kv_key, meta.kv_key + meta.n_kv);
std::vector<const char*> vals(meta.kv_val, meta.kv_val + meta.n_kv);
keys.insert(keys.end(), {"text_config.rope_parameters.rope_type", "text_config.rope_parameters.factor",
"text_config.rope_parameters.original_max_position_embeddings"});
vals.insert(vals.end(), {"yarn", "2", "262144"});
meta.n_kv = (int)keys.size(); meta.kv_key = keys.data(); meta.kv_val = vals.data();
RadBuildCtx c = build_ctx(0, 1);
c.max_tok = 2048; c.max_seqs = 8; c.max_spec = 3; c.max_ctx = 524288;
RadBuilder b;
REQUIRE_EQ(qwen4exp_fp8::declare(&b, &meta, &c), RAD_OK);
int direct = 0, table = 0, compressed = 0;
for (const auto& op : b.ops) {
if (op.op == "rope") ++direct;
else if (op.op == "rope_table") ++table;
else if (op.op == "qsa_block_key") ++compressed;
else continue;
int found = 0;
for (const auto& p : op.p) {
if (p.key == "yarn_factor") { CHECK_EQ(p.dval, 2.0); ++found; }
if (p.key == "yarn_magnitude") { CHECK_NEAR(p.dval, 1.069314718, 1e-7); ++found; }
if (p.key == "scale") CHECK_EQ(p.dval, 1.0);
}
CHECK_EQ(found, 2);
}
CHECK(direct > 0); CHECK(table > 0); CHECK(compressed > 0);
}
TEST(the_encodings_the_model_holds_choose_the_flash_next_kernels) { TEST(the_encodings_the_model_holds_choose_the_flash_next_kernels) {
RadModelMeta meta = qwen4exp_meta(); RadModelMeta meta = qwen4exp_meta();
RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128); RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);