Archived
Add static YaRN to Qwen rotary paths with independent CPU and ROCm vectors
This commit is contained in:
1 parent
d23c3e0d17
commit
2af7fa4022
22 files changed
+7542
-27
No files matched your search
@@ -0,0 +1,46 @@
|
||||
#ifndef RAD_YARN_H
|
||||
#define RAD_YARN_H
|
||||
|
||||
/* Static YaRN coefficients. The architecture resolves the correction bounds using
|
||||
* the ORIGINAL training length, never the deployment/table length. Kernels share
|
||||
* the resolved coefficients so direct and table-backed RoPE cannot disagree. */
|
||||
#include "rad_plugin.h"
|
||||
#include <cmath>
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define RAD_YARN_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_YARN_HD
|
||||
#endif
|
||||
|
||||
struct RadYarn {
|
||||
float factor = 0.0f; /* zero: keep the legacy arithmetic exactly */
|
||||
float low = 0.0f;
|
||||
float high = 0.0f;
|
||||
float magnitude = 1.0f;
|
||||
|
||||
RAD_YARN_HD float frequency(float inv, int i) const {
|
||||
if (factor == 0.0f) return inv;
|
||||
const float width = high == low ? 0.001f : high - low;
|
||||
const float ramp = fminf(1.0f, fmaxf(0.0f, ((float)i - low) / width));
|
||||
/* Keep the blend order used by the reference YaRN implementation. */
|
||||
const float mask = 1.0f - ramp;
|
||||
return (inv / factor) * (1.0f - mask) + inv * mask;
|
||||
}
|
||||
};
|
||||
|
||||
inline RadYarn rad_yarn_args(const RadArgs* a) {
|
||||
return { (float)rad_args_getf_or(a, "yarn_factor", 0.0),
|
||||
(float)rad_args_getf_or(a, "yarn_low", 0.0),
|
||||
(float)rad_args_getf_or(a, "yarn_high", 0.0),
|
||||
(float)rad_args_getf_or(a, "yarn_magnitude", 1.0) };
|
||||
}
|
||||
|
||||
inline bool rad_yarn_valid(const RadYarn& y) {
|
||||
return std::isfinite(y.factor) && (y.factor == 0.0f ||
|
||||
(y.factor >= 1.0f && std::isfinite(y.low) && std::isfinite(y.high) &&
|
||||
y.high >= y.low && std::isfinite(y.magnitude) && y.magnitude > 0.0f));
|
||||
}
|
||||
|
||||
#undef RAD_YARN_HD
|
||||
#endif
|
||||
+84
-2
@@ -16,6 +16,7 @@
|
||||
#include "rad_builder.h"
|
||||
#include "rad_device.h"
|
||||
#include "rad_runtime.h"
|
||||
#include "rad_yarn.h"
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
@@ -626,6 +627,7 @@ struct Geom {
|
||||
float wadd_qk = 0.0f;
|
||||
float theta = 1e6f;
|
||||
float rope_scale = 1.0f;
|
||||
RadYarn yarn;
|
||||
/* M-RoPE: the checkpoint's `mrope_section`, when it has one. A model whose rotary has several
|
||||
* position components declares `rope` with `rope_mode` and these sections and hands it
|
||||
* RadBatch::rope_pos; empty, the rotary is one-component NeoX over `positions`. Stored here
|
||||
@@ -1025,17 +1027,97 @@ inline bool rope_mixed(const RadBatch* b) { return b->rope_pos && b->rope_mixed;
|
||||
|
||||
/* `rope` declared for the geometry's rotary: M-RoPE's mode and sections when the model has them,
|
||||
* `mode` otherwise. */
|
||||
/* Append only for explicit YaRN, preserving stock op identities and tune keys. */
|
||||
inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
|
||||
const RadParam* params, int n, const rad_weight* weights, int nw) {
|
||||
if (g.yarn.factor == 0.0f) return rad_decl_op(b, name, params, n, weights, nw);
|
||||
std::vector<RadParam> p(params, params + n);
|
||||
p.push_back(RAD_F64("yarn_factor", g.yarn.factor));
|
||||
p.push_back(RAD_F64("yarn_low", g.yarn.low));
|
||||
p.push_back(RAD_F64("yarn_high", g.yarn.high));
|
||||
p.push_back(RAD_F64("yarn_magnitude", g.yarn.magnitude));
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* Both modern HF rope_parameters and legacy rope_scaling. Nested text_config is
|
||||
* authoritative for a multimodal target; the draft has its own independent config. */
|
||||
inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int64_t rot) {
|
||||
g.yarn = {};
|
||||
const std::string root(prefix);
|
||||
const std::vector<std::string> homes = root.empty()
|
||||
? std::vector<std::string>{"text_config.rope_parameters.", "rope_parameters.",
|
||||
"text_config.rope_scaling.", "rope_scaling."}
|
||||
: std::vector<std::string>{root + "rope_parameters.", root + "rope_scaling."};
|
||||
std::string home;
|
||||
const char* type = nullptr;
|
||||
for (const auto& h : homes) {
|
||||
type = rad_meta_gets(meta, (h + "rope_type").c_str(),
|
||||
rad_meta_gets(meta, (h + "type").c_str(), nullptr));
|
||||
if (type) { home = h; break; }
|
||||
}
|
||||
if (!type || !std::strcmp(type, "default")) return RAD_OK;
|
||||
auto get = [&](const char* key, double fallback) {
|
||||
const char* text = rad_meta_gets(meta, (home + key).c_str(), nullptr);
|
||||
if (!text) return fallback;
|
||||
char* end = nullptr;
|
||||
const double value = std::strtod(text, &end);
|
||||
if (end == text) return (double)NAN;
|
||||
while (*end == ' ' || *end == '\t' || *end == '\n') ++end;
|
||||
return *end ? (double)NAN : value;
|
||||
};
|
||||
if (!std::strcmp(type, "linear")) {
|
||||
const double factor = get("factor", 0.0);
|
||||
if (!std::isfinite(factor) || factor <= 0.0) return RAD_E_INVAL;
|
||||
g.rope_scale = (float)factor;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (std::strcmp(type, "yarn")) {
|
||||
fprintf(stderr, "radiance: %s rotary type '%s' is unsupported\n", prefix, type);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const double factor = get("factor", 0.0), original = get("original_max_position_embeddings", 0.0);
|
||||
const double fast = get("beta_fast", 32.0), slow = get("beta_slow", 1.0);
|
||||
const double magnitude = get("attention_factor", factor > 1.0 ? 1.0 + 0.1 * std::log(factor) : 1.0);
|
||||
const double truncate = get("truncate", 1.0);
|
||||
if (!std::isfinite(factor) || factor < 1.0 || !std::isfinite(original) || original < 1.0 ||
|
||||
original != std::floor(original) || (truncate != 0.0 && truncate != 1.0) ||
|
||||
!std::isfinite(fast) || !std::isfinite(slow) || slow <= 0.0 || fast < slow ||
|
||||
!std::isfinite(magnitude) || magnitude <= 0.0 || !std::isfinite(g.theta) || g.theta <= 1.0f ||
|
||||
rot < 2 || (rot & 1)) {
|
||||
fprintf(stderr, "radiance: %s YaRN needs finite factor >= 1, original context > 0, "
|
||||
"beta_fast >= beta_slow > 0 and attention_factor > 0\n", prefix);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* mscale variants are a different contract; never silently ignore them. */
|
||||
for (const char* k : {"mscale", "mscale_all_dim"})
|
||||
if (rad_meta_gets(meta, (home + k).c_str(), nullptr)) {
|
||||
fprintf(stderr, "radiance: %s YaRN %s is unsupported; use attention_factor\n", prefix, k);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
auto correction = [&](double beta) {
|
||||
return rot * std::log(original / (beta * 2.0 * 3.14159265358979323846)) /
|
||||
(2.0 * std::log((double)g.theta));
|
||||
};
|
||||
double low = correction(fast), high = correction(slow);
|
||||
if (truncate != 0.0) { low = std::floor(low); high = std::ceil(high); }
|
||||
g.yarn = {(float)factor, (float)std::max(0.0, low),
|
||||
(float)std::min((double)rot - 1, high), (float)magnitude};
|
||||
if (!rad_yarn_valid(g.yarn)) return RAD_E_INVAL;
|
||||
g.rope_scale = 1.0f; /* YaRN blends frequencies; it does not divide positions. */
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline rad_op decl_rope(RadBuilder* b, const Geom& g, int64_t rows, int64_t head_dim,
|
||||
int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode) {
|
||||
if (g.rope_mc)
|
||||
return RAD_OP(b, "rope",
|
||||
return decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", g.rope_mode), RAD_INT("rotary_dim", rot),
|
||||
RAD_STR("sections", g.rope_sections)),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "rope",
|
||||
return decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
@@ -538,7 +538,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* V heads that follow alone, so a K-only tensor is described by n_head = n_head_kv and
|
||||
* n_head_kv = 0: all the heads there are rotate, none follow them. Weightless, so one op
|
||||
* serves every layer. */
|
||||
op_crope = rw(b, RAD_OP(b, "rope",
|
||||
op_crope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
@@ -712,14 +712,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(w_fcb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
}
|
||||
op_qrope = rw(b, RAD_OP(b, "rope",
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, RAD_OP(b, "rope",
|
||||
op_krope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
@@ -237,6 +237,8 @@ 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));
|
||||
|
||||
/* The linear-attention geometry. llama.cpp maps the GGUF ssm keys onto these:
|
||||
* ssm.state_size -> the key AND value head width, ssm.group_count -> key heads,
|
||||
* ssm.time_step_rank -> value heads, ssm.inner_size -> value heads * value width. */
|
||||
|
||||
@@ -340,6 +340,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
|
||||
rad_meta_getf(meta, "draft.rope_theta", 0.0));
|
||||
dg.rope_scale = 1.0f;
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
|
||||
/* PLAIN RMS NORM. The drafter uses the ordinary norm where the trunk uses GemmaRMSNorm, and
|
||||
* the checkpoint agrees rather than only vLLM -- rad_block_dflash2.h has the numbers. Two
|
||||
* conventions in one process, which is exactly why this is a second Geom and not a flag. */
|
||||
@@ -635,6 +636,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));
|
||||
GdnFP8::Config& gc = m.gcfg;
|
||||
const int64_t n_head_k_all = meta_int2(meta, "qwen35.ssm.group_count",
|
||||
"linear_num_key_heads", 0);
|
||||
@@ -952,7 +954,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* which is why `aw.cos_sin` is cleared rather than left pointing at a plane nothing fills. Its
|
||||
* band is the fused prologue's (qk_fuse_rows), so a step the prologue does not serve -- a
|
||||
* prefill chunk, where the fill's grid is one block a TOKEN -- issues no fill either. */
|
||||
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")),
|
||||
|
||||
+2
-2
@@ -371,8 +371,8 @@ that folds dequantisation into its epilogue still receives them.
|
||||
| `attn_paged` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` |
|
||||
| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
|
||||
| `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout |
|
||||
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt | `qkv`:inout, `positions` |
|
||||
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` | `positions` → `cos_sin` |
|
||||
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `qkv`:inout, `positions` |
|
||||
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `positions` → `cos_sin` |
|
||||
| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt | `qkv`:inout, `positions`, `q_w`w, `k_w`w |
|
||||
|
||||
`attn_paged` is the ranged op whose band is `q_len`, not `M`: one query row at decode, up to 64 at
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# Static YaRN for Qwen dense FP8 and DFlash2
|
||||
|
||||
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`,
|
||||
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.
|
||||
|
||||
## Metadata
|
||||
|
||||
| Key within the rotary object | Meaning |
|
||||
| --- | --- |
|
||||
| `rope_type` | `yarn`; default/absent preserves stock behavior; `linear` divides positions uniformly |
|
||||
| `factor` | finite number >= 1, required for YaRN |
|
||||
| `original_max_position_embeddings` | positive integer, required; the **training** length, not the enlarged deployment/table length |
|
||||
| `beta_fast`, `beta_slow` | defaults 32 and 1; finite, fast >= slow > 0 |
|
||||
| `attention_factor` | positive finite cos/sin multiplier; default 1 + 0.1 ln(factor) for factor > 1, otherwise 1 |
|
||||
| `truncate` | 1 (default): floor/ceil correction bounds; 0: retain fractional bounds |
|
||||
|
||||
`mscale` and `mscale_all_dim` variants are refused; specify `attention_factor`
|
||||
explicitly. Other explicit rotary types are refused in this architecture. Rotary
|
||||
width (including partial rotary), theta and M-RoPE section selection are unchanged.
|
||||
|
||||
## Convert a separate container
|
||||
|
||||
Use the original target and drafter checkpoints, the same quantization recipe,
|
||||
and a **new output path**. `--reuse` is valid only for the same source weights and
|
||||
recipe; it is not a way to mix weights from different model revisions.
|
||||
|
||||
```sh
|
||||
rad-convert /checkpoints/Qwen3.8-27B-FP8 \
|
||||
--draft-model /checkpoints/Qwen3.8-27B-DFlash2 \
|
||||
--recipe data/recipes/q38-27b-fp8-df2.recipe \
|
||||
--reuse /models/qwen3.8-27b-fp8.rad \
|
||||
--set text_config.rope_parameters.rope_type=yarn \
|
||||
--set text_config.rope_parameters.factor=2 \
|
||||
--set text_config.rope_parameters.original_max_position_embeddings=262144 \
|
||||
--set draft.rope_parameters.rope_type=yarn \
|
||||
--set draft.rope_parameters.factor=2 \
|
||||
--set draft.rope_parameters.original_max_position_embeddings=262144 \
|
||||
--max-ctx 524288 --kv-cache-dtype bf16 \
|
||||
-o /models/qwen3.8-27b-fp8-yarn2.rad
|
||||
```
|
||||
|
||||
Run with `--plan-only` first. `--max-ctx` is the converter's graph bound, not a
|
||||
replacement for the explicit YaRN metadata or the server's `--max-model-len`.
|
||||
The bundled `.rad` by itself is not a converter input; keep the source checkpoints.
|
||||
Check both target and draft settings with `rad-info --meta` after conversion.
|
||||
|
||||
Serve on enough memory for the requested window:
|
||||
|
||||
```sh
|
||||
radiance --model /models/qwen3.8-27b-fp8-yarn2.rad \
|
||||
--tp 4 --max-model-len 524288 --max-num-seqs 32 --kv-cache-dtype bf16
|
||||
```
|
||||
|
||||
That cache flag controls **both** target and drafter KV. Startup capacity and
|
||||
successful actual long requests must be checked; the command is not a promise
|
||||
of concurrency or accuracy. Keep the unmodified model and serving setup until
|
||||
long-context quality and speed meet the deployment's requirements.
|
||||
|
||||
## Kernel and test contract
|
||||
|
||||
`rope` and `rope_table` take optional resolved coefficients `yarn_factor`,
|
||||
`yarn_low`, `yarn_high`, `yarn_magnitude`. Absent factor is the original path.
|
||||
With YaRN, `scale` must be 1: inverse frequencies are blended rather than all
|
||||
positions being divided. Axial rotary with YaRN is refused. Rebuild the bundled
|
||||
plugins together because their shared op schemas must match.
|
||||
|
||||
The math follows the static YaRN formulation (Peng et al.) and is checked against
|
||||
independent vLLM `YaRNScalingRotaryEmbedding` FP32 vectors for each backend. The fixture generator
|
||||
is `tests/data/generate_yarn_reference.py`; it is not a runtime dependency.
|
||||
Vectors cover target rotary width 64, draft width 128, an additional width 256,
|
||||
and positions through 524287.
|
||||
The CPU fixture uses torch CPU; the HIP fixture uses torch ROCm on gfx1201
|
||||
(`generate_yarn_reference.py cuda`). CPU and ROCm `pow` differ by a few ULPs;
|
||||
at 524K positions their cos/sin values can differ by 0.033 even within torch.
|
||||
Compare each implementation against its backend's independent vectors.
|
||||
The numerical check allows 0.004 absolute cos/sin error; fused versus unfused HIP rotation is checked
|
||||
byte-for-byte separately. Existing stock rotary tests remain active.
|
||||
+16
-1
@@ -54,6 +54,7 @@
|
||||
*/
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
#include "rad_yarn.h"
|
||||
|
||||
using namespace avx;
|
||||
|
||||
@@ -836,6 +837,12 @@ AVX_KERNEL(rope) {
|
||||
}
|
||||
}
|
||||
const int pair_mode = mode == ROPE_GPTJ ? ROPE_GPTJ : ROPE_NEOX;
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn)) return RAD_E_INVAL;
|
||||
if (yarn.factor != 0.0f) {
|
||||
if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED;
|
||||
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
|
||||
}
|
||||
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * rot >= AVX_PAR_MIN)
|
||||
@@ -851,6 +858,8 @@ AVX_KERNEL(rope) {
|
||||
} else {
|
||||
angles(cs, invf, half, (float)ldi(pos, offlin(pos, m)) / div);
|
||||
}
|
||||
if (yarn.factor != 0.0f)
|
||||
for (int64_t i = 0; i < rot; ++i) cs[i] *= yarn.magnitude;
|
||||
/* Q heads then K heads. The V heads that follow are left alone, which is the whole reason
|
||||
* this op takes the fused qkv rather than two tensors. */
|
||||
for (int64_t h = 0; h < n_head + n_head_kv; ++h)
|
||||
@@ -953,7 +962,11 @@ AVX_KERNEL(rope_table) {
|
||||
if (M <= 0 || numel(cs) % rot) return RAD_E_SHAPE;
|
||||
const int64_t rows = numel(cs) / rot;
|
||||
const int64_t half = rot / 2;
|
||||
const float* invf = inv_freqs(half, rot, theta);
|
||||
float* invf = inv_freqs(half, rot, theta);
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL;
|
||||
if (yarn.factor != 0.0f)
|
||||
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * rot >= AVX_PAR_MIN)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
@@ -962,6 +975,8 @@ AVX_KERNEL(rope_table) {
|
||||
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
|
||||
float* buf = scratch_f32((size_t)rot);
|
||||
angles(buf, invf, half, p);
|
||||
if (yarn.factor != 0.0f)
|
||||
for (int64_t i = 0; i < rot; ++i) buf[i] *= yarn.magnitude;
|
||||
/* `cs` may be strided, and offlin has to be evaluated per element there -- which is what
|
||||
* libref does unconditionally. The dense case is one row store. */
|
||||
if (rad_tensor_is_contiguous(cs)) {
|
||||
|
||||
@@ -206,6 +206,17 @@ std::vector<Case> build_cases() {
|
||||
}
|
||||
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 10000.0), HF("scale", 1.0),
|
||||
HS("dtype", "f32") });
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
for (const char* mode : { "neox", "gptj", "imrope" })
|
||||
add("rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 2),
|
||||
HF("theta", 1e7), HF("scale", 1), HS("mode", mode),
|
||||
HI("rotary_dim", 64), HS("sections", "11 11 10"), HS("dtype", dt),
|
||||
HF("yarn_factor", 2), HF("yarn_low", 14), HF("yarn_high", 22),
|
||||
HF("yarn_magnitude", 1.069314718) });
|
||||
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 1e7), HF("scale", 1),
|
||||
HS("dtype", dt), HF("yarn_factor", 2), HF("yarn_low", 14),
|
||||
HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) });
|
||||
}
|
||||
/* The multi-component forms: Qwen3-VL's interleaved M-RoPE over a partial rotary, and a vision
|
||||
* tower's 2-D axial rotary over a whole 72-wide head. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
|
||||
@@ -218,11 +218,15 @@ static const RadOperandSpec oKvStore[] = { OPD("k"), OPD("v"), OPD("slot_mapping
|
||||
|
||||
static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"),
|
||||
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections") };
|
||||
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"),
|
||||
P_F64O("yarn_factor"), P_F64O("yarn_low"),
|
||||
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
|
||||
|
||||
static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"),
|
||||
P_F64("scale"), P_STR("dtype") };
|
||||
P_F64("scale"), P_STR("dtype"),
|
||||
P_F64O("yarn_factor"), P_F64O("yarn_low"),
|
||||
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") };
|
||||
|
||||
static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_common.h"
|
||||
#include "rad_yarn.h"
|
||||
#include "r4d_fp8_wmma.h"
|
||||
|
||||
#include <cstdlib>
|
||||
@@ -356,7 +357,7 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
|
||||
uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos,
|
||||
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, int gptj,
|
||||
float theta, float rscale, uint32_t row_pitch,
|
||||
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane) {
|
||||
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn) {
|
||||
const uint32_t m = blockIdx.x;
|
||||
const uint32_t half = rot / 2;
|
||||
const float div = rscale != 0.0f ? rscale : 1.0f;
|
||||
@@ -376,9 +377,11 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
|
||||
if (mode == 4)
|
||||
inv = 1.0f / powf(theta, (float)(2 * j) / (float)(2 * sec[c]));
|
||||
}
|
||||
inv = yarn.frequency(inv, (int)i);
|
||||
const float ang = p * inv;
|
||||
float c, s;
|
||||
sincosf(ang, &s, &c);
|
||||
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
|
||||
const uint32_t i0 = gptj ? 2 * i : i;
|
||||
const uint32_t i1 = gptj ? 2 * i + 1 : i + half;
|
||||
const float x0 = bf2f(hd[i0]), x1 = bf2f(hd[i1]);
|
||||
@@ -787,7 +790,7 @@ extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_r
|
||||
hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream,
|
||||
(uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim,
|
||||
(uint32_t)n_rope_heads, (uint32_t)rot, gptj, theta, rscale,
|
||||
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane);
|
||||
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, RadYarn{});
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
@@ -1384,6 +1387,18 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
|
||||
|
||||
const float theta = (float)r4d_getf(a, "theta", 10000.0);
|
||||
const float rscale = (float)r4d_getf(a, "scale", 1.0);
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn)) return R4D_NO(RAD_E_INVAL);
|
||||
if (yarn.factor != 0.0f) {
|
||||
if (mc == 4 || rscale != 1.0f) return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
const uint32_t heads = (uint32_t)(n_head + n_head_kv);
|
||||
const uint32_t gy = (heads * (uint32_t)(rot / 2) + kThreads - 1) / kThreads;
|
||||
hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)Mp, gy), dim3(kThreads), 0, (hipStream_t)s,
|
||||
(uint16_t*)r4d_addr(qkv), (const int32_t*)r4d_addr(pos),
|
||||
(uint32_t)head_dim, heads, (uint32_t)rot, gptj, theta, rscale,
|
||||
(uint32_t)pitch, mc, sec[0], sec[1], sec[2], n_sec, (uint32_t)plane, yarn);
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
/* The Q heads and the K heads rotate; the V heads that follow them do not, which is the whole
|
||||
* reason this op takes the fused projection rather than two tensors. */
|
||||
return r4d_rope_mc_bf16(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_common.h"
|
||||
#include "rad_yarn.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <cmath>
|
||||
@@ -205,7 +206,7 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
|
||||
// those here silently changes the model's output -- a different rope is a different model.
|
||||
__global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
|
||||
const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, float theta,
|
||||
float rscale, int cs_f32, int pos_i64) {
|
||||
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
|
||||
@@ -216,9 +217,10 @@ __global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
|
||||
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 = 1.0f / powf(theta, (float)(2 * i) / (float)rot);
|
||||
const float inv = yarn.frequency(1.0f / powf(theta, (float)(2 * i) / (float)rot), 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;
|
||||
@@ -386,8 +388,10 @@ static int rad_rope_table_body(const RadArgs* args, const R4dSink& sk) {
|
||||
|
||||
const float theta = (float)r4d_getf(args, "theta", 10000.0);
|
||||
const float rscale = (float)r4d_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 R4D_NO(RAD_E_INVAL);
|
||||
return R4D_EMIT(sk, r4d_qk_rope_table_kernel, dim3((int)M), dim3(64), 0,
|
||||
r4d_p(po), r4d_wp(cs), (long)(r4d_numel(cs) / rot), (int)rot, theta, rscale,
|
||||
cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0);
|
||||
cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn);
|
||||
}
|
||||
R4D_ENTRY(r4d_rad_rope_table, rad_rope_table_body)
|
||||
@@ -276,6 +276,10 @@ static const RadParamSpec pRopeTable[] = {
|
||||
P_F64("theta"),
|
||||
P_F64("scale"),
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
{ "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 oRopeTable[] = {
|
||||
{ "positions", RAD_OPD_IN, 0 },
|
||||
@@ -1574,6 +1578,10 @@ static const RadParamSpec pRope[] = {
|
||||
{ "mode", RAD_P_STR, RAD_REQUIRED },
|
||||
{ "rotary_dim", RAD_P_INT, 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 },
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------------- the vision tower */
|
||||
|
||||
+36
-3
@@ -45,6 +45,8 @@
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "../vendor/nlohmann/json.hpp"
|
||||
#include <fstream>
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_hc_fp8.h"
|
||||
#include "r4d_fp8_frag.h"
|
||||
@@ -1195,7 +1197,7 @@ static bool restores(const RadKernelInfo* r, const std::vector<RadParam>& lp, in
|
||||
* The q side reads a STRIDED view in the engine (the [q|gate] projection is interleaved per head)
|
||||
* and the unfused norm cannot, so the reference is fed a contiguous copy of the same numbers. The
|
||||
* arithmetic does not depend on the stride; the values are what is being compared. */
|
||||
static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt) {
|
||||
static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = false, int64_t rot = 64) {
|
||||
if (!sel("qk_norm_rope_gate") && !sel("rope_table_f32")) return;
|
||||
/* THE GAIN'S WIDTH IS RUN BOTH WAYS, because the two callers differ: every architecture plugin
|
||||
* here declares an f32 norm gain and vLLM's declares bf16, and one flag inside the kernel picks
|
||||
@@ -1213,7 +1215,12 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt) {
|
||||
* one k buffer does, and 4 query heads is not 12: the wave count the launcher picks is a
|
||||
* function of nq + nkv, so a head count the model does not have exercises a launch it does not
|
||||
* make. */
|
||||
const int64_t M = 512, nq = 12, nkv = 2, hd = 256, rot = 64, ctx = 4096;
|
||||
const int64_t M = 512, nq = 12, nkv = 2, hd = 256, ctx = yarn ? 524288 : 4096;
|
||||
auto add_yarn = [&](std::vector<RadParam>& ps) {
|
||||
if (!yarn) return;
|
||||
ps.push_back(PF("yarn_factor", 2)); ps.push_back(PF("yarn_low", rot == 64 ? 14 : 28));
|
||||
ps.push_back(PF("yarn_high", rot == 64 ? 22 : 43)); ps.push_back(PF("yarn_magnitude", 1.069314718));
|
||||
};
|
||||
const double theta = 1e7, eps = 1e-6, wadd = 1.0;
|
||||
/* MANY ROWS, because the difference this case is hunting is one bf16 in tens of thousands: two
|
||||
* summation orders for the same mean-square agree to a ULP in f32 and that ULP almost never
|
||||
@@ -1222,6 +1229,10 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt) {
|
||||
* near the top. */
|
||||
std::vector<int32_t> pos((size_t)M);
|
||||
for (int64_t i = 0; i < M; ++i) pos[(size_t)i] = (int32_t)((i * 7 + i * i) % ctx);
|
||||
if (yarn) {
|
||||
const int32_t edges[] = {0, 1, 4096, 262143, 262144, 500000, 524287};
|
||||
std::copy(std::begin(edges), std::end(edges), pos.begin());
|
||||
}
|
||||
|
||||
auto rnd = [](int64_t i) { /* deterministic, and spans the exponent */
|
||||
const uint32_t x = (uint32_t)(i * 2654435761u + 12345u);
|
||||
@@ -1311,6 +1322,7 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt) {
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("head_dim", hd), PI("n_head", nh),
|
||||
PI("n_head_kv", 0), PF("theta", theta), PF("scale", 1.0),
|
||||
PS("mode", "neox"), PI("rotary_dim", rot) };
|
||||
add_yarn(ps);
|
||||
run_case(rr, ts, ps);
|
||||
}
|
||||
|
||||
@@ -1319,7 +1331,26 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt) {
|
||||
std::vector<RadTensor> ts = { T(d_p, RAD_I32, { M }), T(d_cs, RAD_F32, { ctx, rot }) };
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("rot", rot), PF("theta", theta),
|
||||
PF("scale", 1.0), PS("dtype", "f32") };
|
||||
add_yarn(ps);
|
||||
run_case(rt, ts, ps);
|
||||
if (yarn) {
|
||||
const std::string here = __FILE__;
|
||||
std::ifstream input(here.substr(0, here.find_last_of('/')) + "/../tests/data/yarn_reference_rocm.json");
|
||||
if (!input) { ok("YaRN independent vectors", false, "fixture missing"); return; }
|
||||
const auto fixture = nlohmann::json::parse(input);
|
||||
const auto& c = fixture["cases"][rot == 64 ? 0 : 1];
|
||||
std::vector<float> row(rot);
|
||||
double worst = 0.0;
|
||||
for (size_t m = 0; m < fixture["positions"].size(); ++m) {
|
||||
st_memcpy(row.data(), (float*)d_cs + (size_t)pos[m] * rot, rot * sizeof(float), hipMemcpyDeviceToHost);
|
||||
for (int i = 0; i < rot / 2; ++i) {
|
||||
worst = std::max(worst, std::abs((double)row[i] - c["cos"][m][i].get<double>()));
|
||||
worst = std::max(worst, std::abs((double)row[rot/2+i] - c["sin"][m][i].get<double>()));
|
||||
}
|
||||
}
|
||||
ok("YaRN GPU table vs independent vLLM through 524287", worst <= 0.004,
|
||||
("worst absolute error " + std::to_string(worst)).c_str());
|
||||
}
|
||||
}
|
||||
{
|
||||
std::vector<RadTensor> ts = {
|
||||
@@ -1381,7 +1412,7 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt) {
|
||||
" vs " + std::to_string(h_bf16(want[i]));
|
||||
}
|
||||
}
|
||||
const std::string tag = std::string(gf32 ? "f32 gain, " : "bf16 gain, ") + what;
|
||||
const std::string tag = std::string(yarn ? "YaRN, " : "") + (gf32 ? "f32 gain, " : "bf16 gain, ") + what;
|
||||
char rate[128];
|
||||
std::snprintf(rate, sizeof rate, "%lld of %zu differ, worst %.2e of full scale",
|
||||
(long long)n_off, got.size(), worst);
|
||||
@@ -10945,6 +10976,8 @@ static void device_phase(const Plugin& pl) {
|
||||
}
|
||||
qk_prologue_case(pl, RAD_BF16);
|
||||
qk_prologue_case(pl, RAD_F32);
|
||||
qk_prologue_case(pl, RAD_F32, true);
|
||||
qk_prologue_case(pl, RAD_F32, true, 128);
|
||||
qk_kv_fold_case(pl, false);
|
||||
qk_kv_fold_case(pl, true);
|
||||
qsa_qprep_case(pl);
|
||||
|
||||
+15
-6
@@ -27,6 +27,7 @@
|
||||
* the two-sided reading libr4d's h128 kernel documents.
|
||||
*/
|
||||
#include "ref_common.h"
|
||||
#include "rad_yarn.h"
|
||||
/* `row_stride`: which axis carries a row of `cols` elements, at whatever rank the operand arrived
|
||||
* in. Every q/k/v/out below goes through it rather than through `rank >= 3 ? stride[rank-3] : cols`
|
||||
* -- the comment above kv_store shows where that shortcut is wrong. */
|
||||
@@ -412,11 +413,11 @@ static int rope_freqs(int mode, int64_t rot, float theta, const int64_t* sec, in
|
||||
}
|
||||
|
||||
static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot, int mode,
|
||||
const RopeFreq& f, const float* pos) {
|
||||
const RopeFreq& f, const float* pos, float magnitude = 1.0f) {
|
||||
const int64_t half = rot / 2;
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const float ang = pos[f.comp[i]] * f.inv[i];
|
||||
const float c = std::cos(ang), s = std::sin(ang);
|
||||
const float c = std::cos(ang) * magnitude, s = std::sin(ang) * magnitude;
|
||||
const int64_t i0 = (mode == ROPE_GPTJ) ? 2 * i : i;
|
||||
const int64_t i1 = (mode == ROPE_GPTJ) ? 2 * i + 1 : i + half;
|
||||
const float x0 = ldt(t, base + i0 * ds), x1 = ldt(t, base + i1 * ds);
|
||||
@@ -471,6 +472,12 @@ int ref_rope(const RadArgs* a, RadStream) {
|
||||
}
|
||||
RopeFreq f;
|
||||
RAD_REF_TRY(rope_freqs(mode, rot, theta, sec, multi ? n_sec : 0, &f));
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn)) return RAD_E_INVAL;
|
||||
if (yarn.factor != 0.0f) {
|
||||
if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED;
|
||||
for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
|
||||
}
|
||||
|
||||
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
|
||||
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
|
||||
@@ -493,7 +500,7 @@ int ref_rope(const RadArgs* a, RadStream) {
|
||||
/* Q heads then K heads. The V heads that follow are left alone, which is the whole reason
|
||||
* this op takes the fused qkv rather than two tensors. */
|
||||
for (int64_t h = 0; h < n_head + n_head_kv; ++h)
|
||||
rope_head(qkv, row + h * head_dim * ds, ds, rot, mode, f, p);
|
||||
rope_head(qkv, row + h * head_dim * ds, ds, rot, mode, f, p, yarn.magnitude);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -577,16 +584,18 @@ int ref_rope_table(const RadArgs* a, RadStream) {
|
||||
const int64_t rows = numel(cs) / rot;
|
||||
const int64_t half = rot / 2;
|
||||
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
const int64_t pp = ld_int(pos->dtype, pos->data, offlin(pos, m));
|
||||
if (pp < 0 || pp >= rows) continue;
|
||||
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const float inv = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot);
|
||||
const float inv = yarn.frequency(1.0f / std::pow(theta, (float)(2 * i) / (float)rot), (int)i);
|
||||
const float ang = p * inv;
|
||||
stt(cs, offlin(cs, pp * rot + i), std::cos(ang));
|
||||
stt(cs, offlin(cs, pp * rot + half + i), std::sin(ang));
|
||||
stt(cs, offlin(cs, pp * rot + i), std::cos(ang) * yarn.magnitude);
|
||||
stt(cs, offlin(cs, pp * rot + half + i), std::sin(ang) * yarn.magnitude);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
|
||||
@@ -278,14 +278,18 @@ static const RadOperandSpec oKvStore[] = { OPD("k"), OPD("v"), OPD("slot_mapping
|
||||
|
||||
static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"),
|
||||
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections") };
|
||||
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"),
|
||||
P_F64O("yarn_factor"), P_F64O("yarn_low"),
|
||||
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
|
||||
|
||||
/* The cos/sin plane a fused prologue reads instead of theta: written at each position's OWN row
|
||||
* of a [max_ctx, rot] table. `rot`, `theta` and `scale` are `rope`'s, spelled the same way,
|
||||
* because the two have to compute the same angles. */
|
||||
static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"),
|
||||
P_F64("scale"), P_STR("dtype") };
|
||||
P_F64("scale"), P_STR("dtype"),
|
||||
P_F64O("yarn_factor"), P_F64O("yarn_low"),
|
||||
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") };
|
||||
|
||||
static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
@@ -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) {
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user