Add static YaRN to Qwen rotary paths with independent CPU and ROCm vectors

This commit is contained in:
hazyumps authored and StillDeadcode committed 2026-10-07 11:09:27 +02:00
1 parent d23c3e0d17
commit 2af7fa4022
22 files changed
+7542 -27

No files matched your search

+28
View File
@@ -550,6 +550,34 @@ TEST(declare_is_a_qwen35_trunk) {
CHECK_EQ(count_op(b, "silu_mul"), 8);
}
TEST(qwen35_bf16_yarn_reaches_every_text_rotary_op) {
RadModelMeta meta = qwen35_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(), {"rope_parameters.rope_type", "rope_parameters.factor",
"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 ctx = build_ctx();
RadBuilder b;
CHECK_OK(qwen35_bf16::declare(&b, &meta, &ctx));
int rotary = 0;
for (const auto& op : b.ops) if (op.op == "rope") {
++rotary;
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_EQ(rotary, 4);
vals[vals.size()-2] = "nan";
RadBuilder invalid;
CHECK_EQ(qwen35_bf16::declare(&invalid, &meta, &ctx), RAD_E_INVAL);
}
TEST(the_alternation_puts_full_attention_at_3_and_7) {
RadBuilder b;
RadModelMeta meta = qwen35_meta();
+27
View File
@@ -0,0 +1,27 @@
"""Generate independent YaRN vectors using vLLM (Apache-2.0).
Run in the reference environment, redirect stdout to yarn_reference.json (CPU)
or pass cuda and redirect to yarn_reference_rocm.json (ROCm/gfx1201).
This script is not a runtime dependency and does not load model weights.
"""
import json
import sys
from types import SimpleNamespace
import torch
from vllm.model_executor.layers.rotary_embedding.yarn_scaling_rope import YaRNScalingRotaryEmbedding
positions = [0, 1, 4096, 262143, 262144, 500000, 524287]
cases = []
device = sys.argv[1] if len(sys.argv) > 1 else 'cpu'
with torch.device(device):
for rot in (64, 128, 256):
cfg = SimpleNamespace(base=10000000.0, rotary_dim=rot, max_position_embeddings=262144,
beta_fast=32, beta_slow=1, truncate=True)
inv = YaRNScalingRotaryEmbedding._compute_inv_freq(cfg, 2.0)
phase = torch.tensor(positions, dtype=torch.float32)[:, None] * inv[None, :]
magnitude = 1.0 + 0.1 * __import__('math').log(2.0)
cases.append(dict(rot=rot, theta=cfg.base, factor=2.0, original=262144,
magnitude=magnitude, inv_freq=inv.tolist(),
cos=(phase.cos()*magnitude).tolist(), sin=(phase.sin()*magnitude).tolist()))
print(json.dumps({'reference': f'vLLM YaRNScalingRotaryEmbedding; torch {device} FP32; static factor=2',
'positions': positions, 'cases': cases}, indent=2))
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+79
View File
@@ -22,6 +22,8 @@
#include "rad_abi.h"
#include "../libref/ref_common.h"
#include "rad_sample.h"
#include "../vendor/nlohmann/json.hpp"
#include <fstream>
#include <deque>
#include <string>
@@ -1779,6 +1781,83 @@ TEST(op_rope) {
CHECK_EQ(qkv.at(5), 9.0f);
}
TEST(yarn_rotary_matches_independent_vllm_vectors) {
const std::string here = __FILE__;
std::ifstream input(here.substr(0, here.find_last_of('/')) + "/data/yarn_reference.json");
REQUIRE(input.good());
const auto fixture = nlohmann::json::parse(input);
const auto positions = fixture["positions"].get<std::vector<int64_t>>();
for (const auto& c : fixture["cases"]) {
const int rot = c["rot"], half = rot / 2, hd = rot + 16;
const double low = rot == 64 ? 14 : (rot == 128 ? 28 : 56);
const double high = rot == 64 ? 22 : (rot == 128 ? 43 : 85);
T pos(RAD_I32, {(int64_t)positions.size()}); pos.n(positions);
T qkv(RAD_F32, {(int64_t)positions.size(), hd * 3});
std::vector<float> values(positions.size() * hd * 3, 9.0f);
for (size_t m = 0; m < positions.size(); ++m)
for (int h = 0; h < 2; ++h)
for (int i = 0; i < rot; ++i) values[m * hd * 3 + h * hd + i] = i < half ? 1.0f : 0.0f;
qkv.f(values);
A direct; direct.t(qkv).t(pos).i("M", positions.size()).i("head_dim", hd).i("n_head", 1).i("n_head_kv", 1)
.i("rotary_dim", rot).d("theta", 1e7).d("scale", 1).s("mode", "neox")
.d("yarn_factor", 2).d("yarn_low", low).d("yarn_high", high).d("yarn_magnitude", c["magnitude"]);
CHECK_OK(run("rope", direct));
/* The table is position-addressed. Allocate its real extent, not a compact stand-in. */
T table(RAD_F32, {524288, rot});
A ta; ta.t(pos).t(table).i("M", positions.size()).i("rot", rot).d("theta", 1e7).d("scale", 1).s("dtype", "f32")
.d("yarn_factor", 2).d("yarn_low", low).d("yarn_high", high).d("yarn_magnitude", c["magnitude"]);
CHECK_OK(run("rope_table", ta));
for (size_t m = 0; m < positions.size(); ++m) {
for (int i = 0; i < half; ++i) {
const float cosine = c["cos"][m][i], sine = c["sin"][m][i];
/* FP32 libm/pow versus torch; at long positions an inverse-frequency ULP
* is amplified into the phase. Bound the actual absolute cosine error. */
CHECK_NEAR(qkv.at(m * hd * 3 + i), cosine, 0.004);
CHECK_NEAR(qkv.at(m * hd * 3 + half + i), sine, 0.004);
CHECK_EQ(table.at(positions[m] * rot + i), qkv.at(m * hd * 3 + i));
CHECK_EQ(table.at(positions[m] * rot + half + i), qkv.at(m * hd * 3 + half + i));
CHECK_EQ(qkv.at(m * hd * 3 + hd + i), qkv.at(m * hd * 3 + i));
}
for (int i = rot; i < hd; ++i) CHECK_EQ(qkv.at(m * hd * 3 + i), 9.0f);
for (int i = 0; i < hd; ++i) CHECK_EQ(qkv.at(m * hd * 3 + 2 * hd + i), 9.0f);
}
}
}
TEST(yarn_multimodal_positions_and_invalid_parameters) {
const int rot = 64, hd = 80;
T positions(RAD_I32, {3, 1}); positions.n({262144, 500000, 524287});
T mixed(RAD_F32, {1, hd});
std::vector<float> seed(hd, 9.0f);
for (int i = 0; i < rot; ++i) seed[i] = i < rot/2 ? 1.0f : 0.0f;
mixed.f(seed);
auto params = [&](A& a, const char* mode) -> A& {
return a.i("M", 1).i("head_dim", hd).i("n_head", 1).i("n_head_kv", 0)
.i("rotary_dim", rot).d("theta", 1e7).d("scale", 1).s("mode", mode)
.s("sections", "11 11 10").d("yarn_factor", 2).d("yarn_low", 14)
.d("yarn_high", 22).d("yarn_magnitude", 1.069314718);
};
A ma; ma.t(mixed).t(positions); params(ma, "imrope");
CHECK_OK(run("rope", ma));
for (int component = 0; component < 3; ++component) {
T plain(RAD_F32, {1, hd}); plain.f(seed);
T pos(RAD_I32, {1}); pos.n({positions.iat(component)});
A a; a.t(plain).t(pos); params(a, "neox");
CHECK_OK(run("rope", a));
for (int i = 0; i < 32; ++i) {
const int selected = i % 3 == 1 && i < 33 ? 1 : (i % 3 == 2 && i < 30 ? 2 : 0);
if (selected != component) continue;
CHECK_EQ(mixed.at(i), plain.at(i)); CHECK_EQ(mixed.at(i+32), plain.at(i+32));
}
}
for (int i = rot; i < hd; ++i) CHECK_EQ(mixed.at(i), 9.0f);
T single(RAD_I32, {1}); single.n({1});
A invalid; invalid.t(mixed).t(single); params(invalid, "axial");
CHECK_EQ(run("rope", invalid), RAD_E_UNSUPPORTED);
for (auto& p : invalid.ps) if (!std::strcmp(p.key, "yarn_factor")) p = RAD_F64("yarn_factor", NAN);
CHECK_EQ(run("rope", invalid), RAD_E_INVAL);
}
/* THE EPILOGUE IS THE UNFUSED CHAIN: the biased product, then the activation of it, then the
* residual -- each rounded where a separate tensor would be. */
TEST(op_gemm_nt_bias_epilogue) {
+67
View File
@@ -0,0 +1,67 @@
#include "rad_test.h"
#include "../arch/common/rad_arch.h"
using rad::arch::Geom;
using rad::arch::yarn_from;
TEST(yarn_metadata_is_independent_of_deployment_context) {
const char* keys[] = {"rope_parameters.rope_type", "rope_parameters.factor",
"rope_parameters.original_max_position_embeddings", "draft.rope_parameters.rope_type",
"draft.rope_parameters.factor", "draft.rope_parameters.original_max_position_embeddings"};
const char* vals[] = {"yarn", "2", "262144", "yarn", "2", "262144"};
RadModelMeta m{}; m.n_kv = 6; m.kv_key = keys; m.kv_val = vals;
Geom target{}, draft{}; target.theta = draft.theta = 1e7f;
target.max_ctx = draft.max_ctx = 524288;
CHECK_OK(yarn_from(target, &m, "", 64));
CHECK_OK(yarn_from(draft, &m, "draft.", 128));
CHECK_EQ(target.yarn.low, 14.0f); CHECK_EQ(target.yarn.high, 22.0f);
CHECK_EQ(draft.yarn.low, 28.0f); CHECK_EQ(draft.yarn.high, 43.0f);
CHECK_NEAR(target.yarn.magnitude, 1.069314718, 1e-7);
target.max_ctx = 1048576;
CHECK_OK(yarn_from(target, &m, "", 64));
CHECK_EQ(target.yarn.low, 14.0f);
vals[4] = "4";
CHECK_OK(yarn_from(draft, &m, "draft.", 128));
CHECK_EQ(draft.yarn.factor, 4.0f); CHECK_EQ(target.yarn.factor, 2.0f);
}
TEST(yarn_metadata_rejects_bad_inputs_and_preserves_default) {
const char* keys[] = {"rope_parameters.rope_type", "rope_parameters.factor",
"rope_parameters.original_max_position_embeddings"};
const char* vals[] = {"yarn", "2", "262144"};
RadModelMeta m{}; m.n_kv = 3; m.kv_key = keys; m.kv_val = vals;
Geom g{}; g.theta = 1e7f;
for (const char* bad : {"0", "-1", "nan", "inf", "bogus", "2garbage"}) {
vals[1] = bad;
CHECK(yarn_from(g, &m, "", 64) != RAD_OK);
}
vals[1] = "2"; m.n_kv = 2;
CHECK(yarn_from(g, &m, "", 64) != RAD_OK);
vals[0] = "dynamic";
CHECK_EQ(yarn_from(g, &m, "", 64), RAD_E_UNSUPPORTED);
vals[0] = "default"; g.rope_scale = 1.0f;
CHECK_OK(yarn_from(g, &m, "", 64));
CHECK_EQ(g.yarn.factor, 0.0f); CHECK_EQ(g.rope_scale, 1.0f);
vals[0] = "linear";
CHECK_OK(yarn_from(g, &m, "", 64)); CHECK_EQ(g.rope_scale, 2.0f);
}
TEST(yarn_legacy_explicit_magnitude_and_fractional_bounds) {
const char* keys[] = {"rope_scaling.type", "rope_scaling.factor",
"rope_scaling.original_max_position_embeddings", "rope_scaling.attention_factor",
"rope_scaling.truncate", "rope_scaling.beta_fast", "rope_scaling.beta_slow"};
const char* vals[] = {"yarn", "2", "262144", "1.25", "0", "32", "1"};
RadModelMeta m{}; m.n_kv = 7; m.kv_key = keys; m.kv_val = vals;
Geom g{}; g.theta = 1e7f;
CHECK_OK(yarn_from(g, &m, "", 64));
CHECK_EQ(g.yarn.magnitude, 1.25f);
CHECK(g.yarn.low > 14.0f && g.yarn.low < 15.0f);
CHECK(g.yarn.high > 21.0f && g.yarn.high < 22.0f);
vals[4] = "2"; CHECK(yarn_from(g, &m, "", 64) != RAD_OK);
vals[4] = "0"; vals[2] = "262144.5";
CHECK(yarn_from(g, &m, "", 64) != RAD_OK);
vals[2] = "262144"; vals[5] = "0.5";
CHECK(yarn_from(g, &m, "", 64) != RAD_OK);
}
RAD_TEST_MAIN()