From 59d36ae9280fc781d16192d9b989fef0744e1cf8 Mon Sep 17 00:00:00 2001 From: hazyumps Date: Tue, 6 Oct 2026 17:10:33 -0500 Subject: [PATCH] Extend YaRN to Qwen4 attention and compressed index keys --- arch/common/rad_qsa.h | 4 +-- arch/qwen4exp_fp8/qwen4exp_fp8.cpp | 3 +- docs/OPS.md | 2 +- docs/YARN.md | 19 ++++++++++-- libr4d/r4d_qsa_block_key_bf16.hip | 16 +++++++---- libr4d/r4d_rows.cpp | 4 +++ libr4d/r4d_selftest.cpp | 46 ++++++++++++++++++++++++++++++ tests/arch_test.cpp | 29 +++++++++++++++++++ 8 files changed, 112 insertions(+), 11 deletions(-) diff --git a/arch/common/rad_qsa.h b/arch/common/rad_qsa.h index 0b3621e1..62b406c5 100644 --- a/arch/common/rad_qsa.h +++ b/arch/common/rad_qsa.h @@ -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 * writes into a [work, 3] `bpos` when it is handed the step's rotary planes. */ 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_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot), 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("sections", g.rope_sections)), 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_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot), RAD_INT("block_size", c.ratio), diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index 265252e4..64a8bf44 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -364,6 +364,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c 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 * 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 @@ -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 * 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_INT("rot", m.n_rot), RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), RAD_STR("dtype", "f32")), diff --git a/docs/OPS.md b/docs/OPS.md index ff31f5fd..d8285f15 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -1165,7 +1165,7 @@ hands it unsorted runs gets a wrong order, not a slow one. | 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_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` | diff --git a/docs/YARN.md b/docs/YARN.md index f3b346d4..c0baf7d4 100644 --- a/docs/YARN.md +++ b/docs/YARN.md @@ -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 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 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. 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 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 | Key within the rotary object | Meaning | diff --git a/libr4d/r4d_qsa_block_key_bf16.hip b/libr4d/r4d_qsa_block_key_bf16.hip index 64440383..c2020181 100644 --- a/libr4d/r4d_qsa_block_key_bf16.hip +++ b/libr4d/r4d_qsa_block_key_bf16.hip @@ -31,6 +31,7 @@ #include "r4d.h" #include "r4d_args.h" +#include "rad_yarn.h" #include "r4d_emit.h" #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, 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) { + 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]; @@ -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] : (pos0 + (long long)b * ratio); 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; 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); } @@ -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, 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, - const R4dSink& sk) { + const R4dSink& sk, RadYarn yarn = {}) { int emit_rc = RAD_OK; if (!k || !w || !out) return -1; 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, (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); + s2, bstep, mc, yarn); 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); const long long kp = r4d_row_pitch(k), op = r4d_row_pitch(o); 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( r4d_addr(k), r4d_addr(w), r4d_addr(pg), r4d_addr(bp), r4d_addr(o), (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, "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; } diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 62007a40..d706234f 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1100,6 +1100,10 @@ static const RadParamSpec pQsaBlockKey[] = { * its `sections`, read against a [3, M] component-major `pos` list. Absent is NeoX. */ { "mode", 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[] = { { "k", RAD_OPD_IN, 0 }, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index cf1a8642..e90b44c1 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -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 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. */ +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>(); + 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 keys(M * ratio * n, h_to_bf16(1.0f)); + std::vector 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 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 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 got(M*n); + st_memcpy(got.data(),dout,got.size()*2,hipMemcpyDeviceToHost); + double worst=0; + for (int64_t m=0;m keys(meta.kv_key, meta.kv_key + meta.n_kv); + std::vector 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) { RadModelMeta meta = qwen4exp_meta(); RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);