Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac79f4dc8a | ||
|
|
6fa7707dff | ||
|
|
ee5fcf1024 | ||
|
|
432b50d7dd | ||
|
|
32cdaa5cc7 | ||
|
|
d579bd7d45 | ||
|
|
1e27172c14 | ||
|
|
76727fa050 | ||
|
|
82da8eab69 | ||
|
|
73691a1189 | ||
|
|
92eb44619b | ||
|
|
e31be583a9 | ||
|
|
33778b2b8c | ||
|
|
6fd7421f79 | ||
|
|
59d36ae928 | ||
|
|
2af7fa4022 | ||
|
|
d23c3e0d17 | ||
|
|
e95d397288 | ||
|
|
7001841e45 |
No files matched your search
+1
-1
@@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21)
|
||||
# VERSION is what /version reports and what a client checks compatibility against. It is NOT the
|
||||
# ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because
|
||||
# a plugin contract and a server release do not move together.
|
||||
project(radiance VERSION 1.1.0 LANGUAGES C CXX)
|
||||
project(radiance VERSION 1.2.2 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
@@ -2,13 +2,17 @@ radiance
|
||||
Copyright 2026 Deadcode and the radiance contributors
|
||||
|
||||
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14
|
||||
(the MXFP4 GEMM and the GDN kernels' overflow guards), goodman-b (four-rank tensor parallelism
|
||||
(the MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake
|
||||
(the MXFP4 decode and prefill GEMMs and the MXFP4 linear, stop strings after the reasoning block,
|
||||
and the draft refill on a prefix hit), goodman-b (four-rank tensor parallelism
|
||||
for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the fused four-rank
|
||||
writes, the n-gram table in RAM, the four-class expert split, the Grafana dashboard, the routed
|
||||
GEMM's decode loads and run search, the gated residual's prefill read form and row groups, and
|
||||
the fused router launch), mechkbfan (the token embedding in the pinned host pool), Code000 (the
|
||||
n-gram gather on the card and the MTP head's history-pass skip) and baKon (three-rank tensor
|
||||
parallelism, serving any world size from the shipped container, and the request log).
|
||||
GEMM's decode loads and run search, the gated residual's prefill read form and row groups, the
|
||||
fused router launch, the adaptive draft window, the MoE prefill forms and the sorted operand's
|
||||
decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000 (the n-gram
|
||||
gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor parallelism,
|
||||
serving any world size from the shipped container, the request log, an uneven world's per-rank
|
||||
KV and weights split, and --rope-scaling) and hazyumps (static YaRN for the Qwen rotary paths).
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
|
||||
@@ -17,6 +17,7 @@ If you wish to support the developement of the radiance engine you can do so [he
|
||||
|---|---|---|---|
|
||||
| Qwen3.8-Flash-Next: 4-bit experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-fp8-iq4r-moe.rad` (114 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe) | `flashnext.yaml` |
|
||||
| Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` |
|
||||
| Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` |
|
||||
| Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` |
|
||||
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
|
||||
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
|
||||
|
||||
@@ -39,6 +39,10 @@ typedef struct RadModelMeta {
|
||||
|
||||
float rms_eps;
|
||||
float rope_theta;
|
||||
/* Always 1. A rotary's scaling is a TYPE with parameters -- linear, YaRN, llama3, longrope --
|
||||
* and it is carried in the free-form keys below (rope_parameters.* / rope_scaling.*, with
|
||||
* text_config.* and draft.* forms), which arch/common/rad_arch.h's yarn_from reads and refuses
|
||||
* by name. A bare factor here would read every scheme as a linear position divide. */
|
||||
float rope_scale;
|
||||
|
||||
/* Free-form key/value from the container header, for anything the struct above does not
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#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) {
|
||||
const float factor = (float)rad_args_getf_or(a, "yarn_factor", 0.0);
|
||||
/* Disabled YaRN ignores every auxiliary coefficient on every backend. */
|
||||
if (factor == 0.0f) return {};
|
||||
return { factor,
|
||||
(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
|
||||
+126
-3
@@ -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
|
||||
@@ -789,7 +791,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.wire_min_bytes = c->tp_wire_min_bytes;
|
||||
g.eps = m->rms_eps;
|
||||
g.theta = m->rope_theta;
|
||||
g.rope_scale= m->rope_scale ? m->rope_scale : 1.0f;
|
||||
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
|
||||
g.dtype = dtype;
|
||||
g.act_dtype = act_dtype;
|
||||
{
|
||||
@@ -1023,19 +1025,140 @@ inline RadOperand rope_posmc(const Geom& g, const RadBatch* b, int64_t T) {
|
||||
* cannot rotate. */
|
||||
inline bool rope_mixed(const RadBatch* b) { return b->rope_pos && b->rope_mixed; }
|
||||
|
||||
/* A rotary op declared with the geometry's YaRN coefficients appended. A model without YaRN declares
|
||||
* exactly the parameters it was given, so its op identities and tune keys are unchanged. */
|
||||
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);
|
||||
}
|
||||
|
||||
/* THE ONE READER OF A MODEL'S ROTARY SCALING. Every architecture calls it after geom_from, for the
|
||||
* target ("") and for a drafter with a config of its own ("draft."), and it sets `g.rope_scale` and
|
||||
* `g.yarn` from the free-form keys and from nothing else. RadModelMeta::rope_scale is not read: a
|
||||
* factor without its type would be a linear position divide for a scheme that is not one.
|
||||
*
|
||||
* The object read is the first of `text_config.rope_parameters.`, `rope_parameters.`,
|
||||
* `text_config.rope_scaling.`, `rope_scaling.` (a drafter: `draft.rope_parameters.`,
|
||||
* `draft.rope_scaling.`) that names a type in `rope_type` or `type`; a multimodal target's
|
||||
* text_config is authoritative. core/format/rope_override.h writes --rope-scaling into the same
|
||||
* object, found in the same order.
|
||||
*
|
||||
* default, mrope no scaling (`mrope` is the legacy Qwen2-VL spelling of default + sections)
|
||||
* linear positions divided by `factor`
|
||||
* yarn static YaRN: frequencies blended over the correction range that `factor`,
|
||||
* `original_max_position_embeddings`, `beta_fast`/`beta_slow` and `truncate`
|
||||
* give, cos/sin scaled by `attention_factor` (default 1 + 0.1 ln factor). The
|
||||
* factor is the config's, read as vLLM and transformers read it.
|
||||
*
|
||||
* Anything else -- llama3, longrope, dynamic -- is refused by name, as is YaRN's `mscale` form. A
|
||||
* refusal leaves the geometry as it was. */
|
||||
inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int64_t rot) {
|
||||
const std::string root(prefix);
|
||||
const char* who = root.empty() ? "target" : "draft";
|
||||
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, type_key;
|
||||
const char* type = nullptr;
|
||||
for (const auto& h : homes) {
|
||||
for (const char* t : {"rope_type", "type"})
|
||||
if ((type = rad_meta_gets(meta, (h + t).c_str(), nullptr))) { type_key = h + t; break; }
|
||||
if (type) { home = h; break; }
|
||||
}
|
||||
if (!type || !std::strcmp(type, "default") || !std::strcmp(type, "mrope")) {
|
||||
g.yarn = {};
|
||||
g.rope_scale = 1.0f;
|
||||
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);
|
||||
const float scale = (float)factor;
|
||||
if (!std::isfinite(factor) || factor <= 0.0 || !std::isfinite(scale) || scale <= 0.0f) {
|
||||
fprintf(stderr, "radiance: %s linear rotary scaling (%s) needs a finite factor > 0\n",
|
||||
who, home.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g.yarn = {};
|
||||
g.rope_scale = scale;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (std::strcmp(type, "yarn")) {
|
||||
fprintf(stderr, "radiance: %s rotary type '%s' (%s) is not implemented; default, linear "
|
||||
"and yarn are\n", who, type, type_key.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* `truncate` is a JSON boolean, which the converter writes as 1 or 0; true and false spelled
|
||||
* out are the same answer. */
|
||||
double truncate = 1.0;
|
||||
if (const char* t = rad_meta_gets(meta, (home + "truncate").c_str(), nullptr))
|
||||
truncate = !std::strcmp(t, "true") ? 1.0 : !std::strcmp(t, "false") ? 0.0 : get("truncate", 1.0);
|
||||
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);
|
||||
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 (%s) needs a finite factor >= 1, an integral "
|
||||
"original_max_position_embeddings > 0, beta_fast >= beta_slow > 0, "
|
||||
"attention_factor > 0 and truncate true or false\n", who, home.c_str());
|
||||
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%s is not implemented; attention_factor is\n",
|
||||
who, home.c_str(), 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); }
|
||||
const RadYarn y = {(float)factor, (float)std::max(0.0, low),
|
||||
(float)std::min((double)rot - 1, high), (float)magnitude};
|
||||
if (!rad_yarn_valid(y)) {
|
||||
fprintf(stderr, "radiance: %s YaRN (%s) resolves to an empty correction range\n", who,
|
||||
home.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g.yarn = y;
|
||||
g.rope_scale = 1.0f; /* YaRN blends frequencies; it does not divide positions. */
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* `rope` declared for the geometry's rotary: M-RoPE's mode and sections when the model has them,
|
||||
* `mode` otherwise. */
|
||||
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),
|
||||
|
||||
@@ -121,7 +121,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
|
||||
0, { q_dim, kv_dim, kv_dim }));
|
||||
|
||||
op_rope = rw(b, RAD_OP(b, "rope",
|
||||
op_rope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.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),
|
||||
|
||||
@@ -508,7 +508,7 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* THE POSITION IS THE COMMITTED TOKEN'S OWN, which is what makes the split passes equal the
|
||||
* reference's one concatenated rope: it hands `k` the full position range and `q` only the
|
||||
* last `q_len` of it, so a context row at absolute position p is rotated by p either way. */
|
||||
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),
|
||||
@@ -667,14 +667,14 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
{w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
}
|
||||
|
||||
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),
|
||||
|
||||
@@ -122,10 +122,11 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
|
||||
/* The fold, over the same weights and into the same activation the pair writes. Not
|
||||
* RAD_ARCH_TRY: a plugin without the row is the ordinary case and the pair still runs. It
|
||||
* multiplies fp8 codes by a block-fp8 gate_up, so a plain gate_up has no fold. */
|
||||
* multiplies fp8 codes by a block-fp8 gate_up, so a plain gate_up has no fold -- and neither
|
||||
* has an MXFP4 one: libr4d's gated fold is an fp8a8 tile, and the pair serves it. */
|
||||
{
|
||||
const int64_t hi = g.max_tok < 64 ? g.max_tok : 64;
|
||||
if (hi > 0 && !gate_up.bf16) {
|
||||
if (hi > 0 && !gate_up.bf16 && !gate_up.mx) {
|
||||
op_gated = rw(b, RAD_OP(b, "gemm_nt_q_gated",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", gate_up.N),
|
||||
RAD_INT("K", gate_up.K),
|
||||
|
||||
@@ -506,6 +506,31 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
/* WHETHER A CHECKPOINT SHIPS ONE LAYER'S EXPERTS STACKED OR ONE BY ONE, as the Src it fills.
|
||||
* Recent releases stack them -- `<prefix>.gate_up_proj` and `<prefix>.down_proj` -- and a
|
||||
* quantised export (AutoRound's) writes each expert on its own, `<prefix>.<e>.{gate,up,down}_proj`.
|
||||
* Each form is asked of the checkpoint through a probe name mapped to its first expert, which the
|
||||
* checkpoint answers or does not. Stacked is the answer when neither is found: a container is
|
||||
* read by declared name, the same under both maps, so it asks nothing here. `tag` keeps one
|
||||
* caller's probe name apart from another's for the same layer. */
|
||||
inline int moe_expert_sources(RadBuilder* b, Names& nm, const char* tag, const char* prefix,
|
||||
MoeFP8::Src* src) {
|
||||
const char* gu = nm.ckpt("%s.gate_up_proj", prefix);
|
||||
const char* probe = nm.f("probe.%s.%s.0", tag, prefix);
|
||||
RadEncoding e{};
|
||||
RAD_ARCH_TRY(map_concat(b, probe, { nm.ckpt("%s.0.gate_proj.weight", prefix),
|
||||
nm.ckpt("%s.0.up_proj.weight", prefix) }));
|
||||
if (weight_enc(b, probe, &e)) {
|
||||
src->experts = nm.ckpt("%s", prefix);
|
||||
src->experts_gate_up = src->experts_down = nullptr;
|
||||
} else {
|
||||
src->experts = nullptr;
|
||||
src->experts_gate_up = gu;
|
||||
src->experts_down = nm.ckpt("%s.down_proj", prefix);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The gate_up and down name maps of one expert: a dim-0 slice of the stacked tensors, or the
|
||||
* checkpoint's per-expert gate and up joined along rows. `gate_up` false maps down alone. */
|
||||
inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
|
||||
|
||||
@@ -681,6 +681,15 @@ struct LinearFP8 {
|
||||
* GEMM. Read off the weight's encoding like `bf16`. */
|
||||
bool i8 = false;
|
||||
rad_op op_q = 0;
|
||||
/* AN OCP-MXFP4 WEIGHT, read by `gemm_nt_q` at dtype mxfp4a8 against the SAME E4M3 pair every
|
||||
* other linear here reads (`a.q`, `a.s` at an f32 scale per (row, 128)): e2m1 codes and one
|
||||
* E8M0 exponent per 32 of K, as libquant writes `codes=fp4_e2m1 group=32 scale=e8m0`. libr4d
|
||||
* folds each block's exponent into the e4m3 operand against a per-row reference, so the scale
|
||||
* plane is handed over TWICE: as `b_scale` and as `b_ref`, whose layout hook reduces the same
|
||||
* plane to that reference -- `wref` is the second view. The activation grid is the fp8 family's, so every producer's fused quantiser
|
||||
* feeds an MXFP4 linear unchanged. Read off the weight's encoding like `bf16` and `i8`. */
|
||||
bool mx = false;
|
||||
rad_weight wref = 0;
|
||||
/* What probe() read: the weight is int8. Lets a model learn its trunk's format from one linear
|
||||
* before it declares the activation buffers that format decides (ActFP8::declare_qs's `i8`). */
|
||||
bool probed_i8 = false;
|
||||
@@ -778,6 +787,16 @@ inline bool linear_is_w8(const RadEncoding& e) {
|
||||
sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
/* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes one a value and an E8M0 exponent
|
||||
* per [1 x 32], no transform -- what libr4d's MXFP4 layout hook accepts. */
|
||||
enum { RAD_MX_GROUP = 32 };
|
||||
inline bool linear_is_mxfp4(const RadEncoding& e) {
|
||||
if (!rad_enc_is(&e, "affine") || e.n_planes != 2 || e.transform[0]) return false;
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
return e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[1] == 1 && sc &&
|
||||
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
|
||||
}
|
||||
|
||||
inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* base,
|
||||
std::initializer_list<const char*> src) {
|
||||
if (src.size() == 0) return RAD_E_INVAL;
|
||||
@@ -918,6 +937,67 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
/* ---- AN OCP-MXFP4 WEIGHT over the E4M3 pair. Three views of one stored weight: the codes,
|
||||
* the exponent plane as `b_scale`, and the same plane again as `b_ref`. Every view takes the
|
||||
* weight's row parts as they are -- the exponent grid is one row tall -- and a column slice in
|
||||
* whole 128s, which is the ACTIVATION's scale block and so the stricter of the two. */
|
||||
mx = known && linear_is_mxfp4(enc);
|
||||
if (mx) {
|
||||
if (!a.q || !a.s) {
|
||||
fprintf(stderr, "radiance: '%s' is an MXFP4 weight read against its input's E4M3 "
|
||||
"pair, and its input has none\n", wn);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows in "
|
||||
"16s and K in whole %d-column activation scale blocks.\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
int64_t parts[RAD_MAX_ROW_PARTS] = {0};
|
||||
int np = 0;
|
||||
for (int64_t p : row_parts) {
|
||||
if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL;
|
||||
if (p % 16) {
|
||||
fprintf(stderr, "radiance: '%s' stacks a %lld-row part, which is not a whole "
|
||||
"number of 16-row MXFP4 tiles; it cannot be row-sharded.\n",
|
||||
base, (long long)p);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
parts[np++] = p;
|
||||
}
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
const char* rn = nm.f("%s.ref", base);
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, RAD_ACCESS_PER_TOKEN,
|
||||
shard, grp, parts, np);
|
||||
ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
if (!w || !ws || !wref) return RAD_E_INVAL;
|
||||
if (span_hi > 0) {
|
||||
const bool col = shard == RAD_SHARD_COL;
|
||||
if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
|
||||
"%d-column activation scale block.\n", base, (long long)span_lo,
|
||||
(long long)span_hi, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t lo = col ? span_lo / RAD_MX_GROUP : span_lo;
|
||||
const int64_t hi = col ? span_hi / RAD_MX_GROUP : span_hi;
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, lo, hi));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi));
|
||||
}
|
||||
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
|
||||
op = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
|
||||
RAD_WEIGHTS(w, ws, wref)),
|
||||
{ a.q, a.s }, { y });
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The one geometric precondition, checked here so it is reported once per weight with the
|
||||
* weight named rather than as a kernel miss with a band in it. These are PER-RANK extents, so
|
||||
* this is also the check that a tensor-parallel width does not cut a scale block in half. */
|
||||
@@ -1016,6 +1096,12 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (mx) {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
|
||||
brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref));
|
||||
return;
|
||||
}
|
||||
if (op_m1 && rows <= mv_rows)
|
||||
RAD_ISSUE_N(c, op_m1, rows, brow_slice(a.x, r0, rows, K), RAD_NONE,
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -185,7 +185,6 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
|
||||
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;
|
||||
/* PLAIN RMS NORM: the reference norms with Qwen3RMSNorm and the config says `model_type:
|
||||
* qwen3`. It happens to agree with this MiniCPM5 target, and it is asked of the DRAFTER's
|
||||
* config anyway -- two conventions in one process is exactly why this is a second Geom. */
|
||||
@@ -201,6 +200,7 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
(long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
|
||||
int s;
|
||||
if ((s = divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head)) < 0) return s;
|
||||
if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s;
|
||||
@@ -431,6 +431,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"%lld\n", (long long)m.n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* ---- the KV cache. One group: every layer is full attention. */
|
||||
RadKVGroupDecl fd{};
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -339,7 +339,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
|
||||
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 +635,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 +953,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")),
|
||||
|
||||
@@ -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
|
||||
@@ -520,8 +521,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
? (int64_t)g.rank * (mc.n_expert / g.world) : 0;
|
||||
{
|
||||
MoeFP8::Src ps{};
|
||||
ps.experts_gate_up = nm.ckpt("model.language_model.layers.0.mlp.experts.gate_up_proj");
|
||||
ps.experts_down = nm.ckpt("model.language_model.layers.0.mlp.experts.down_proj");
|
||||
RAD_ARCH_TRY(moe_expert_sources(b, nm, "format",
|
||||
"model.language_model.layers.0.mlp.experts", &ps));
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, 0, ps, &mc));
|
||||
}
|
||||
/* A CHECKPOINT SERVED AS IT SHIPS IS bf16 THROUGHOUT. Plain experts mean a container
|
||||
@@ -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")),
|
||||
@@ -1205,8 +1206,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
MoeFP8::Src ms{};
|
||||
ms.cfg = m.moecfg;
|
||||
ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l);
|
||||
ms.experts_gate_up = nm.ckpt("%s.%lld.mlp.experts.gate_up_proj", pre, (long long)l);
|
||||
ms.experts_down = nm.ckpt("%s.%lld.mlp.experts.down_proj", pre, (long long)l);
|
||||
RAD_ARCH_TRY(moe_expert_sources(b, nm, "layer",
|
||||
nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l), &ms));
|
||||
if (m.moecfg.n_ff_shared > 0) {
|
||||
ms.shared = nm.ckpt("%s.%lld.mlp.shared_expert", pre, (long long)l);
|
||||
ms.shared_gate = nm.ckpt("%s.%lld.mlp.shared_expert_gate.weight", pre, (long long)l);
|
||||
@@ -1367,8 +1368,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
ts.mlp.cfg = m.moecfg;
|
||||
ts.mlp.router = nm.ckpt("%s.layers.0.mlp.gate.weight", mpre);
|
||||
ts.mlp.experts_gate_up = nm.ckpt("%s.layers.0.mlp.experts.gate_up_proj", mpre);
|
||||
ts.mlp.experts_down = nm.ckpt("%s.layers.0.mlp.experts.down_proj", mpre);
|
||||
RAD_ARCH_TRY(moe_expert_sources(b, nm, "mtp", nm.ckpt("%s.layers.0.mlp.experts", mpre),
|
||||
&ts.mlp));
|
||||
if (m.moecfg.n_ff_shared > 0) {
|
||||
ts.mlp.shared = nm.ckpt("%s.layers.0.mlp.shared_expert", mpre);
|
||||
ts.mlp.shared_gate = nm.ckpt("%s.layers.0.mlp.shared_expert_gate.weight", mpre);
|
||||
|
||||
@@ -97,6 +97,22 @@ function(rad_add_plugin name kind)
|
||||
"because the language a project compiles in is the project's own decision.")
|
||||
endif()
|
||||
set_source_files_properties(${P_HIP_SOURCES} PROPERTIES LANGUAGE HIP)
|
||||
# EVERY DEVICE SOURCE NAMES ITS OWN COMPILATION UNIT ID, from the plugin's name and the
|
||||
# source's path inside the plugin's directory. Left to clang, the ID is a hash of the absolute
|
||||
# input path, the output path and the command line, so one source built in two directories --
|
||||
# the tree and an out-of-tree build of the same plugin -- gets two IDs. The ID becomes a symbol
|
||||
# (__hip_cuid_<hash of it>) whose name is not of fixed length, and a longer one shifts the code
|
||||
# object's read-only data and with it every PC-relative address .text forms into it: the same
|
||||
# instructions, different bytes. Named from what identifies the unit and nothing about where it
|
||||
# was built, the ID is the same wherever the plugin is built and still differs between any two
|
||||
# sources, which is the property clang needs of it.
|
||||
foreach(src ${P_HIP_SOURCES})
|
||||
get_filename_component(_rad_abs "${src}" ABSOLUTE)
|
||||
file(RELATIVE_PATH _rad_rel "${CMAKE_CURRENT_SOURCE_DIR}" "${_rad_abs}")
|
||||
string(SHA256 _rad_cuid "${name}/${_rad_rel}")
|
||||
string(SUBSTRING "${_rad_cuid}" 0 16 _rad_cuid)
|
||||
set_property(SOURCE "${src}" APPEND PROPERTY COMPILE_OPTIONS "-cuid=${_rad_cuid}")
|
||||
endforeach()
|
||||
list(APPEND srcs ${P_HIP_SOURCES})
|
||||
endif()
|
||||
add_library(${name} MODULE ${srcs})
|
||||
|
||||
+30
-1
@@ -129,7 +129,7 @@ static std::vector<std::string> home_subdirs(const std::string& home, const char
|
||||
|
||||
int rad_tools_load_plugins(const std::string& home, const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id, const std::string& quant,
|
||||
LoadedPlugins* out) {
|
||||
LoadedPlugins* out, bool imported) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = LoadedPlugins{};
|
||||
|
||||
@@ -188,6 +188,35 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
|
||||
}
|
||||
}
|
||||
|
||||
/* AN IMPORTED QUANTISATION is served by the family's quantised plugin (startup.h). */
|
||||
if (imported && !arch_id.empty() && out->arch_plugin.empty()) {
|
||||
std::vector<const Plugin*> fam, quantised;
|
||||
for (const Plugin& p : r.plugins())
|
||||
if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id) {
|
||||
fam.push_back(&p);
|
||||
if (!p.arch_quant.empty()) quantised.push_back(&p);
|
||||
}
|
||||
const Plugin* pick = quantised.size() == 1 ? quantised[0]
|
||||
: quantised.empty() && fam.size() == 1 ? fam[0] : nullptr;
|
||||
if (!pick && quantised.size() > 1) {
|
||||
std::string names;
|
||||
for (const Plugin* p : quantised) names += (names.empty() ? "" : ", ") + p->arch_quant;
|
||||
RAD_ERR("'%s' is quantised by %s and imported weight by weight, and '%s' has more than "
|
||||
"one quantised plugin (%s) to serve it; none is chosen for it",
|
||||
arch_id.c_str(), quant.c_str(), arch_id.c_str(), names.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
if (pick) {
|
||||
out->arch_plugin = pick->name;
|
||||
out->arch_version = pick->version;
|
||||
out->arch_id = pick->arch_id;
|
||||
out->arch_quant = pick->arch_quant;
|
||||
RAD_INFO("quantisation '%s' is imported weight by weight; '%s' serves it as %s",
|
||||
quant.c_str(), pick->name.c_str(),
|
||||
pick->arch_quant.empty() ? "(unquantised)" : pick->arch_quant.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
if (out->kernels.empty()) {
|
||||
RAD_ERR("no kernel plugin loaded from %s/kernels. Every weight's layout comes from the "
|
||||
"kernel that will read it, so there is nothing to lay a container out for.",
|
||||
|
||||
@@ -66,11 +66,19 @@ std::string rad_home_file(const std::string& home, const std::string& rel);
|
||||
* has one plugin per weight format and they all answer the same architecture id. `quant` is the
|
||||
* container's own descriptor -- RadModelMeta::quant, RadFileHeader::quant -- and "" is the
|
||||
* unquantised case, which matches a plugin that says "" and nothing else. */
|
||||
/*
|
||||
* `imported` is a checkpoint whose quantisation is imported weight by weight
|
||||
* (Checkpoint::imports): its descriptor names the tool that made it and no plugin claims it, so
|
||||
* the plugin is the architecture's QUANTISED one -- the one plugin of the family claiming a
|
||||
* descriptor, or the family's only plugin when that claims none. Two quantised plugins are a
|
||||
* choice this cannot make, and are refused by name. `out->arch_quant` is the descriptor chosen,
|
||||
* which is what a container converted from it records. */
|
||||
int rad_tools_load_plugins(const std::string& radiance_home,
|
||||
const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id,
|
||||
const std::string& quant,
|
||||
LoadedPlugins* out);
|
||||
LoadedPlugins* out,
|
||||
bool imported = false);
|
||||
|
||||
/* `also` declares into the SAME builder after the architecture plugin has. That is what puts the
|
||||
* sampler chain in the same Program: its ops resolve through the same hierarchy at the same
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
* (spec §6).
|
||||
*/
|
||||
#include "rad_core.h"
|
||||
#include "format/rope_override.h"
|
||||
#include "sample/host_ref.h"
|
||||
#include "server/oai.h"
|
||||
|
||||
@@ -28,6 +29,15 @@ struct Flag {
|
||||
const char* help;
|
||||
};
|
||||
|
||||
/* Built from kDraftWindowDefault, so the default is stated in one place. Defined before the table
|
||||
* that points at it: the two are initialised in this order. */
|
||||
static const std::string g_draft_window_help =
|
||||
std::string("fixed | adaptive: how many drafts each sequence carries. fixed drafts\n"
|
||||
" --num-speculative-tokens every step; adaptive makes that\n"
|
||||
" the ceiling and follows each sequence's acceptance and the\n"
|
||||
" measured step cost (a serial draft head only). Default ") +
|
||||
draft_window_name(kDraftWindowDefault);
|
||||
|
||||
static const Flag g_flags[] = {
|
||||
{ "--model", "PATH", "the .rad container, or a checkpoint served as it stands" },
|
||||
{ "--radiance-home", "DIRS", "where kernels/, architectures/ and quantizers/ live; several\n"
|
||||
@@ -39,9 +49,14 @@ static const Flag g_flags[] = {
|
||||
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 4,\n"
|
||||
"none at 8" },
|
||||
{ "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" },
|
||||
{ "--p2p", "MODE", "how the collectives reach the other cards: auto (default)\n"
|
||||
"asks the driver, on requires peer access and stops without\n"
|
||||
"it, off exchanges through pinned host memory" },
|
||||
{ "--max-num-batched-tokens", "N", "the largest token count one step may carry" },
|
||||
{ "--max-num-seqs", "N", "the largest number of sequences one step may carry" },
|
||||
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
|
||||
{ "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
|
||||
"keys, no reconvert (docs/YARN.md); none: off" },
|
||||
|
||||
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
|
||||
{ "--vram-weights-mib", "N", "the resident weight slab; 0 derives it from the card" },
|
||||
@@ -95,6 +110,7 @@ static const Flag g_flags[] = {
|
||||
{ "--num-speculative-tokens", "N", "speculative window; 0 disables. Default `auto`: the drafter's\n"
|
||||
" own operating point, which the plugin states. A container\n"
|
||||
" with no draft head is unaffected -- auto resolves to 0." },
|
||||
{ "--draft-window", "MODE", g_draft_window_help.c_str() },
|
||||
{ "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" },
|
||||
|
||||
{ "--host", "ADDR", "listen address" },
|
||||
@@ -120,6 +136,10 @@ static const Flag g_flags[] = {
|
||||
" set is the template's: Qwen3.8 takes xhigh|medium|low and defaults\n"
|
||||
" to xhigh, which on a short task can spend the whole token budget\n"
|
||||
" inside <think> and answer nothing. \"none\" turns thinking off" },
|
||||
{ "--reasoning-effort-map", "MAP", "FROM=TO[,FROM=TO...]: a `reasoning_effort` a request sends, replaced before\n"
|
||||
" the chat template sees it -- high=xhigh lets a client that always sends\n"
|
||||
" OpenAI's top level reach Qwen3.8's. TO is checked against the template at\n"
|
||||
" startup; none and minimal turn thinking off. Repeatable" },
|
||||
{ "--thinking-token-budget", "N", "default `thinking_token_budget` for chat requests that do not set one: at\n"
|
||||
" N reasoning tokens the reasoning block is closed and the answer follows,\n"
|
||||
" so a client's max_tokens is not spent on reasoning alone. Unset is no\n"
|
||||
@@ -362,10 +382,29 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (!std::strcmp(v, "wht6")) c->tp_wire_exact = 0;
|
||||
else { RAD_ERR("--tp-wire takes exact or wht6, not '%s'", v); return RAD_E_INVAL; }
|
||||
}
|
||||
else if (S("--p2p")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "auto")) c->p2p = RAD_P2P_AUTO;
|
||||
else if (!std::strcmp(v, "on")) c->p2p = RAD_P2P_ON;
|
||||
else if (!std::strcmp(v, "off")) c->p2p = RAD_P2P_OFF;
|
||||
else { RAD_ERR("--p2p takes auto, on or off, not '%s'", v); return RAD_E_INVAL; }
|
||||
}
|
||||
else if (S("--tp-wire-min-kb")) { if (!(v = need(i))) return RAD_E_INVAL; c->tp_wire_min_kb = atoll(v); }
|
||||
else if (S("--max-num-batched-tokens")){ if (!(v = need(i))) return RAD_E_INVAL; c->max_tok = atoll(v); }
|
||||
else if (S("--max-num-seqs")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_seqs = atoll(v); }
|
||||
else if (S("--max-model-len")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_ctx = atoll(v); }
|
||||
else if (S("--rope-scaling")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
/* Checked here, so a typo is a refusal at the command line and not a model served
|
||||
* with its trained rotary at a length it cannot reach. */
|
||||
RopeSpec rs;
|
||||
if (!rope_spec_parse(v, &rs) || rs.kind == RopeSpec::Keep) {
|
||||
RAD_ERR("--rope-scaling takes yarn:FACTOR (above 1) with an optional :ORIG trained "
|
||||
"length, or none -- got '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->rope_scaling = v;
|
||||
}
|
||||
else if (S("--vram-weights-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_weights_mib = atoll(v); }
|
||||
else if (S("--vram-kv-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_kv_mib = atoll(v); }
|
||||
/* --gpu-headroom takes the short name too: it is the flag an operator reaches for and
|
||||
@@ -429,6 +468,15 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-window")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "fixed")) c->draft_window = DraftWindow::Fixed;
|
||||
else if (!std::strcmp(v, "adaptive")) c->draft_window = DraftWindow::Adaptive;
|
||||
else {
|
||||
RAD_ERR("--draft-window takes fixed or adaptive, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-model")) {
|
||||
/* REFUSED, NOT QUIETLY IGNORED. Accepting this flag and then serving the container's
|
||||
* own drafter -- or none -- would hand the caller a server that is not the one they
|
||||
@@ -470,6 +518,24 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
else if (S("--reasoning-effort")) { if (!(v = need(i))) return RAD_E_INVAL;
|
||||
c->reasoning_effort = v; }
|
||||
else if (S("--reasoning-effort-map")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
const std::string all = v;
|
||||
size_t at = 0;
|
||||
while (at <= all.size()) {
|
||||
const size_t end = std::min(all.find(',', at), all.size());
|
||||
const std::string pair = all.substr(at, end - at);
|
||||
const size_t eq = pair.find('=');
|
||||
if (eq == std::string::npos || eq == 0 || eq + 1 == pair.size() ||
|
||||
pair.find('=', eq + 1) != std::string::npos) {
|
||||
RAD_ERR("--reasoning-effort-map takes FROM=TO pairs separated by commas, "
|
||||
"not '%s'", pair.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->reasoning_effort_map[pair.substr(0, eq)] = pair.substr(eq + 1);
|
||||
at = end + 1;
|
||||
}
|
||||
}
|
||||
else if (S("--thinking-token-budget")) { if (!(v = need(i)) ||
|
||||
!parse_int(a.c_str(), v, 0, INT32_MAX,
|
||||
&c->thinking_token_budget))
|
||||
|
||||
+86
-11
@@ -1023,10 +1023,15 @@ void loc_keep(const void* host_base, size_t bytes, intptr_t shift, uint64_t owne
|
||||
h.gen = gen;
|
||||
}
|
||||
|
||||
/* The host ranges this backend pinned itself (see "pinned host memory, in pieces"): base ->
|
||||
* length, ordered so an inner address finds its range. */
|
||||
/* The host ranges this backend pinned itself (see "pinned host memory, in pieces"), by base,
|
||||
* ordered so an inner address finds its range. `pool` is the host-pool allocation the range sits
|
||||
* in when it was not locked in pieces, and null when it was. */
|
||||
struct Pinned {
|
||||
int64_t len = 0;
|
||||
void* pool = nullptr;
|
||||
};
|
||||
std::mutex g_pinned_mu;
|
||||
std::map<uintptr_t, int64_t> g_pinned;
|
||||
std::map<uintptr_t, Pinned> g_pinned;
|
||||
|
||||
bool pinned_range(const void* p, uintptr_t* lo, int64_t* len) {
|
||||
const uintptr_t a = (uintptr_t)p;
|
||||
@@ -1034,9 +1039,9 @@ bool pinned_range(const void* p, uintptr_t* lo, int64_t* len) {
|
||||
auto it = g_pinned.upper_bound(a);
|
||||
if (it == g_pinned.begin()) return false;
|
||||
--it;
|
||||
if (a - it->first >= (uintptr_t)it->second) return false;
|
||||
if (a - it->first >= (uintptr_t)it->second.len) return false;
|
||||
if (lo) *lo = it->first;
|
||||
if (len) *len = it->second;
|
||||
if (len) *len = it->second.len;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -2040,6 +2045,20 @@ int a_vmem_decommit(void* addr, int64_t bytes) {
|
||||
* of one reservation are consecutive on the card too. Each piece is checked rather than assumed,
|
||||
* because the pools, the mover and the activation arena all hand a kernel base + offset.
|
||||
*
|
||||
* THAT TAKES THE KERNEL DRIVER'S SVM API, AND WITHOUT IT THE RANGE IS ONE ALLOCATION OF THE HOST
|
||||
* POOL. A lock lands at its host address because ROCr's thunk registers the range through the
|
||||
* KFD's SVM API, which maps a range where it is. A driver that does not offer it -- amdgpu could
|
||||
* not register the card's memory with HMM, seen in a KVM guest with both cards passed through --
|
||||
* gets a userptr buffer object instead, at an address the thunk's own aperture hands out: below
|
||||
* the host address, and each piece a guard page away from the one before, so the pieces are
|
||||
* neither where the host has them nor next to each other on the card. hsa_amd_vmem cannot join
|
||||
* them (ROCm 7.2 refuses a vmem handle on the host pool). The host pool's own allocation can: the
|
||||
* thunk maps it for the CPU at the address the aperture gave the cards. It is one buffer object,
|
||||
* as hipHostMalloc made before the pieces, so a host whose IOMMU refuses a large pin AND whose
|
||||
* driver has no SVM API has no large pinned range at all; the refusal names both. Which path a
|
||||
* process takes is the runtime's HSA_AMD_SYSTEM_INFO_SVM_SUPPORTED, the same capability the thunk
|
||||
* decides by, and the log says it once.
|
||||
*
|
||||
* What hipHostMalloc does besides the pin is kept, so the pages are the same pages: shared
|
||||
* anonymous memory, huge pages advised from 2 MiB up, a preferred NUMA node that is the one
|
||||
* nearest the current card (ROCr allocates from that node's pool), fine-grained coherence (the
|
||||
@@ -2093,7 +2112,56 @@ const char* hsa_why(hsa_status_t st) {
|
||||
return hsa_status_string(st, &m) == HSA_STATUS_SUCCESS && m ? m : "unknown HSA status";
|
||||
}
|
||||
|
||||
/* Whether every card's driver offers the SVM API, so that a locked piece is mapped in place. */
|
||||
bool svm_in_place() {
|
||||
static const bool on = [] {
|
||||
bool svm = false;
|
||||
if (hsa_system_get_info((hsa_system_info_t)HSA_AMD_SYSTEM_INFO_SVM_SUPPORTED, &svm) !=
|
||||
HSA_STATUS_SUCCESS)
|
||||
svm = false;
|
||||
if (!svm)
|
||||
RAD_INFO("device: the kernel driver offers no SVM API, so a pinned host range is one "
|
||||
"allocation of the host pool rather than locked in pieces of %s",
|
||||
humanb(kPinPiece).c_str());
|
||||
return svm;
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
/* The range as one allocation of the host pool, for a driver without the SVM API. The pool
|
||||
* aligns only a buffer's end to 2 MiB, so one alignment more is asked for and the base rounded
|
||||
* up inside it. */
|
||||
void* pin_whole(int64_t bytes, const std::vector<hsa_agent_t>& cards) {
|
||||
const int64_t align = RAD_ALIGN_POOL;
|
||||
const int64_t len = align_up(bytes, 4096);
|
||||
const int64_t ask = align_up(len, align) + align;
|
||||
void* q = nullptr;
|
||||
hsa_status_t st = hsa_amd_memory_pool_allocate(G().host_fine, (size_t)ask, 0, &q);
|
||||
if (st != HSA_STATUS_SUCCESS) {
|
||||
device_set_error("rad_dev_alloc(%s): the kernel driver offers no SVM API, so a pinned "
|
||||
"range has to be one allocation of the host pool (locked pieces would "
|
||||
"land apart on the cards), and the pool refused %s: %s",
|
||||
humanb(bytes).c_str(), humanb(ask).c_str(), hsa_why(st));
|
||||
return nullptr;
|
||||
}
|
||||
st = hsa_amd_agents_allow_access((uint32_t)cards.size(), cards.data(), nullptr, q);
|
||||
if (st != HSA_STATUS_SUCCESS) {
|
||||
device_set_error("rad_dev_alloc(%s): giving the cards access to the host-pool range: %s",
|
||||
humanb(bytes).c_str(), hsa_why(st));
|
||||
(void)hsa_amd_memory_pool_free(q);
|
||||
return nullptr;
|
||||
}
|
||||
char* const p = (char*)(((uintptr_t)q + (uintptr_t)align - 1) & ~((uintptr_t)align - 1));
|
||||
std::lock_guard<std::mutex> lk(g_pinned_mu);
|
||||
g_pinned.emplace((uintptr_t)p, Pinned{len, q});
|
||||
return p;
|
||||
}
|
||||
|
||||
void* pin_pieces(int64_t bytes) {
|
||||
std::vector<hsa_agent_t> cards;
|
||||
for (const Dev& d : G().dev) cards.push_back(d.agent);
|
||||
if (!svm_in_place()) return pin_whole(bytes, cards);
|
||||
|
||||
const int64_t align = RAD_ALIGN_POOL;
|
||||
const int64_t len = align_up(bytes, 4096);
|
||||
/* One alignment over, trimmed at both ends, so the range starts on a 2 MiB boundary: a pool's
|
||||
@@ -2113,8 +2181,6 @@ void* pin_pieces(int64_t bytes) {
|
||||
prefer_numa_node(p, len, current_card_numa_node());
|
||||
if (len >= ((int64_t)2 << 20)) ::madvise(p, (size_t)len, MADV_HUGEPAGE);
|
||||
|
||||
std::vector<hsa_agent_t> cards;
|
||||
for (const Dev& d : G().dev) cards.push_back(d.agent);
|
||||
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
|
||||
int done = 0;
|
||||
for (; done < pieces; ++done) {
|
||||
@@ -2133,7 +2199,9 @@ void* pin_pieces(int64_t bytes) {
|
||||
if (on_card != p + off) {
|
||||
++done;
|
||||
device_set_error("rad_dev_alloc(%s): piece %d of %d is mapped on the cards at %p, not "
|
||||
"at its host address %p, so the pieces are not one range there",
|
||||
"at its host address %p, so the pieces are not one range there, "
|
||||
"although the kernel driver reports the SVM API that maps a lock in "
|
||||
"place",
|
||||
humanb(bytes).c_str(), done, pieces, on_card, (void*)(p + off));
|
||||
break;
|
||||
}
|
||||
@@ -2144,12 +2212,12 @@ void* pin_pieces(int64_t bytes) {
|
||||
return nullptr;
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(g_pinned_mu);
|
||||
g_pinned.emplace((uintptr_t)p, len);
|
||||
g_pinned.emplace((uintptr_t)p, Pinned{len, nullptr});
|
||||
return p;
|
||||
}
|
||||
|
||||
void unpin_pieces(void* p) {
|
||||
int64_t len = 0;
|
||||
Pinned r;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_pinned_mu);
|
||||
auto it = g_pinned.find((uintptr_t)p);
|
||||
@@ -2158,9 +2226,16 @@ void unpin_pieces(void* p) {
|
||||
"leaked rather than unpinned", p);
|
||||
return;
|
||||
}
|
||||
len = it->second;
|
||||
r = it->second;
|
||||
g_pinned.erase(it);
|
||||
}
|
||||
if (r.pool) {
|
||||
const hsa_status_t st = hsa_amd_memory_pool_free(r.pool);
|
||||
if (st != HSA_STATUS_SUCCESS)
|
||||
RAD_WARN("device: freeing pinned host-pool range %p: %s", r.pool, hsa_why(st));
|
||||
return;
|
||||
}
|
||||
const int64_t len = r.len;
|
||||
for (int64_t off = 0; off < len; off += kPinPiece) {
|
||||
const hsa_status_t st = hsa_amd_memory_unlock((char*)p + off);
|
||||
if (st != HSA_STATUS_SUCCESS)
|
||||
|
||||
+28
-4
@@ -665,16 +665,17 @@ int Engine::step_loop() {
|
||||
for (const StepEntry& e : plan.e) {
|
||||
if (e.ckpt_restore < 0) continue;
|
||||
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
|
||||
for (auto& rk : ranks_) {
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& rk = ranks_[ri];
|
||||
/* This rank's device, for its own stream and its own state slots. */
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
|
||||
const int s = rk->kv.checkpoint_restore(ckpt_slots_.data(),
|
||||
(int)ckpt_slots_.size(),
|
||||
e.ckpt_restore, rk->ctx.stream());
|
||||
if (s < 0) {
|
||||
RAD_ERR("could not restore sequence %llu from checkpoint slot %d: %s",
|
||||
(unsigned long long)e.seq, (int)e.ckpt_restore,
|
||||
rad_strerror(s));
|
||||
RAD_ERR("could not restore sequence %llu from checkpoint slot %d on "
|
||||
"rank %d: %s", (unsigned long long)e.seq,
|
||||
(int)e.ckpt_restore, (int)ri, rad_strerror(s));
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
|
||||
return s;
|
||||
}
|
||||
@@ -2149,6 +2150,7 @@ int Engine::run_server() {
|
||||
o.max_n = cfg_.max_n > 0 ? (int)cfg_.max_n : (int)std::max<int64_t>(o.max_n, cfg_.max_seqs);
|
||||
o.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
o.default_reasoning_effort = cfg_.reasoning_effort;
|
||||
o.reasoning_effort_map = cfg_.reasoning_effort_map;
|
||||
o.default_thinking_budget = cfg_.thinking_token_budget;
|
||||
o.default_sampling = resolve_sampling_defaults(meta_, file_ != nullptr, cfg_);
|
||||
o.default_dry_breakers_set = cfg_.sample_dry_seq_breakers.has_value();
|
||||
@@ -2275,6 +2277,28 @@ int Engine::run_server() {
|
||||
"that sends no reasoning effort of its own will be answered 400: %s",
|
||||
cfg_.reasoning_effort.c_str(), eff_why.c_str());
|
||||
}
|
||||
/* THE EFFORTS THE TEMPLATE TAKES, said once: a client sending another gets this set back in
|
||||
* its 400 and can read it off /server_info beforehand. A map whose target the template
|
||||
* refuses would refuse every request it maps, so it stops startup. */
|
||||
if (d.chat) {
|
||||
const std::vector<std::string> efforts = srv.probe_reasoning_efforts();
|
||||
std::string mapped;
|
||||
for (const auto& [from, to] : cfg_.reasoning_effort_map)
|
||||
mapped += fmt("%s%s -> %s", mapped.empty() ? "" : ", ", from.c_str(), to.c_str());
|
||||
if (!efforts.empty()) {
|
||||
std::string list;
|
||||
for (const std::string& e : efforts) list += (list.empty() ? "" : ", ") + e;
|
||||
RAD_INFO("chat: the template takes reasoning_effort %s, and none or minimal turn "
|
||||
"thinking off%s%s", list.c_str(), mapped.empty() ? "" : "; mapped: ",
|
||||
mapped.c_str());
|
||||
} else if (!mapped.empty()) {
|
||||
RAD_INFO("chat: reasoning_effort mapped: %s", mapped.c_str());
|
||||
}
|
||||
if (const std::string why = srv.check_reasoning_effort_map(); !why.empty()) {
|
||||
RAD_ERR("--reasoning-effort-map %s", why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
/* A BUDGET THE MODEL CANNOT HOLD STOPS STARTUP, as --chat-template-kwargs does: the default
|
||||
* would apply to no request at all, and the operator who set it would not find out. */
|
||||
if (const std::string why = srv.check_thinking_budget(); !why.empty()) {
|
||||
|
||||
@@ -93,6 +93,15 @@ private:
|
||||
std::vector<std::thread> rank_threads_;
|
||||
|
||||
Config cfg_;
|
||||
/* THE SPLIT EACH RANK ACTUALLY TAKES. Equal to cfg_ on every rank whose cache costs as much per
|
||||
* token as the dearest rank's -- every rank of a world whose ranks all cost the same; a rank
|
||||
* whose cache costs less (an attention-zero rank) gets a KV pool sized for the common token
|
||||
* count and the difference in its weights pool. Engine::plan fills it, and every reader of the
|
||||
* resolved pool sizes -- Pools::configure and the planner -- takes its rank's entry, never
|
||||
* cfg_: a grown pool the planner never reads is an empty pool, and plan() refuses a rank whose
|
||||
* plan and weights pool disagree. */
|
||||
std::vector<Config> rank_cfg_;
|
||||
int64_t kv_planned_tokens_ = 0; /* the common token count plan() sized the re-split pools for */
|
||||
|
||||
/* The model's source, one of the two. A container stays mapped for the life of the engine:
|
||||
* the mapped and file tiers read it where it lies (spec §4.2). A checkpoint served directly
|
||||
@@ -117,6 +126,9 @@ private:
|
||||
int load_plugins();
|
||||
int read_metadata();
|
||||
int read_checkpoint_metadata();
|
||||
/* --rope-scaling over the free-form keys, then the startup line and the context checks;
|
||||
* runs on meta_kv_k_/meta_kv_v_ before their pointer arrays are built. */
|
||||
int apply_rope_scaling();
|
||||
int declare();
|
||||
int plan();
|
||||
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
|
||||
|
||||
+291
-53
@@ -14,6 +14,7 @@
|
||||
#include "device/device.h"
|
||||
#include "device/directio.h"
|
||||
#include "format/radfile.h"
|
||||
#include "format/rope_override.h"
|
||||
#include "format/share.h"
|
||||
#include "format/table_copy.h"
|
||||
#include "rad_plugin.h"
|
||||
@@ -231,15 +232,22 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
|
||||
}
|
||||
}
|
||||
}
|
||||
/* A refusal with room under both is not a capacity one, and advice to shrink the pool
|
||||
* would send the reader after the wrong cause: the device's reason above is the answer. */
|
||||
const int64_t want = (int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024 + pinned + mapped;
|
||||
const bool fits = cap > 0 && avail >= 0 && want <= cap && want <= avail;
|
||||
RAD_ERR("host: --host-pool-mib %lld is pinned once per rank, so %d rank(s) pin %s; this "
|
||||
"process had taken %s of pinned host memory before rank %d's pool. The amdgpu "
|
||||
"driver caps pinned memory system-wide at %s (ttm.pages_limit, half of RAM unless "
|
||||
"raised), and %s of RAM is available. Lower --host-pool-mib, or raise the cap",
|
||||
"raised), and %s of RAM is available. %s",
|
||||
(long long)cfg.host_pool_mib, cfg.tp,
|
||||
humanb((int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024).c_str(),
|
||||
humanb(pinned + mapped).c_str(), rank,
|
||||
cap > 0 ? humanb(cap).c_str() : "an unreadable limit",
|
||||
avail >= 0 ? humanb(avail).c_str() : "an unknown amount");
|
||||
avail >= 0 ? humanb(avail).c_str() : "an unknown amount",
|
||||
fits ? "The pools fit under both, so the refusal is not one of size; the reason "
|
||||
"the device gave is above"
|
||||
: "Lower --host-pool-mib, or raise the cap");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -676,7 +684,9 @@ int Engine::read_metadata() {
|
||||
meta_.n_expert_shared = geti("n_expert_shared", 0);
|
||||
meta_.rms_eps = getf("rms_eps", 1e-6);
|
||||
meta_.rope_theta = getf("rope_theta", 10000.0);
|
||||
meta_.rope_scale = getf("rope_scale", 1.0);
|
||||
/* 1 (abi/rad_builder.h): the rotary's scaling is read with its type from the free-form keys.
|
||||
* An older container's `rope_scale` key holds the factor alone and is not read. */
|
||||
meta_.rope_scale = 1.0f;
|
||||
|
||||
/* A container that says nothing about its own shape is refused HERE, by name, rather than at
|
||||
* declare as an "invalid argument" from a plugin that was handed zeros. */
|
||||
@@ -700,6 +710,7 @@ int Engine::read_metadata() {
|
||||
default: meta_kv_v_.push_back(file_->str(kv.v.s)); break;
|
||||
}
|
||||
}
|
||||
RAD_TRY(apply_rope_scaling());
|
||||
meta_kv_kp_.clear(); meta_kv_vp_.clear();
|
||||
for (auto& s : meta_kv_k_) meta_kv_kp_.push_back(s.c_str());
|
||||
for (auto& s : meta_kv_v_) meta_kv_vp_.push_back(s.c_str());
|
||||
@@ -734,6 +745,7 @@ int Engine::read_checkpoint_metadata() {
|
||||
}
|
||||
meta_kv_k_ = mo.keys;
|
||||
meta_kv_v_ = mo.vals;
|
||||
RAD_TRY(apply_rope_scaling());
|
||||
meta_kv_kp_.clear(); meta_kv_vp_.clear();
|
||||
for (auto& k : meta_kv_k_) meta_kv_kp_.push_back(k.c_str());
|
||||
for (auto& v : meta_kv_v_) meta_kv_vp_.push_back(v.c_str());
|
||||
@@ -747,10 +759,61 @@ int Engine::read_checkpoint_metadata() {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* --rope-scaling (format/rope_override.h): YaRN written into the container's own rotary keys at
|
||||
* load, where the architecture's reader takes them, so an existing container serves past its
|
||||
* trained context with no reconvert -- and is checked by the same reader a converted one is. The
|
||||
* drafter, when there is one, gets the same factor over its own trained length. Then one line says
|
||||
* what the rotary is, and a context past what it covers is named. */
|
||||
int Engine::apply_rope_scaling() {
|
||||
RopeSpec spec;
|
||||
if (!rope_spec_parse(cfg_.rope_scaling.c_str(), &spec)) {
|
||||
RAD_ERR("--rope-scaling '%s': yarn:FACTOR (above 1) with an optional :ORIG, or none",
|
||||
cfg_.rope_scaling.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (spec.kind != RopeSpec::Keep) {
|
||||
std::string why;
|
||||
if (!rope_override_group(meta_kv_k_, meta_kv_v_, spec, "", meta_.n_ctx_train, &why)) {
|
||||
RAD_ERR("--rope-scaling %s: %s", cfg_.rope_scaling.c_str(), why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RopeKeys kv{ meta_kv_k_, meta_kv_v_ };
|
||||
if (kv.any_prefix("draft.")) {
|
||||
int64_t dtrain = meta_.n_ctx_train;
|
||||
if (const std::string* t = kv.get("draft.max_position_embeddings"))
|
||||
dtrain = std::atoll(t->c_str());
|
||||
if (!rope_override_group(meta_kv_k_, meta_kv_v_, spec, "draft.", dtrain, &why)) {
|
||||
RAD_ERR("--rope-scaling %s: %s", cfg_.rope_scaling.c_str(), why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const RopeResolved r = rope_resolve(meta_kv_k_, meta_kv_v_, "");
|
||||
const long long want = cfg_.max_ctx > 0 ? (long long)cfg_.max_ctx : (long long)meta_.n_ctx_train;
|
||||
if (r.type == "yarn" && r.factor > 1.0) {
|
||||
const long long reach = (long long)(r.orig * r.factor);
|
||||
RAD_INFO("rope: YaRN factor %g over %lld trained positions -- the rotary reaches %lld; "
|
||||
"--max-model-len %lld%s", r.factor, (long long)r.orig, reach, want,
|
||||
spec.kind == RopeSpec::Yarn ? " (--rope-scaling)" : " (the container's own)");
|
||||
if (want > reach)
|
||||
RAD_WARN("--max-model-len %lld is past the %lld positions YaRN factor %g covers; "
|
||||
"positions beyond them are extrapolated", want, reach, r.factor);
|
||||
} else if (meta_.n_ctx_train > 0 && want > meta_.n_ctx_train &&
|
||||
!(r.type == "linear" && r.factor > 1.0)) {
|
||||
RAD_WARN("--max-model-len %lld is past the %lld positions the model was trained on and "
|
||||
"nothing scales its rotary, so positions beyond them are extrapolated; a model "
|
||||
"card's YaRN extension is --rope-scaling yarn:FACTOR (docs/YARN.md)", want,
|
||||
(long long)meta_.n_ctx_train);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== 3 + 4. plugins, declare */
|
||||
int Engine::load_plugins() {
|
||||
int s = rad_tools_load_plugins(cfg_.radiance_home, cfg_.kernel_hierarchy,
|
||||
meta_.arch_id, meta_.quant ? meta_.quant : "", &plugins_);
|
||||
meta_.arch_id, meta_.quant ? meta_.quant : "", &plugins_,
|
||||
ckpt_ && ckpt_->imports() != Checkpoint::Import::None);
|
||||
if (s < 0) {
|
||||
/* rad_tools_load_plugins has said why -- a plugin refused, or no architecture plugin for
|
||||
* this model -- each by name. What it does not know is that this was the engine's start. */
|
||||
@@ -1225,9 +1288,111 @@ int Engine::plan() {
|
||||
r->program.arena_stage_bytes = vb.stage;
|
||||
r->program.arena_bytes = r->program.arena_stage_off + vb.stage;
|
||||
}
|
||||
|
||||
/* ---- AN UNEVEN WORLD: EACH RANK'S OWN POOLS FOR THE ONE TOKEN COUNT -------------------
|
||||
*
|
||||
* The split above is the dearest rank's, applied to every card, and one block table serves
|
||||
* every rank -- configure_kv caps each at the least rank's paged tokens. A rank whose cache
|
||||
* costs less per token (an attention-zero rank keeps no attention cache, only what its
|
||||
* other groups cost) would reserve the common KV pool and page a fraction of it, while its
|
||||
* experts beyond the common weights pool sit in the pinned host pool. So such a rank gets a
|
||||
* KV pool that pages exactly the common token count and the difference in its weights
|
||||
* pool, up to every one of its weights resident. The token count, the carve, the loan and
|
||||
* the dearest ranks' pools are what they were.
|
||||
*
|
||||
* Only a DERIVED split under expert_tiered is re-split. An operator who stated either pool
|
||||
* has decided what every card gets. And under `auto` a rank whose grown pool covers all of
|
||||
* its weights would choose all_vram while its peers spill -- one strategy per world is the
|
||||
* contract that keeps their movers alike, so `auto` keeps the common split. A cache that
|
||||
* does not lend (--deterministic, or a device without virtual memory management) is
|
||||
* re-split all the same: the bytes it would never page are bytes its experts can hold, and
|
||||
* without virtual memory management they are allocated whole.
|
||||
* Where every rank's cache costs the same per token no rank qualifies and rank_cfg_ is cfg_
|
||||
* on every rank, field for field. A rank that qualifies and is not re-split is named with
|
||||
* the reason, once. */
|
||||
rank_cfg_.assign(ranks_.size(), cfg_);
|
||||
kv_planned_tokens_ = 0;
|
||||
constexpr int64_t kMiB = (int64_t)1 << 20;
|
||||
int64_t kv_max = 0;
|
||||
for (const VramFacts& f : facts) kv_max = std::max(kv_max, f.kv_ceiling);
|
||||
std::vector<size_t> cheaper;
|
||||
for (size_t i = 0; i < facts.size() && i < ranks_.size(); ++i)
|
||||
if (facts[i].kv_ceiling < kv_max) cheaper.push_back(i);
|
||||
/* Why no cheaper rank is re-split, where the reason holds for the whole world. */
|
||||
std::string kept;
|
||||
std::vector<std::unique_ptr<KVManager>> probes(ranks_.size());
|
||||
int64_t T = -1;
|
||||
if (cheaper.empty()) {
|
||||
/* Every rank's cache costs the same per token: there is nothing to re-split. */
|
||||
} else if (!vb.derived_kv || !vb.derived_weights) {
|
||||
kept = "a stated --vram-kv-mib or --vram-weights-mib is applied to every card";
|
||||
} else if (cfg_.placement != "expert_tiered") {
|
||||
kept = fmt("--placement %s keeps one split for every card; only expert_tiered re-splits",
|
||||
cfg_.placement.c_str());
|
||||
} else {
|
||||
/* THE TOKEN COUNT configure_kv WILL SETTLE ON: every rank's paged tokens in the common
|
||||
* pool, the least of them. Asked of the same plan configure_kv makes, against the same
|
||||
* bytes: nothing reserves from a KV pool before its carve. */
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
probes[i] = std::make_unique<KVManager>();
|
||||
if (probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
|
||||
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
|
||||
break;
|
||||
}
|
||||
const int64_t t = probes[i]->paged_tokens(cfg_.vram_kv_mib * kMiB);
|
||||
if (t == KVManager::kUnboundedTokens) continue;
|
||||
if (T < 0 || t < T) T = t;
|
||||
}
|
||||
if (kept.empty() && T <= 0)
|
||||
kept = "no rank's cache pages a bounded token count in the common pool";
|
||||
}
|
||||
for (size_t i : cheaper) {
|
||||
const std::string costs =
|
||||
fmt("kv: rank %d's cache costs %s at the worst case where its dearest peer's costs "
|
||||
"%s", ranks_[i]->index, humanb(facts[i].kv_ceiling).c_str(),
|
||||
humanb(kv_max).c_str());
|
||||
if (!kept.empty()) {
|
||||
RAD_INFO("%s; its pools stay the common split: %s", costs.c_str(), kept.c_str());
|
||||
continue;
|
||||
}
|
||||
/* EXACT, NO MARGIN: paged_split is monotone in the budget, so the least whole MiB that
|
||||
* pages T here pages at least T in configure_kv -- the same plan, the same arithmetic,
|
||||
* a pool whose budget is exactly this many MiB. The pool's own alignment is already
|
||||
* among the plan's fixed costs (a RAD_ALIGN_UNIT a reservation). */
|
||||
const int64_t need = probes[i]->pool_mib_for_tokens(T, cfg_.vram_kv_mib);
|
||||
if (need < 0) {
|
||||
RAD_INFO("%s; its pools stay the common split: it does not page the common %lld "
|
||||
"tokens in the common %lld MiB", costs.c_str(), (long long)T,
|
||||
(long long)cfg_.vram_kv_mib);
|
||||
continue;
|
||||
}
|
||||
const int64_t cap = facts[i].statics + expert_vram_floor(wfs[i], 0);
|
||||
const RankSplit rs =
|
||||
vram_budget_rank_split(cfg_.vram_weights_mib, cfg_.vram_kv_mib, need, cap);
|
||||
if (!rs.resplit) {
|
||||
RAD_INFO("%s; its pools stay the common split: it needs all %lld MiB of the common "
|
||||
"pool to page the common %lld tokens", costs.c_str(),
|
||||
(long long)cfg_.vram_kv_mib, (long long)T);
|
||||
continue;
|
||||
}
|
||||
rank_cfg_[i].vram_kv_mib = rs.kv_mib;
|
||||
rank_cfg_[i].vram_weights_mib = rs.weights_mib;
|
||||
kv_planned_tokens_ = T;
|
||||
RAD_INFO("%s, so its KV pool pages the common %lld tokens in %lld MiB instead of %lld; "
|
||||
"its weights pool grows %lld -> %lld MiB (every weight resident wants %s)%s",
|
||||
costs.c_str(), (long long)T, (long long)rs.kv_mib, (long long)cfg_.vram_kv_mib,
|
||||
(long long)cfg_.vram_weights_mib, (long long)rs.weights_mib,
|
||||
humanb(cap).c_str(),
|
||||
rs.unusable_mib > 0
|
||||
? fmt(", and %lld MiB stay unclaimed", (long long)rs.unusable_mib).c_str()
|
||||
: "");
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& r : ranks_) {
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& r = ranks_[ri];
|
||||
/* This rank's own split: cfg_ field for field unless the block above re-split it. */
|
||||
const Config& rc = rank_cfg_[ri];
|
||||
LogRank lr(r->index);
|
||||
/* THE MAIN THREAD RUNS EVERY RANK'S STARTUP, one rank after another, and every allocator
|
||||
* reachable from here takes the CURRENT device -- rad_dev_alloc has no device argument.
|
||||
@@ -1241,18 +1406,18 @@ int Engine::plan() {
|
||||
/* Every pool is budgeted explicitly. No profiling pass, no utilisation fraction, no
|
||||
* inference about what the workload will be (spec §6). Pools refuses by name and by how
|
||||
* much rather than shrinking anything. */
|
||||
int s = r->pools.configure(cfg_, props.vram_bytes);
|
||||
int s = r->pools.configure(rc, props.vram_bytes);
|
||||
RAD_INFO("pools:\n%s", r->pools.fit_report().c_str());
|
||||
if (s < 0) {
|
||||
report_pool_refusal(r->index, r->device, r->pools, cfg_);
|
||||
report_pool_refusal(r->index, r->device, r->pools, rc);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Under tensor parallel the placement unit is a SHARD of a weight, so each rank plans
|
||||
* against its own card's budget (spec §5.3). */
|
||||
* against its own card's budget (spec §5.3) -- the same split its pools were given. */
|
||||
PlannerInput in{};
|
||||
in.program = &r->program;
|
||||
in.config = &cfg_;
|
||||
in.config = &rc;
|
||||
in.rank = r->index;
|
||||
in.world_size = cfg_.tp;
|
||||
if (file_ && file_->header().prof_count) {
|
||||
@@ -1265,6 +1430,16 @@ int Engine::plan() {
|
||||
if (cfg_.debug_placement || s < 0)
|
||||
fputs(r->plan.report(r->program).c_str(), stderr);
|
||||
if (s < 0) return s;
|
||||
/* The slab the planner filled is the pool the mover will fill: one split, read twice. */
|
||||
RAD_TRY(plan_check_weights_pool(r->plan, r->pools.weights().bytes()));
|
||||
/* --host-pool-mib IS ONE NUMBER FOR EVERY RANK, allocated whole by Pools::configure, so a
|
||||
* re-split rank whose grown weights pool took every weight still holds it. Said, because
|
||||
* the `kv: rank N ...` line above reads as if that rank's memory were all accounted for. */
|
||||
if (rc.vram_kv_mib < cfg_.vram_kv_mib && cfg_.host_pool_mib > 0 &&
|
||||
r->plan.totals.bytes[(int)Tier::HostPinned] == 0)
|
||||
RAD_INFO("kv: rank %d's weights all fit its grown weights pool, so its pinned host pool "
|
||||
"holds no weights; its %lld MiB (--host-pool-mib) stay allocated, as on every "
|
||||
"rank", r->index, (long long)cfg_.host_pool_mib);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -2551,10 +2726,22 @@ int Engine::configure_kv() {
|
||||
* every rank is capped at the least before any carves. At an even split the cap is what
|
||||
* every rank would have carved anyway. */
|
||||
int64_t least = -1;
|
||||
for (auto& r : ranks_) {
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
auto& r = ranks_[i];
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
|
||||
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
|
||||
/* A RANK plan() RE-SIZED FOR THE COMMON TOKEN COUNT PAGES AT LEAST THAT COUNT, by
|
||||
* construction: its pool is the least whole MiB whose paged split reaches it, asked of the
|
||||
* same plan against the same bytes. Short of it, this rank would set every rank's count
|
||||
* under what its dearest peer pages -- a broken construction, refused by name. */
|
||||
if (rank_cfg_[i].vram_kv_mib < cfg_.vram_kv_mib && t < kv_planned_tokens_) {
|
||||
RAD_ERR("kv: rank %d's KV pool was sized at %lld MiB to page the common %lld tokens "
|
||||
"and pages %lld: the pool and the plan that sized it disagree", r->index,
|
||||
(long long)rank_cfg_[i].vram_kv_mib, (long long)kv_planned_tokens_,
|
||||
(long long)t);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (t == KVManager::kUnboundedTokens) continue; /* holds no cache; limits nobody */
|
||||
if (least < 0 || t < least) least = t;
|
||||
}
|
||||
@@ -2730,16 +2917,20 @@ int Engine::configure_kv() {
|
||||
sc.n_ckpt_slots = ck_disk_slots;
|
||||
sc.n_block_slots = ((cfg_.prefix_cache_disk_mib << 20)
|
||||
- ck_disk_slots * ck_slot_bytes) / slot_bytes;
|
||||
/* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE. A cached block is only
|
||||
* meaningful under the container and layout that produced it; read back under
|
||||
* another, it is a lossless function of somebody else's weights. */
|
||||
/* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE, and it is built from
|
||||
* everything a cached block's bytes actually depend on. Read back under a
|
||||
* different container, layout or KV width, a block is a lossless function of
|
||||
* somebody else's weights -- fluent, confident and wrong. There is no cheaper
|
||||
* check than refusing the whole store, because a block carries no evidence of
|
||||
* what produced it beyond the tokens it was keyed by. */
|
||||
* different container, layout, KV width or rotary, a block is a lossless
|
||||
* function of somebody else's weights -- fluent, confident and wrong. There is
|
||||
* no cheaper check than refusing the whole store, because a block carries no
|
||||
* evidence of what produced it beyond the tokens it was keyed by.
|
||||
*
|
||||
* The rotary is the RESOLVED one, target and drafter, after --rope-scaling
|
||||
* (rope_identity): a YaRN container converted from the same checkpoint has the
|
||||
* same name and shapes as the stock one, and every cached key and QSA block key
|
||||
* is rotated differently under it. */
|
||||
{
|
||||
char theta[32];
|
||||
std::snprintf(theta, sizeof theta, "%.9g", (double)meta_.rope_theta);
|
||||
const std::string id =
|
||||
std::string(meta_.name ? meta_.name : "") + "|" +
|
||||
std::string(meta_.arch_id ? meta_.arch_id : "") + "|" +
|
||||
@@ -2747,7 +2938,8 @@ int Engine::configure_kv() {
|
||||
std::to_string(ranks_[0]->prefix.block_size()) + "|" +
|
||||
std::to_string(slot_bytes) + "|" + std::to_string(ck_slot_bytes) + "|" +
|
||||
cfg_.kv_cache_dtype + "|" +
|
||||
std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION;
|
||||
std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION +
|
||||
"|theta=" + theta + "|" + rope_identity(meta_kv_k_, meta_kv_v_);
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
for (char c : id) { h ^= (unsigned char)c; h *= 1099511628211ull; }
|
||||
sc.fingerprint = h;
|
||||
@@ -3021,9 +3213,11 @@ int Engine::start() {
|
||||
/* PEER ACCESS, MEASURED BEFORE ANYTHING IS SELECTED. A kernel that reads or writes another
|
||||
* card's memory says so with a constraint on device.p2p (rad_types.h), and the selector reads
|
||||
* it from here: on a machine where some pair of the ranks' cards cannot reach each other such a
|
||||
* kernel is not selected, and declare names the constraint instead of the all-reduce faulting
|
||||
* or hanging on its first message. Every ordered pair, because access is granted one way at a
|
||||
* time. */
|
||||
* kernel is not selected, and one that exchanges through host memory takes the op instead (or
|
||||
* declare names the constraint) rather than the all-reduce faulting or hanging on its first
|
||||
* message. Every ordered pair, because access is granted one way at a time. --p2p overrides the
|
||||
* answer in one direction each way (Config::p2p): off turns it down whatever the driver says,
|
||||
* on refuses to start without it. */
|
||||
{
|
||||
long long p2p = 1;
|
||||
std::string blocked;
|
||||
@@ -3041,14 +3235,27 @@ int Engine::start() {
|
||||
blocked += fmt("%s%d->%d", blocked.empty() ? "" : ", ", devs[i], devs[j]);
|
||||
}
|
||||
}
|
||||
if (cfg_.tp > 1 && cfg_.p2p == RAD_P2P_ON && !p2p) {
|
||||
RAD_ERR("device: --p2p on, but the driver reports no peer-to-peer access between cards "
|
||||
"%s. IOMMU settings and the PCIe topology decide this, not radiance; --p2p auto "
|
||||
"serves through host memory instead", blocked.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const bool forced_off = cfg_.p2p == RAD_P2P_OFF;
|
||||
if (forced_off) p2p = 0;
|
||||
rad_tools_registry().set_device_fact(RAD_FACT_P2P, p2p);
|
||||
if (cfg_.tp > 1) {
|
||||
if (p2p) RAD_INFO("device: the %d cards reach each other's memory directly (peer to "
|
||||
"peer)", cfg_.tp);
|
||||
else RAD_WARN("device: no peer-to-peer access between cards %s. A kernel that needs "
|
||||
"it (device.p2p == 1) is not selected; if nothing else implements its "
|
||||
"op, startup stops below naming it. IOMMU settings and the PCIe "
|
||||
"topology decide this, not radiance", blocked.c_str());
|
||||
else if (forced_off)
|
||||
RAD_INFO("device: --p2p off: the collectives exchange through pinned host memory%s",
|
||||
blocked.empty() ? " although the driver reports peer-to-peer access"
|
||||
: "");
|
||||
else RAD_WARN("device: no peer-to-peer access between cards %s. The collectives "
|
||||
"exchange through pinned host memory instead, and a kernel that needs "
|
||||
"peer access (device.p2p == 1) is not selected; if nothing else "
|
||||
"implements its op, startup stops below naming it. IOMMU settings and "
|
||||
"the PCIe topology decide this, not radiance", blocked.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3310,55 +3517,86 @@ int Engine::start() {
|
||||
*
|
||||
* Everything above this line allocated: the two pools, the activation arena, the step batch
|
||||
* staging, the weight tables a grouped GEMM walks. What is left on the card should now be
|
||||
* --gpu-headroom-mib and nothing else, and this is the only place that can say whether it is.
|
||||
* --gpu-headroom-mib plus what the budget kept for later, and this is the only place that can
|
||||
* say whether it is.
|
||||
*
|
||||
* Both directions are worth a line. TOO LITTLE means the terms the resolver could not compute
|
||||
* -- anything still allocated lazily, and whatever the driver took after the reading -- ate
|
||||
* into the memory the operator asked to keep, and the next thing to allocate on this card is
|
||||
* whatever fails. TOO MUCH means the budget left VRAM on the floor, which on a model whose
|
||||
* experts do not fit is milliseconds of decode step for every unspent GiB -- the exact
|
||||
* failure this resolver exists to remove.
|
||||
* TOO LITTLE is memory taken after the budget read the card that the budget did not count:
|
||||
* another process on the card (a desktop, a second server), or a driver allocation made
|
||||
* after the reading. It comes out of the room a kernel's first launch allocates its code
|
||||
* object and scratch from, and running out of that is a fault inside the HIP runtime.
|
||||
*
|
||||
* A slack of one arena is tolerated silently: MiB rounding and a kernel plugin's own
|
||||
* workspaces live in there, and naming a number this close to right would be noise. */
|
||||
const int64_t headroom = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * (1ll << 20);
|
||||
for (auto& r : ranks_) {
|
||||
* THE WARNING IS ON THE ROOM, NOT ON THE FLAG. Raising --gpu-headroom-mib raises what is left
|
||||
* here and what this compares it with by the same amount, so a check of free memory against
|
||||
* the flag can never be satisfied by the flag: the gap is whatever was taken after the
|
||||
* reading, and it is there at every value. The room a first launch has -- what is free less
|
||||
* what the budget kept for later -- is what the flag actually moves, and it is held against
|
||||
* this engine's own allowance for its first launches (the flag's default). A card short of
|
||||
* that is warned with the value that clears it; one that kept the allowance but lost part of
|
||||
* a larger stated headroom says so on its INFO line.
|
||||
*
|
||||
* TOO MUCH means the budget left VRAM on the floor, which on a model whose experts do not
|
||||
* fit is milliseconds of decode step for every unspent GiB. A slack of 256 MiB is tolerated
|
||||
* silently: MiB rounding and a kernel plugin's own workspaces live in there. */
|
||||
const int64_t MiB = 1024 * 1024;
|
||||
const int64_t headroom = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * MiB;
|
||||
const int64_t allowance = Config{}.gpu_headroom_mib * MiB;
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& r = ranks_[ri];
|
||||
LogRank lr(r->index);
|
||||
RadDeviceProps props{};
|
||||
if (rad_dev_props(r->device, &props) < 0 || props.vram_bytes <= 0) continue;
|
||||
|
||||
/* AGAINST THE HEADROOM AND WHAT THE BUDGET KEPT FOR LATER, because both are still free
|
||||
* here: the step staging is allocated by serve(), and the KV tiers' staging and a second
|
||||
* compute lane are built on first use. A card at exactly the headroom now would be under
|
||||
* it once those exist. */
|
||||
const int64_t MiB = 1024 * 1024;
|
||||
* compute lane are built on first use. */
|
||||
const int64_t late = late_step_bytes_ + late_lazy_bytes_;
|
||||
const int64_t want = headroom + late;
|
||||
const int64_t got = props.vram_free;
|
||||
const int64_t room = got - late;
|
||||
const std::string asked =
|
||||
late > 0 ? fmt("%s (the %s --gpu-headroom-mib and %s kept for the step staging and "
|
||||
"for what is built on first use)", humanb(want).c_str(),
|
||||
humanb(headroom).c_str(), humanb(late).c_str())
|
||||
: fmt("%s --gpu-headroom-mib", humanb(want).c_str());
|
||||
if (got < want) {
|
||||
/* WHAT THIS SHORTFALL THREATENS is whatever allocates after startup: a kernel's code
|
||||
* object, loaded on its FIRST launch, and a spilling kernel's scratch, sized on its
|
||||
* first launch by the whole grid. Neither is knowable when the budget is resolved, and
|
||||
* running out for either is a fault inside the HIP runtime rather than an error. */
|
||||
RAD_WARN("card %d settled at %s free against %s. The difference is allocations "
|
||||
"made after the budget was resolved, and it comes out of the room a kernel's "
|
||||
"first launch allocates from. Raise --gpu-headroom-mib by at least %s so the "
|
||||
"budget is resolved against the right number.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).c_str());
|
||||
}
|
||||
else if (got > want + 256 * MiB) {
|
||||
if (room < allowance) {
|
||||
const int64_t raise_mib = (allowance - room + MiB - 1) / MiB;
|
||||
RAD_WARN("card %d settled at %s free against %s, which leaves %s for a kernel's first "
|
||||
"launch to load its code object and size its scratch in -- under the %s this "
|
||||
"engine allows for its own. %s Set --gpu-headroom-mib to at least %lld: what "
|
||||
"is left here rises with it one for one.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(),
|
||||
humanb(std::max<int64_t>(room, 0)).c_str(), humanb(allowance).c_str(),
|
||||
got < want
|
||||
? fmt("%s of the headroom was taken after the budget read the card, by "
|
||||
"another process on it or an allocation the budget does not "
|
||||
"count.", humanb(want - got).c_str()).c_str()
|
||||
: "",
|
||||
(long long)(std::max<int64_t>(cfg_.gpu_headroom_mib, 0) + raise_mib));
|
||||
} else if (got < want) {
|
||||
RAD_INFO("card %d settled at %s free against %s: %s of the headroom was taken after "
|
||||
"the budget read the card, by another process on it or an allocation the "
|
||||
"budget does not count, and %s is left for first launches",
|
||||
r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).c_str(),
|
||||
humanb(room).c_str());
|
||||
} else if (got > want + 256 * MiB) {
|
||||
/* AND "TOO MUCH" IS ONLY A FAULT WHERE SOMEBODY STATED THE BUDGET. Where the resolver
|
||||
* made the split, what is left is left because neither pool could address another
|
||||
* byte -- a small dense model already at the largest context its cache can hold
|
||||
* leaves most of the card -- and vram_budget.cpp printed it on the `unusable` line.
|
||||
* Warning here would contradict that receipt and send the reader looking for a flag
|
||||
* to set. */
|
||||
if (cfg_.vram_budget_derived)
|
||||
* to set. A rank plan() re-split for the common token count also leaves what its
|
||||
* weights could not use, and the `kv: rank N ...` line said how much. */
|
||||
const int64_t unclaimed_mib =
|
||||
(cfg_.vram_weights_mib + cfg_.vram_kv_mib) -
|
||||
(rank_cfg_[ri].vram_weights_mib + rank_cfg_[ri].vram_kv_mib);
|
||||
if (cfg_.vram_budget_derived && unclaimed_mib > 0)
|
||||
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: %lld "
|
||||
"MiB are what rank %d's weights could not use of what its KV pool did not "
|
||||
"need, on the `kv: rank %d ...` line above, and the rest is the `unusable` "
|
||||
"line of the VRAM budget.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(), (long long)unclaimed_mib,
|
||||
r->index, r->index);
|
||||
else if (cfg_.vram_budget_derived)
|
||||
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: "
|
||||
"neither pool could address another byte, which is the `unusable` line of "
|
||||
"the VRAM budget above.",
|
||||
|
||||
+332
-11
@@ -253,7 +253,10 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0;
|
||||
m.rms_eps = (float)gf("rms_norm_eps", 1e-6);
|
||||
m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0));
|
||||
m.rope_scale = (float)gf("rope_scaling.factor", 1.0);
|
||||
/* The rotary's scaling stays in the free-form keys with its type beside it; the architecture
|
||||
* reads both (arch/common/rad_arch.h, yarn_from). A factor copied here without its type would
|
||||
* be a linear position divide for llama3, longrope or YaRN. */
|
||||
m.rope_scale = 1.0f;
|
||||
|
||||
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
|
||||
* "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
|
||||
@@ -300,7 +303,48 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
m.n_expert_shared= gi("expert_shared_count", 0);
|
||||
m.rms_eps = (float)gf("attention.layer_norm_rms_epsilon", 1e-6);
|
||||
m.rope_theta = (float)gf("rope.freq_base", 10000.0);
|
||||
m.rope_scale = (float)gf("rope.scaling.factor", 1.0);
|
||||
m.rope_scale = 1.0f;
|
||||
|
||||
/* THE ROTARY'S SCALING, written as the config.json keys a safetensors release carries, because
|
||||
* those are what the architecture reads (arch/common/rad_arch.h, yarn_from) -- one reader, so
|
||||
* a type is refused or honoured by name whichever file it came from. llama.cpp's YaRN
|
||||
* attn_factor, ext_factor and log multiplier modify the magnitude and ramp in ways config.json
|
||||
* has no spelling for, so a file that sets one to anything but its neutral value is refused
|
||||
* here rather than served as plain YaRN. */
|
||||
{
|
||||
/* llama.cpp's reading: the type defaults to linear, the factor is rope.scaling.factor or
|
||||
* the older rope.scale_linear, and 0 or 1 is no scaling. */
|
||||
std::string type = "linear";
|
||||
g.get_str(a + ".rope.scaling.type", &type);
|
||||
const double factor = gf("rope.scaling.factor", gf("rope.scale_linear", 0.0));
|
||||
const bool none = type == "none" || (type == "linear" && (factor == 0.0 || factor == 1.0));
|
||||
if (!none) {
|
||||
const struct { const char* key; double neutral; } kOff[] = {
|
||||
{ "rope.scaling.attn_factor", 1.0 }, { "rope.scaling.yarn_attn_factor", 1.0 },
|
||||
{ "rope.scaling.yarn_log_multiplier", 0.0 } };
|
||||
for (const auto& k : kOff)
|
||||
if (gf(k.key, k.neutral) != k.neutral) {
|
||||
RAD_ERR("the GGUF sets %s.%s = %g; that modifier of the rotary's scaling is "
|
||||
"not implemented", a.c_str(), k.key, gf(k.key, k.neutral));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const double ext = gf("rope.scaling.yarn_ext_factor", -1.0);
|
||||
if (ext >= 0.0 && ext != 1.0) {
|
||||
RAD_ERR("the GGUF sets %s.rope.scaling.yarn_ext_factor = %g; YaRN is implemented "
|
||||
"at extrapolation factor 1", a.c_str(), ext);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
out->kv("rope_scaling.type", type);
|
||||
if (factor != 0.0) out->kv("rope_scaling.factor", fmt("%.17g", factor));
|
||||
const int64_t orig = gi("rope.scaling.original_context_length", 0);
|
||||
if (orig > 0) out->kv("rope_scaling.original_max_position_embeddings",
|
||||
fmt("%lld", (long long)orig));
|
||||
for (const char* beta : { "beta_fast", "beta_slow" }) {
|
||||
const double v = gf((std::string("rope.scaling.yarn_") + beta).c_str(), 0.0);
|
||||
if (v != 0.0) out->kv(std::string("rope_scaling.") + beta, fmt("%.17g", v));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> toks;
|
||||
if (g.get_strs("tokenizer.ggml.tokens", &toks)) m.n_vocab = (int64_t)toks.size();
|
||||
@@ -432,10 +476,169 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
fp8_bc_ = c;
|
||||
}
|
||||
}
|
||||
detect_import();
|
||||
meta_.finish();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* WHICH PUBLISHED QUANTISATION THIS IS, from quantization_config alone: the tensors are checked
|
||||
* one by one when a weight is resolved (import_piece), so a file that says one thing and holds
|
||||
* another is refused at the weight that differs. */
|
||||
void Checkpoint::detect_import() {
|
||||
auto qc = [&](const std::string& k) {
|
||||
const char* v = meta_.get("quantization_config." + k);
|
||||
return v ? std::string(v) : std::string();
|
||||
};
|
||||
auto any_under = [&](const std::string& prefix) {
|
||||
for (const std::string& k : meta_.keys)
|
||||
if (k.rfind("quantization_config." + prefix, 0) == 0) return true;
|
||||
return false;
|
||||
};
|
||||
const std::string qm = qc("quant_method");
|
||||
if (qm == "auto-round") {
|
||||
/* AutoRound's GPTQ-compatible export; its own `auto_round` packing is another layout. */
|
||||
const std::string pf = qc("packing_format");
|
||||
if (pf == "auto_round:auto_gptq") import_ = Import::Gptq;
|
||||
else import_why_ = "AutoRound's packing_format '" + pf + "' is not one this reads; its "
|
||||
"auto_round:auto_gptq export is";
|
||||
} else if (qm == "gptq") {
|
||||
/* v1, the format auto_gptq writes: the zero point stored less one. gptq_v2 stores it as
|
||||
* it is, and reading it as v1 would shift every code by one. */
|
||||
const std::string cf = qc("checkpoint_format");
|
||||
if (cf.empty() || cf == "gptq") import_ = Import::Gptq;
|
||||
else import_why_ = "GPTQ's checkpoint_format '" + cf + "' is not one this reads; 'gptq' is";
|
||||
} else if (qm == "quark") {
|
||||
const std::string w = "global_quant_config.weight.";
|
||||
if (qc(w + "dtype") == "fp4" && qc(w + "qscheme") == "per_group" &&
|
||||
qc(w + "group_size") == "32" && qc(w + "scale_format") == "e8m0" &&
|
||||
!any_under("layer_quant_config.") && !any_under("layer_type_quant_config."))
|
||||
import_ = Import::QuarkMx;
|
||||
else
|
||||
import_why_ = "Quark's weight scheme here is not MXFP4 (fp4, per_group 32, e8m0 scales) "
|
||||
"throughout, which is the one this reads";
|
||||
}
|
||||
/* THE TOOL'S DESCRIPTION IS KEPT, UNDER ANOTHER NAME. A plugin reads quantization_config as
|
||||
* the statement of the format it serves (qwen35_fp8 checks quant_method is "fp8"), and an
|
||||
* imported checkpoint's says how a tool made it instead: every weight states its own
|
||||
* encoding. Renamed, it still travels into the container as provenance. */
|
||||
if (import_ != Import::None)
|
||||
for (std::string& k : meta_.keys)
|
||||
if (k.rfind("quantization_config.", 0) == 0) k = "imported_" + k;
|
||||
}
|
||||
|
||||
int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
|
||||
const SrcTensor** scale, std::string* why) {
|
||||
auto refuse = [&](int rc, std::string m) {
|
||||
if (why) *why = std::move(m);
|
||||
return rc;
|
||||
};
|
||||
if (import_ == Import::None) return RAD_E_NOTFOUND;
|
||||
if (auto hit = imported_.find(name); hit != imported_.end()) {
|
||||
*codes = hit->second.first;
|
||||
*scale = hit->second.second;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (import_ == Import::QuarkMx) {
|
||||
/* QUARK'S MXFP4 IS THE ENCODING AS IT STANDS: two codes a byte, element 2j in the low
|
||||
* nibble, and one biased exponent a 32 of K -- `fp4_e2m1*e8m0[1x32]`. A view renames the
|
||||
* dtypes and the logical width; no byte moves. Its excluded layers are plain tensors. */
|
||||
const SrcTensor* w = find(name);
|
||||
const SrcTensor* e = w ? find(name + "_scale") : nullptr;
|
||||
if (!w || !e || w->rad_dtype != RAD_U8) return RAD_E_NOTFOUND;
|
||||
if (e->rad_dtype != RAD_U8 || w->shape.size() != 2 || e->shape.size() != 2 ||
|
||||
e->shape[0] != w->shape[0] || e->shape[1] * 32 != w->shape[1] * 2)
|
||||
return refuse(RAD_E_SHAPE, "'" + e->name + "' is not the [N, K/32] exponent plane of '" +
|
||||
w->name + "'");
|
||||
SrcTensor c = *w;
|
||||
c.rad_dtype = RAD_FP4E2M1;
|
||||
c.shape = { w->shape[0], w->shape[1] * 2 };
|
||||
SrcTensor x = *e;
|
||||
x.rad_dtype = RAD_E8M0;
|
||||
sliced_.push_back(std::move(c));
|
||||
*codes = &sliced_.back();
|
||||
sliced_.push_back(std::move(x));
|
||||
*scale = &sliced_.back();
|
||||
imported_[name] = { *codes, *scale };
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* GPTQ-PACKED: `X.weight` is shipped as X.qweight, X.scales, X.qzeros and, optionally,
|
||||
* X.g_idx. The width is read off the tensors rather than quantization_config, because a
|
||||
* release may mix widths -- int4 experts beside int8 projections -- and say so only per layer. */
|
||||
const std::string suffix = ".weight";
|
||||
if (name.size() <= suffix.size() ||
|
||||
name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
|
||||
return RAD_E_NOTFOUND;
|
||||
const std::string base = name.substr(0, name.size() - suffix.size());
|
||||
const SrcTensor* qw = find(base + ".qweight");
|
||||
if (!qw) return RAD_E_NOTFOUND;
|
||||
const SrcTensor* sc = find(base + ".scales");
|
||||
const SrcTensor* qz = find(base + ".qzeros");
|
||||
const SrcTensor* gi = find(base + ".g_idx");
|
||||
const std::string what = "'" + qw->name + "'";
|
||||
if (qw->rad_dtype != RAD_I32 || qw->shape.size() != 2)
|
||||
return refuse(RAD_E_FORMAT, what + " is not an int32 [K*bits/32, N] matrix");
|
||||
if (!sc || sc->shape.size() != 2 ||
|
||||
(sc->rad_dtype != RAD_F16 && sc->rad_dtype != RAD_BF16 && sc->rad_dtype != RAD_F32))
|
||||
return refuse(RAD_E_FORMAT, what + " has no float [groups, N] '" + base + ".scales' beside it");
|
||||
if (!qz || qz->rad_dtype != RAD_I32 || qz->shape.size() != 2)
|
||||
return refuse(RAD_E_FORMAT, what + " has no int32 '" + base + ".qzeros' beside it");
|
||||
const int64_t N = qw->shape[1];
|
||||
const int64_t bits = N > 0 && (qz->shape[1] * 32) % N == 0 ? qz->shape[1] * 32 / N : 0;
|
||||
if (bits != 4 && bits != 8)
|
||||
return refuse(RAD_E_UNSUPPORTED, what + " packs " + std::to_string(bits) + "-bit codes "
|
||||
"(from its qzeros' width); 4 and 8 are read");
|
||||
const int64_t K = qw->shape[0] * 32 / bits;
|
||||
const int64_t G = sc->shape[0];
|
||||
if (sc->shape[1] != N || G <= 0 || K % G)
|
||||
return refuse(RAD_E_SHAPE, "'" + sc->name + "' is not a [groups, " + std::to_string(N) +
|
||||
"] scale tensor for " + std::to_string(K) + " columns");
|
||||
const int64_t group = K / G;
|
||||
/* THE SERVED SCALE COVERS 128 OF K, so a group of 128 is one scale each and a wider one --
|
||||
* per channel included -- repeats; a narrower group has no form the kernels read. */
|
||||
if (K % 128 || group % 128)
|
||||
return refuse(RAD_E_UNSUPPORTED, what + " has groups of " + std::to_string(group) +
|
||||
" columns; the imported form scales a 128 of K, so the "
|
||||
"group must be a multiple of 128");
|
||||
if (qz->shape[0] != G)
|
||||
return refuse(RAD_E_SHAPE, "'" + qz->name + "' has " + std::to_string(qz->shape[0]) +
|
||||
" rows for " + std::to_string(G) + " groups");
|
||||
/* SYMMETRIC, OR NOT READ: every zero point the v1 2^(bits-1) - 1, which is what makes a code
|
||||
* the signed value it offsets to. An asymmetric weight would need a zero plane. */
|
||||
const uint32_t zero = bits == 4 ? 0x77777777u : 0x7f7f7f7fu;
|
||||
for (int64_t i = 0; i < qz->numel(); ++i) {
|
||||
uint32_t v;
|
||||
std::memcpy(&v, (const uint8_t*)qz->data + i * 4, 4);
|
||||
if (v != zero)
|
||||
return refuse(RAD_E_UNSUPPORTED, "'" + qz->name + "' holds a zero point other than "
|
||||
"the symmetric one; an asymmetric weight is not read");
|
||||
}
|
||||
/* AND IN ORDER: act-order (desc_act) permutes the columns' groups, which a [1x128] scale
|
||||
* cannot follow. The identity, or none, is the only g_idx read. */
|
||||
if (gi) {
|
||||
if (gi->rad_dtype != RAD_I32 || gi->numel() != K)
|
||||
return refuse(RAD_E_FORMAT, "'" + gi->name + "' is not an int32 [K] group index");
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
int32_t v;
|
||||
std::memcpy(&v, (const uint8_t*)gi->data + k * 4, 4);
|
||||
if (v != k / group)
|
||||
return refuse(RAD_E_UNSUPPORTED, "'" + gi->name + "' reorders the columns' groups "
|
||||
"(act-order); only an in-order index is read");
|
||||
}
|
||||
}
|
||||
SrcTensor c = *qw;
|
||||
c.rad_dtype = bits == 4 ? RAD_I4 : RAD_I8;
|
||||
c.shape = { N, K };
|
||||
c.gptq_bits = (int32_t)bits;
|
||||
c.gptq_group = group;
|
||||
sliced_.push_back(std::move(c));
|
||||
*codes = &sliced_.back();
|
||||
*scale = sc;
|
||||
imported_[name] = { *codes, *scale };
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Checkpoint::open(const std::string& path) {
|
||||
path_ = path;
|
||||
const bool gguf = path.size() > 5 && path.compare(path.size() - 5, 5, ".gguf") == 0;
|
||||
@@ -577,6 +780,22 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
for (const Src1& s1 : srcs) {
|
||||
const SrcTensor* st = ck.find(s1.name);
|
||||
const SrcTensor* sc = st ? ck.find(scale_name(s1.name)) : nullptr;
|
||||
/* A WEIGHT THE CHECKPOINT SHIPS IN AN IMPORTED FORM is read through that form's views. */
|
||||
{
|
||||
const SrcTensor *ic = nullptr, *is = nullptr;
|
||||
std::string iw;
|
||||
const int ir = ck.import_piece(s1.name, &ic, &is, &iw);
|
||||
if (ir == RAD_OK) {
|
||||
if (s1.index >= 0)
|
||||
return refuse(RAD_E_UNSUPPORTED, "it is a slice of '" + std::string(s1.name) +
|
||||
"', which the checkpoint ships quantised; an "
|
||||
"imported tensor is read whole");
|
||||
st = ic;
|
||||
sc = is;
|
||||
} else if (ir != RAD_E_NOTFOUND) {
|
||||
return refuse(ir, iw);
|
||||
}
|
||||
}
|
||||
/* A SUB-TENSOR INDEX IS TAKEN, never ignored: ignoring it gives every expert a copy of
|
||||
* the whole stack, in a model that loads and answers. Its scale plane is stacked the same
|
||||
* way and sliced at the same index. */
|
||||
@@ -636,6 +855,40 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
|
||||
} else if (!same) {
|
||||
out->why = "its pieces are stored in different dtypes";
|
||||
} else if (p0.gptq_bits) {
|
||||
/* GPTQ-PACKED, IMPORTED: one width and one group throughout, joined only along rows --
|
||||
* a column join would put two pieces' groups in one scale block. */
|
||||
out->imported = true;
|
||||
for (size_t k = 1; k < out->pieces.size() && out->imported; ++k)
|
||||
if (out->pieces[k]->gptq_bits != p0.gptq_bits ||
|
||||
out->pieces[k]->gptq_group != p0.gptq_group) {
|
||||
out->imported = false;
|
||||
out->why = "its GPTQ-packed pieces differ in width or group";
|
||||
}
|
||||
if (out->imported && d != 0 && out->pieces.size() > 1) {
|
||||
out->imported = false;
|
||||
out->why = "its GPTQ-packed pieces are joined along a column, across their groups";
|
||||
}
|
||||
if (out->imported) {
|
||||
rad_enc_clear(&out->enc);
|
||||
rad_enc_copy_str(out->enc.scheme, "affine");
|
||||
rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
|
||||
rad_enc_add_plane(&out->enc, "scale", RAD_BF16, 1, 128);
|
||||
out->why = "it is GPTQ-packed int" + std::to_string(p0.gptq_bits) + ", which "
|
||||
"rad-convert imports with its scales rounded to bf16 -- serve the "
|
||||
"container it writes";
|
||||
}
|
||||
} else if (dt == RAD_FP4E2M1 && scaled) {
|
||||
/* QUARK'S MXFP4, byte for byte: the codes and exponents are the planes of
|
||||
* `fp4_e2m1*e8m0[1x32]`. Joined only along rows, which is how gate and up become one. */
|
||||
out->trivial = d == 0 || out->pieces.size() == 1;
|
||||
if (!out->trivial) out->why = "its MXFP4 pieces are joined along a column";
|
||||
if (out->trivial) {
|
||||
rad_enc_clear(&out->enc);
|
||||
rad_enc_copy_str(out->enc.scheme, "affine");
|
||||
rad_enc_add_plane(&out->enc, "codes", RAD_FP4E2M1, 1, 1);
|
||||
rad_enc_add_plane(&out->enc, "scale", RAD_E8M0, 1, 32);
|
||||
}
|
||||
} else if ((dt == RAD_F8E4M3 || dt == RAD_F8E5M2) && scaled) {
|
||||
/* BLOCK-SCALED FP8, byte for byte: the codes and the scale plane are the planes of
|
||||
* `fp8_e4m3*bf16[128x128]` (whatever the scale's own dtype). Joined only along rows, and
|
||||
@@ -785,6 +1038,21 @@ struct Joined {
|
||||
|
||||
/* `n` elements of a stored-dtype piece from element `e`, as f32. */
|
||||
int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
|
||||
if (t.gptq_bits) {
|
||||
/* the signed code: element (row, k) of the logical [N, K] matrix is field k % (32/bits)
|
||||
* of word [k / (32/bits), row], less its zero point */
|
||||
const int64_t N = t.shape[0], K = t.shape[1];
|
||||
const int64_t per = 32 / t.gptq_bits;
|
||||
const uint32_t mask = (1u << t.gptq_bits) - 1u;
|
||||
const int zp = 1 << (t.gptq_bits - 1);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t row = (e + i) / K, k = (e + i) % K;
|
||||
uint32_t w;
|
||||
std::memcpy(&w, (const uint8_t*)t.data + ((k / per) * N + row) * 4, 4);
|
||||
out[i] = (float)((int)((w >> ((k % per) * t.gptq_bits)) & mask) - zp);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (t.rad_dtype == RAD_DT_INVALID) {
|
||||
/* a GGUF block type: whole rows only, and a row is whole blocks */
|
||||
const int64_t cols = t.shape.back();
|
||||
@@ -807,7 +1075,7 @@ int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
case RAD_F16: case RAD_F8E4M3: case RAD_F8E5M2:
|
||||
case RAD_F16: case RAD_F8E4M3: case RAD_F8E5M2: case RAD_FP4E2M1:
|
||||
case RAD_I8: case RAD_U8: case RAD_I16: case RAD_I32: case RAD_U32: case RAD_U16:
|
||||
for (int64_t i = 0; i < n; ++i) out[i] = rad_load_f32(p, t.rad_dtype, e + i);
|
||||
return RAD_OK;
|
||||
@@ -841,8 +1109,25 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
|
||||
: "?")
|
||||
: std::string(rad_dtype_name(w.pieces[0]->rad_dtype))) +
|
||||
")");
|
||||
/* FP8 IS ITS CODE TIMES ITS BLOCK'S SCALE: the pieces are joined along rows, so logical row
|
||||
* r is in the piece whose rows cover it, and its scales are that piece's. */
|
||||
/* A GPTQ-PACKED CODE TIMES ITS GROUP'S SCALE, the scale read as shipped: the scale tensor is
|
||||
* [groups, N], so row r's scales are a column of it. */
|
||||
if (w.imported) {
|
||||
int64_t base = 0;
|
||||
for (size_t k = 0; k < w.pieces.size(); ++k) {
|
||||
const SrcTensor& pk = *w.pieces[k];
|
||||
const SrcTensor& sk = *w.scales[k];
|
||||
const int64_t pr = pk.shape[0];
|
||||
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r)
|
||||
for (int64_t c = 0; c < w.cols; ++c)
|
||||
out[(r - r0) * w.cols + c] *=
|
||||
rad_load_f32(sk.data, sk.rad_dtype, (c / pk.gptq_group) * pr + (r - base));
|
||||
base += pr;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
/* FP8 IS ITS CODE TIMES ITS BLOCK'S SCALE (and MXFP4 its code times its exponent): the pieces
|
||||
* are joined along rows, so logical row r is in the piece whose rows cover it, and its scales
|
||||
* are that piece's. */
|
||||
if (!w.scales.empty() && w.scales[0]) {
|
||||
const int64_t br = w.enc.n_planes > 1 ? w.enc.plane[1].block[0] : 128;
|
||||
const int64_t bc = w.enc.n_planes > 1 ? w.enc.plane[1].block[1] : 128;
|
||||
@@ -869,8 +1154,8 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
|
||||
if (why) *why = std::move(m);
|
||||
return rc;
|
||||
};
|
||||
if (!w.trivial || k < 0 || k >= w.enc.n_planes)
|
||||
return refuse(RAD_E_STATE, "not a plane of a trivial encoding");
|
||||
if (!(w.trivial || w.imported) || k < 0 || k >= w.enc.n_planes)
|
||||
return refuse(RAD_E_STATE, "not a plane of a trivial or imported encoding");
|
||||
const std::vector<const SrcTensor*>& src = k == 0 ? w.pieces : w.scales;
|
||||
int64_t pr = 0, pc = 0;
|
||||
rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr, &pc);
|
||||
@@ -878,14 +1163,50 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
|
||||
const uint32_t dt = w.enc.plane[k].dtype;
|
||||
const int64_t eb = rad_dtype_bits(dt) / 8;
|
||||
uint8_t* o = (uint8_t*)dst;
|
||||
if (w.imported) {
|
||||
/* GPTQ-PACKED, RE-LAID: a row of codes is a column of the qweight, its words' bytes in
|
||||
* order -- two codes a byte for int4, low nibble first, as the encoding packs them -- each
|
||||
* offset to signed by flipping the top bit of every field; a row of scales is a column of
|
||||
* the scale tensor, one a 128 of K, rounded to bf16. */
|
||||
int64_t base = 0;
|
||||
for (size_t p = 0; p < w.pieces.size(); ++p) {
|
||||
const SrcTensor& c = *w.pieces[p];
|
||||
const SrcTensor& s = *w.scales[p];
|
||||
const int64_t N = c.shape[0], K = c.shape[1];
|
||||
const uint8_t flip = c.gptq_bits == 4 ? 0x88 : 0x80;
|
||||
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) {
|
||||
const int64_t n = r - base;
|
||||
if (k == 0) {
|
||||
const uint8_t* q = (const uint8_t*)c.data;
|
||||
for (int64_t wi = 0; wi < K * c.gptq_bits / 32; ++wi) {
|
||||
uint32_t v;
|
||||
std::memcpy(&v, q + (wi * N + n) * 4, 4);
|
||||
for (int b = 0; b < 4; ++b) *o++ = (uint8_t)(v >> (8 * b)) ^ flip;
|
||||
}
|
||||
} else {
|
||||
for (int64_t g = 0; g < K / 128; ++g) {
|
||||
const uint16_t h = rad_f32_to_bf16(
|
||||
rad_load_f32(s.data, s.rad_dtype, ((g * 128) / c.gptq_group) * N + n));
|
||||
std::memcpy(o, &h, 2);
|
||||
o += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
base += N;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (k == 0) {
|
||||
/* the codes: the pieces joined, bytes as they are */
|
||||
/* the codes: the pieces joined, bytes as they are. A sub-byte code (MXFP4) joins along
|
||||
* rows of even width, so every run starts and ends on a byte. */
|
||||
const int64_t bits = rad_dtype_bits(dt);
|
||||
Joined j;
|
||||
j.init(src, w.concat_dim);
|
||||
return j.walk(r0 * pc, (r0 + nr) * pc, [&](int p, int64_t e, int64_t n) {
|
||||
std::memcpy(o, (const uint8_t*)src[(size_t)p]->data + e * eb, (size_t)(n * eb));
|
||||
o += n * eb;
|
||||
return RAD_OK;
|
||||
if ((e * bits) % 8 || (n * bits) % 8) return (int)RAD_E_SHAPE;
|
||||
std::memcpy(o, (const uint8_t*)src[(size_t)p]->data + e * bits / 8, (size_t)(n * bits / 8));
|
||||
o += n * bits / 8;
|
||||
return (int)RAD_OK;
|
||||
});
|
||||
}
|
||||
/* an FP8 scale plane: the pieces' scale rows one after another */
|
||||
|
||||
@@ -10,9 +10,16 @@
|
||||
* resolves it to -- concatenations, alternatives and expert slices included -- with the
|
||||
* encoding they already are when that encoding is trivial, and the rows of it on demand.
|
||||
*
|
||||
* Trivial is the set spec §4.3 names: plain f32, f16 and bf16 (GGUF's too), and block-scaled
|
||||
* FP8, where `X.weight_scale_inv` is the scale plane of `X.weight`. Anything else is a weight
|
||||
* whose served form needs quantisation work, which a recipe does ahead of time.
|
||||
* Trivial is the set spec §4.3 names: plain f32, f16 and bf16 (GGUF's too), block-scaled FP8,
|
||||
* where `X.weight_scale_inv` is the scale plane of `X.weight`, and MXFP4 as AMD Quark ships it
|
||||
* (`X.weight` U8 codes, `X.weight_scale` U8 exponents), which is `fp4_e2m1*e8m0[1x32]` byte for
|
||||
* byte. Anything else is a weight whose served form needs quantisation work, which a recipe does
|
||||
* ahead of time -- or, for a published GPTQ-packed release (AutoRound, GPTQ), an IMPORT: the
|
||||
* shipped integer codes and group scales re-laid as an encoding the kernels read, at convert time.
|
||||
*
|
||||
* AN IMPORTED QUANTISATION IS STATED WEIGHT BY WEIGHT. The checkpoint's quantisation descriptor
|
||||
* (`auto-round`, `gptq`, `quark`) names the tool that made it, not a served form, so no
|
||||
* architecture plugin claims it; the plugin is chosen as Checkpoint::imports() describes.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_internal.h"
|
||||
@@ -42,6 +49,13 @@ struct SrcTensor {
|
||||
std::vector<int64_t> shape; /* row-major */
|
||||
const void* data = nullptr;
|
||||
int64_t bytes = 0;
|
||||
/* GPTQ-PACKED (auto_gptq's layout, which AutoRound's `auto_round:auto_gptq` export shares):
|
||||
* `data` is the qweight's int32 words [K * bits / 32, N], each packing 32 / bits codes along
|
||||
* K from the low bits up, stored unsigned with the zero point 2^(bits-1). The tensor this
|
||||
* describes is the logical [N, K] code matrix, `rad_dtype` RAD_I4 or RAD_I8; `gptq_group` is
|
||||
* the K columns one row of its scale tensor covers. 0 for any other tensor. */
|
||||
int32_t gptq_bits = 0;
|
||||
int64_t gptq_group = 0;
|
||||
|
||||
int64_t numel() const {
|
||||
int64_t n = 1;
|
||||
@@ -109,10 +123,29 @@ public:
|
||||
int64_t fp8_block_rows() const { return fp8_br_; }
|
||||
int64_t fp8_block_cols() const { return fp8_bc_; }
|
||||
|
||||
/* THE CHECKPOINT'S QUANTISATION, IMPORTED WEIGHT BY WEIGHT, or None. Read from
|
||||
* quantization_config at open: AutoRound's `auto_round:auto_gptq` export and GPTQ's own (v1,
|
||||
* the zero point stored less one) are Gptq; Quark's MXFP4 (fp4 weights, per_group 32, e8m0
|
||||
* scales, no per-layer overrides) is QuarkMx. A quantisation of one of those tools in a form
|
||||
* this does not read stays None, with the reason in import_refusal(). */
|
||||
/* Its quantization_config keys are then renamed `imported_quantization_config.*`: they
|
||||
* describe the tool, not a served format, and a plugin reads the latter there. */
|
||||
enum class Import { None, Gptq, QuarkMx };
|
||||
Import imports() const { return import_; }
|
||||
const std::string& import_refusal() const { return import_why_; }
|
||||
|
||||
/* The pieces an imported weight is read from, as views owned here: for `name` (a `.weight`)
|
||||
* the GPTQ-packed codes and their scale tensor, or Quark's codes and exponents as their RAD
|
||||
* dtypes. RAD_E_NOTFOUND when the checkpoint ships `name` as an ordinary tensor or not at
|
||||
* all; another error, with `why`, when it ships an imported form this cannot read. */
|
||||
int import_piece(const std::string& name, const SrcTensor** codes, const SrcTensor** scale,
|
||||
std::string* why);
|
||||
|
||||
private:
|
||||
int add_shard(const std::string& p, const std::string& prefix = "");
|
||||
int open_safetensors(const std::string& path);
|
||||
int open_gguf(const std::string& path);
|
||||
void detect_import();
|
||||
|
||||
enum Kind { None, Gguf, SafeT } kind_ = None;
|
||||
std::string path_, dir_;
|
||||
@@ -123,6 +156,10 @@ private:
|
||||
std::unordered_map<std::string, size_t> index_;
|
||||
std::deque<SrcTensor> sliced_; /* views; a deque never moves what it holds */
|
||||
int64_t fp8_br_ = 128, fp8_bc_ = 128;
|
||||
Import import_ = Import::None;
|
||||
std::string import_why_;
|
||||
/* import_piece's answers by name, so a weight resolved twice reads one pair of views. */
|
||||
std::unordered_map<std::string, std::pair<const SrcTensor*, const SrcTensor*>> imported_;
|
||||
};
|
||||
|
||||
/* ================================================================== logical weights */
|
||||
@@ -138,6 +175,11 @@ struct CkptWeight {
|
||||
int64_t rows = 0, cols = 0; /* its [rows, cols] view (rad_enc_view) */
|
||||
/* The encoding the pieces ARE, when it is trivial; `why` says what is not when it is not. */
|
||||
bool trivial = false;
|
||||
/* GPTQ-PACKED PIECES, read into `enc` (`i4` or `i8` codes, bf16 scales a 128 of K) by
|
||||
* ckpt_plane_rows: the codes transposed and offset to signed, the f16 scales rounded to bf16.
|
||||
* Not trivial -- the rounding means the numbers are not served as shipped -- so the loader
|
||||
* refuses one and rad-convert keeps it in `enc`, as it keeps a trivial weight. */
|
||||
bool imported = false;
|
||||
RadEncoding enc{};
|
||||
std::string why;
|
||||
};
|
||||
@@ -161,8 +203,8 @@ bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>&
|
||||
* plain float widened, FP8 times its block scale, a GGUF block type dequantised. */
|
||||
int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::string* why);
|
||||
|
||||
/* Rows [r0, r0 + nr) of plane `k` of a TRIVIAL `w`, in the plane's own elements, dense into
|
||||
* `dst`: the bytes a container entry holds for it. */
|
||||
/* Rows [r0, r0 + nr) of plane `k` of a TRIVIAL or IMPORTED `w`, in the plane's own elements, dense
|
||||
* into `dst`: the bytes a container entry holds for it. */
|
||||
int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
|
||||
std::string* why);
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
/* --rope-scaling, over a container's free-form metadata.
|
||||
*
|
||||
* Static YaRN is read by the architecture (arch/common/rad_arch.h, yarn_from) out of the model's
|
||||
* own keys: `text_config.rope_parameters.`, `rope_parameters.`, `text_config.rope_scaling.`,
|
||||
* `rope_scaling.`, in that order, the FIRST of them that names a rotary type being the one that
|
||||
* counts; a DFlash2 drafter reads `draft.rope_parameters.` / `draft.rope_scaling.` on its own. A
|
||||
* container converted without YaRN therefore needs a reconvert to get it -- or these keys rewritten
|
||||
* when it is loaded, which is all this does. The architecture then resolves the result exactly as
|
||||
* it would a converted container, so there is one reader and one set of checks.
|
||||
*
|
||||
* The rewrite goes into the object the reader would take, not beside it. A Qwen3.8 container says
|
||||
* `text_config.rope_parameters.rope_type = default`; a YaRN written under `rope_parameters.` would
|
||||
* sit behind that and never be read.
|
||||
*
|
||||
* Pure functions over two parallel string vectors, so they are tested without an engine
|
||||
* (tests/yarn_test.cpp holds them to yarn_from). */
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct RopeSpec {
|
||||
enum Kind { Keep, None, Yarn } kind = Keep;
|
||||
double factor = 0.0;
|
||||
int64_t orig = 0; /* 0: the container's own trained length */
|
||||
};
|
||||
|
||||
/* "yarn:FACTOR[:ORIG]" with FACTOR > 1 and ORIG > 0, or "none"; empty is Keep. False for anything
|
||||
* else, so a typo is refused where it was typed. */
|
||||
inline bool rope_spec_parse(const char* s, RopeSpec* out) {
|
||||
RopeSpec r;
|
||||
if (!s || !*s) { *out = r; return true; }
|
||||
if (!std::strcmp(s, "none")) { r.kind = RopeSpec::None; *out = r; return true; }
|
||||
if (std::strncmp(s, "yarn:", 5)) return false;
|
||||
char* e = nullptr;
|
||||
r.factor = std::strtod(s + 5, &e);
|
||||
if (e == s + 5 || !(r.factor > 1.0) || r.factor > 1e6) return false;
|
||||
if (*e == ':') {
|
||||
char* e2 = nullptr;
|
||||
const long long o = std::strtoll(e + 1, &e2, 10);
|
||||
if (e2 == e + 1 || *e2 || o <= 0) return false;
|
||||
r.orig = o;
|
||||
} else if (*e) {
|
||||
return false;
|
||||
}
|
||||
r.kind = RopeSpec::Yarn;
|
||||
*out = r;
|
||||
return true;
|
||||
}
|
||||
|
||||
struct RopeKeys {
|
||||
std::vector<std::string>& k;
|
||||
std::vector<std::string>& v;
|
||||
|
||||
int find(const std::string& key) const {
|
||||
for (size_t i = 0; i < k.size(); ++i)
|
||||
if (k[i] == key) return (int)i;
|
||||
return -1;
|
||||
}
|
||||
const std::string* get(const std::string& key) const {
|
||||
const int i = find(key);
|
||||
return i < 0 ? nullptr : &v[(size_t)i];
|
||||
}
|
||||
void set(const std::string& key, const std::string& val) {
|
||||
const int i = find(key);
|
||||
if (i >= 0) { v[(size_t)i] = val; return; }
|
||||
k.push_back(key);
|
||||
v.push_back(val);
|
||||
}
|
||||
void erase(const std::string& key) {
|
||||
const int i = find(key);
|
||||
if (i < 0) return;
|
||||
k.erase(k.begin() + i);
|
||||
v.erase(v.begin() + i);
|
||||
}
|
||||
bool any_prefix(const char* pre) const {
|
||||
const size_t n = std::strlen(pre);
|
||||
for (const auto& s : k)
|
||||
if (!s.compare(0, n, pre)) return true;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/* The reader's order -- yarn_from's, kept in step with it. */
|
||||
inline std::vector<std::string> rope_homes(const char* group) {
|
||||
if (!*group)
|
||||
return { "text_config.rope_parameters.", "rope_parameters.", "text_config.rope_scaling.",
|
||||
"rope_scaling." };
|
||||
return { std::string(group) + "rope_parameters.", std::string(group) + "rope_scaling." };
|
||||
}
|
||||
|
||||
/* The object the reader takes and the key that names its type, or empty strings when no object
|
||||
* names one (the model's rotary is then the default). */
|
||||
inline void rope_authoritative(const RopeKeys& kv, const char* group, std::string* home,
|
||||
std::string* type_key) {
|
||||
home->clear();
|
||||
type_key->clear();
|
||||
for (const auto& h : rope_homes(group))
|
||||
for (const char* t : { "rope_type", "type" })
|
||||
if (kv.get(h + t)) { *home = h; *type_key = h + t; return; }
|
||||
}
|
||||
|
||||
struct RopeResolved {
|
||||
std::string type; /* "" when nothing names one */
|
||||
double factor = 1.0;
|
||||
double orig = 0.0;
|
||||
};
|
||||
|
||||
inline RopeResolved rope_resolve(std::vector<std::string>& k, std::vector<std::string>& v,
|
||||
const char* group) {
|
||||
RopeKeys kv{ k, v };
|
||||
RopeResolved r;
|
||||
std::string home, tk;
|
||||
rope_authoritative(kv, group, &home, &tk);
|
||||
if (home.empty()) return r;
|
||||
r.type = *kv.get(tk);
|
||||
if (const std::string* f = kv.get(home + "factor")) r.factor = std::strtod(f->c_str(), nullptr);
|
||||
if (const std::string* o = kv.get(home + "original_max_position_embeddings"))
|
||||
r.orig = std::strtod(o->c_str(), nullptr);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Apply SPEC to one rotary group ("" the target, "draft." a DFlash2 drafter). `trained` is the
|
||||
* group's own trained length, the default ORIG. Returns false, with *why set, when the group's
|
||||
* rotary is one this flag does not stack YaRN over (linear position interpolation, say). */
|
||||
inline bool rope_override_group(std::vector<std::string>& k, std::vector<std::string>& v,
|
||||
const RopeSpec& spec, const char* group, int64_t trained,
|
||||
std::string* why) {
|
||||
if (spec.kind == RopeSpec::Keep) return true;
|
||||
RopeKeys kv{ k, v };
|
||||
std::string home, tk;
|
||||
rope_authoritative(kv, group, &home, &tk);
|
||||
const std::string type = home.empty() ? std::string() : *kv.get(tk);
|
||||
if (spec.kind == RopeSpec::None) {
|
||||
if (type == "yarn") kv.set(tk, "default");
|
||||
return true;
|
||||
}
|
||||
/* `mrope` is the legacy Qwen2-VL spelling of default with sections. */
|
||||
if (!type.empty() && type != "default" && type != "mrope" && type != "yarn") {
|
||||
*why = "the " + std::string(*group ? "drafter's" : "model's") + " rotary is '" + type +
|
||||
"' (" + tk + "); YaRN over it is not --rope-scaling's to decide";
|
||||
return false;
|
||||
}
|
||||
if (home.empty()) {
|
||||
home = *group ? std::string(group) + "rope_parameters."
|
||||
: kv.any_prefix("text_config.") ? "text_config.rope_parameters."
|
||||
: "rope_parameters.";
|
||||
tk = home + "rope_type";
|
||||
}
|
||||
/* A checkpoint's own YaRN keeps its trained length unless one is given; anything that was
|
||||
* tied to its old factor goes, so the reader derives it for the new one. */
|
||||
int64_t orig = spec.orig;
|
||||
if (!orig && type == "yarn")
|
||||
if (const std::string* o = kv.get(home + "original_max_position_embeddings"))
|
||||
orig = std::atoll(o->c_str());
|
||||
if (!orig) orig = trained;
|
||||
if (orig <= 0) {
|
||||
*why = "no trained length to scale from; give one: yarn:FACTOR:ORIG";
|
||||
return false;
|
||||
}
|
||||
char buf[64];
|
||||
kv.set(tk, "yarn");
|
||||
std::snprintf(buf, sizeof buf, "%.17g", spec.factor);
|
||||
kv.set(home + "factor", buf);
|
||||
std::snprintf(buf, sizeof buf, "%lld", (long long)orig);
|
||||
kv.set(home + "original_max_position_embeddings", buf);
|
||||
for (const char* stale : { "attention_factor", "mscale", "mscale_all_dim" })
|
||||
kv.erase(home + stale);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* THE ROTARY AS A CACHED KEY DEPENDS ON IT: every key with a path component naming `rope` or
|
||||
* `rotary` -- rope_parameters.*, rope_scaling.*, rope_theta, partial_rotary_factor, their
|
||||
* text_config. and draft. forms, a GGUF's <arch>.rope.* -- as key=value, sorted, after
|
||||
* --rope-scaling has been applied. A persisted prefix store is fingerprinted with it: a container
|
||||
* converted from the same checkpoint with YaRN has the same name and the same shapes, and its
|
||||
* stock-rotated keys (and QSA block keys) read back under YaRN would be attended to at the wrong
|
||||
* angles. Key order and unrelated keys do not change it. */
|
||||
inline std::string rope_identity(const std::vector<std::string>& k,
|
||||
const std::vector<std::string>& v) {
|
||||
auto names_rotary = [](const std::string& key) {
|
||||
size_t s = 0;
|
||||
while (s <= key.size()) {
|
||||
size_t e = key.find('.', s);
|
||||
if (e == std::string::npos) e = key.size();
|
||||
const std::string part = key.substr(s, e - s);
|
||||
if (part.find("rope") != std::string::npos || part.find("rotary") != std::string::npos)
|
||||
return true;
|
||||
s = e + 1;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
std::vector<std::string> rows;
|
||||
for (size_t i = 0; i < k.size() && i < v.size(); ++i)
|
||||
if (names_rotary(k[i])) rows.push_back(k[i] + "=" + v[i]);
|
||||
std::sort(rows.begin(), rows.end());
|
||||
std::string out;
|
||||
for (const auto& r : rows) { out += r; out += ';'; }
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+67
-10
@@ -395,6 +395,27 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
|
||||
return tokens;
|
||||
}
|
||||
|
||||
int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
|
||||
const int64_t MiB = (int64_t)1 << 20;
|
||||
if (max_mib <= 0) return -1;
|
||||
const auto reaches = [&](int64_t mib) {
|
||||
/* The fixed costs (recurrent state, its alignment) come first on every rank -- a rank
|
||||
* whose only paged group is zero still has to hold them. */
|
||||
if (mib * MiB < fixed_) return false;
|
||||
const int64_t t = paged_split(mib * MiB, nullptr);
|
||||
return t == kUnboundedTokens || t >= tokens;
|
||||
};
|
||||
if (!reaches(max_mib)) return -1;
|
||||
/* reaches(hi) holds throughout; lo is the largest size known to fall short (or 0). */
|
||||
int64_t lo = 0, hi = max_mib;
|
||||
if (reaches(lo)) return 0;
|
||||
while (hi - lo > 1) {
|
||||
const int64_t mid = lo + (hi - lo) / 2;
|
||||
if (reaches(mid)) hi = mid; else lo = mid;
|
||||
}
|
||||
return hi;
|
||||
}
|
||||
|
||||
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
|
||||
if (tokens == kUnboundedTokens) return 0;
|
||||
const int64_t b = tokens / p.block_size;
|
||||
@@ -1338,6 +1359,10 @@ void KVManager::free_checkpoint(int32_t slot) {
|
||||
if (ck_store_) ck_store_->free(slot);
|
||||
}
|
||||
|
||||
bool KVManager::checkpoint_held(int32_t slot) const {
|
||||
return ck_store_ && ck_store_->in_use(slot);
|
||||
}
|
||||
|
||||
void* KVManager::checkpoint_ptr(int32_t slot) const {
|
||||
if (!ck_store_) return nullptr;
|
||||
char* p = (char*)ck_store_->at(slot);
|
||||
@@ -1351,11 +1376,29 @@ void* KVManager::checkpoint_ptr(int32_t slot) const {
|
||||
int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot,
|
||||
bool save, RadStream s) {
|
||||
/* A SLOT NOBODY HOLDS IS NOT ONE TO WRITE. Rank 0 hands the ids out, so a follower checks the
|
||||
* shared store rather than a list of its own. */
|
||||
if (!ck_store_ || !ck_store_->in_use(ck_slot)) return RAD_E_INVAL;
|
||||
* shared store rather than a list of its own. Each refusal says which check it is: a slot the
|
||||
* store gave back is a lifetime fault in whoever handed the id out, and nothing about the copy. */
|
||||
const char* dir = save ? "save into" : "restore from";
|
||||
if (!ck_store_) {
|
||||
RAD_ERR("checkpoint %s slot %d: this rank has no snapshot store", dir, (int)ck_slot);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!ck_store_->in_use(ck_slot)) {
|
||||
RAD_ERR("checkpoint %s slot %d: the store does not hold that slot (%lld of %lld in use) -- "
|
||||
"it was given back after its id was handed out", dir, (int)ck_slot,
|
||||
(long long)ck_store_->used_slots(), (long long)ck_store_->capacity());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
char* ck = (char*)checkpoint_ptr(ck_slot);
|
||||
if (!ck) return RAD_E_INVAL;
|
||||
if (!state_slots || n_slots < (int)plans_.size()) return RAD_E_INVAL;
|
||||
if (!ck) {
|
||||
RAD_ERR("checkpoint %s slot %d: the store has no address for it", dir, (int)ck_slot);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!state_slots || n_slots < (int)plans_.size()) {
|
||||
RAD_ERR("checkpoint %s slot %d: %d state slot(s) named for %d group(s)", dir, (int)ck_slot,
|
||||
state_slots ? n_slots : 0, (int)plans_.size());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ONE PITCHED COPY A GROUP. Within a group the state of one sequence is a row a layer, one
|
||||
* layer_stride apart in the pool and packed end to end in the slot, so a group's whole share
|
||||
@@ -1365,20 +1408,34 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
if (!p.stateful()) continue;
|
||||
const int32_t slot = state_slots[g];
|
||||
if (slot < 0) return RAD_E_STATE; /* no state to save, or none to restore into */
|
||||
if (slot < 0) { /* no state to save, or none to restore into */
|
||||
RAD_ERR("checkpoint %s slot %d: the sequence holds no state slot in group %d", dir,
|
||||
(int)ck_slot, (int)g);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const int64_t nbytes = p.layer_bytes_per_state();
|
||||
void* st = state_ptr((int32_t)g, 0, slot);
|
||||
if (!st || p.n_layers <= 0) return RAD_E_STATE;
|
||||
if (!st || p.n_layers <= 0) {
|
||||
RAD_ERR("checkpoint %s slot %d: group %d has no address for state slot %d", dir,
|
||||
(int)ck_slot, (int)g, (int)slot);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (off + nbytes * p.n_layers > checkpoint_bytes_) {
|
||||
RAD_ERR("checkpoint slot %d holds %lld bytes a rank and this sequence's linear state "
|
||||
"needs more than that; the store was sized from the same plans, so the two "
|
||||
"have gone out of step", (int)ck_slot, (long long)checkpoint_bytes_);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
RAD_TRY(save ? rad_memcpy_2d_async(ck + off, nbytes, st, p.layer_stride(), nbytes,
|
||||
p.n_layers, s)
|
||||
: rad_memcpy_2d_async(st, p.layer_stride(), ck + off, nbytes, nbytes,
|
||||
p.n_layers, s));
|
||||
const int cs = save ? rad_memcpy_2d_async(ck + off, nbytes, st, p.layer_stride(), nbytes,
|
||||
p.n_layers, s)
|
||||
: rad_memcpy_2d_async(st, p.layer_stride(), ck + off, nbytes, nbytes,
|
||||
p.n_layers, s);
|
||||
if (cs < 0) {
|
||||
RAD_ERR("checkpoint %s slot %d: the device refused the copy of group %d (%lld rows of "
|
||||
"%lld bytes): %s", dir, (int)ck_slot, (int)g, (long long)p.n_layers,
|
||||
(long long)nbytes, rad_strerror(cs));
|
||||
return cs;
|
||||
}
|
||||
off += nbytes * p.n_layers;
|
||||
}
|
||||
return RAD_OK;
|
||||
|
||||
@@ -182,6 +182,11 @@ public:
|
||||
* cost it nothing, so it takes what the ranks holding the cache carve and limits nobody. */
|
||||
static constexpr int64_t kUnboundedTokens = INT64_MAX;
|
||||
int64_t paged_tokens(int64_t budget_bytes) const { return paged_split(budget_bytes, nullptr); }
|
||||
/* THE INVERSE OF paged_tokens: the least whole MiB of pool whose paged split reaches `tokens`,
|
||||
* searched up to max_mib; -1 when even max_mib does not. Pure arithmetic on the plan (no pool,
|
||||
* no cap), for Engine::plan sizing an uneven world's cheaper rank to the token count its
|
||||
* dearest peer sets. paged_split is monotone in the budget, so the search is exact. */
|
||||
int64_t pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const;
|
||||
void cap_paged_tokens(int64_t tokens) { tokens_cap_ = tokens > 0 ? tokens : 0; }
|
||||
int carve(Pool& kv_pool);
|
||||
|
||||
@@ -435,6 +440,8 @@ public:
|
||||
int alloc_checkpoint(int32_t* slot_out);
|
||||
void free_checkpoint(int32_t slot);
|
||||
void* checkpoint_ptr(int32_t slot) const;
|
||||
/* The store holds `slot`: it was allocated and not given back since. */
|
||||
bool checkpoint_held(int32_t slot) const;
|
||||
|
||||
/* SNAPSHOT AND RESUME A SEQUENCE'S WHOLE LINEAR STATE. This is what makes a prefix hit legal
|
||||
* on a hybrid model: the attention half of a hit is carried by the adopted blocks, and the
|
||||
|
||||
+50
-17
@@ -224,7 +224,8 @@ void PrefixCache::touch(const BlockHash& h) const {
|
||||
|
||||
CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
std::vector<std::vector<int32_t>>* blocks_out) const {
|
||||
std::vector<std::vector<int32_t>>* blocks_out,
|
||||
const HitCap* cap) const {
|
||||
CacheHit hit;
|
||||
if (blocks_out) { blocks_out->assign(groups_.size(), {}); }
|
||||
if (!enabled_ || tokens.empty()) return hit;
|
||||
@@ -261,6 +262,43 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
* forward pass. */
|
||||
if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched;
|
||||
|
||||
/* OVER THE SNAPSHOTS, NOT OVER THE POSITIONS. A checkpoint sits on the interval or at the
|
||||
* tail of a prompt (Scheduler::plan_chunk), which is any block boundary, so the deepest one
|
||||
* at or below `limit` is found by asking each snapshot whether this chain passes through it:
|
||||
* its key is the chained hash at its own position, which matches only on the same prefix. The
|
||||
* index holds a few hundred snapshots against tens of thousands of block positions. */
|
||||
auto deepest = [&](int64_t limit) {
|
||||
auto best = ck_by_prefix_.end();
|
||||
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
|
||||
const Ckpt& c = it->second;
|
||||
if (!c.valid || c.detached || c.slot < 0 || c.pos <= 0 || c.pos > limit ||
|
||||
c.pos % block_size_ != 0)
|
||||
continue;
|
||||
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
|
||||
if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue;
|
||||
best = it;
|
||||
}
|
||||
return best;
|
||||
};
|
||||
/* What a hit of `m` blocks lets a sequence skip: all of it, or with recurrent state only up
|
||||
* to the deepest checkpoint under it (Scheduler::admit_one resumes there). */
|
||||
auto reusable = [&](int64_t m) -> int64_t {
|
||||
if (!has_linear_) return m * block_size_;
|
||||
const auto b = deepest(m * block_size_);
|
||||
return b == ck_by_prefix_.end() ? 0 : b->second.pos;
|
||||
};
|
||||
if (cap && matched > cap->tokens / block_size_) {
|
||||
const int64_t whole = reusable(matched);
|
||||
if (whole > cap->tokens) {
|
||||
const int64_t m = cap->tokens > 0 ? cap->tokens / block_size_ : 0;
|
||||
const int64_t lost = whole - reusable(m);
|
||||
if (lost <= cap->max_give_back) {
|
||||
matched = m;
|
||||
hit.given_back = (int32_t)lost;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int64_t b = 0; b < matched; ++b) {
|
||||
touch(hs[(size_t)b]);
|
||||
if (!blocks_out) continue;
|
||||
@@ -287,21 +325,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
hit.n_linear_tokens = hit.n_attn_tokens;
|
||||
return hit;
|
||||
}
|
||||
/* OVER THE SNAPSHOTS, NOT OVER THE POSITIONS. A checkpoint sits on the interval or at the
|
||||
* tail of a prompt (Scheduler::plan_chunk), which is any block boundary, so the deepest one
|
||||
* under the hit is found by asking each snapshot whether this chain passes through it: its
|
||||
* key is the chained hash at its own position, which matches only on the same prefix. The
|
||||
* index holds a few hundred snapshots against tens of thousands of block positions. */
|
||||
auto best = ck_by_prefix_.end();
|
||||
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
|
||||
const Ckpt& c = it->second;
|
||||
if (!c.valid || c.detached || c.slot < 0 || c.pos <= 0 || c.pos > hit.n_attn_tokens ||
|
||||
c.pos % block_size_ != 0)
|
||||
continue;
|
||||
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
|
||||
if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue;
|
||||
best = it;
|
||||
}
|
||||
const auto best = deepest(hit.n_attn_tokens);
|
||||
if (best == ck_by_prefix_.end()) {
|
||||
++stats_.ckpt_misses;
|
||||
return hit;
|
||||
@@ -716,6 +740,9 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
int64_t freed = 0;
|
||||
for (const auto& a : all) {
|
||||
if (std::binary_search(keep.begin(), keep.end(), a.first)) { kept.push_back(a.second); continue; }
|
||||
/* NOR ONE HANDED OUT THIS STEP, whatever the policy says of its position: the admission it
|
||||
* was handed to restores from the slot ahead of the step, and that is after this runs. */
|
||||
if (handed(a.second)) { kept.push_back(a.second); continue; }
|
||||
auto e = ck_by_prefix_.find(a.second);
|
||||
if (e == ck_by_prefix_.end()) continue;
|
||||
/* A SNAPSHOT THE DISK HOLDS LEAVES THE SLOT AND STAYS IN THE INDEX: the policy is about
|
||||
@@ -769,6 +796,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
*slot_out = existing->second.slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* ONE HANDED OUT THIS STEP IS NOT RETIRED either: an admission restores from it ahead of
|
||||
* the step. This chunk goes without a checkpoint, which costs a later hit some replay. */
|
||||
if (handed(prefix)) return RAD_E_FULL;
|
||||
const uint64_t vs = existing->second.session;
|
||||
retire_ckpt(existing);
|
||||
auto sit = ck_by_session_.find(vs);
|
||||
@@ -817,6 +847,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
/* NOR ONE A DISK WRITE IS READING: its slot comes back only when the write
|
||||
* reports, so retiring it now loses the snapshot and frees nothing yet. */
|
||||
if (tiers_ && tiers_->slot_reading(kvp.second.slot)) continue;
|
||||
/* NOR ONE A LOOKUP HANDED OUT THIS STEP: its admission restores from the slot
|
||||
* ahead of the step, and a slot freed under it restores nothing. */
|
||||
if (handed(kvp.first)) continue;
|
||||
auto sit = ck_by_session_.find(kvp.second.session);
|
||||
bool is_tip = false;
|
||||
if (sit != ck_by_session_.end()) {
|
||||
@@ -945,7 +978,7 @@ bool PrefixCache::free_checkpoint_for_restore() {
|
||||
const Ckpt& c = kvp.second;
|
||||
if (c.detached || c.slot < 0 || !c.valid) continue;
|
||||
if (victim && c.used >= victim->used) continue;
|
||||
if (std::find(handed_.begin(), handed_.end(), kvp.first) != handed_.end()) continue;
|
||||
if (handed(kvp.first)) continue;
|
||||
if (!tiers_->snapshot_backed(kvp.first)) continue;
|
||||
victim = &c;
|
||||
}
|
||||
|
||||
+27
-5
@@ -54,6 +54,7 @@
|
||||
#include "mem/kv.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <list>
|
||||
#include <memory>
|
||||
@@ -108,6 +109,18 @@ struct CacheHit {
|
||||
int32_t n_attn_tokens = 0; /* attention KV reused directly, always a whole block multiple */
|
||||
int32_t n_linear_tokens = 0; /* linear state reused; <= n_attn_tokens, a checkpoint multiple */
|
||||
int32_t checkpoint_slot = -1; /* the snapshot holding that state, -1 if none */
|
||||
int32_t given_back = 0; /* reusable tokens a HitCap took off the whole hit */
|
||||
};
|
||||
|
||||
/* A HIT ENDED EARLY ON PURPOSE. The hit ends no later than `tokens` -- at a block and, for a model
|
||||
* with recurrent state, at the deepest checkpoint at or below it -- unless that gives back more
|
||||
* than `max_give_back` of what the whole hit would reuse, in which case the whole hit stands. It
|
||||
* exists for a drafter whose own KV the cache does not hold (Scheduler::init, --draft-refill):
|
||||
* recomputing the prompt's tail gives it context, and a cap whose nearest checkpoint is far below
|
||||
* would recompute far more than that tail. */
|
||||
struct HitCap {
|
||||
int64_t tokens = 0;
|
||||
int64_t max_give_back = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ retention policy */
|
||||
@@ -181,10 +194,11 @@ public:
|
||||
*
|
||||
* NEVER returns the whole prompt: at least one token must remain for the step to compute a
|
||||
* logit from, so a full hit is backed off by one block. That is not a subtlety the caller
|
||||
* should have to know. */
|
||||
* should have to know. `cap`, when given, ends the hit early (HitCap). */
|
||||
CacheHit lookup(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
std::vector<std::vector<int32_t>>* blocks_out = nullptr) const;
|
||||
std::vector<std::vector<int32_t>>* blocks_out = nullptr,
|
||||
const HitCap* cap = nullptr) const;
|
||||
|
||||
/* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of
|
||||
* cached_groups()[i]. Takes a KV reference on every newly indexed block. */
|
||||
@@ -312,7 +326,9 @@ public:
|
||||
size_t resident_prefix(const std::vector<BlockHash>& chain) const;
|
||||
void release(uint64_t req);
|
||||
/* A step's admissions begin. The snapshots the last step's lookups handed out have been read
|
||||
* by its forward, which committed before this step was planned. */
|
||||
* by its forward, which committed before this step was planned. Until then a handed snapshot
|
||||
* keeps its slot through every path that would give one up: retention, the eviction in
|
||||
* reserve_checkpoint, and free_checkpoint_for_restore. */
|
||||
void begin_step() { handed_.clear(); }
|
||||
/* The tiers lost it -- the disk store let it go, a failed read, or an entry they were told to
|
||||
* forget. Erase the index entry and give back the slot, if it still has one. */
|
||||
@@ -326,7 +342,10 @@ public:
|
||||
bool is_checkpoint(int64_t pos) const { return interval_ > 0 && pos > 0 && pos % interval_ == 0; }
|
||||
|
||||
/* Reserve a snapshot slot for `session` at `pos`. Applies the retention policy when the slot
|
||||
* pool is exhausted, never evicting a session tip. RAD_E_FULL when even that is not enough. */
|
||||
* pool is exhausted, then evicts the least recently used snapshot, a session's tip last. A
|
||||
* snapshot a lookup handed out this step is never given up: the admission it was handed to
|
||||
* restores from the slot ahead of the step, after this reservation was made. RAD_E_FULL when
|
||||
* nothing else can be given up. */
|
||||
int reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix,
|
||||
int32_t* slot_out);
|
||||
/* The state named by `prefix` is now IN its slot. Until this is called the reservation is only
|
||||
@@ -422,8 +441,11 @@ private:
|
||||
bool released_ = false;
|
||||
mutable std::unordered_map<BlockHash, Ckpt, BlockHashHash> ck_by_prefix_;
|
||||
std::unordered_map<uint64_t, std::vector<BlockHash>> ck_by_session_;
|
||||
/* Snapshots lookup handed out since begin_step: not a restore's to take (free_checkpoint_for_restore). */
|
||||
/* Snapshots lookup handed out since begin_step: kept in their slots until then (begin_step). */
|
||||
mutable std::vector<BlockHash> handed_;
|
||||
bool handed(const BlockHash& h) const {
|
||||
return std::find(handed_.begin(), handed_.end(), h) != handed_.end();
|
||||
}
|
||||
mutable uint64_t clock_ = 0;
|
||||
std::unique_ptr<CheckpointPolicy> policy_;
|
||||
mutable Stats stats_;
|
||||
|
||||
@@ -47,10 +47,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
VramBudget b;
|
||||
if (per_rank.empty()) { if (out) *out = b; return RAD_OK; }
|
||||
|
||||
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is applied to every rank. Ranks
|
||||
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is derived for every rank. Ranks
|
||||
* of one deployment normally hold the same shard shapes and the same program, so these folds
|
||||
* are no-ops -- they exist so that a mixed pair degrades to the card that binds instead of
|
||||
* overcommitting the smaller one on the first allocation. */
|
||||
* overcommitting the smaller one on the first allocation. An uneven world's cheaper ranks are
|
||||
* re-split from this answer afterwards (vram_budget_rank_split, called by Engine::plan). */
|
||||
b.capacity = per_rank[0].capacity;
|
||||
int64_t freeb = per_rank[0].free;
|
||||
int64_t layer_max = 0, kv_one = 0;
|
||||
@@ -393,4 +394,23 @@ int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank,
|
||||
return resolve(c, per_rank, out, false);
|
||||
}
|
||||
|
||||
RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_mib,
|
||||
int64_t need_kv_mib, int64_t weights_cap_bytes) {
|
||||
RankSplit s;
|
||||
s.weights_mib = common_weights_mib;
|
||||
s.kv_mib = common_kv_mib;
|
||||
if (need_kv_mib < 0 || need_kv_mib >= common_kv_mib) return s;
|
||||
const int64_t saved = common_kv_mib - need_kv_mib;
|
||||
/* NEVER LESS THAN THE COMMON WEIGHTS POOL, and never more than every weight resident: a weights
|
||||
* pool is one whole allocation, so MiB past what this rank could ever place are left unclaimed
|
||||
* rather than allocated empty. */
|
||||
const int64_t cap = std::max(common_weights_mib, to_mib_up(weights_cap_bytes));
|
||||
const int64_t grown = std::min(common_weights_mib + saved, cap);
|
||||
s.kv_mib = need_kv_mib;
|
||||
s.weights_mib = grown;
|
||||
s.unusable_mib = saved - (grown - common_weights_mib);
|
||||
s.resplit = true;
|
||||
return s;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+18
-1
@@ -125,7 +125,8 @@ struct VramBudget {
|
||||
};
|
||||
|
||||
/* Writes the answer into cfg.vram_weights_mib / cfg.vram_kv_mib -- ONE resolved number that every
|
||||
* consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree.
|
||||
* consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree
|
||||
* (an uneven world's cheaper rank takes its own copy of it: vram_budget_rank_split below).
|
||||
* Takes the SMALLEST capacity and free across ranks and the LARGEST arena, because a split has to
|
||||
* fit on every card it is applied to.
|
||||
*
|
||||
@@ -137,4 +138,20 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
* placement). */
|
||||
int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
|
||||
|
||||
/* AN UNEVEN WORLD'S CHEAPER RANK. The resolver above derives one split, the dearest rank's, and one
|
||||
* block table serves every rank -- so a rank whose cache costs less per token (an attention-zero
|
||||
* rank keeps no attention cache) would reserve the common KV pool for tokens configure_kv then caps
|
||||
* away. Given the common split, the MiB that rank's pool needs to page the SAME tokens, and what
|
||||
* every one of its weights would take resident (statics + all experts + their spare slots), this
|
||||
* moves the difference to its weights pool, no further than that cap; what the cap leaves stays
|
||||
* unclaimed. Nothing changes when the need is not below the common pool. */
|
||||
struct RankSplit {
|
||||
int64_t weights_mib = 0;
|
||||
int64_t kv_mib = 0;
|
||||
int64_t unusable_mib = 0; /* saved from the KV pool but past the weights cap: never allocated */
|
||||
bool resplit = false;
|
||||
};
|
||||
RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_mib,
|
||||
int64_t need_kv_mib, int64_t weights_cap_bytes);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -113,6 +113,15 @@ int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room) {
|
||||
return std::min(all, std::max<int64_t>(all + 2 * wf.expert_unit_max - host_room, 0));
|
||||
}
|
||||
|
||||
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
|
||||
if (p.vram_budget == pool_bytes) return RAD_OK;
|
||||
RAD_ERR("placement: rank %d planned against a %s weights budget (%lld bytes) and its weights "
|
||||
"pool holds %s (%lld bytes): the planner and the pool were given different splits",
|
||||
p.rank, humanb(p.vram_budget).c_str(), (long long)p.vram_budget,
|
||||
humanb(pool_bytes).c_str(), (long long)pool_bytes);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram) {
|
||||
if (!out) return;
|
||||
|
||||
@@ -416,6 +416,13 @@ int64_t file_stage_reserve(int64_t widest, bool routed);
|
||||
* A weight budget of the statics and this much places every expert in VRAM or the host pool. */
|
||||
int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room);
|
||||
|
||||
/* THE PLAN AND ITS RANK'S WEIGHTS POOL READ ONE SPLIT. The planner places against
|
||||
* Plan::vram_budget and the mover fills the pool Pools::configure allocated, each from the Config
|
||||
* it was handed; a rank given two different Configs plans a slab the pool does not have, or leaves
|
||||
* part of the pool unplanned and empty, and nothing downstream would say so. RAD_E_STATE, naming
|
||||
* the rank and both sizes, when they differ. */
|
||||
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes);
|
||||
|
||||
/* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight
|
||||
* that at least one op reads and that only `embed_lookup` reads is a token embedding table, and
|
||||
* one only `embed_lookup_q` reads is an n-gram table. A lookup reads M rows a step, which is what
|
||||
|
||||
+46
-3
@@ -129,6 +129,27 @@ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped =
|
||||
* decides it and writes the answer into Config, so every rank plans from one choice. */
|
||||
enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 };
|
||||
const char* table_placement_name(TablePlacement p);
|
||||
/* --draft-window: how many drafts a step verifies for each sequence (core/sched/draft.h).
|
||||
* Fixed every sequence drafts --num-speculative-tokens.
|
||||
* Adaptive that is the ceiling; each step's head depth and each sequence's stop follow the
|
||||
* measured acceptance and the measured step cost. A serial drafter's policy only.
|
||||
* The default is kDraftWindowDefault, and the help text and the startup line read it from there.
|
||||
*
|
||||
* FIXED IS THE DEFAULT BECAUSE ADAPTIVE LOSES WHERE A SERVER IS BUSY. Qwen3.8-Flash-Next at TP2 on
|
||||
* two R9700, distinct prompts a sequence, tokens a second over a steady window against fixed depth 3:
|
||||
*
|
||||
* concurrent sequences 1 2 4 8
|
||||
* adaptive, ceiling 3 +0.4% -0.1% +1.7% -0.3%
|
||||
* adaptive, ceiling 5 +7.1% -2.3% +7.4% -11.9%
|
||||
*
|
||||
* At eight the head runs five rounds for little more text: 43.0 against 36.3 ms a step (1.18x) for
|
||||
* 23.3 against 22.3 tokens. The cost model's prior puts depth 5 over depth 3 at 1.10x, and a depth
|
||||
* not yet timed at a load is priced on the prior. */
|
||||
enum class DraftWindow { Fixed = 0, Adaptive = 1 };
|
||||
constexpr DraftWindow kDraftWindowDefault = DraftWindow::Fixed;
|
||||
inline const char* draft_window_name(DraftWindow w) {
|
||||
return w == DraftWindow::Adaptive ? "adaptive" : "fixed";
|
||||
}
|
||||
enum class Site { Device = 0, DeviceStaged = 1, DeviceZeroCopy = 2, Host = 3 };
|
||||
|
||||
/* Tier-indexed arrays are sized by this rather than by a literal: the report, the live view and
|
||||
@@ -583,6 +604,9 @@ struct Request {
|
||||
|
||||
/* ================================================================== engine config */
|
||||
|
||||
/* --p2p: whether the collectives use the cards' peer access. */
|
||||
enum { RAD_P2P_AUTO = 0, RAD_P2P_ON = 1, RAD_P2P_OFF = 2 };
|
||||
|
||||
struct Config {
|
||||
std::string model; /* path to the .rad */
|
||||
std::string radiance_home;
|
||||
@@ -609,9 +633,21 @@ struct Config {
|
||||
* floor that compresses everything which benefits while leaving single-sequence decode
|
||||
* exact. */
|
||||
int64_t tp_wire_min_kb = 128; /* --tp-wire-min-kb */
|
||||
/* HOW THE COLLECTIVES REACH THE OTHER CARDS. Auto asks the driver, for every ordered pair of
|
||||
* the ranks' cards, whether one can address the other's memory, and takes the P2P kernels only
|
||||
* if every pair can. A driver can answer yes on a board where peer traffic is broken or slower
|
||||
* than going through host memory, and that is what `off` is for: it takes the host-mailbox
|
||||
* collectives whatever the driver says. `on` takes the P2P kernels and stops startup naming
|
||||
* the pairs the driver refuses, rather than falling back -- a deployment that was measured on
|
||||
* P2P should not quietly serve on something else. */
|
||||
int p2p = RAD_P2P_AUTO; /* --p2p auto|on|off */
|
||||
int64_t max_tok = 8192; /* --max-num-batched-tokens */
|
||||
int64_t max_seqs = 256;
|
||||
int64_t max_ctx = 0; /* 0 = the model's training context */
|
||||
/* --rope-scaling: "yarn:FACTOR[:ORIG]" writes YaRN over the checkpoint's own rotary keys (the
|
||||
* model card's extension past its trained context, no reconvert); "none" takes a checkpoint's
|
||||
* YaRN off; empty serves what the checkpoint says. Engine::apply_rope_scaling. */
|
||||
std::string rope_scaling;
|
||||
|
||||
/* THE OPERATOR STATES A BUDGET OR THE ENGINE DERIVES ONE FROM THE CARD, AND EITHER WAY IT IS
|
||||
* STATED IN FULL BEFORE ANYTHING IS ALLOCATED.
|
||||
@@ -623,7 +659,10 @@ struct Config {
|
||||
* what the driver already holds is measured rather than assumed. core/mem/vram_budget.cpp does
|
||||
* that sum and writes the answer back into the two fields below, so every consumer downstream
|
||||
* -- the planner, the KV manager, the pool report -- reads one resolved number and there is no
|
||||
* second place for them to disagree.
|
||||
* second place for them to disagree. Engine::plan derives each rank's own copy from it
|
||||
* (rank_cfg_, see docs/TP3.md §1), and the rank's pools and planner both read that copy --
|
||||
* still one number per card, and the same number on every card whose cache costs as much per
|
||||
* token as the dearest rank's.
|
||||
*
|
||||
* Zero means "derive"; a stated --vram-weights-mib / --vram-kv-mib still wins outright. */
|
||||
int64_t vram_weights_mib = 0;
|
||||
@@ -710,8 +749,8 @@ struct Config {
|
||||
* code object, which HIP loads on the kernel's FIRST LAUNCH and not at startup, and which
|
||||
* faults inside the HIP runtime rather than returning an error when there is no room. */
|
||||
|
||||
/* The speculative window, and the whole of the draft policy: the depth is constant and this
|
||||
* is it. See core/sched/draft.h. */
|
||||
/* The speculative window: the depth, or under --draft-window adaptive its ceiling. See
|
||||
* core/sched/draft.h. */
|
||||
/* -1 is `auto`: engine_bringup asks rad_arch_probe for the depth THIS container's drafter was
|
||||
* trained at, and a container with no draft head resolves to 0 with a line saying so.
|
||||
*
|
||||
@@ -721,6 +760,7 @@ struct Config {
|
||||
* paying for it again in VRAM, and then running at one token a step -- a small fraction of
|
||||
* the throughput the same container gives at its declared depth. */
|
||||
int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */
|
||||
DraftWindow draft_window = kDraftWindowDefault; /* --draft-window */
|
||||
|
||||
/* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ----------------
|
||||
*
|
||||
@@ -745,6 +785,9 @@ struct Config {
|
||||
/* The chat endpoint's default `reasoning_effort`, empty for the template's own default.
|
||||
* Passed through verbatim: the legal set belongs to the template, not to us. */
|
||||
std::string reasoning_effort;
|
||||
/* --reasoning-effort-map FROM=TO,...: an effort a request sends, replaced before the template
|
||||
* sees it. */
|
||||
std::map<std::string, std::string> reasoning_effort_map;
|
||||
/* --thinking-token-budget: the chat endpoint's default `thinking_token_budget`, -1 for none. */
|
||||
int64_t thinking_token_budget = -1;
|
||||
int port = 8000;
|
||||
|
||||
@@ -73,6 +73,10 @@ struct StepEntry {
|
||||
bool draft_out = false;
|
||||
bool is_prefill = false;
|
||||
bool produces_token = false; /* this entry's last token is the sequence's last */
|
||||
/* ITS DRAFTS CAME FROM PROMPT LOOKUP, not from the declared drafter. Their outcome is counted
|
||||
* in the reported acceptance like any other, and kept out of the adaptive window's estimate,
|
||||
* which describes the draft head (DraftController, draft.h). */
|
||||
bool ngram = false;
|
||||
/* A DEVICE ROW: the card fills its tokens, positions, rollback count and slots from the slot's
|
||||
* StepSlot before the pass runs (advance.h), and what the host staged for them is replaced.
|
||||
* `ctx_len` is then an upper bound, which is what the host-side ceilings read. The other three
|
||||
|
||||
+255
-1
@@ -1,9 +1,46 @@
|
||||
/* draft.cpp -- the static draft-depth policy. See draft.h for why it is static.
|
||||
/* draft.cpp -- the static draft-depth policy, and the adaptive one `--draft-window adaptive` turns
|
||||
* on. See draft.h for why the first is the default and what the second changes.
|
||||
*/
|
||||
#include "draft.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
/* THE STEP-COST PRIOR, a shape and not a measurement: every draft adds six percent to a step --
|
||||
* one round of a serial head and one more verify row against a weight-bound step. It prices a
|
||||
* depth nothing has measured yet, and only its RATIOS are read once anything has been measured:
|
||||
* an unmeasured depth is the nearest measured one scaled by prior(d) / prior(d'). */
|
||||
constexpr double kCostSlope = 0.06;
|
||||
double cost_prior(int d) { return 1.0 + kCostSlope * (double)d; }
|
||||
|
||||
/* A STEP TIME'S MEAN IS A RUNNING MEAN FOR ITS FIRST STEPS AND THEN A MOVING AVERAGE WITH A
|
||||
* HALF-LIFE OF 32 STEPS. Long enough that the scatter of one step against the next -- a tier
|
||||
* copy, a recording, a prefix-cache trim -- averages out; short enough to follow a context that
|
||||
* grows by a few thousand tokens over a reply. */
|
||||
constexpr double kCostHalfLife = 32.0;
|
||||
/* AND ONE STEP COUNTS FOR AT MOST FOUR TIMES THE KEY'S MEAN, once the mean is over four steps. A
|
||||
* step that waited on something other than its own work -- a first recording, an allocation, a
|
||||
* host stall -- says nothing about what its depth costs, and one such step would otherwise move a
|
||||
* short mean by more than any depth. A mean over fewer steps is not yet a reference to clip
|
||||
* against: its first step may itself be the odd one. */
|
||||
constexpr double kCostOutlier = 4.0;
|
||||
constexpr int64_t kCostClipAfter = 4;
|
||||
|
||||
/* THE PRIOR WEIGHS AS MUCH AS THIS MANY VERIFIES. The (n+1)-th real one moves an estimate by
|
||||
* 1 / (n + k + 1) -- a running mean over the prior and the evidence -- until that step falls below
|
||||
* the half-life's, and from then on it is the moving average it is meant to be. Without it a
|
||||
* sequence would spend its first ~16 verifies at whatever window the prior chose, which is most of
|
||||
* a short answer. */
|
||||
constexpr double kPriorWeight = 4.0;
|
||||
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int DraftController::configure(const Params& p) {
|
||||
if (p.max_depth < 0 || p.max_depth > RAD_SCHED_MAX_SPEC) {
|
||||
RAD_ERR("draft depth %d is outside 0..%d -- the verify kernel band is %d query rows",
|
||||
@@ -14,6 +51,24 @@ int DraftController::configure(const Params& p) {
|
||||
tot_drafted_ = tot_accepted_ = 0;
|
||||
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) { reach_[j] = 0; hit_[j] = 0; }
|
||||
seen_ = 0;
|
||||
|
||||
adapt_ = p.adapt && p.max_depth > 0;
|
||||
alpha_ = 1.0 - std::exp2(-1.0 / kHalfLife);
|
||||
step_d_ = 0;
|
||||
step_w_ = 0;
|
||||
step_held_ = 0;
|
||||
prior_n_ = 0;
|
||||
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) prior_[j] = 0.0f;
|
||||
for (int d = 0; d <= RAD_SCHED_MAX_SPEC; ++d) {
|
||||
by_depth_[d] = 0;
|
||||
for (int c = 0; c < kCostClasses; ++c) { cost_ms_[d][c] = 0.0; cost_n_[d][c] = 0; }
|
||||
}
|
||||
if (adapt_)
|
||||
RAD_INFO("draft depth: ADAPTIVE (--draft-window adaptive), %d..%d -- the step's head depth "
|
||||
"maximises the tokens its sequences are expected to emit over the step's measured "
|
||||
"cost, and a sequence stops at the first draft emitted less than %.0f%% of the "
|
||||
"time; moves at +%.0f%% and at most every %d steps",
|
||||
kMinDepth, p_.max_depth, 100.0 * kDraftMinChance, 100.0 * kHyst, kHold);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -34,6 +89,205 @@ void DraftController::observe(int drafted, int accepted) {
|
||||
if (j < accepted) ++hit_[j];
|
||||
}
|
||||
if (drafted > seen_) seen_ = drafted;
|
||||
if (adapt_) ++by_depth_[drafted];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step's cost */
|
||||
int DraftController::cost_class(int n_rows) {
|
||||
int c = 0;
|
||||
while (c + 1 < kCostClasses && n_rows >= (2 << c)) ++c;
|
||||
return c;
|
||||
}
|
||||
|
||||
void DraftController::step_time(int depth, int n_rows, double ms) {
|
||||
if (!adapt_ || depth < 1 || depth > p_.max_depth || n_rows < 1 || !(ms > 0.0) ||
|
||||
!std::isfinite(ms))
|
||||
return;
|
||||
const int c = cost_class(n_rows);
|
||||
double& m = cost_ms_[depth][c];
|
||||
int64_t& n = cost_n_[depth][c];
|
||||
if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
|
||||
const double w = std::fmax(1.0 - std::exp2(-1.0 / kCostHalfLife), 1.0 / (double)(n + 1));
|
||||
m = n ? m + w * (ms - m) : ms;
|
||||
++n;
|
||||
}
|
||||
|
||||
int64_t DraftController::cost_samples(int depth, int n_rows) const {
|
||||
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC || n_rows < 1) return 0;
|
||||
return cost_n_[depth][cost_class(n_rows)];
|
||||
}
|
||||
|
||||
double DraftController::step_cost(int depth, int n_rows) const {
|
||||
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC) return 0.0;
|
||||
const int c = n_rows >= 1 ? cost_class(n_rows) : 0;
|
||||
if (cost_n_[depth][c] > 0) return cost_ms_[depth][c];
|
||||
/* THE NEAREST MEASURED KEY: in this class first, the nearest depth and the shallower on a
|
||||
* tie; then the nearest class. Only its ratio to the prior is borrowed, so a class whose steps
|
||||
* are twice as dear prices every depth twice as dear, and the comparison D makes -- depths at
|
||||
* ONE class -- reads the prior's shape until its own depths are measured. */
|
||||
for (int dc = 0; dc < kCostClasses; ++dc) {
|
||||
for (int sgn = 0; sgn < 2; ++sgn) {
|
||||
const int k = sgn ? c + dc : c - dc;
|
||||
if (k < 0 || k >= kCostClasses || (dc == 0 && sgn)) continue;
|
||||
int best = -1;
|
||||
for (int d = 1; d <= p_.max_depth; ++d) {
|
||||
if (cost_n_[d][k] <= 0) continue;
|
||||
if (best < 0 || std::abs(d - depth) < std::abs(best - depth)) best = d;
|
||||
}
|
||||
if (best > 0) return cost_ms_[best][k] * cost_prior(depth) / cost_prior(best);
|
||||
}
|
||||
}
|
||||
return cost_prior(depth);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ one sequence */
|
||||
int DraftController::stop_of(const float* a) const {
|
||||
double p = 1.0;
|
||||
int d = 0;
|
||||
while (d < p_.max_depth) {
|
||||
p *= (double)a[d];
|
||||
if (p < kDraftMinChance) break;
|
||||
++d;
|
||||
}
|
||||
return d < kMinDepth ? kMinDepth : d;
|
||||
}
|
||||
|
||||
double DraftController::prior_at(int j) const {
|
||||
if (j < 0 || j >= RAD_SCHED_MAX_SPEC) return 0.0;
|
||||
return prior_n_ >= kPriorMinSeqs ? (double)prior_[j] : kPrior;
|
||||
}
|
||||
|
||||
void DraftController::start(DraftAdapt& s) const {
|
||||
/* Each position from the sequences that finished before it once there are enough of them
|
||||
* (adapt_retire); otherwise from the fixed prior, which is optimistic on purpose (kPrior). */
|
||||
for (int j = 0; j < p_.max_depth; ++j) {
|
||||
s.a[j] = (float)prior_at(j);
|
||||
s.n[j] = 0;
|
||||
}
|
||||
s.depth = stop_of(s.a);
|
||||
s.held = 0;
|
||||
}
|
||||
|
||||
void DraftController::adapt_retire(const DraftAdapt& s) {
|
||||
if (!adapt_ || s.depth <= 0 || (double)s.n[0] < kHalfLife) return;
|
||||
const double w = std::fmax(1.0 - std::exp2(-1.0 / kPriorHalfLifeSeqs),
|
||||
1.0 / (double)(prior_n_ + 1));
|
||||
for (int j = 0; j < p_.max_depth; ++j)
|
||||
prior_[j] = prior_n_ ? (float)((double)prior_[j] + w * ((double)s.a[j] - (double)prior_[j]))
|
||||
: s.a[j];
|
||||
++prior_n_;
|
||||
}
|
||||
|
||||
double DraftController::yield(const DraftAdapt& s, int d) const {
|
||||
if (d > p_.max_depth) d = p_.max_depth;
|
||||
double e = 1.0, run = 1.0;
|
||||
for (int k = 1; k <= d; ++k) { run *= (double)s.a[k - 1]; e += run; }
|
||||
return e;
|
||||
}
|
||||
|
||||
int DraftController::window_of(const DraftAdapt& s) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) return 0;
|
||||
const int D = step_d_ > 0 ? step_d_ : p_.max_depth;
|
||||
return s.depth < D ? s.depth : D;
|
||||
}
|
||||
|
||||
int DraftController::window_for(DraftAdapt& s) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) start(s);
|
||||
return window_of(s);
|
||||
}
|
||||
|
||||
int DraftController::adapt_observe(DraftAdapt& s, int drafted, int accepted) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) start(s);
|
||||
if (drafted <= 0) return s.depth;
|
||||
const int D = p_.max_depth;
|
||||
if (drafted > D) drafted = D;
|
||||
if (accepted < 0) accepted = 0;
|
||||
if (accepted > drafted) accepted = drafted;
|
||||
|
||||
/* THE POSITIONS THIS VERIFY EVALUATED, by observe()'s rule: every one before the first
|
||||
* rejection, taken, and the rejected one, refused. A position behind the rejection was drafted
|
||||
* and never looked at, and says nothing either way. */
|
||||
const int last = accepted < drafted ? accepted : drafted - 1;
|
||||
for (int j = 0; j <= last; ++j) {
|
||||
const double w = std::fmax(alpha_, 1.0 / ((double)s.n[j] + kPriorWeight + 1.0));
|
||||
const double x = j < accepted ? 1.0 : 0.0;
|
||||
s.a[j] = (float)((double)s.a[j] + w * (x - (double)s.a[j]));
|
||||
if (s.n[j] < UINT16_MAX) ++s.n[j];
|
||||
}
|
||||
/* AND THE POSITIONS THE WINDOW DID NOT REACH DRIFT TOWARD THE DEEPEST ONE IT DID. Nothing is
|
||||
* learned about them while the window is shorter -- and a sequence held at three by prose that
|
||||
* turns into code would otherwise keep pricing positions four and up at whatever they read
|
||||
* before, and never draft deep enough to find out. The guess is that acceptance decays with
|
||||
* position rather than falling off a cliff, so the window's edge stands in for what lies past
|
||||
* it. Where that is wrong it costs a move out, the verifies that refute it, and a move back. */
|
||||
const double edge = (double)s.a[drafted - 1];
|
||||
for (int j = drafted; j < D; ++j)
|
||||
s.a[j] = (float)((double)s.a[j] + alpha_ * (edge - (double)s.a[j]));
|
||||
|
||||
/* THE STOP MOVES ONLY PAST THE HOLD: it is this sequence's share of the step's shape. */
|
||||
if (s.held < INT32_MAX) ++s.held;
|
||||
if (s.held < kHold) return s.depth;
|
||||
const int d = stop_of(s.a);
|
||||
if (d != s.depth) {
|
||||
s.depth = d;
|
||||
s.held = 0;
|
||||
}
|
||||
return s.depth;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step */
|
||||
int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
|
||||
if (!adapt_ || n_seq <= 0) return step_d_;
|
||||
if (n_rows < n_seq) n_rows = n_seq;
|
||||
const int M = p_.max_depth;
|
||||
|
||||
/* THE STEP'S EXPECTED TOKENS AT EVERY HEAD DEPTH: sum_i E_i(min(D, stop_i)), plus one for
|
||||
* every row that does not draft. A depth past every stop is the deepest stop's step -- no
|
||||
* sequence drafts further and the head runs no further -- so the candidates end there. */
|
||||
double tok[RAD_SCHED_MAX_SPEC + 1] = {};
|
||||
int top = kMinDepth;
|
||||
for (int i = 0; i < n_seq; ++i) {
|
||||
DraftAdapt& s = *seq[i];
|
||||
if (s.depth <= 0) start(s);
|
||||
if (s.depth > top) top = s.depth;
|
||||
double e = 1.0, run = 1.0;
|
||||
for (int d = 1; d <= M; ++d) {
|
||||
if (d <= s.depth) { run *= (double)s.a[d - 1]; e += run; }
|
||||
tok[d] += e;
|
||||
}
|
||||
}
|
||||
const double plain = (double)(n_rows - n_seq);
|
||||
if (top > M) top = M;
|
||||
|
||||
int best = kMinDepth;
|
||||
double best_g = -1.0;
|
||||
for (int d = kMinDepth; d <= top; ++d) {
|
||||
const double g = (tok[d] + plain) / step_cost(d, n_rows);
|
||||
if (g > best_g) { best_g = g; best = d; }
|
||||
}
|
||||
|
||||
/* THE MOVE, rate-limited twice: not within kHold steps of the last one, and only for a depth
|
||||
* worth kHyst more than the one in force. The first step that drafts takes the best outright. */
|
||||
if (step_d_ <= 0) {
|
||||
step_d_ = best;
|
||||
step_held_ = 0;
|
||||
} else {
|
||||
if (step_held_ < INT32_MAX) ++step_held_;
|
||||
const int cur = step_d_ < top ? step_d_ : top;
|
||||
const double cur_g = (tok[cur] + plain) / step_cost(cur, n_rows);
|
||||
if (best != cur && step_held_ >= kHold && best_g > cur_g * (1.0 + kHyst)) {
|
||||
RAD_DEBUG("draft window: head depth %d -> %d over %d drafting of %d rows (%.3f -> "
|
||||
"%.3f tokens per unit of step cost)", step_d_, best, n_seq, n_rows, cur_g,
|
||||
best_g);
|
||||
step_d_ = best;
|
||||
step_held_ = 0;
|
||||
}
|
||||
}
|
||||
step_w_ = step_d_ < top ? step_d_ : top;
|
||||
return step_d_;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+190
-4
@@ -1,8 +1,8 @@
|
||||
/* draft.h -- the speculative draft-depth controller.
|
||||
*
|
||||
* IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
|
||||
* BY DEFAULT IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
|
||||
*
|
||||
* No dynamic policy sits here, and the reason is structural rather than a tuning failure. The
|
||||
* No dynamic policy sits there, and the reason is structural rather than a tuning failure. The
|
||||
* dynamic policy this engine is otherwise modelled on -- a confidence-product gate against a
|
||||
* decayed per-position acceptance estimate, plus a batch-size ceiling schedule -- gates on the
|
||||
* DRAFTER's own top-1 confidences, per slot, on device, after the drafter has run. The scheduler
|
||||
@@ -16,6 +16,42 @@
|
||||
*
|
||||
* What survives is the accounting, because the acceptance rate is a reported metric (spec §14)
|
||||
* and because a verify that accepts nothing has to be visible.
|
||||
*
|
||||
* UNDER `--draft-window adaptive` THE PREMISE ABOVE IS WHAT DOES NOT HOLD. On a model whose
|
||||
* weights stream -- a MoE that reads experts per verify row, a serial head that runs one pass a
|
||||
* round -- a step is NOT flat in depth: each draft is one more round of the head and one more
|
||||
* verify row. And the best depth is not a property of the model pair but of the TEXT:
|
||||
* per-position acceptance stays high deep into the window on code and JSON and falls off after a
|
||||
* position or two on prose and summaries. No constant is right for all of them, and the one that
|
||||
* is right for one costs the others either rounds nobody accepts or tokens nobody drafted.
|
||||
*
|
||||
* So the adaptive window is a policy on the host, in two halves:
|
||||
*
|
||||
* PER SEQUENCE (DraftAdapt): a smoothed estimate of each draft position's conditional
|
||||
* acceptance, fed by the same verify outcomes observe() counts, and the sequence's STOP -- the
|
||||
* deepest draft whose chance of being emitted still pays for the verify row it adds
|
||||
* (kDraftMinChance).
|
||||
*
|
||||
* PER STEP (plan_step): the HEAD DEPTH D. A serial head runs as many rounds as the deepest
|
||||
* window in the step, so depth is a property of the step and not of one sequence: D maximises
|
||||
* the tokens the whole step is expected to emit, sum_i E_i(min(D, stop_i)), over what a step
|
||||
* at that depth and that many sequences costs, T(D, n) -- with E(d) = 1 + sum_k prod_{j<=k} a_j
|
||||
* and T measured online (step_time). Every sequence then drafts min(D, stop_i).
|
||||
*
|
||||
* Both move only past a hold, and D also past a hysteresis, because a window is a pass shape and
|
||||
* a new shape is a new recording before it plays (runtime/ctx.h). `max_depth` stays the ceiling,
|
||||
* and everything sized for it stays sized for it.
|
||||
*
|
||||
* IT IS THE SERIAL DRAFTER'S POLICY. A block drafter proposes its whole block in one pass, and
|
||||
* prompt lookup runs no pass at all, so neither pays the rounds the policy prices; the scheduler
|
||||
* turns it on only for a serial drafter (Scheduler::init) and says so when it does not.
|
||||
*
|
||||
* IT CHANGES HOW MANY DRAFTS A STEP VERIFIES AND NOTHING ELSE. Acceptance is the rule in
|
||||
* core/sample/accept.h, so what a step emits is the target's own token at every position whatever
|
||||
* window it verified. At temperature 0 that is the same text at every window, to exactly the
|
||||
* degree a speculative run matches a plain one at all: exact given the same logits, and a verify
|
||||
* row's logits are computed at an M that now moves with the window (accept.h says what that does
|
||||
* and does not change).
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
@@ -26,18 +62,148 @@ namespace rad {
|
||||
* band (spec §10), so 64 is the largest window any batch can carry. */
|
||||
enum { RAD_SCHED_MAX_SPEC = 64 };
|
||||
|
||||
/* ONE SEQUENCE'S HALF OF THE ADAPTIVE POLICY: what the drafter has done on this sequence's own
|
||||
* text, and how deep that makes it worth drafting. It lives in the scheduler's per-request state
|
||||
* and the controller does the arithmetic, so neither has to look the other up.
|
||||
*
|
||||
* `depth` 0 is "not started": the first ask fills the estimate from the prior and sets the stop.
|
||||
* It belongs to the REQUEST, not to the cache it holds -- a preemption keeps it, because the text
|
||||
* it describes is still the text the request is writing -- and a recycled slot starts it over. */
|
||||
struct DraftAdapt {
|
||||
int32_t depth = 0; /* the sequence's stop; 0 = not started */
|
||||
int32_t held = 0; /* verifies since `depth` last moved */
|
||||
float a[RAD_SCHED_MAX_SPEC] = {}; /* conditional acceptance at each draft position */
|
||||
uint16_t n[RAD_SCHED_MAX_SPEC] = {}; /* verifies that evaluated each one, saturating */
|
||||
};
|
||||
|
||||
class DraftController {
|
||||
public:
|
||||
struct Params {
|
||||
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
|
||||
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
|
||||
/* THE ADAPTIVE POLICY (see the top of this file): `--draft-window adaptive` with a serial
|
||||
* drafter, which Scheduler::init decides. Off, the depth is max_depth, as it always was. */
|
||||
bool adapt = false;
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------- the policy's constants
|
||||
* Named rather than configurable: each is a property of how the policy works, not of a
|
||||
* deployment, and the one property that IS a deployment's -- what a step costs -- is
|
||||
* measured (step_time). */
|
||||
|
||||
/* A WINDOW MOVES ONLY FOR TWO PERCENT MORE YIELD. One draft more or less moves E/T by several
|
||||
* percent on any drafter worth speculating with, while a smoothed estimate wobbles by about
|
||||
* a percent verify to verify; below two percent a move would flip D between two near-equal
|
||||
* neighbours and pay a recording each time. */
|
||||
static constexpr double kHyst = 0.02;
|
||||
/* AND NOT WITHIN EIGHT VERIFIES (steps, for D) OF THE LAST MOVE. A pass shape is recorded the
|
||||
* second time its key is seen and played from the third (runtime/ctx.h), so a shape held for
|
||||
* eight steps plays from the tape for most of them; and eight verifies at the half-life below
|
||||
* move an estimate by about a third of the way to a new rate, which is a trend rather than
|
||||
* one rejection. */
|
||||
static constexpr int kHold = 8;
|
||||
/* EACH POSITION'S ESTIMATE HAS A HALF-LIFE OF SIXTEEN VERIFIES THAT EVALUATE IT. At a few
|
||||
* tokens a verify that is some fifty tokens of text: short enough to follow a reply from prose
|
||||
* into a code block and back, long enough that a single rejection moves an estimate by four
|
||||
* percent rather than resetting it. */
|
||||
static constexpr double kHalfLife = 16.0;
|
||||
/* A POSITION NOTHING HAS MEASURED STARTS AT 0.8, optimistic on purpose: a window that starts
|
||||
* deep evaluates every position and learns all of them, one that starts shallow learns nothing
|
||||
* about the positions it never drafts to. 0.8 sits between what draft heads measure on prose
|
||||
* and on code at the first positions, so a wrong start is corrected within a hold. */
|
||||
static constexpr double kPrior = 0.8;
|
||||
/* ONCE FOUR SEQUENCES HAVE FINISHED, A NEW ONE STARTS FROM WHAT THEY ENDED ON (adapt_retire):
|
||||
* the mean of their estimates, a running mean and then a moving average with a half-life of 32
|
||||
* sequences, so a deployment that moves from one kind of traffic to another follows it within
|
||||
* a few dozen requests. Four, because a mean over fewer is one text's. A sequence counts only
|
||||
* once it has had a half-life of verifies: before that its estimate is mostly the prior it
|
||||
* started from, and folding it back would feed the prior to itself. */
|
||||
static constexpr int kPriorMinSeqs = 4;
|
||||
static constexpr double kPriorHalfLifeSeqs = 32.0;
|
||||
/* NEVER FEWER THAN ONE DRAFT. A sequence at zero would evaluate no position, so nothing could
|
||||
* ever move its estimate off zero again. */
|
||||
static constexpr int kMinDepth = 1;
|
||||
/* A SEQUENCE STOPS AT THE FIRST DRAFT WHOSE CHANCE OF BEING EMITTED -- every draft before it
|
||||
* and itself accepted, prod_{j<=d} a_j -- IS UNDER ONE IN TEN. The draft adds a verify row to
|
||||
* the step whatever D is, and that row is the only cost a sequence adds once the head runs D
|
||||
* rounds for its deepest neighbour. At one sequence the step-cost prior (1 + 0.06 d) already
|
||||
* breaks even near that chance -- one more draft is worth it while p_d / E exceeds the 5-6 %
|
||||
* it adds to the step, with E around two -- and a verify row alone costs less than a round
|
||||
* plus a row, so the threshold is never stricter than D's own trade. A constant rather than a
|
||||
* measurement: a row's share of the step is not separable from the head's rounds in step
|
||||
* times keyed by depth, and the measured T(D, n) already prices the rounds. */
|
||||
static constexpr double kDraftMinChance = 0.1;
|
||||
/* STEP TIMES ARE KEPT IN THESE RUNNING-SEQUENCE CLASSES: 1, 2-3, 4-7, 8-15, 16 and up. A
|
||||
* step's cost moves with how many rows share its weight reads, and a class a power of two
|
||||
* wide keeps every key fed often enough to mean something. */
|
||||
static constexpr int kCostClasses = 5;
|
||||
|
||||
int configure(const Params& p);
|
||||
const Params& params() const { return p_; }
|
||||
|
||||
/* The draft depth for the next step. 0 means "do not speculate". Constant by construction. */
|
||||
/* The draft depth for the next step. 0 means "do not speculate". Constant by construction:
|
||||
* under the adaptive policy it is the CEILING, and window_for() is the window. */
|
||||
int next_depth() const { return p_.max_depth; }
|
||||
|
||||
/* ---------------------------------------------------------- the adaptive policy */
|
||||
bool adaptive() const { return adapt_; }
|
||||
/* The window this sequence may draft into: min(D, its stop), starting its estimate on the
|
||||
* first ask; max_depth when the policy is off. Before any step has chosen D, D is the
|
||||
* ceiling. */
|
||||
int window_for(DraftAdapt& s) const;
|
||||
/* The same for a sequence whose estimate has started, without starting one: 0 when it has
|
||||
* not. For reporting. */
|
||||
int window_of(const DraftAdapt& s) const;
|
||||
/* One verify of this sequence: `drafted` proposed, a prefix of `accepted` taken. Moves its
|
||||
* estimate, and its stop past the hold. Returns the stop after. */
|
||||
int adapt_observe(DraftAdapt& s, int drafted, int accepted) const;
|
||||
/* A SEQUENCE THAT HAS FINISHED: its estimate joins the prior the next sequences start from.
|
||||
*
|
||||
* PER SEQUENCE, NOT PER VERIFY. The deployment's own counts -- accepted(j) / reached(j) over
|
||||
* every verify -- are what a fixed window would want, and under this policy they are biased:
|
||||
* only a sequence whose drafts keep being accepted is given a window that reaches the deep
|
||||
* positions, so those positions are measured almost only on the texts that predict well, and
|
||||
* a new sequence would start as if every text did. Each finished sequence counts once here, at
|
||||
* every position, and at a position it never reached its estimate is the extrapolation from
|
||||
* its own window's edge (adapt_observe) -- a shallow text pulls the deep positions down as
|
||||
* much as a deep one holds them up. */
|
||||
void adapt_retire(const DraftAdapt& s);
|
||||
/* The prior a sequence starting now is given at position `j`. For tests and logs. */
|
||||
double prior_at(int j) const;
|
||||
|
||||
/* D FOR THE STEP THAT IS OPENING. `seq` are the estimates of the `n_seq` sequences that will
|
||||
* draft in it, `n_rows` the decode rows it carries in all (the rest emit one token each and
|
||||
* draft nothing). Started here if they have not been. Moves D past the hold and the
|
||||
* hysteresis; with no sequence to draft, D stays. Returns D. */
|
||||
int plan_step(DraftAdapt* const* seq, int n_seq, int n_rows);
|
||||
/* The step depth in force: 0 before the first step chose one. */
|
||||
int step_depth() const { return step_d_; }
|
||||
/* The deepest window a step at that depth carries: D, but no deeper than the deepest stop it
|
||||
* was chosen over, since no head-drafting sequence drafts past its stop; the ceiling before
|
||||
* any step chose one, and with the policy off. What a proposal from outside the head (prompt
|
||||
* lookup) is held to, so it adds no deeper pass shape than the head's own. */
|
||||
int step_window() const { return adapt_ && step_w_ > 0 ? step_w_ : p_.max_depth; }
|
||||
|
||||
/* T(depth, n): a decode step whose deepest window was `depth`, with `n_rows` decode rows,
|
||||
* took `ms` from the end of the step before it. Fed by Scheduler::step_finished; only the
|
||||
* adaptive policy reads it. */
|
||||
void step_time(int depth, int n_rows, double ms);
|
||||
/* What a step at `depth` with `n_rows` rows is expected to cost, in ms when anything has
|
||||
* been measured: the key's own mean when it has samples; the nearest measured key scaled by
|
||||
* the prior's ratio (1 + 0.06 d) when it does not; the prior itself when nothing has been
|
||||
* measured. */
|
||||
double step_cost(int depth, int n_rows) const;
|
||||
/* Samples behind a key: for tests and logs. */
|
||||
int64_t cost_samples(int depth, int n_rows) const;
|
||||
|
||||
/* E(d) for `s`'s estimate as it stands: the tokens a verify of d drafts is expected to emit,
|
||||
* the verified token included. For tests and logs. */
|
||||
double yield(const DraftAdapt& s, int d) const;
|
||||
/* Verifies by the window they carried, counted only under the policy: the histogram of the
|
||||
* depths it actually chose, which the mean gauge on its own cannot show. */
|
||||
int64_t verified_at(int d) const {
|
||||
return (d >= 0 && d <= RAD_SCHED_MAX_SPEC) ? by_depth_[d] : 0;
|
||||
}
|
||||
|
||||
/* One verify's outcome: `drafted` tokens were proposed and a prefix of `accepted` of them was
|
||||
* taken. Feeds the reported metrics and nothing else. */
|
||||
void observe(int drafted, int accepted);
|
||||
@@ -76,6 +242,26 @@ private:
|
||||
int64_t reach_[RAD_SCHED_MAX_SPEC] = {};
|
||||
int64_t hit_ [RAD_SCHED_MAX_SPEC] = {};
|
||||
int seen_ = 0;
|
||||
|
||||
/* The adaptive policy as configure() resolved it. */
|
||||
bool adapt_ = false;
|
||||
double alpha_ = 0.0; /* the smoothing step from kHalfLife */
|
||||
int64_t by_depth_[RAD_SCHED_MAX_SPEC + 1] = {};
|
||||
int32_t step_d_ = 0; /* D; 0 until a step chose one */
|
||||
int32_t step_w_ = 0; /* min(D, the deepest stop it saw) */
|
||||
int32_t step_held_ = 0; /* steps since D last moved */
|
||||
/* The prior from finished sequences (adapt_retire), and how many are behind it. */
|
||||
float prior_[RAD_SCHED_MAX_SPEC] = {};
|
||||
int64_t prior_n_ = 0;
|
||||
/* T(d, class): the mean step time of each key, and the steps behind it. */
|
||||
double cost_ms_[RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
|
||||
int64_t cost_n_ [RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
|
||||
|
||||
/* Fill a sequence's estimate from the prior and set its first stop. */
|
||||
void start(DraftAdapt& s) const;
|
||||
/* The deepest draft whose chance of being emitted is at least kDraftMinChance. */
|
||||
int stop_of(const float* a) const;
|
||||
static int cost_class(int n_rows);
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+12
-5
@@ -117,6 +117,11 @@ struct IKVManager {
|
||||
* it, so the batch builder is its one caller: it keeps the device's copy of a table and
|
||||
* stages only what moved. 0 is always a correct answer -- it restages the whole table. */
|
||||
virtual int64_t take_table_changes(uint64_t seq, int32_t group) const = 0;
|
||||
|
||||
/* THE SNAPSHOT STORE STILL HOLDS `slot`: it was allocated and not given back since. A step
|
||||
* that restores from a slot the store gave back would read another session's state or
|
||||
* nothing, so the scheduler asks before it builds one. */
|
||||
virtual bool checkpoint_held(int32_t slot) const = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the prefix cache */
|
||||
@@ -148,8 +153,9 @@ struct IPrefixCache {
|
||||
/* The request is gone -- finished, failed or cancelled -- and holds nothing any more. */
|
||||
virtual void release(const Request&) {}
|
||||
|
||||
virtual CacheHit lookup(const Request& r,
|
||||
std::vector<std::vector<int32_t>>* blocks_out) const = 0;
|
||||
/* `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */
|
||||
virtual CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* blocks_out,
|
||||
const HitCap* cap) const = 0;
|
||||
virtual const std::vector<int32_t>& cached_groups() const = 0;
|
||||
|
||||
/* PUBLISH what this sequence computed, so the next request sharing the prefix can adopt it.
|
||||
@@ -306,6 +312,7 @@ struct KVBinding final : IKVManager {
|
||||
int64_t take_table_changes(uint64_t s, int32_t g) const override {
|
||||
return m->take_table_changes(s, g);
|
||||
}
|
||||
bool checkpoint_held(int32_t slot) const override { return m->checkpoint_held(slot); }
|
||||
};
|
||||
|
||||
/* The prefix cache's own lookup takes tokens and content-hashed multimodal keys rather than a
|
||||
@@ -335,10 +342,10 @@ struct PCBinding final : IPrefixCache {
|
||||
mutable std::vector<MMContentKey> mm_;
|
||||
explicit PCBinding(PC* p) : m(p) {}
|
||||
|
||||
CacheHit lookup(const Request& r,
|
||||
std::vector<std::vector<int32_t>>* out) const override {
|
||||
CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* out,
|
||||
const HitCap* cap) const override {
|
||||
media_keys(r, &mm_);
|
||||
return m->lookup(r.prompt, mm_, out);
|
||||
return m->lookup(r.prompt, mm_, out, cap);
|
||||
}
|
||||
|
||||
/* Installed by the engine when the idle tiers are on; empty otherwise. */
|
||||
|
||||
@@ -123,6 +123,10 @@ struct SchedMetrics {
|
||||
/* Speculation (§10). */
|
||||
int64_t draft_tokens = 0;
|
||||
int64_t draft_accepted = 0;
|
||||
/* Prefix hits ended early so a windowed block drafter has context (Scheduler::draft_refill_),
|
||||
* and the reusable tokens they gave back to be recomputed. */
|
||||
int64_t draft_refills = 0;
|
||||
int64_t draft_refill_tokens = 0;
|
||||
float draft_acceptance = 0.0f;
|
||||
int draft_depth = 0; /* what the controller would choose right now */
|
||||
/* Per draft POSITION, so a cliff can be told from a decay: `reached` is how often every
|
||||
@@ -133,6 +137,13 @@ struct SchedMetrics {
|
||||
int draft_depth_seen = 0;
|
||||
int64_t draft_pos_reached [RAD_METRICS_MAX_SPEC] = {};
|
||||
int64_t draft_pos_accepted[RAD_METRICS_MAX_SPEC] = {};
|
||||
/* THE ADAPTIVE WINDOW (--draft-window adaptive, draft.h), all zero while it is off. The mean
|
||||
* window it gives the sequences running now -- at one sequence, that sequence's window -- and
|
||||
* the verifies by the window they carried, index = drafts verified, cumulative: the gauge says
|
||||
* where the policy stands, the histogram where it has been. */
|
||||
bool draft_adaptive = false;
|
||||
float draft_depth_adaptive = 0.0f;
|
||||
int64_t draft_verify_depth[RAD_METRICS_MAX_SPEC + 1] = {};
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+192
-8
@@ -87,10 +87,39 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
n_paged, pc->cached_groups().size(),
|
||||
hit_holes_draft_ ? "LEAVES a hole in a drafter's own KV" : "leaves no hole");
|
||||
}
|
||||
draft_refill_ = 0;
|
||||
if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 &&
|
||||
hit_holes_draft_) {
|
||||
draft_refill_ = prog.drafter.window;
|
||||
RAD_INFO("draft refill: a prefix hit ends %lld tokens before the prompt's end, so the "
|
||||
"drafter's window is recomputed", (long long)draft_refill_);
|
||||
}
|
||||
|
||||
DraftController::Params dp;
|
||||
dp.max_depth = cfg.n_spec;
|
||||
/* THE ADAPTIVE WINDOW IS THE SERIAL DRAFTER'S POLICY (draft.h): it prices a draft as one more
|
||||
* round of the head. A block drafter proposes its block in one pass and prompt lookup runs no
|
||||
* pass at all, so for either the window stays fixed -- decided here, once, before any step
|
||||
* has counted an acceptance, and said, because a flag that changes nothing reads exactly
|
||||
* like a flag that made no difference. */
|
||||
if (cfg.draft_window == DraftWindow::Adaptive) {
|
||||
const RadDrafterDecl& dd = prog.drafter;
|
||||
if (cfg.n_spec <= 0)
|
||||
RAD_WARN("--draft-window adaptive: this deployment does not speculate "
|
||||
"(--num-speculative-tokens %d), so there is no window to adapt", cfg.n_spec);
|
||||
else if (dd.kind != RAD_DRAFT_SERIAL || dd.depth <= 0)
|
||||
RAD_WARN("--draft-window adaptive: the window is fixed at %d with %s -- the adaptive "
|
||||
"window prices the rounds of a serial draft head, which this deployment does "
|
||||
"not run", cfg.n_spec,
|
||||
dd.kind == RAD_DRAFT_BLOCK ? "a block drafter, which proposes its block in one "
|
||||
"pass"
|
||||
: "prompt lookup only");
|
||||
else
|
||||
dp.adapt = true;
|
||||
}
|
||||
RAD_TRY(draft_.configure(dp));
|
||||
draft_est_.clear();
|
||||
draft_est_.reserve((size_t)cfg.max_seqs);
|
||||
|
||||
RAD_TRY(builder_.init(prog, cfg, geo_, kvgeom_, ranks));
|
||||
/* The builder's bound and not a second derivation of it: it is what the block tables were
|
||||
@@ -171,6 +200,9 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
s.card = -1;
|
||||
s.running = false;
|
||||
s.drafter_reset();
|
||||
/* A NEW REQUEST'S TEXT, so a new estimate: the slot's last tenant was writing something else. */
|
||||
s.adapt.depth = 0;
|
||||
s.adapt.held = 0;
|
||||
s.sched_tokens = 0;
|
||||
s.entry = -1;
|
||||
s.entry_next = -1;
|
||||
@@ -214,8 +246,15 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
|
||||
|
||||
/* THE NEXT STEP ALREADY VERIFIES THESE. It was planned with the count the drafter issued, and
|
||||
* the card already put the tokens in its batch; the host copy is what that step's commit
|
||||
* emits the accepted ones from, so it takes exactly those, unclamped. */
|
||||
* emits the accepted ones from, so it takes exactly those, unclamped.
|
||||
*
|
||||
* UNDER THE ADAPTIVE WINDOW THE DRAFTER RAN AS MANY ROUNDS AS THE DEEPEST SEQUENCE WANTED,
|
||||
* and expect_draft() already cut this one's count to its own window -- the card verifies the
|
||||
* FIRST draft_next of the proposals, which are these. So a longer proposal is cut to that
|
||||
* count here, against the number the step was planned with: the window itself may have moved
|
||||
* at the commit in between, and the planned step is what these tokens are for. */
|
||||
if (next_open_ && s.entry_next >= 0) {
|
||||
if (draft_.adaptive() && n > s.draft_next) n = s.draft_next;
|
||||
if (n != s.draft_next) {
|
||||
RAD_ERR("request %llu: %d draft(s) published for a step planned to verify %d",
|
||||
(unsigned long long)id, n, s.draft_next);
|
||||
@@ -237,7 +276,7 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int cap = draft_.next_depth();
|
||||
int cap = draft_cap(s);
|
||||
if (n > cap) n = cap;
|
||||
if (n > RAD_SCHED_MAX_SPEC) n = RAD_SCHED_MAX_SPEC;
|
||||
for (int i = 0; i < n; ++i) s.draft[i] = tokens[i];
|
||||
@@ -346,6 +385,12 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
}
|
||||
|
||||
if (cfg_.prefix_cache && pc_) pc_->release(*s.req);
|
||||
/* What the draft head did on this text is now part of what the next text starts from --
|
||||
* once: the estimate is marked unstarted, so a second close of the same request adds nothing. */
|
||||
if (draft_.adaptive()) {
|
||||
draft_.adapt_retire(s.adapt);
|
||||
s.adapt.depth = 0;
|
||||
}
|
||||
|
||||
if (defer_free) {
|
||||
if (!s.pending_free) ++n_deferred_;
|
||||
@@ -788,7 +833,16 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
* context back instead of re-prefilling it: it costs a copy, and the alternative
|
||||
* costs a prefill. */
|
||||
if (pc_->restore(r) == IPrefixCache::Restore::Wait) return kAdmitWait;
|
||||
CacheHit h = pc_->lookup(r, &hit_blocks_);
|
||||
HitCap cap;
|
||||
if (draft_refill_ > 0) {
|
||||
cap.tokens = std::max<int64_t>(0, (int64_t)r.prompt.size() - draft_refill_);
|
||||
cap.max_give_back = 2 * draft_refill_;
|
||||
}
|
||||
const CacheHit h = pc_->lookup(r, &hit_blocks_, draft_refill_ > 0 ? &cap : nullptr);
|
||||
if (h.given_back > 0) {
|
||||
m_.draft_refill_tokens += h.given_back;
|
||||
++m_.draft_refills;
|
||||
}
|
||||
int32_t reuse = h.n_attn_tokens;
|
||||
if (geo_.checkpoints() && h.n_linear_tokens < reuse) {
|
||||
/* A hit landing between checkpoints reuses the attention blocks and must replay the
|
||||
@@ -908,6 +962,8 @@ void Scheduler::undo_hit(SchedReq& s) {
|
||||
/* ------------------------------------------------------------------ the step */
|
||||
const RadBatch* Scheduler::step() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
/* A cycle opens here, so its head depth is chosen here (scheduler.h, draft_cycle). */
|
||||
draft_cycle();
|
||||
|
||||
/* The drafter's snapshots describe the step before this one and nothing reads them from here
|
||||
* on. block_end() and serial_end() clear them already; this covers a drafter that stopped
|
||||
@@ -963,10 +1019,22 @@ const RadBatch* Scheduler::step() {
|
||||
/* THE LAST GATE, and it has to be here rather than only at set_draft, because the
|
||||
* n-gram fallback below fills any proposal a drafter left empty -- so refusing a
|
||||
* draft upstream and stopping there hands the request a different draft instead of
|
||||
* none. Request::may_speculate says why a request can be ineligible. */
|
||||
* none. Request::may_speculate says why a request can be ineligible.
|
||||
*
|
||||
* AND THE CAP IS THE SEQUENCE'S OWN WINDOW, which is `depth` unless the adaptive
|
||||
* policy is on -- then it is what this sequence's acceptance of the HEAD's drafts pays
|
||||
* for. The n-gram fallback is not the head and that estimate says nothing about it, so
|
||||
* it is held to the step's window instead: as deep as the head drafts this step and no
|
||||
* deeper, which adds no pass shape the head's own windows do not. */
|
||||
const int cap = draft_.adaptive() ? draft_cap(s) : depth;
|
||||
bool ngram = false;
|
||||
if (!r.may_speculate) s.n_draft = 0;
|
||||
else if (s.n_draft == 0) s.n_draft = (int32_t)draft_ngram(s, depth);
|
||||
if (s.n_draft > depth) s.n_draft = depth;
|
||||
else if (s.n_draft == 0) {
|
||||
s.n_draft = (int32_t)draft_ngram(s, draft_.step_window());
|
||||
ngram = s.n_draft > 0;
|
||||
}
|
||||
if (!ngram && s.n_draft > cap) s.n_draft = cap;
|
||||
s.draft_ngram = ngram;
|
||||
/* NO VERIFIED POSITION AT OR PAST THE CONTEXT. The step computes positions n_computed
|
||||
* .. n_computed + n_draft, and nothing past ctx_limit_ - 1 has a rotary row or a
|
||||
* block-table column. commit() finishes a sequence before its length reaches the
|
||||
@@ -1053,6 +1121,7 @@ const RadBatch* Scheduler::step() {
|
||||
e.draft = s.draft;
|
||||
e.n_draft = s.n_draft;
|
||||
e.is_prefill = prefill;
|
||||
e.ngram = !prefill && s.draft_ngram && s.n_draft > 0;
|
||||
e.produces_token = (r.n_computed + want >= target);
|
||||
/* The snapshot a hit resumes from, consumed once: the state is in the slot for the whole
|
||||
* sequence after this, and restoring it again on a later chunk would rewind it. */
|
||||
@@ -1247,8 +1316,23 @@ const RadBatch* Scheduler::step() {
|
||||
}();
|
||||
if (force_mixed && plan_.phase == RAD_PHASE_DECODE) plan_.phase = RAD_PHASE_MIXED;
|
||||
|
||||
/* EVERY SNAPSHOT THIS STEP RESTORES FROM IS STILL IN THE STORE. The prefix cache keeps a
|
||||
* handed-out snapshot's slot until the next step begins (PrefixCache::begin_step), so this
|
||||
* holds by construction; it is checked because a restore from a slot the store gave back
|
||||
* reads another session's state or nothing, and the engine can only stop on it. A step that
|
||||
* finds one is abandoned like a failed staging, below: the request gives its hit back and is
|
||||
* prefilled again, and the rest re-schedule unchanged. */
|
||||
bool lost_restore = false;
|
||||
for (const StepEntry& e : plan_.e) {
|
||||
if (e.ckpt_restore < 0 || kv_->checkpoint_held(e.ckpt_restore)) continue;
|
||||
RAD_ERR("sequence %llu was to resume from checkpoint slot %d, which the store no longer "
|
||||
"holds; its hit is given back and its prompt prefilled again",
|
||||
(unsigned long long)e.seq, (int)e.ckpt_restore);
|
||||
lost_restore = true;
|
||||
}
|
||||
|
||||
step_start_ = std::chrono::steady_clock::now();
|
||||
const RadBatch* b = builder_.build(plan_, *kv_, step_);
|
||||
const RadBatch* b = lost_restore ? nullptr : builder_.build(plan_, *kv_, step_);
|
||||
if (!b) {
|
||||
/* Staging failed. Nothing was computed, so nothing is committed and n_computed did not
|
||||
* advance: the next step re-schedules the same chunks and the KV allocations already made
|
||||
@@ -1304,12 +1388,39 @@ void Scheduler::take_encodes(std::vector<std::shared_ptr<mm::Item>>* out) {
|
||||
out->swap(enc_want_);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step's head depth */
|
||||
void Scheduler::draft_cycle() {
|
||||
if (!draft_.adaptive()) return;
|
||||
/* THE ROWS THE OPENING STEP WILL DECODE: every running sequence past its prompt. Those that
|
||||
* may speculate draft, and their estimates choose D; the rest emit one token each, which is
|
||||
* part of what the step yields and of what it costs. A sequence still prefilling is neither. */
|
||||
draft_est_.clear();
|
||||
int n_rows = 0;
|
||||
for (int32_t slot : running_) {
|
||||
SchedReq& s = *reqs_[(size_t)slot];
|
||||
if (!s.req || !s.running) continue;
|
||||
const Request& r = *s.req;
|
||||
if (r.n_computed < (int64_t)r.prompt.size() || r.n_computed + 1 < s.seq_len()) continue;
|
||||
++n_rows;
|
||||
if (r.may_speculate) draft_est_.push_back(&s.adapt);
|
||||
}
|
||||
(void)draft_.plan_step(draft_est_.data(), (int)draft_est_.size(), n_rows);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the next step */
|
||||
void Scheduler::expect_draft(uint64_t id, int n) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = by_id_.find(id);
|
||||
if (it == by_id_.end()) return;
|
||||
reqs_[(size_t)it->second]->draft_next = n > 0 ? n : 0;
|
||||
SchedReq& s = *reqs_[(size_t)it->second];
|
||||
/* UNDER THE ADAPTIVE WINDOW THE ROUNDS RAN FOR THE DEEPEST SEQUENCE, and this one verifies the
|
||||
* first of them up to its own window -- the cap serial_begin sized the rounds from, unchanged
|
||||
* since: nothing commits between the two, and D is the cycle's (draft_cycle). */
|
||||
if (draft_.adaptive() && n > 0) {
|
||||
const int cap = draft_cap(s);
|
||||
if (n > cap) n = cap;
|
||||
}
|
||||
s.draft_next = n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
const RadBatch* Scheduler::step_next() {
|
||||
@@ -1393,6 +1504,10 @@ const RadBatch* Scheduler::step_next_locked() {
|
||||
void Scheduler::promote_next() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (!next_open_) return;
|
||||
/* The other place a cycle opens: the step issued ahead becomes this one, and step() is not
|
||||
* called. Its proposals were counted under the last cycle's D; the next ones are drafted
|
||||
* under this one. */
|
||||
draft_cycle();
|
||||
std::swap(plan_, plan_next_);
|
||||
plan_next_.reset();
|
||||
step_prefill_tok_ = 0;
|
||||
@@ -1550,6 +1665,28 @@ int Scheduler::commit(const StepResult& res) {
|
||||
|
||||
if (e.n_spec > 0) {
|
||||
draft_.observe(e.n_spec, a);
|
||||
/* AND THIS SEQUENCE'S OWN ESTIMATE, from the same outcome, under the adaptive
|
||||
* window -- when the head drafted it. A prompt-lookup proposal is accepted on
|
||||
* different text by a different rule, and folding it in would price the head's
|
||||
* next window on what the lookup found. A move takes effect at the next draft:
|
||||
* this step's drafter has already run, sized from the estimate as it stood before
|
||||
* this commit. */
|
||||
if (draft_.adaptive() && !e.ngram) {
|
||||
const int was = s.adapt.depth;
|
||||
const int now = draft_.adapt_observe(s.adapt, e.n_spec, a);
|
||||
if (now != was && was > 0 && (int)log_level() >= (int)Log::Debug) {
|
||||
char est[8 * RAD_SCHED_MAX_SPEC];
|
||||
int o = 0;
|
||||
for (int j = 0; j < draft_.next_depth() && o < (int)sizeof est - 8; ++j)
|
||||
o += std::snprintf(est + o, sizeof est - (size_t)o, "%s%.2f",
|
||||
j ? " " : "", (double)s.adapt.a[j]);
|
||||
est[o] = 0;
|
||||
RAD_DEBUG("draft window: request %llu stops at %d, was %d (expected "
|
||||
"tokens a verify %.3f -> %.3f; acceptance by position %s)",
|
||||
(unsigned long long)r.id, now, was, draft_.yield(s.adapt, was),
|
||||
draft_.yield(s.adapt, now), est);
|
||||
}
|
||||
}
|
||||
m_.draft_tokens += e.n_spec;
|
||||
m_.draft_accepted += a;
|
||||
server::sink_drafts(r.sink, e.n_spec, a);
|
||||
@@ -1676,6 +1813,16 @@ void Scheduler::step_finished() {
|
||||
if (m_.prefill_tps < 0.05f) m_.prefill_tps = 0.0f;
|
||||
if (m_.decode_tps < 0.05f) m_.decode_tps = 0.0f;
|
||||
}
|
||||
/* AND WHAT THE STEP COST AT ITS DEPTH, for the adaptive window (draft.h): the same wall time,
|
||||
* which is the step's share of the loop -- the draft rounds that followed it included, and a
|
||||
* step issued ahead counted from the end of the one before rather than twice. A decode step
|
||||
* only: a prefill chunk's time is the chunk's, not the window's. Keyed by the deepest window
|
||||
* the step verified, which is the head depth it ran at whenever D held from the step before. */
|
||||
if (draft_.adaptive() && plan_.phase == RAD_PHASE_DECODE && plan_.n_spec > 0 && wall > 0) {
|
||||
int rows = 0;
|
||||
for (const StepEntry& e : plan_.e) rows += (e.produces_token && !e.is_prefill) ? 1 : 0;
|
||||
draft_.step_time((int)plan_.n_spec, rows, wall * 1e3);
|
||||
}
|
||||
last_step_at_ = step_end;
|
||||
/* So a second call, or one on a loop iteration that ran no step, charges nothing. */
|
||||
step_start_ = {};
|
||||
@@ -1709,6 +1856,27 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
|
||||
if (depth > 0 && *rounds > depth) *rounds = depth;
|
||||
if (*rounds > RAD_SCHED_MAX_SPEC) *rounds = RAD_SCHED_MAX_SPEC;
|
||||
|
||||
/* UNDER THE ADAPTIVE WINDOW, NO MORE ROUNDS THAN THE DEEPEST SEQUENCE WANTS. A round is one
|
||||
* pass of the head over every drafting row, so the step runs as many as its deepest window,
|
||||
* and a sequence that wants fewer verifies the first of them (expect_draft, set_draft); a
|
||||
* round past the deepest window is a pass whose proposal nobody verifies. Only a row that will
|
||||
* draft and be given its drafts counts. When no row does, the rounds stay as they are: round 0
|
||||
* is the history pass, and that still has to run. The reservation below is then made for the
|
||||
* rounds that will actually run, which is what it is for. */
|
||||
if (may_draft && draft_.adaptive()) {
|
||||
int want = 0;
|
||||
for (const StepEntry& e : plan_.e) {
|
||||
if (!e.produces_token || e.slot < 0 || (size_t)e.slot >= reqs_.size()) continue;
|
||||
SchedReq& s = *reqs_[(size_t)e.slot];
|
||||
if (!s.req || s.req->state != ReqState::Running || !s.running ||
|
||||
!s.req->may_speculate)
|
||||
continue;
|
||||
const int c = draft_cap(s);
|
||||
if (c > want) want = c;
|
||||
}
|
||||
if (want > 0 && *rounds > want) *rounds = want;
|
||||
}
|
||||
|
||||
int n_draft_rows = 0;
|
||||
int64_t cu = 0; /* this entry's first token in the step just run */
|
||||
for (size_t i = 0; i < plan_.e.size(); ++i) {
|
||||
@@ -2262,6 +2430,22 @@ SchedMetrics Scheduler::metrics_locked() const {
|
||||
m.draft_pos_reached [j] = draft_.reached(j);
|
||||
m.draft_pos_accepted[j] = draft_.hits(j);
|
||||
}
|
||||
if (draft_.adaptive()) {
|
||||
m.draft_adaptive = true;
|
||||
/* Over the running sequences whose estimate has started; one that has not drafted yet
|
||||
* has no window to report. */
|
||||
int64_t sum = 0, n = 0;
|
||||
for (int32_t slot : running_) {
|
||||
const SchedReq& s = *reqs_[(size_t)slot];
|
||||
if (s.adapt.depth <= 0) continue;
|
||||
/* The window it drafts into: its stop under the step's head depth. */
|
||||
sum += draft_.window_of(s.adapt);
|
||||
++n;
|
||||
}
|
||||
m.draft_depth_adaptive = n ? (float)((double)sum / (double)n) : 0.0f;
|
||||
const int kDepth = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
|
||||
for (int d = 0; d < kDepth; ++d) m.draft_verify_depth[d] = draft_.verified_at(d);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
+44
-2
@@ -109,6 +109,14 @@ struct SchedReq {
|
||||
draft_hi = 0;
|
||||
}
|
||||
|
||||
/* THE ADAPTIVE DRAFT WINDOW'S ESTIMATE FOR THIS REQUEST (--draft-window adaptive, draft.h), and
|
||||
* deliberately NOT in drafter_reset(): it describes the text the request is writing, which a
|
||||
* preemption does not change, rather than any cache the request holds. A recycled slot starts
|
||||
* it over in add_locked. Untouched while the policy is off. */
|
||||
DraftAdapt adapt;
|
||||
/* The proposal the step being planned carries came from prompt lookup (StepEntry::ngram). */
|
||||
bool draft_ngram = false;
|
||||
|
||||
int32_t sched_tokens = 0; /* tokens given to this request in the current step */
|
||||
int32_t entry = -1; /* its index in the current StepPlan, or -1 */
|
||||
/* Its index in the NEXT step, already issued while this one runs (step_next), or -1; and the
|
||||
@@ -280,7 +288,8 @@ public:
|
||||
* the one that is stuck. Returns how many were written. */
|
||||
int requests(ReqStat* out, int max) const;
|
||||
|
||||
/* The drafter's proposal for a request's next step. n is clamped to the controller's depth. */
|
||||
/* The drafter's proposal for a request's next step. n is clamped to the sequence's window
|
||||
* (draft_cap): the controller's depth, or what the adaptive policy gives the sequence. */
|
||||
int set_draft(uint64_t id, const int32_t* tokens, int n);
|
||||
|
||||
/* ---------------------------------------------------------- media the encoder owes
|
||||
@@ -318,7 +327,8 @@ public:
|
||||
* from one to the other.
|
||||
*
|
||||
* expect_draft after the drafter is issued: how many drafts it proposes for a sequence,
|
||||
* which is how many the next step verifies.
|
||||
* which is how many the next step verifies -- capped at the sequence's window,
|
||||
* which under the adaptive policy can be fewer than the rounds that ran.
|
||||
* step_next plans and builds that step: every row of this one, as a device row, at
|
||||
* the furthest context it can reach. Null -- and the engine plans with step()
|
||||
* after this one commits -- whenever the step needs a decision only a
|
||||
@@ -472,6 +482,15 @@ private:
|
||||
* also skips on a block-size mismatch. A bound like this lives in exactly one place; a second
|
||||
* copy is free to drift out of step with the first. */
|
||||
bool hit_holes_draft_ = true;
|
||||
/* DRAFT REFILL. Where a hit leaves a hole in a WINDOWED block drafter's cache, the drafter is
|
||||
* declined until its window has slid past the hole, which on the follow-up turn of a chat --
|
||||
* the turn a prefix hit is for -- is most or all of the reply. So the hit is ended one window
|
||||
* before the end of the prompt (HitCap): the trunk recomputes that window, the drafter's
|
||||
* context pass covers it, and the sequence drafts from its first decode step. Output is
|
||||
* unchanged; only which tokens are recomputed moves. A hit whose nearest checkpoint below
|
||||
* that point would give back more than two windows is kept whole. The drafter's window, or 0
|
||||
* where no hit can leave such a hole. */
|
||||
int64_t draft_refill_ = 0;
|
||||
BatchBuilder builder_;
|
||||
DraftController draft_;
|
||||
|
||||
@@ -482,6 +501,29 @@ private:
|
||||
return hit_holes_draft_ ? ctx_len : 0;
|
||||
}
|
||||
|
||||
/* THE WINDOW A SEQUENCE MAY DRAFT INTO: the configured depth, or under the adaptive window
|
||||
* min(D, its stop) (DraftController::window_for, which starts the estimate on the first ask).
|
||||
* It is the rule every site that caps a proposal applies -- step(), set_draft(),
|
||||
* expect_draft() and the rounds in serial_begin() -- and with the policy off it is
|
||||
* next_depth(), exactly as before. */
|
||||
int draft_cap(SchedReq& s) const {
|
||||
return draft_.adaptive() ? draft_.window_for(s.adapt) : draft_.next_depth();
|
||||
}
|
||||
|
||||
/* THE STEP'S HEAD DEPTH D IS CHOSEN ONCE A CYCLE AND HELD, by draft_cycle(), which is the
|
||||
* first thing step() and promote_next() do -- every cycle opens with exactly one of the two.
|
||||
* A cycle's proposal passes through four sites -- the plan that verifies it, the rounds that
|
||||
* draft the next one, expect_draft() and set_draft() -- and the step issued ahead holds them
|
||||
* to agree: it was built with the count expect_draft() gave it, and set_draft() refuses a
|
||||
* different one. A D read live could move between them, because a commit or a client hanging
|
||||
* up changes the running set mid-cycle; held, it moves only where a cycle starts, and a
|
||||
* proposal drafted under one D and planned under the next is only ever cut shorter.
|
||||
*
|
||||
* `draft_est_` is the list plan_step reads, reserved at init so the step path does not
|
||||
* allocate. */
|
||||
std::vector<DraftAdapt*> draft_est_;
|
||||
void draft_cycle();
|
||||
|
||||
/* The built-in prompt-lookup drafter (scheduler.cpp). Fills s.draft and returns how many
|
||||
* tokens it proposed; 0 when the sequence has no repeated pattern to extend. The pattern
|
||||
* lengths it tries, longest first. */
|
||||
|
||||
@@ -268,6 +268,7 @@ public:
|
||||
o.draft_acceptance = m.draft_acceptance;
|
||||
o.prefill_tokens = m.prefill_tokens; o.decode_tokens = m.decode_tokens;
|
||||
o.draft_tokens = m.draft_tokens; o.draft_accepted = m.draft_accepted;
|
||||
o.draft_refills = m.draft_refills; o.draft_refill_tokens = m.draft_refill_tokens;
|
||||
o.linear_hit_rate = m.linear_hit_rate;
|
||||
o.attn_cached_tokens = m.attn_cached_tokens;
|
||||
o.linear_cached_tokens = m.linear_cached_tokens;
|
||||
@@ -279,6 +280,13 @@ public:
|
||||
o.draft_pos_reached [j] = m.draft_pos_reached [j];
|
||||
o.draft_pos_accepted[j] = m.draft_pos_accepted[j];
|
||||
}
|
||||
o.draft_adaptive = m.draft_adaptive;
|
||||
o.draft_depth_adaptive = m.draft_depth_adaptive;
|
||||
{
|
||||
const int ka = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
|
||||
const int kb = (int)(sizeof o.draft_verify_depth / sizeof o.draft_verify_depth[0]);
|
||||
for (int d = 0; d < ka && d < kb; ++d) o.draft_verify_depth[d] = m.draft_verify_depth[d];
|
||||
}
|
||||
o.preemptions = m.preemptions;
|
||||
o.total_requests = m.admitted;
|
||||
o.steps = m.steps;
|
||||
@@ -311,6 +319,7 @@ public:
|
||||
std::string push(int32_t t) override { return d_.push(t); }
|
||||
std::string flush() override { return d_.flush(); }
|
||||
bool stopped() const override { return d_.stopped(); }
|
||||
void defer_stops_until(const std::string& m) override { d_.defer_stops_until(m); }
|
||||
private:
|
||||
Detokenizer d_;
|
||||
};
|
||||
@@ -553,6 +562,7 @@ public:
|
||||
o.grammar = opt.grammar;
|
||||
o.json_schema = opt.json_schema;
|
||||
o.template_kwargs = opt.template_kwargs;
|
||||
o.quiet = opt.quiet;
|
||||
|
||||
ChatPrompt p;
|
||||
const int st = t_.apply(messages, tools, o, &p);
|
||||
@@ -595,6 +605,8 @@ public:
|
||||
gq.generation_prompt = p.generation_prompt;
|
||||
gq.parallel_tool_calls = opt.parallel_tool_calls;
|
||||
gq.extract_reasoning = opt.reasoning_format != "none";
|
||||
gq.require_call = calls && opt.tool_choice == "required";
|
||||
gq.only_tool = opt.tool_name;
|
||||
ChatGrammar g;
|
||||
std::string gerr;
|
||||
if (chat_format_grammar(f, gq, &g, &gerr) < 0) {
|
||||
|
||||
+15
-4
@@ -161,6 +161,7 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
if (kw != b.end() && kw->is_object())
|
||||
for (auto it = kw->begin(); it != kw->end(); ++it)
|
||||
opt.template_kwargs[it.key()] = json_dump(it.value());
|
||||
map_reasoning_effort(lim_, &opt);
|
||||
|
||||
json tools = json::array();
|
||||
auto t = b.find("tools");
|
||||
@@ -168,10 +169,8 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
|
||||
ChatRender render;
|
||||
std::string why;
|
||||
if (deps_.chat->apply(*msgs, tools, opt, &render, &why) < 0)
|
||||
return error_response(err_bad("messages", why.empty()
|
||||
? "the chat template could not render this request"
|
||||
: why), req.peer);
|
||||
if (const int rs = deps_.chat->apply(*msgs, tools, opt, &render, &why); rs < 0)
|
||||
return error_response(template_refusal(opt, lim_, rs, why), req.peer);
|
||||
toks = deps_.tok->encode(render.prompt,
|
||||
get_bool_or(b, "add_special_tokens", false),
|
||||
/*parse_special=*/true);
|
||||
@@ -299,6 +298,15 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
|
||||
caps["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
|
||||
caps["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
|
||||
caps["logprobs"] = opt_.supports_logprobs;
|
||||
/* THE EFFORTS A CHAT REQUEST MAY SEND, as probed from the template at startup: null when it
|
||||
* takes any word. "none" and "minimal" are this server's, and turn thinking off. */
|
||||
if (lim_.reasoning_efforts.empty()) {
|
||||
caps["reasoning_efforts"] = nullptr;
|
||||
} else {
|
||||
std::vector<std::string> e = { "none", "minimal" };
|
||||
e.insert(e.end(), lim_.reasoning_efforts.begin(), lim_.reasoning_efforts.end());
|
||||
caps["reasoning_efforts"] = e;
|
||||
}
|
||||
|
||||
/* WHAT A REQUEST THAT LEAVES A FIELD OUT GETS, under the request's own spelling of each
|
||||
* field, so a client can read off exactly what leaving one out means on this deployment. */
|
||||
@@ -325,6 +333,9 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
|
||||
defs["max_tokens"] = srv["default_max_tokens"];
|
||||
defs["reasoning_effort"] = opt_.default_reasoning_effort.empty()
|
||||
? json(nullptr) : json(opt_.default_reasoning_effort);
|
||||
json emap = json::object();
|
||||
for (const auto& [from, to] : lim_.reasoning_effort_map) emap[from] = to;
|
||||
defs["reasoning_effort_map"] = std::move(emap);
|
||||
defs["thinking_token_budget"] = opt_.default_thinking_budget < 0
|
||||
? json(nullptr) : json(opt_.default_thinking_budget);
|
||||
json kw = json::object();
|
||||
|
||||
@@ -102,6 +102,9 @@ struct SchedMetrics {
|
||||
/* The exact pair the ratio is computed from, for the same reason. */
|
||||
int64_t draft_tokens = 0;
|
||||
int64_t draft_accepted = 0;
|
||||
/* Prefix hits ended early for a windowed block drafter, and the tokens they gave back. */
|
||||
int64_t draft_refills = 0;
|
||||
int64_t draft_refill_tokens = 0;
|
||||
/* THE PER-POSITION DRAFT HAZARD. `draft_acceptance` above is pooled over the whole window and
|
||||
* cannot distinguish a drafter that decays with depth from one whose later rounds are broken:
|
||||
* both read as one small number. These carry the conditional rate at each position -- of the
|
||||
@@ -111,6 +114,11 @@ struct SchedMetrics {
|
||||
int draft_depth_seen = 0;
|
||||
int64_t draft_pos_reached [MAX_DRAFT_POS] = {};
|
||||
int64_t draft_pos_accepted[MAX_DRAFT_POS] = {};
|
||||
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive), all zero while it is off: the mean window
|
||||
* of the running sequences, and the verifies by the window they carried (index = drafts). */
|
||||
bool draft_adaptive = false;
|
||||
double draft_depth_adaptive = 0.0;
|
||||
int64_t draft_verify_depth[MAX_DRAFT_POS + 1] = {};
|
||||
int64_t preemptions = 0;
|
||||
int64_t total_requests = 0;
|
||||
/* ENGINE STEPS. One forward pass of the model plus whatever draft rounds followed it, which
|
||||
@@ -299,6 +307,9 @@ public:
|
||||
* search text that can no longer contain what it is searching for, and the generation would
|
||||
* run to max_tokens. Default false, for a decoder that leaves stop handling to us. */
|
||||
virtual bool stopped() const { return false; }
|
||||
/* Match the stop strings only after `marker` has been generated (core/text Detokenizer::
|
||||
* defer_stops_until): the reply starts inside its reasoning block. */
|
||||
virtual void defer_stops_until(const std::string& /*marker*/) {}
|
||||
};
|
||||
|
||||
class ITokenizer {
|
||||
@@ -367,10 +378,14 @@ struct ChatRenderOptions {
|
||||
bool enable_thinking = true;
|
||||
bool parallel_tool_calls = true;
|
||||
std::string tool_choice = "auto"; /* auto | none | required */
|
||||
std::string tool_name; /* a named tool_choice's function, or "" */
|
||||
std::string grammar; /* the caller's GBNF, or "" */
|
||||
std::string json_schema; /* a response_format schema, as JSON text, or "" */
|
||||
std::string reasoning_format = "auto";
|
||||
std::map<std::string, std::string> template_kwargs;
|
||||
/* A render whose refusal is an answer and not an error -- the startup probes of what the
|
||||
* template takes -- so the template's refusal is not logged. */
|
||||
bool quiet = false;
|
||||
};
|
||||
|
||||
/* What it gives back. A STRING IS NOT ENOUGH, and that is the whole reason this struct exists: a
|
||||
|
||||
+47
-1
@@ -140,11 +140,23 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
for (int j = 0; j < seen; ++j) {
|
||||
const int64_t r = m.draft_pos_reached[j];
|
||||
g_draft_pos_reached_[j].set((double)r);
|
||||
g_draft_pos_accepted_[j].set((double)m.draft_pos_accepted[j]);
|
||||
g_draft_pos_[j].set(r ? (double)m.draft_pos_accepted[j] / (double)r : 0.0);
|
||||
}
|
||||
/* Published after the gauges it bounds, so a concurrent render never lists a position whose
|
||||
* gauge has not been written yet. */
|
||||
draft_pos_seen_.store(seen, std::memory_order_release);
|
||||
if (m.draft_adaptive) {
|
||||
g_draft_depth_adapt_.set(m.draft_depth_adaptive);
|
||||
int top = 0;
|
||||
for (int d = 1; d <= (int)MAX_DRAFT_POS; ++d) {
|
||||
g_draft_vdepth_[d].set((double)m.draft_verify_depth[d]);
|
||||
if (m.draft_verify_depth[d] > 0) top = d;
|
||||
}
|
||||
/* After the gauges, for the reason above. */
|
||||
draft_vdepth_top_.store(top, std::memory_order_release);
|
||||
draft_adapt_on_.store(true, std::memory_order_release);
|
||||
}
|
||||
c_preemptions_.inc(std::max(0.0, (double)m.preemptions - c_preemptions_.get()));
|
||||
c_steps_.inc(std::max(0.0, (double)m.steps - c_steps_.get()));
|
||||
c_steps_prefill_.inc(std::max(0.0, (double)m.steps_prefill - c_steps_prefill_.get()));
|
||||
@@ -160,6 +172,9 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
c_decode_tokens_.inc(std::max(0.0, (double)m.decode_tokens - c_decode_tokens_.get()));
|
||||
c_draft_tokens_.inc(std::max(0.0, (double)m.draft_tokens - c_draft_tokens_.get()));
|
||||
c_draft_accepted_.inc(std::max(0.0, (double)m.draft_accepted - c_draft_accepted_.get()));
|
||||
c_draft_refills_.inc(std::max(0.0, (double)m.draft_refills - c_draft_refills_.get()));
|
||||
c_draft_refill_tokens_.inc(
|
||||
std::max(0.0, (double)m.draft_refill_tokens - c_draft_refill_tokens_.get()));
|
||||
c_attn_cached_.inc(std::max(0.0, (double)m.attn_cached_tokens - c_attn_cached_.get()));
|
||||
c_linear_cached_.inc(std::max(0.0, (double)m.linear_cached_tokens - c_linear_cached_.get()));
|
||||
c_checkpoints_.inc(std::max(0.0, (double)m.checkpoints_written - c_checkpoints_.get()));
|
||||
@@ -345,6 +360,12 @@ std::string Metrics::render() const {
|
||||
w.counter("radiance:draft_accepted_total",
|
||||
"Speculative tokens accepted; the pair the acceptance ratio is computed from.",
|
||||
L, c_draft_accepted_.get());
|
||||
w.counter("radiance:draft_refills_total",
|
||||
"Prefix hits ended a drafter window early so a windowed block drafter has context.",
|
||||
L, c_draft_refills_.get());
|
||||
w.counter("radiance:draft_refill_tokens_total",
|
||||
"Cached prompt tokens those hits gave back to be recomputed.",
|
||||
L, c_draft_refill_tokens_.get());
|
||||
|
||||
/* PREFIX CACHING, DECOUPLED (spec §7.3). vllm:gpu_prefix_cache_hit_rate is the ATTENTION one,
|
||||
* because that is what vLLM's single number has always meant. The linear side hits at a
|
||||
@@ -373,7 +394,9 @@ std::string Metrics::render() const {
|
||||
/* CONDITIONAL, per draft position: of the verifies that reached position j -- every earlier
|
||||
* one accepted -- the fraction that took j as well. The pooled ratio above cannot tell a
|
||||
* drafter that decays from one whose later rounds are broken; these can, and the companion
|
||||
* `_reached_total` says how much evidence each position carries. */
|
||||
* `_reached_total` says how much evidence each position carries. `_accepted_total` gives the
|
||||
* same ratio over any window: at a fixed depth the next position's reach would do, but an
|
||||
* adaptive window can end at j with j taken. */
|
||||
const int seen = draft_pos_seen_.load(std::memory_order_acquire);
|
||||
if (seen > 0) {
|
||||
const std::string base = L.substr(0, L.size() - 1);
|
||||
@@ -388,6 +411,29 @@ std::string Metrics::render() const {
|
||||
for (int j = 0; j < seen; ++j)
|
||||
w.out += "radiance:draft_position_reached_total" + base + ",position=\"" +
|
||||
std::to_string(j) + "\"} " + num(g_draft_pos_reached_[j].get()) + '\n';
|
||||
w.help("radiance:draft_position_accepted_total",
|
||||
"Verifies that accepted each draft position.", "counter");
|
||||
for (int j = 0; j < seen; ++j)
|
||||
w.out += "radiance:draft_position_accepted_total" + base + ",position=\"" +
|
||||
std::to_string(j) + "\"} " + num(g_draft_pos_accepted_[j].get()) + '\n';
|
||||
}
|
||||
/* THE ADAPTIVE DRAFT WINDOW, only while --draft-window adaptive is in force: where the policy stands --
|
||||
* at one sequence, that sequence's window -- and where it has been, as verifies by the
|
||||
* number of drafts they carried. */
|
||||
if (draft_adapt_on_.load(std::memory_order_acquire)) {
|
||||
w.gauge("radiance:draft_depth_adaptive",
|
||||
"Mean draft window the adaptive policy gives the running sequences.",
|
||||
L, g_draft_depth_adapt_.get());
|
||||
const int top = draft_vdepth_top_.load(std::memory_order_acquire);
|
||||
if (top > 0) {
|
||||
const std::string base = L.substr(0, L.size() - 1);
|
||||
w.help("radiance:draft_verify_depth_total",
|
||||
"Verifies by the number of drafts they carried, under the adaptive window.",
|
||||
"counter");
|
||||
for (int d = 1; d <= top; ++d)
|
||||
w.out += "radiance:draft_verify_depth_total" + base + ",depth=\"" +
|
||||
std::to_string(d) + "\"} " + num(g_draft_vdepth_[d].get()) + '\n';
|
||||
}
|
||||
}
|
||||
w.gauge("radiance:num_requests_preempted",
|
||||
"Requests currently preempted and awaiting recompute.", L, g_preempted_.get());
|
||||
|
||||
@@ -121,7 +121,15 @@ private:
|
||||
enum { MAX_DRAFT_POS = 64 };
|
||||
Gauge g_draft_pos_[MAX_DRAFT_POS];
|
||||
Gauge g_draft_pos_reached_[MAX_DRAFT_POS];
|
||||
Gauge g_draft_pos_accepted_[MAX_DRAFT_POS];
|
||||
std::atomic<int> draft_pos_seen_{0};
|
||||
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive): the mean window of the running sequences,
|
||||
* and the verifies by the window they carried, index = drafts. Rendered only while the policy
|
||||
* is on, so a deployment without it exposes exactly what it always did. */
|
||||
Gauge g_draft_depth_adapt_;
|
||||
Gauge g_draft_vdepth_[MAX_DRAFT_POS + 1];
|
||||
std::atomic<bool> draft_adapt_on_{false};
|
||||
std::atomic<int> draft_vdepth_top_{0}; /* the deepest window with a verify counted */
|
||||
|
||||
/* sample() turns the scheduler's cumulative totals into counter increments by reading each
|
||||
* counter and adding the difference. Two scrapes doing that at once both read the old value
|
||||
@@ -144,6 +152,7 @@ private:
|
||||
* answers "how much between these two scrapes", and only the second survives a comparison
|
||||
* between two runs that settled into different mixes. */
|
||||
Counter c_prefill_tokens_, c_decode_tokens_, c_draft_tokens_, c_draft_accepted_;
|
||||
Counter c_draft_refills_, c_draft_refill_tokens_;
|
||||
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
|
||||
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
|
||||
Gauge g_linear_hit_;
|
||||
|
||||
+82
-24
@@ -142,6 +142,7 @@ std::string ApiError::dump() const {
|
||||
e["type"] = type;
|
||||
if (param.empty()) e["param"] = nullptr; else e["param"] = param;
|
||||
if (code.empty()) e["code"] = nullptr; else e["code"] = code;
|
||||
if (!supported.empty()) e["supported"] = supported;
|
||||
json o;
|
||||
o["error"] = e;
|
||||
return o.dump();
|
||||
@@ -652,6 +653,53 @@ void apply_template_defaults(const json& b, const OaiLimits& lim, ChatRenderOpti
|
||||
opt->reasoning_format = lim.reasoning_format;
|
||||
}
|
||||
|
||||
void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt) {
|
||||
if (lim.reasoning_effort_map.empty()) return;
|
||||
auto it = opt->template_kwargs.find("reasoning_effort");
|
||||
if (it == opt->template_kwargs.end()) return;
|
||||
const json v = json::parse(it->second, nullptr, false);
|
||||
if (!v.is_string()) return;
|
||||
auto m = lim.reasoning_effort_map.find(v.get<std::string>());
|
||||
if (m == lim.reasoning_effort_map.end()) return;
|
||||
if (m->second == "none" || m->second == "minimal") {
|
||||
opt->enable_thinking = false;
|
||||
opt->template_kwargs.erase(it);
|
||||
} else {
|
||||
it->second = json(m->second).dump();
|
||||
}
|
||||
}
|
||||
|
||||
ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, int rs,
|
||||
const std::string& why) {
|
||||
/* AN EFFORT OUTSIDE THE SET IS THE REASON, when the set is known and the word is not in it:
|
||||
* the render that refused carried no other variable the template was probed for. The
|
||||
* template's own sentence is a traceback through its source, which says nothing a client can
|
||||
* act on that the set does not. */
|
||||
auto it = opt.template_kwargs.find("reasoning_effort");
|
||||
if (it != opt.template_kwargs.end() && !lim.reasoning_efforts.empty()) {
|
||||
const json v = json::parse(it->second, nullptr, false);
|
||||
const std::vector<std::string>& set = lim.reasoning_efforts;
|
||||
if (v.is_string() && std::find(set.begin(), set.end(), v.get<std::string>()) == set.end()) {
|
||||
std::string list;
|
||||
for (size_t i = 0; i < set.size(); ++i)
|
||||
list += (i ? (i + 1 == set.size() ? " and " : ", ") : "") + ("'" + set[i] + "'");
|
||||
ApiError e = err_bad("reasoning_effort",
|
||||
"'" + v.get<std::string>() + "' is not a level this model's chat "
|
||||
"template takes. It takes " + list + "; 'none' and 'minimal' "
|
||||
"turn thinking off");
|
||||
e.code = "unsupported_value";
|
||||
e.supported = { "none", "minimal" };
|
||||
e.supported.insert(e.supported.end(), set.begin(), set.end());
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return rs == RAD_E_UNSUPPORTED
|
||||
? err_unsupported("messages", why.empty() ? "the chat template refused this request"
|
||||
: why)
|
||||
: err_bad("messages", why.empty() ? "the chat template could not render this "
|
||||
"request" : why);
|
||||
}
|
||||
|
||||
static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions* opt,
|
||||
ApiError* err) {
|
||||
auto kw = b.find("chat_template_kwargs");
|
||||
@@ -677,6 +725,7 @@ static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions
|
||||
}
|
||||
}
|
||||
}
|
||||
map_reasoning_effort(lim, opt);
|
||||
|
||||
bool think = opt->enable_thinking;
|
||||
if (!get_bool(b, "enable_thinking", &think, err)) return RAD_E_INVAL;
|
||||
@@ -713,6 +762,10 @@ static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions
|
||||
* An explicit chat_template_kwargs entry still wins: emplace does not overwrite. */
|
||||
std::string effort;
|
||||
if (!get_str(b, "reasoning_effort", &effort, err)) return RAD_E_INVAL;
|
||||
/* --reasoning-effort-map, before "none" and "minimal" are read, so a map can name either. */
|
||||
if (auto m = lim.reasoning_effort_map.find(effort);
|
||||
!effort.empty() && m != lim.reasoning_effort_map.end())
|
||||
effort = m->second;
|
||||
/* The deployment's default, where the request did not say. Last, so every explicit spelling
|
||||
* above it wins; emplace, so a chat_template_kwargs entry that already set the key stands.
|
||||
* "none" and "minimal" are an enable_thinking default, so any word about thinking drops them;
|
||||
@@ -1323,14 +1376,10 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
out->n_tools = (int)tools.size();
|
||||
}
|
||||
|
||||
/* FORCING A CALL IS REFUSED, and not because the grammar is out of reach -- the template
|
||||
* returns one. It is that the grammar it returns for a forced choice does not force anything:
|
||||
* it admits leading prose (the template invites "optional reasoning BEFORE the function
|
||||
* call") and then an unbounded run of calls with no terminating state, so the reply is prose
|
||||
* followed by invented calls and `finish_reason: "length"`. Serving that would be worse than
|
||||
* refusing it: the caller asked for exactly one call and would get a request that never stops.
|
||||
* `parallel_tool_calls: false` IS honoured -- that one narrows the grammar's repetition rule,
|
||||
* which is a change the generator actually makes. */
|
||||
/* A forced choice -- "required", or an object naming one function -- makes the call grammar
|
||||
* the whole reply instead of a lazy one: the reasoning block, then the calls (one when
|
||||
* `parallel_tool_calls` is false), then nothing, so the reply ends at the last call. A named
|
||||
* function narrows the calls to that one. */
|
||||
std::string tool_choice = "auto", named;
|
||||
auto tcit = b.find("tool_choice");
|
||||
if (tcit != b.end() && !tcit->is_null()) {
|
||||
@@ -1355,17 +1404,22 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
if (tool_choice == "none") {
|
||||
tools = json::array();
|
||||
} else if (tool_choice == "required") {
|
||||
*err = err_unsupported(
|
||||
"tool_choice",
|
||||
named.empty()
|
||||
? "\"auto\" and \"none\" are implemented. \"required\" is not: the grammar this "
|
||||
"model's template produces for it admits prose before the call and an unbounded "
|
||||
"run of calls after it, so it does not force one call -- it produces a reply "
|
||||
"that runs to max_tokens. Send \"auto\" and check the response for a call."
|
||||
: "a named function is not implemented, for the same reason \"required\" is not: "
|
||||
"the template's forced-call grammar does not terminate. Send \"auto\" with only "
|
||||
"that function in `tools`.");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
if (tools.empty()) {
|
||||
*err = err_bad("tool_choice", "a tool call is required, but `tools` is empty");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!named.empty() &&
|
||||
std::none_of(tools.begin(), tools.end(), [&](const json& t) {
|
||||
return t.at("function").at("name") == named;
|
||||
})) {
|
||||
*err = err_bad("tool_choice", "names \"" + named + "\", which is not in `tools`");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!schema_json.empty() || !out->sp.grammar.empty()) {
|
||||
*err = err_bad("tool_choice", "a forced tool call is the whole reply, so it cannot be "
|
||||
"combined with `response_format` or `grammar`");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
} else if (tool_choice != "auto") {
|
||||
*err = err_bad("tool_choice", "must be \"none\", \"auto\", \"required\", or an object");
|
||||
return RAD_E_INVAL;
|
||||
@@ -1392,7 +1446,9 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
out->tools_present = !tools.empty();
|
||||
|
||||
ChatRenderOptions opt;
|
||||
opt.quiet = lim.probe;
|
||||
opt.tool_choice = tool_choice;
|
||||
opt.tool_name = named;
|
||||
opt.parallel_tool_calls = parallel;
|
||||
if (!get_bool(b, "add_generation_prompt", &opt.add_generation_prompt, err)) return RAD_E_INVAL;
|
||||
|
||||
@@ -1412,11 +1468,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
std::string why;
|
||||
const int rs = d.chat->apply(messages, tools, opt, &render, &why);
|
||||
if (rs < 0) {
|
||||
*err = rs == RAD_E_UNSUPPORTED
|
||||
? err_unsupported("messages", why.empty() ? "the chat template refused this "
|
||||
"request" : why)
|
||||
: err_bad("messages", why.empty() ? "the chat template could not render this "
|
||||
"request" : why);
|
||||
*err = template_refusal(opt, lim, rs, why);
|
||||
return rs;
|
||||
}
|
||||
if (render.prompt.empty()) {
|
||||
@@ -1456,6 +1508,12 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
if (std::find(out->stop.begin(), out->stop.end(), s) == out->stop.end())
|
||||
out->stop.push_back(s);
|
||||
|
||||
/* A reply that starts inside the reasoning block: its stop strings are the answer's, so they
|
||||
* apply only after the block's closer (Detokenizer::defer_stops_until). The chat format says
|
||||
* whether the rendered prompt leaves the block open and what closes it. */
|
||||
if (render.think_starts_open && !render.think_close.empty())
|
||||
out->stops_after = render.think_close;
|
||||
|
||||
/* Checked HERE, where the answer is still a 400. The grammar being validated may be the
|
||||
* caller's, or one the template produced for its own tool-call syntax; either way the first
|
||||
* moment it can fail is when the automaton is built, and building it on the step path would
|
||||
|
||||
@@ -37,6 +37,9 @@ struct ApiError {
|
||||
std::string message;
|
||||
std::string param; /* "" when the error is not about one field */
|
||||
std::string code; /* "" when there is nothing more specific to say */
|
||||
/* The values `param` takes, when the error is a value outside a known set: `supported` in the
|
||||
* envelope, so a client can retry with one rather than parse the sentence. */
|
||||
std::vector<std::string> supported;
|
||||
|
||||
std::string dump() const; /* the OpenAI error envelope, as a JSON string */
|
||||
};
|
||||
@@ -77,6 +80,9 @@ struct OaiRequest {
|
||||
SamplingParams sp;
|
||||
int32_t max_tokens = 0;
|
||||
std::vector<std::string> stop;
|
||||
/* The reasoning block's closer when the reply starts inside the block, else "": the stop
|
||||
* strings above then apply only after it (IDetokenizer::defer_stops_until). */
|
||||
std::string stops_after;
|
||||
/* Generate past end-of-text, to max_tokens. See Request::ignore_eos. */
|
||||
bool ignore_eos = false;
|
||||
int priority = 0;
|
||||
@@ -144,6 +150,22 @@ struct OaiLimits {
|
||||
* dial at all. Seeded only when the request says nothing, so a caller always wins. */
|
||||
std::string default_reasoning_effort;
|
||||
|
||||
/* THE WORDS THE CHAT TEMPLATE TAKES AS `reasoning_effort`, found at startup by rendering each
|
||||
* word this server knows of (Server::probe_reasoning_efforts). Empty when the template takes
|
||||
* any word -- it does not read the variable, or reads it without refusing one -- and when
|
||||
* nothing was probed. A request whose effort the template refuses is answered with this set
|
||||
* rather than with the template's traceback (template_refusal). */
|
||||
std::vector<std::string> reasoning_efforts;
|
||||
|
||||
/* --reasoning-effort-map: an effort a request sends, replaced by the deployment's word before
|
||||
* the template sees it. For a client that always sends a word of OpenAI's ladder ("high")
|
||||
* to a model whose template has its own ("xhigh"). */
|
||||
std::map<std::string, std::string> reasoning_effort_map;
|
||||
|
||||
/* A STARTUP PROBE, NOT A REQUEST: what the template refuses is the answer being asked for, so
|
||||
* its refusal is not logged (ChatRenderOptions::quiet). */
|
||||
bool probe = false;
|
||||
|
||||
/* THE DEPLOYMENT'S DEFAULT `thinking_token_budget`, -1 for none. For the same reason the
|
||||
* effort default exists: an agent framework sizes max_tokens per turn and sends no budget, and
|
||||
* a reasoning block that spends the whole of max_tokens returns a turn with no answer in it.
|
||||
@@ -193,6 +215,19 @@ RequestThinking request_thinking(const json& b);
|
||||
* prompt served by the other. */
|
||||
void apply_template_defaults(const json& b, const OaiLimits& lim, ChatRenderOptions* opt);
|
||||
|
||||
/* --reasoning-effort-map, on the effort chat_template_kwargs put in the render options: a mapped
|
||||
* word replaces it, and a word mapped to "none" or "minimal" turns thinking off instead. The chat
|
||||
* endpoint maps the top-level `reasoning_effort` itself, before it reads "none" and "minimal";
|
||||
* this is the kwargs spelling, for it and for /tokenize. */
|
||||
void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt);
|
||||
|
||||
/* THE 400 FOR A TEMPLATE THAT REFUSED A RENDER. An effort outside the template's known set
|
||||
* (OaiLimits::reasoning_efforts) is named as `reasoning_effort` with the set in `supported`, the
|
||||
* way OpenAI answers an unsupported value; anything else is `messages` with the template's own
|
||||
* sentence. */
|
||||
ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, int rs,
|
||||
const std::string& why);
|
||||
|
||||
/* True when `v` is a legal value of the sampler field a request spells `field`; otherwise `why`
|
||||
* says what the legal set is, in the words a 400 carries. The same table checks a request and the
|
||||
* command-line flag that sets the field's default, so a default the command line accepts is one
|
||||
|
||||
+71
-2
@@ -30,6 +30,10 @@ struct Server::Generation {
|
||||
Finish finish = Finish::None;
|
||||
bool closed = false; /* the server has decided this choice is over */
|
||||
size_t scanned = 0; /* how far the stop-string scan has reached */
|
||||
/* OaiRequest::stops_after: where in `text` the reasoning block's closer ends (npos until it
|
||||
* has been generated) and how far the search for it has reached. */
|
||||
size_t stops_floor = std::string::npos;
|
||||
size_t closer_scanned = 0;
|
||||
size_t stop_cut = std::string::npos;
|
||||
size_t emitted = 0; /* streaming: text already handed to the delta stream */
|
||||
bool retired = false; /* reap() has been said for this id, at most once */
|
||||
@@ -65,6 +69,7 @@ Server::Server(const Deps& d, const ServerOptions& o)
|
||||
lim_.default_sampling = opt_.default_sampling;
|
||||
lim_.default_dry_breakers_set = opt_.default_dry_breakers_set;
|
||||
lim_.default_template_kwargs = opt_.default_template_kwargs;
|
||||
lim_.reasoning_effort_map = opt_.reasoning_effort_map;
|
||||
lim_.reasoning_format = opt_.reasoning_format;
|
||||
|
||||
odeps_.tok = deps_.tok;
|
||||
@@ -192,6 +197,7 @@ void Server::check_template_defaults(std::string* kwargs_why, std::string* effor
|
||||
OaiLimits l = lim_;
|
||||
l.default_template_kwargs.clear();
|
||||
l.default_reasoning_effort.clear();
|
||||
l.probe = true;
|
||||
if (!render(l, nullptr)) return;
|
||||
l.default_template_kwargs = lim_.default_template_kwargs;
|
||||
if (!l.default_template_kwargs.empty() && !render(l, kwargs_why)) return;
|
||||
@@ -199,6 +205,50 @@ void Server::check_template_defaults(std::string* kwargs_why, std::string* effor
|
||||
if (!l.default_reasoning_effort.empty()) render(l, effort_why);
|
||||
}
|
||||
|
||||
std::vector<std::string> Server::probe_reasoning_efforts() {
|
||||
lim_.reasoning_efforts.clear();
|
||||
if (!deps_.chat) return {};
|
||||
OaiLimits l = lim_;
|
||||
l.default_template_kwargs.clear();
|
||||
l.default_reasoning_effort.clear();
|
||||
l.reasoning_effort_map.clear();
|
||||
l.probe = true;
|
||||
auto takes = [&](const std::string& effort) {
|
||||
std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1)";
|
||||
if (!effort.empty()) body += R"(,"reasoning_effort":)" + json(effort).dump();
|
||||
body += "}";
|
||||
OaiRequest r;
|
||||
ApiError e;
|
||||
return parse_chat_request(body, odeps_, l, &r, &e) >= 0;
|
||||
};
|
||||
/* A render that fails with no effort at all says nothing about efforts, and one that takes a
|
||||
* word no ladder has takes every word. */
|
||||
if (!takes("") || takes("radiance-probe-not-a-level")) return {};
|
||||
std::vector<std::string> set;
|
||||
for (const char* w : { "low", "medium", "high", "xhigh", "max" })
|
||||
if (takes(w)) set.push_back(w);
|
||||
lim_.reasoning_efforts = set;
|
||||
return set;
|
||||
}
|
||||
|
||||
std::string Server::check_reasoning_effort_map() const {
|
||||
if (!deps_.chat) return std::string();
|
||||
OaiLimits l = lim_;
|
||||
l.default_template_kwargs.clear();
|
||||
l.default_reasoning_effort.clear();
|
||||
l.reasoning_effort_map.clear();
|
||||
l.probe = true;
|
||||
for (const auto& [from, to] : lim_.reasoning_effort_map) {
|
||||
const std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1,)"
|
||||
R"("reasoning_effort":)" + json(to).dump() + "}";
|
||||
OaiRequest r;
|
||||
ApiError e;
|
||||
if (parse_chat_request(body, odeps_, l, &r, &e) < 0)
|
||||
return from + "=" + to + ": the chat template refuses '" + to + "': " + e.message;
|
||||
}
|
||||
return std::string();
|
||||
}
|
||||
|
||||
std::string Server::check_thinking_budget() const {
|
||||
if (!deps_.chat || lim_.default_thinking_budget < 0) return std::string();
|
||||
const std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1,)"
|
||||
@@ -330,6 +380,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
|
||||
*err = err_not_implemented("the tokenizer did not supply an incremental decoder");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!r.stops_after.empty()) g.detok->defer_stops_until(r.stops_after);
|
||||
|
||||
Request rq;
|
||||
rq.prompt = r.prompts[p].tokens;
|
||||
@@ -338,7 +389,9 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
|
||||
* Offsetting is enough: the sampler's stream is seeded, not chained. */
|
||||
rq.sp.seed = r.sp.seed + (uint64_t)k;
|
||||
rq.max_tokens = r.max_tokens;
|
||||
rq.stop = r.stop;
|
||||
/* With the stop strings deferred past the reasoning block, the scheduler -- which
|
||||
* cannot tell reasoning from answer -- gets none; the decoder and pump() cut. */
|
||||
rq.stop = r.stops_after.empty() ? r.stop : std::vector<std::string>{};
|
||||
rq.ignore_eos = r.ignore_eos;
|
||||
rq.priority = r.priority;
|
||||
rq.stream = r.stream;
|
||||
@@ -429,8 +482,24 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
|
||||
* string straddles token boundaries and only the detokenised text can be searched, so the
|
||||
* authoritative cut is made here. Scanning restarts (maxstop-1) bytes behind the previous
|
||||
* end so a match spanning two drains is still found. */
|
||||
if (maxstop && g.stop_cut == std::string::npos && !g.text.empty()) {
|
||||
/* Stop strings deferred past the reasoning block match only after its closer. The closer
|
||||
* is searched for incrementally, from (closer length - 1) bytes behind the previous end,
|
||||
* so a reply that thinks for a long time is not rescanned from its start every drain. */
|
||||
size_t floor = 0;
|
||||
if (!r.stops_after.empty()) {
|
||||
if (g.stops_floor == std::string::npos) {
|
||||
const size_t n = r.stops_after.size();
|
||||
const size_t from = g.closer_scanned >= n ? g.closer_scanned - n + 1 : 0;
|
||||
const size_t m = g.text.find(r.stops_after, from);
|
||||
g.closer_scanned = g.text.size();
|
||||
if (m != std::string::npos) g.stops_floor = m + n;
|
||||
}
|
||||
floor = g.stops_floor;
|
||||
}
|
||||
if (maxstop && floor != std::string::npos && g.stop_cut == std::string::npos &&
|
||||
!g.text.empty()) {
|
||||
size_t start = g.scanned >= maxstop ? g.scanned - maxstop + 1 : 0;
|
||||
if (start < floor) start = floor;
|
||||
for (const auto& s : r.stop) {
|
||||
if (s.empty()) continue;
|
||||
size_t at = g.text.find(s, start);
|
||||
|
||||
@@ -85,6 +85,8 @@ struct ServerOptions {
|
||||
bool default_dry_breakers_set = false;
|
||||
/* The deployment's chat template variables and reply format. See OaiLimits. */
|
||||
std::map<std::string, std::string> default_template_kwargs;
|
||||
/* --reasoning-effort-map. See OaiLimits::reasoning_effort_map. */
|
||||
std::map<std::string, std::string> reasoning_effort_map;
|
||||
std::string reasoning_format = "auto";
|
||||
bool allow_image = false;
|
||||
bool allow_video = false;
|
||||
@@ -148,6 +150,15 @@ public:
|
||||
* would ask for it. Empty when this model's reasoning block can hold one; otherwise the 400 a
|
||||
* request naming the budget would get, which says why. */
|
||||
std::string check_thinking_budget() const;
|
||||
/* THE EFFORTS THE CHAT TEMPLATE TAKES, found by parsing a one-message chat with each word this
|
||||
* server knows of (low, medium, high, xhigh, max) the way a request would send it, with no
|
||||
* deployment defaults. A template that takes a word nobody uses takes any word, and the answer
|
||||
* is empty. Kept for the refusal of a word outside the set and for /server_info; called once,
|
||||
* before run(). */
|
||||
std::vector<std::string> probe_reasoning_efforts();
|
||||
/* --reasoning-effort-map's targets, each rendered as a request's effort would be. Empty when
|
||||
* the template takes every one; otherwise the first refusal, naming the target. */
|
||||
std::string check_reasoning_effort_map() const;
|
||||
void stop();
|
||||
int port() const { return transport_.port(); } /* 0 until run() is accepting */
|
||||
|
||||
|
||||
+1
-1
@@ -198,7 +198,7 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
|
||||
try {
|
||||
p = common_chat_templates_apply(impl_->tmpls.get(), in);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_ERR("chat: template refused the request: %s", e.what());
|
||||
if (!opt.quiet) RAD_ERR("chat: template refused the request: %s", e.what());
|
||||
out->error = e.what();
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ struct ChatOptions {
|
||||
bool add_bos = false;
|
||||
bool add_eos = false;
|
||||
std::map<std::string, std::string> template_kwargs;
|
||||
bool quiet = false; /* a refusal is not logged: a startup probe */
|
||||
};
|
||||
|
||||
/* Everything the scheduler and the sampler need for one request, produced in one pass. */
|
||||
|
||||
+32
-8
@@ -577,6 +577,13 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
const ojson& tools = req.tools ? *req.tools : none;
|
||||
const bool has_tools = f.has_tools() && tools.is_array() && !tools.empty();
|
||||
const bool has_rf = req.json_schema && req.json_schema->is_object() && !req.json_schema->empty();
|
||||
if (req.require_call && (has_rf || !has_tools)) {
|
||||
if (why)
|
||||
*why = has_rf ? "a required tool call and a response format cannot both be the "
|
||||
"whole reply"
|
||||
: "a tool call is required, but there are no tools this format can call";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!has_rf && !(has_tools && !f.triggers.empty())) return RAD_OK;
|
||||
|
||||
const std::string opener = f.call_open.empty() ? f.name_prefix : f.call_open;
|
||||
@@ -598,12 +605,9 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
b.resolve_refs(schema);
|
||||
}
|
||||
|
||||
if (has_rf) {
|
||||
/* The whole reply: what follows the generation prompt, the reasoning block, and
|
||||
* the document, fenced or not. */
|
||||
b.add_rule("response-format", b.add_schema("response-format-schema",
|
||||
*req.json_schema));
|
||||
add_json_rules(b);
|
||||
/* A grammar that is the whole reply starts where the generation prompt does, so the
|
||||
* prompt's assistant prefix and the reasoning block come first. */
|
||||
auto whole_reply = [&]() {
|
||||
std::string gp = req.generation_prompt;
|
||||
if (f.has_reasoning() && !f.reasoning_open.empty()) {
|
||||
const size_t at = gp.find(f.reasoning_open);
|
||||
@@ -612,6 +616,15 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
std::vector<G> root{ gp.empty() ? eps() : lit(gp), space() };
|
||||
if (f.has_reasoning() && req.extract_reasoning) root.push_back(reasoning_expr(f, breaks));
|
||||
root.push_back(space());
|
||||
return root;
|
||||
};
|
||||
if (has_rf) {
|
||||
/* The whole reply: what follows the generation prompt, the reasoning block, and
|
||||
* the document, fenced or not. */
|
||||
b.add_rule("response-format", b.add_schema("response-format-schema",
|
||||
*req.json_schema));
|
||||
add_json_rules(b);
|
||||
std::vector<G> root = whole_reply();
|
||||
root.push_back(alt({ seq({ lit("```json"), space(), rule_ref("response-format"), space(),
|
||||
lit("```") }),
|
||||
rule_ref("response-format") }));
|
||||
@@ -630,6 +643,7 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
continue;
|
||||
const auto& fn = tool.at("function");
|
||||
const std::string name = fn.at("name");
|
||||
if (!req.only_tool.empty() && name != req.only_tool) continue;
|
||||
auto params = fn.contains("parameters") ? fn.at("parameters") : ojson::object();
|
||||
const auto properties = params.contains("properties") ? params.at("properties")
|
||||
: ojson::object();
|
||||
@@ -687,6 +701,8 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
b.add_rule(rule_name("tool-" + name), render(func));
|
||||
choices.push_back(rule_ref(rule_name("tool-" + name)));
|
||||
}
|
||||
if (choices.empty() && !req.only_tool.empty())
|
||||
throw std::invalid_argument("no tool named \"" + req.only_tool + "\" to call");
|
||||
if (typed) add_json_rules(b);
|
||||
if (!choices.empty()) b.add_rule("until-suffix", until_pattern({ f.arg_value_suffix }));
|
||||
|
||||
@@ -704,13 +720,21 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
: seq({ lit(""), space(), choice, space(), lit("") });
|
||||
}
|
||||
b.add_rule("tool-call", render(calls));
|
||||
b.add_rule("root", "tool-call");
|
||||
if (req.require_call) {
|
||||
/* The calls and nothing after them: a complete grammar admits only the end of
|
||||
* the turn, so the reply stops at the last call's closer. */
|
||||
std::vector<G> root = whole_reply();
|
||||
root.push_back(rule_ref("tool-call"));
|
||||
b.add_rule("root", render(seq(std::move(root))));
|
||||
} else {
|
||||
b.add_rule("root", "tool-call");
|
||||
}
|
||||
});
|
||||
} catch (const std::exception& e) {
|
||||
if (why) *why = e.what();
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->lazy = !has_rf;
|
||||
out->lazy = !has_rf && !req.require_call;
|
||||
if (out->lazy) out->trigger_words = f.triggers;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+8
-2
@@ -146,14 +146,20 @@ std::string chat_format_describe(const ChatFormat& f);
|
||||
* The GBNF that constrains a reply to the format, generated from the description. For a tool
|
||||
* request it is LAZY: the reply is free until one of `triggers` appears, and from there the
|
||||
* grammar admits the call syntax with each argument constrained by its schema. For a response
|
||||
* format it is the whole reply. Rule names and structure follow the vendored generator so the
|
||||
* two produce the same grammar for a template-analysed format. */
|
||||
* format, and for a request that requires a call, it is the whole reply. Rule names and structure
|
||||
* follow the vendored generator so the two produce the same grammar for a template-analysed
|
||||
* format. */
|
||||
struct ChatGrammarRequest {
|
||||
const nlohmann::ordered_json* tools = nullptr; /* the request's tools, or null */
|
||||
const nlohmann::ordered_json* json_schema = nullptr; /* a response format's schema, or null */
|
||||
std::string generation_prompt;
|
||||
bool parallel_tool_calls = true;
|
||||
bool extract_reasoning = true; /* reasoning_format != "none" */
|
||||
/* tool_choice "required" or a named function: the grammar is the whole reply rather than lazy,
|
||||
* the reasoning block and then the calls with nothing after them, and `only_tool` (when set)
|
||||
* narrows the calls to that one function. */
|
||||
bool require_call = false;
|
||||
std::string only_tool;
|
||||
};
|
||||
|
||||
struct ChatGrammar {
|
||||
|
||||
+21
-2
@@ -1606,13 +1606,32 @@ std::string Detokenizer::push(int32_t token) {
|
||||
all_ += p;
|
||||
pending_ += p;
|
||||
|
||||
/* Inside the reasoning block no stop string applies (defer_stops_until). The closer is
|
||||
* searched for incrementally in all_, from (closer length - 1) bytes behind the previous end.
|
||||
* Once it has been generated, matching starts in the text AFTER it: the closer may still be in
|
||||
* pending_, and nothing before its end may count. */
|
||||
size_t from = 0;
|
||||
if (!armed_) {
|
||||
const size_t n = arm_after_.size();
|
||||
const size_t start = arm_scanned_ >= n ? arm_scanned_ - n + 1 : 0;
|
||||
const size_t m = all_.find(arm_after_, start);
|
||||
arm_scanned_ = all_.size();
|
||||
if (m == std::string::npos) {
|
||||
from = std::string::npos;
|
||||
} else {
|
||||
armed_ = true;
|
||||
const size_t pending_at = all_.size() - pending_.size();
|
||||
from = m + n > pending_at ? m + n - pending_at : 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* A complete stop string inside pending_ ends the stream. Everything before it is emitted;
|
||||
* the stop string and anything after it never is. */
|
||||
if (!stops_.empty()) {
|
||||
if (!stops_.empty() && from != std::string::npos) {
|
||||
size_t best = std::string::npos;
|
||||
const std::string* which = nullptr;
|
||||
for (const std::string& s : stops_) {
|
||||
const size_t m = pending_.find(s);
|
||||
const size_t m = pending_.find(s, from);
|
||||
if (m != std::string::npos && m < best) { best = m; which = &s; }
|
||||
}
|
||||
if (which) {
|
||||
|
||||
@@ -247,6 +247,19 @@ public:
|
||||
bool stopped() const { return stopped_; }
|
||||
const std::string& stop_hit() const { return stop_hit_; }
|
||||
|
||||
/* STOP STRINGS ARE THE ANSWER'S, NOT THE REASONING'S. A generation that starts inside its
|
||||
* reasoning block is matched against its stop strings only after `marker` -- the block's
|
||||
* closer -- has been generated, and only in the text after it. Otherwise a stop string the
|
||||
* model happens to write while thinking ends the request with the reasoning cut short and no
|
||||
* answer at all: a few-shot harness that stops on "Q:" loses every reply whose reasoning
|
||||
* restates the question. "" = match from the first token, the behaviour of every request that
|
||||
* does not start in a block. */
|
||||
void defer_stops_until(std::string marker) {
|
||||
arm_after_ = std::move(marker);
|
||||
armed_ = arm_after_.empty();
|
||||
arm_scanned_ = 0;
|
||||
}
|
||||
|
||||
/* Everything pushed so far, stop string included. The scheduler wants this to decide whether
|
||||
* a request finished on a stop or on a length limit. */
|
||||
const std::string& text() const { return all_; }
|
||||
@@ -264,6 +277,9 @@ private:
|
||||
std::string stop_hit_;
|
||||
size_t max_stop_ = 0;
|
||||
bool first_ = true;
|
||||
std::string arm_after_; /* see defer_stops_until */
|
||||
bool armed_ = true;
|
||||
size_t arm_scanned_ = 0; /* how far into all_ the search for arm_after_ has reached */
|
||||
Tokenizer tok_; /* over v_, set up by the first push */
|
||||
bool tok_ready_ = false;
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# q38-27b-quark-mxfp4-df2.recipe -- AMD's Quark AWQ-MXFP4 Qwen3.8-27B with the DFlash2 drafter.
|
||||
#
|
||||
# rad-convert <amd/Qwen3.8-27B-Quark-AWQ-MXFP4> --draft-model <z-lab/Qwen3.8-27B-DFlash2> \
|
||||
# --recipe q38-27b-quark-mxfp4-df2.recipe -o q38-27b-quark-mxfp4-df2.rad
|
||||
#
|
||||
# Quark's MXFP4 linears are read as `fp4_e2m1*e8m0[1x32]`, byte for byte, so no rule names them:
|
||||
# the trunk is served at the 4-bit weights Quark shipped, against E4M3 activations. The checkpoint
|
||||
# is served by the family's quantised plugin (qwen35_fp8). The delta net's a/b projection is
|
||||
# declared bf16, and every MXFP4 value is exact in bf16, so `cast` keeps Quark's values that way.
|
||||
# The rest is as in q38-27b-fp8-df2.recipe: the head at block fp8, the drafter's linears at block
|
||||
# fp8, and its 2-bit copy of the target's head.
|
||||
|
||||
blk.*.ssm_ab.weight cast dtype=bf16
|
||||
|
||||
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16
|
||||
|
||||
dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
@@ -0,0 +1,38 @@
|
||||
# qwen4exp-autoround-i8-hc8m.recipe -- a Qwen3.8-Flash-Next released as AutoRound int4
|
||||
# (`auto_round:auto_gptq`, symmetric, group 128), such as
|
||||
# ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound, arranged as the production container is
|
||||
# around its experts.
|
||||
#
|
||||
# rad-convert <AutoRound checkpoint> --recipe data/recipes/qwen4exp-autoround-i8-hc8m.recipe \
|
||||
# -o swift-autoround.rad
|
||||
#
|
||||
# The routed experts are named by no rule: rad-convert imports the release's int4 codes and group
|
||||
# scales as `i4*bf16[1x128]` (the scales rounded from f16 to bf16), served on the four-bit expert
|
||||
# GEMM. The release ships its block linears in int4 as well, which the trunk's W8A8 GEMMs do not
|
||||
# read, so they are made int8 from the int4 values the release holds -- a 128 of K each, as their
|
||||
# groups are. Everything the release keeps in bf16 is quantised as qwen4exp-w4nl64-i8-hc8m.recipe
|
||||
# quantises it, the MTP layer's experts rounded to the experts' own format.
|
||||
|
||||
# The MTP layer's experts, bf16 in the release (blk.48 is the MTP layer).
|
||||
blk.48.ffn_*_exps.*.weight rtn codes=i4 group=128 scale=bf16
|
||||
|
||||
# The connections' mixing matrices and the MTP head's fc matrices, as in production.
|
||||
*_hc_down.weight rtn codes=fp8_e4m3 group=128 scale=f32
|
||||
*_hc_up.weight rtn codes=fp8_e4m3 group=80 scale=f32
|
||||
mtp.fc_hidden.weight rtn codes=fp8_e4m3 group=128 scale=f32
|
||||
mtp.fc_embedding.weight rtn codes=fp8_e4m3 group=128 scale=f32
|
||||
|
||||
# The trunk's block linears as int8, a scale per 128 columns searched for least error.
|
||||
blk.*.attn_qg.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.attn_k.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.attn_v.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.attn_output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ssm_inz.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ssm_out.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ffn_gate_up_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ffn_down_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
|
||||
# The n-gram table at one fixed E4M3 scale, and the MTP head's 2-bit draft head.
|
||||
blk.*.ple_ngram.weight rtn codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4
|
||||
mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16
|
||||
@@ -0,0 +1,12 @@
|
||||
# Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk (4-bit weights, E4M3 activations) and its DFlash2
|
||||
# block-diffusion drafter merged into the container; the speculation depth is the drafter's own
|
||||
# operating point.
|
||||
name: radiance-qwen3.8-27b-mxfp4
|
||||
services:
|
||||
radiance:
|
||||
extends: { file: common.yaml, service: radiance }
|
||||
container_name: radiance-qwen3.8-27b-mxfp4
|
||||
command: >
|
||||
--model /models/qwen3.8-27b-mxfp4.rad
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8
|
||||
@@ -28,11 +28,10 @@ Window values are counter ratios with the definitions of the since-start gauges:
|
||||
| prompt from attention cache | `attn_cached_tokens` / `prompt_tokens` | `vllm:gpu_prefix_cache_hit_rate` |
|
||||
| prompt from linear checkpoint | `linear_cached_tokens` / (`linear_cached_tokens` + `prefill_tokens`) | `radiance:linear_prefix_cache_hit_rate` |
|
||||
| draft acceptance | `draft_accepted` / `draft_tokens` | `radiance:draft_acceptance_ratio` |
|
||||
| conditional acceptance at j | `draft_position_reached`(j+1) / `draft_position_reached`(j) | `radiance:draft_position_acceptance_ratio` |
|
||||
| conditional acceptance at j | `draft_position_accepted`(j) / `draft_position_reached`(j) | `radiance:draft_position_acceptance_ratio` |
|
||||
|
||||
Position j+1 is evaluated only when j was accepted, so its reach counts j's acceptances. The last
|
||||
position's acceptances are the total accepted minus every later reach. Draft blocks per decode step is
|
||||
the reach of position 0 over `engine_steps_decode_total` (GUIDE §6.3).
|
||||
Draft blocks per decode step is the reach of position 0 over `engine_steps_decode_total` (GUIDE §6.3).
|
||||
The adaptive draft window and verifies by draft depth have data only under `--draft-window adaptive`.
|
||||
|
||||
Prometheus extrapolates `rate()` inside the window and VictoriaMetrics does not, so short windows at
|
||||
the edge of a burst differ between the two. The overview's ratios are taken over the dashboard's time
|
||||
|
||||
+143
-33
@@ -1252,7 +1252,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"description": "In the window: of the verifies that reached position j, the fraction that took j as well. Position j+1 is reached only when j was accepted, so this is reached(j+1) / reached(j); the last position is the total accepted minus every later reach. A late position that collapses while the pooled rate looks fine shows here first.",
|
||||
"description": "In the window: of the verifies that reached position j, the fraction that took j as well, accepted(j) / reached(j). A late position that collapses while the pooled rate looks fine shows here first.",
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
@@ -1265,7 +1265,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 0",
|
||||
"refId": "A",
|
||||
"range": true,
|
||||
@@ -1276,7 +1276,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 1",
|
||||
"refId": "B",
|
||||
"range": true,
|
||||
@@ -1287,7 +1287,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 2",
|
||||
"refId": "C",
|
||||
"range": true,
|
||||
@@ -1298,7 +1298,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 3",
|
||||
"refId": "D",
|
||||
"range": true,
|
||||
@@ -1309,7 +1309,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 4",
|
||||
"refId": "E",
|
||||
"range": true,
|
||||
@@ -1320,7 +1320,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 5",
|
||||
"refId": "F",
|
||||
"range": true,
|
||||
@@ -1331,7 +1331,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 6",
|
||||
"refId": "G",
|
||||
"range": true,
|
||||
@@ -1342,7 +1342,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 7",
|
||||
"refId": "H",
|
||||
"range": true,
|
||||
@@ -1353,7 +1353,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 8",
|
||||
"refId": "I",
|
||||
"range": true,
|
||||
@@ -1364,7 +1364,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 9",
|
||||
"refId": "J",
|
||||
"range": true,
|
||||
@@ -1375,7 +1375,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 10",
|
||||
"refId": "K",
|
||||
"range": true,
|
||||
@@ -1386,7 +1386,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 11",
|
||||
"refId": "L",
|
||||
"range": true,
|
||||
@@ -1397,7 +1397,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 12",
|
||||
"refId": "M",
|
||||
"range": true,
|
||||
@@ -1408,7 +1408,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 13",
|
||||
"refId": "N",
|
||||
"range": true,
|
||||
@@ -1419,7 +1419,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 14",
|
||||
"refId": "O",
|
||||
"range": true,
|
||||
@@ -1430,8 +1430,8 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "(sum(rate(radiance:draft_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval])) - sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position!=\"0\"}[$__rate_interval]))) / min(sum by (position) (rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval])))",
|
||||
"legendFormat": "last position",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 15",
|
||||
"refId": "P",
|
||||
"range": true,
|
||||
"instant": false
|
||||
@@ -1743,6 +1743,116 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Adaptive draft window",
|
||||
"id": 42,
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"description": "Mean draft window the adaptive policy gives the running sequences; a gap while none runs. Only under --draft-window adaptive; no data otherwise.",
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 43
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "max by (instance) (radiance:draft_depth_adaptive{instance=~\"$instance\", model_name=~\"$model_name\"}) > 0",
|
||||
"legendFormat": "{{instance}}",
|
||||
"refId": "A",
|
||||
"range": true,
|
||||
"instant": false
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 5,
|
||||
"showPoints": "never",
|
||||
"stacking": {
|
||||
"mode": "none",
|
||||
"group": "A"
|
||||
}
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Verifies by draft depth",
|
||||
"id": 43,
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"description": "Share of verifies by the number of drafts they carried, under the adaptive window. Only under --draft-window adaptive; no data otherwise.",
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 43
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum by (depth) (rate(radiance:draft_verify_depth_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval]))",
|
||||
"legendFormat": "depth {{depth}}",
|
||||
"refId": "A",
|
||||
"range": true,
|
||||
"instant": false
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 40,
|
||||
"showPoints": "never",
|
||||
"stacking": {
|
||||
"mode": "percent",
|
||||
"group": "A"
|
||||
}
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "row",
|
||||
"title": "Scheduler",
|
||||
@@ -1753,7 +1863,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 43
|
||||
"y": 51
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -1769,7 +1879,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 44
|
||||
"y": 52
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -1846,7 +1956,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 44
|
||||
"y": 52
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -1912,7 +2022,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 44
|
||||
"y": 52
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -1977,7 +2087,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 52
|
||||
"y": 60
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -1993,7 +2103,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 53
|
||||
"y": 61
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2070,7 +2180,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 53
|
||||
"y": 61
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2147,7 +2257,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 53
|
||||
"y": 61
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2221,7 +2331,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 61
|
||||
"y": 69
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -2237,7 +2347,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 62
|
||||
"y": 70
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2294,7 +2404,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 62
|
||||
"y": 70
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2362,7 +2472,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 62
|
||||
"y": 70
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2447,7 +2557,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 70
|
||||
"y": 78
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -2463,7 +2573,7 @@
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 71
|
||||
"y": 79
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2518,7 +2628,7 @@
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 71
|
||||
"y": 79
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
|
||||
@@ -123,6 +123,7 @@ the cards the engine runs on.
|
||||
| `flashnext-bf16.yaml` | `qwen3.8-flash-next-bf16.rad` | Qwen3.8-Flash-Next in bf16, streamed from the disk tier. A reference, not a production server |
|
||||
| `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 |
|
||||
| `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower |
|
||||
| `qwen3.8-27b-mxfp4.yaml` | `qwen3.8-27b-mxfp4.rad` | Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk, its DFlash2 drafter and vision tower |
|
||||
| `qwen3.8-27b-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 |
|
||||
| `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter |
|
||||
| `minicpm5-2b-bf16.yaml` | `minicpm5-2b-bf16.rad` | MiniCPM5-2B in bf16 with its DSpark drafter |
|
||||
|
||||
+143
-27
@@ -191,8 +191,8 @@ code is built for every family's generic target besides, whatever is named here.
|
||||
## 2. Five things to know before you start
|
||||
|
||||
**1. A model is a checkpoint served as it stands, or a `.rad` container.** A checkpoint whose
|
||||
weights are bf16, f16, f32 or block-scaled fp8 is served at that precision straight from its
|
||||
directory. Anything that needs quantising is quantised once, by `rad-convert` and a recipe, into a
|
||||
weights are bf16, f16, f32, block-scaled fp8 or Quark's MXFP4 is served at that precision straight
|
||||
from its directory. Anything that needs quantising is quantised once, by `rad-convert` and a recipe, into a
|
||||
container. A container holds each weight as the planes of its *encoding* — codes, scales, zero
|
||||
points, a rotation — in one canonical arrangement, plus the tokeniser, the chat template, the
|
||||
metadata, the recipe it was quantised with and optionally a draft head. No kernel library is named
|
||||
@@ -208,7 +208,7 @@ Three ship with the tree:
|
||||
|
||||
| library | |
|
||||
|---|---|
|
||||
| `libr4d` | the device library: AMD RDNA4 (`gfx12xx`). Paged and dense attention, gated delta net, P2P all-reduce, skinny and tiled quantised GEMM, rotate-and-quantise fusions. Built when ROCm is present and the build targets a `gfx12` card |
|
||||
| `libr4d` | the device library: AMD RDNA4 (`gfx12xx`). Paged and dense attention, gated delta net, all-reduce over P2P or a host-memory mailbox, skinny and tiled quantised GEMM, rotate-and-quantise fusions. Built when ROCm is present and the build targets a `gfx12` card |
|
||||
| `libref` | every op naively and generically. The last-resort fallback **and** the correctness oracle `rad-kbench` measures against |
|
||||
| `libavx` | the host library: the same vocabulary in hand-written x86 SIMD, dispatched by CPU feature at load. Serves every op placed on the host, the n-gram embedding's gather among them. Built on x86-64 |
|
||||
|
||||
@@ -311,6 +311,33 @@ rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
|
||||
The conversions of record live in `scripts/convfn.sh` and `scripts/convdspark.sh`, with their
|
||||
recipes in `data/recipes/`.
|
||||
|
||||
**A release someone else already quantised is read as it ships.** Two forms are imported weight
|
||||
by weight, so their quantised linears need no recipe rule:
|
||||
|
||||
| `quantization_config` | read as | |
|
||||
|---|---|---|
|
||||
| `quark`, MXFP4 weights (fp4, per_group 32, e8m0) | `fp4_e2m1*e8m0[1x32]` | byte for byte: the same codes and exponents. A checkpoint of this form is also served as it stands (§3.4) |
|
||||
| `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16. Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped |
|
||||
|
||||
The width is read per tensor, so a release mixing int4 experts with int8 projections imports both.
|
||||
What an import cannot read — an asymmetric zero point, an act-order index, a group under 128 — is
|
||||
refused by name at the weight. The release's `quantization_config` names the tool, not a served
|
||||
form, so it is kept in the container as `imported_quantization_config.*`, and the model is served by
|
||||
its family's quantised plugin (`qwen35_fp8` for Qwen3.8-27B; `qwen4exp_fp8` for Flash-Next).
|
||||
|
||||
A weight the architecture declares in another form than the release holds still takes a rule: the
|
||||
recipe dequantises the import exactly and quantises from that. The two recipes of record:
|
||||
|
||||
```sh
|
||||
# AMD's Quark AWQ-MXFP4 Qwen3.8-27B with the DFlash2 drafter
|
||||
rad-convert ~/models/amd/Qwen3.8-27B-Quark-AWQ-MXFP4 --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 \
|
||||
--recipe data/recipes/q38-27b-quark-mxfp4-df2.recipe -o q38-27b-quark-mxfp4-df2.rad
|
||||
|
||||
# An AutoRound int4 Qwen3.8-Flash-Next: its experts imported, its int4 projections made int8
|
||||
rad-convert ~/models/ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound \
|
||||
--recipe data/recipes/qwen4exp-autoround-i8-hc8m.recipe -o swift-autoround.rad
|
||||
```
|
||||
|
||||
### 3.3 Look at what you built
|
||||
|
||||
```sh
|
||||
@@ -427,6 +454,20 @@ The cache never gets less than one `--max-model-len` sequence, and when both sid
|
||||
whole. With a lending cache, `--host-pool-mib` is what moves the split: a larger pool takes experts
|
||||
off the card and gives the cache more.
|
||||
|
||||
**An uneven world re-splits its cheaper ranks.** The split above is worked out once, for the rank
|
||||
whose cache costs most, and one block table serves every rank. Where a rank's cache costs less per
|
||||
token -- an attention-zero rank at `--tp 3` keeps no attention cache -- it gets, under
|
||||
`expert_tiered` with both pools derived, a KV pool that pages exactly the common token count and the
|
||||
difference in its weights pool, up to every one of its weights resident; the startup log names the
|
||||
rank and both sizes (`kv: rank N's cache costs ...`). It holds with or without a lending cache:
|
||||
under `--deterministic`, or on a device without virtual memory management, the bytes that rank
|
||||
would never page go to its experts all the same. A stated `--vram-kv-mib` or `--vram-weights-mib`
|
||||
is applied to every card unchanged, and a rank whose cache costs as much per token as the dearest
|
||||
rank's is never re-split -- which at `--tp 2` and `--tp 4` is every rank. A rank that costs less and
|
||||
keeps the common split says why on the same `kv: rank N's cache costs ...` line. Every rank still
|
||||
allocates its whole `--host-pool-mib`, a re-split rank whose weights all fit on the card included,
|
||||
and that rank's log says its pinned host pool holds no weights ([`TP3.md`](TP3.md) §1).
|
||||
|
||||
**The cache's size decides whether multi-turn works.** The KV side is not only concurrency: prefix
|
||||
caching holds a finished sequence's blocks so the next turn can reuse them. When the pool cannot
|
||||
hold the *live sessions*, the cache drops prefixes the next turn wanted and that turn re-prefills
|
||||
@@ -543,16 +584,18 @@ run to pay for cache nobody is using.
|
||||
|
||||
What it leans on is `--gpu-headroom-mib`. That reserve is what the card keeps for allocations
|
||||
this engine does not make — chief among them a kernel's code object, which HIP loads on the
|
||||
kernel's *first launch*, not at startup. A deployment whose budget settles *below* its stated
|
||||
headroom has already spent it, and the slab growing into what is left collides with the first
|
||||
kernel that has never run: a draft head's, a sampler chain's, whatever the early requests did not
|
||||
reach. It fails its load and faults inside the HIP runtime, which arrives as a segfault in a
|
||||
kernel that is correct, on a server that had been serving fine.
|
||||
kernel's *first launch*, not at startup. A card with too little of it left collides with the
|
||||
first kernel that has never run: a draft head's, a sampler chain's, whatever the early requests
|
||||
did not reach. It fails its load and faults inside the HIP runtime, which arrives as a segfault in
|
||||
a kernel that is correct, on a server that had been serving fine.
|
||||
|
||||
Startup measures that shortfall and holds it back on top of the reserve, so a run that did not
|
||||
quite keep its headroom is safe rather than fatal — but it is costing you the VRAM twice. Raise
|
||||
`--gpu-headroom-mib` past the number startup names, so the budget resolver sees it and the expert
|
||||
plane is sized against it instead of trimmed afterwards.
|
||||
Startup checks what is left once everything is allocated (`card N settled at ... free`). Memory
|
||||
taken after the budget read the card — another process on it, such as a desktop, or a driver
|
||||
allocation — comes out of the headroom, and the line says how much. It warns only when the room
|
||||
left for first launches is under the 96 MiB the engine allows for its own, and then names the
|
||||
`--gpu-headroom-mib` value that clears it: what is left rises one for one with the flag, so that
|
||||
value is a fixed point. A larger headroom that lost part of itself to another process is reported
|
||||
on the INFO line and not warned.
|
||||
|
||||
What the engine itself allocates after the card is read is charged before the split, so it never
|
||||
comes out of the headroom: the step staging, the KV tiers' copy staging, and its hardware queues.
|
||||
@@ -697,6 +740,42 @@ error that says so rather than being quietly ignored.
|
||||
|
||||
When you measure speculation, **measure step time, not tokens per second.**
|
||||
|
||||
A drafter with a sliding window over its own cache (DFlash2) keeps that cache outside the prefix
|
||||
cache, so a prefix hit leaves it with nothing to attend to for the cached part of the prompt, and
|
||||
it cannot draft until its window has slid past the hit. On the follow-up turn of a chat that is
|
||||
most of the reply. Such a hit is therefore ended one drafter window before the end of the prompt,
|
||||
at a checkpoint: the window is recomputed, which costs that much prefill, and the drafter drafts
|
||||
from the first token. The reply is the same either way. A hit whose nearest checkpoint below that
|
||||
point would give back more than two windows is kept whole. `radiance:draft_refills_total` counts
|
||||
the hits ended early and `radiance:draft_refill_tokens_total` the tokens they recomputed.
|
||||
|
||||
**One depth for every request is a compromise; `--draft-window adaptive` lets the text decide.**
|
||||
Acceptance depends on the text: code and JSON keep accepting deep into the window, prose and
|
||||
summaries fall off after a position or two. With the adaptive window, `--num-speculative-tokens` is
|
||||
the ceiling and the engine keeps a smoothed acceptance per draft position for every sequence:
|
||||
|
||||
```sh
|
||||
radiance --model m.rad --num-speculative-tokens 6 --draft-window adaptive
|
||||
```
|
||||
|
||||
A serial draft head runs as many rounds as the deepest window in the step, so the depth is chosen
|
||||
for the step, not for one sequence: each step's head depth is the one that maximises the tokens all
|
||||
its sequences are expected to emit over what such a step costs. The cost is measured as the server
|
||||
runs — the time of every decode step, by its depth and by how many sequences it carried — so there
|
||||
is nothing to enter; a depth not yet measured is priced from the nearest one that was. Under that
|
||||
depth each sequence stops at the first draft that would be emitted — it and every draft before it
|
||||
accepted — less than one time in ten, so a prose reply beside a code reply does not pay verify rows
|
||||
for drafts nobody takes. The depth moves only after eight steps and for a two-percent gain, because
|
||||
every new window is a new pass shape and a new recording. A new sequence starts from what the
|
||||
sequences before it finished on, each counted once.
|
||||
|
||||
The adaptive window is the serial draft head's policy. With a block drafter, with prompt lookup
|
||||
alone, or with speculation off the window stays fixed, and the server says so at startup. Prompt
|
||||
lookup proposals made when the head declines are counted in the acceptance metrics but do not move
|
||||
the head's window. At temperature 0 the text is that of a fixed depth wherever fixed depths agree
|
||||
with each other; above 0 it is distribution-exact. `radiance:draft_depth_adaptive` and
|
||||
`radiance:draft_verify_depth_total` (§6.3) show where the windows stand. The default is `fixed`.
|
||||
|
||||
### 4.7 Two cards
|
||||
|
||||
```sh
|
||||
@@ -729,13 +808,25 @@ the decode and verify steps — up to `--max-num-seqs` × (1 + `--num-speculativ
|
||||
prefill chunk, and a message that goes out on the tiered-int8 wire, runs the unfused chain, where
|
||||
the all-reduce's own size choice between one-shot and two-shot applies.
|
||||
|
||||
**The cards must reach each other's memory directly** (peer to peer, P2P). The all-reduce
|
||||
kernels push into the other card's memory. At launch radiance asks the driver, for every pair of
|
||||
the cards it will use, whether that works, and logs the answer. When some pair cannot, those
|
||||
kernels are not selected, and startup stops naming `device.p2p` instead of the first all-reduce
|
||||
faulting or hanging. Whether P2P works is decided by the platform: the IOMMU setting, the PCIe
|
||||
topology, and whether the cards sit behind a switch that allows peer traffic. The startup line
|
||||
names the pairs that failed.
|
||||
**Cards that cannot reach each other's memory still serve.** The all-reduce kernels normally push
|
||||
into the other card's memory directly (peer to peer, P2P). At launch radiance asks the driver,
|
||||
for every pair of the cards it will use, whether that works, and logs the answer. Whether it does
|
||||
is decided by the platform: the IOMMU setting, the PCIe topology, and whether the cards sit behind
|
||||
a switch that allows peer traffic. When some pair cannot, the same kernels run with their
|
||||
exchange buffers in pinned host memory instead: every card writes its share to host RAM over its
|
||||
own link and reads the others' back the same way, and no card touches another card's VRAM. The
|
||||
startup line names the pairs that failed, and the selection report names the `_host` rows that
|
||||
took the collectives. The results are the same bytes either way; the cost is a message crossing
|
||||
two links instead of one. On two R9700s on PCIe 4.0 that cost is within run-to-run noise for
|
||||
decode, at one stream and at four, and 2–10% on a 23.6K-token prefill, because there the peer
|
||||
link is no faster than the host link. A machine whose cards reach host memory over a narrower
|
||||
link than they reach each other pays more.
|
||||
|
||||
`--p2p` overrides the driver's answer. `off` takes the host-memory path even where the driver
|
||||
reports peer access, for a board where peer traffic is broken or slow while the driver still says
|
||||
it works. `on` takes the peer-to-peer kernels and stops at startup, naming the pairs, if the driver
|
||||
refuses any of them, so a deployment measured on P2P never quietly serves on host memory. `auto`,
|
||||
the default, trusts the driver.
|
||||
|
||||
### 4.8 Finished conversations: copied to host, VRAM given up on demand
|
||||
|
||||
@@ -853,6 +944,24 @@ refuses is a warning at startup: requests that send their own effort still work.
|
||||
radiance --model m.rad --reasoning-effort medium
|
||||
```
|
||||
|
||||
**The template's set is probed at startup** by rendering each of `low`, `medium`, `high`, `xhigh`
|
||||
and `max`, and startup names the ones it takes. `/server_info` publishes them as
|
||||
`capabilities.reasoning_efforts` (with `none` and `minimal`, which are the server's own; `null`
|
||||
when the template takes any word). A request outside the set gets a 400 with `param:
|
||||
"reasoning_effort"`, `code: "unsupported_value"` and the set in `error.supported`, rather than the
|
||||
template's traceback.
|
||||
|
||||
**`--reasoning-effort-map FROM=TO,...`** rewrites a request's effort before the template sees it,
|
||||
for a client that always sends a word of OpenAI's ladder. Qwen3.8 has no `high`, so:
|
||||
|
||||
```sh
|
||||
radiance --model m.rad --reasoning-effort-map high=xhigh
|
||||
```
|
||||
|
||||
It applies to both spellings (`reasoning_effort` and `chat_template_kwargs.reasoning_effort`), and
|
||||
before `none` and `minimal` are read, so `minimal=low` keeps thinking on. A `TO` the template
|
||||
refuses stops startup.
|
||||
|
||||
**`--thinking-token-budget N`** caps the reasoning instead of its depth. At N tokens inside the
|
||||
reasoning block the block is closed, by masking the next position to its end token
|
||||
(`</think>`), and the answer follows. This makes a client's `max_tokens` buy an answer, where
|
||||
@@ -885,6 +994,7 @@ one line naming each one the command line moved.
|
||||
| `--max-num-batched-tokens N` | 8192 | largest token count one step may carry |
|
||||
| `--max-num-seqs N` | 256 | largest number of sequences one step may carry |
|
||||
| `--max-model-len N` | 0 | context bound; 0 takes the model's training context |
|
||||
| `--rope-scaling SPEC` | — | `yarn:FACTOR[:ORIG]`: static YaRN over the container's own rotary keys, no reconvert; `none` takes a checkpoint's YaRN off ([YARN.md](YARN.md)) |
|
||||
|
||||
**Memory**
|
||||
|
||||
@@ -925,12 +1035,14 @@ one line naming each one the command line moved.
|
||||
| `--tp N` | 1 | tensor-parallel ranks |
|
||||
| `--tp-wire MODE` | exact | `exact` or `wht6`, the lossy wire (§4.7) |
|
||||
| `--tp-wire-min-kb N` | 128 | smallest all-reduce the lossy wire is used for |
|
||||
| `--p2p MODE` | auto | `auto` asks the driver, `on` requires peer access, `off` exchanges through host memory (§4.7) |
|
||||
|
||||
**Speculation**
|
||||
|
||||
| flag | default | |
|
||||
|---|---|---|
|
||||
| `--num-speculative-tokens N` | auto | speculative window; 0 disables |
|
||||
| `--num-speculative-tokens N` | auto | speculative window; 0 disables. The ceiling under `--draft-window adaptive` |
|
||||
| `--draft-window MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, serial draft heads only (§4.6) |
|
||||
| `--draft-model PATH` | — | **not implemented** — merge at convert time |
|
||||
|
||||
**Server**
|
||||
@@ -971,6 +1083,7 @@ that names the field wins.
|
||||
| `--max-stop-strings N`, `--max-stop-bytes N` | 64, 4096 | how many stop strings a request may send, and how long each may be |
|
||||
| `--chat-template-kwargs JSON` | — | variables for the chat template on every chat request; a JSON object or `@FILE`, repeatable |
|
||||
| `--reasoning-effort S` | template's own | default `reasoning_effort` for chat |
|
||||
| `--reasoning-effort-map MAP` | — | `FROM=TO,...`: a request's `reasoning_effort` rewritten before the template sees it; `TO` is checked at startup |
|
||||
| `--thinking-token-budget N` | none | default `thinking_token_budget` for chat: the reasoning block is closed at N tokens |
|
||||
| `--reasoning-format MODE` | auto | `auto` returns reasoning as `reasoning_content`; `none` leaves it inline in `content` |
|
||||
|
||||
@@ -1213,9 +1326,9 @@ curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \
|
||||
| `ignore_eos` | generate to `max_tokens` whatever the model emits |
|
||||
| `stream`, `stream_options.include_usage` | |
|
||||
| `logprobs`, `top_logprobs` | **not implemented** — refused, not returned as nulls. `/server_info` reports `logprobs: false` |
|
||||
| `tools`, `tool_choice`, `parallel_tool_calls` | chat only |
|
||||
| `tools`, `tool_choice`, `parallel_tool_calls` | chat only. `tool_choice` is `auto`, `none`, `required` or `{"type":"function","function":{"name":...}}`; the last two hold the whole reply to calls (after the reasoning block), the named form to that one function, and cannot be combined with `response_format` or `grammar` |
|
||||
| `add_generation_prompt`, `chat_template_kwargs` | chat only |
|
||||
| `reasoning_effort`, `enable_thinking` | chat only |
|
||||
| `reasoning_effort`, `enable_thinking` | chat only. The levels are the template's (`capabilities.reasoning_efforts` on `/server_info`); `none` and `minimal` turn thinking off |
|
||||
| `thinking_token_budget`, `thinking_budget` | chat only. ≥ 0: the reasoning tokens after which the block is closed — see §5.2. Default `--thinking-token-budget`, else none |
|
||||
| `preserve_thinking` | chat only. The chat template variable of that name, as llama.cpp maps it; Qwen3.6 and later keep earlier turns' reasoning in the prompt with it |
|
||||
| `response_format` | chat only. Mutually exclusive with `grammar` |
|
||||
@@ -1375,8 +1488,9 @@ the startup log too — but a startup log is on a machine, in a file, from a pro
|
||||
been restarted since.
|
||||
|
||||
Its `request_defaults` object says what a request that leaves a field out is served with: every
|
||||
sampler field, `max_tokens`, `reasoning_effort`, `chat_template_kwargs` and `reasoning_format`,
|
||||
under the request's own spelling of each. `server.default_max_tokens` is `null` for `auto`, and
|
||||
sampler field, `max_tokens`, `reasoning_effort`, `reasoning_effort_map`, `chat_template_kwargs` and
|
||||
`reasoning_format`, under the request's own spelling of each. `capabilities.reasoning_efforts`
|
||||
lists the efforts the chat template takes, or is `null` when it takes any. `server.default_max_tokens` is `null` for `auto`, and
|
||||
`server.max_tokens_cap` is `null` when there is none.
|
||||
|
||||
### 6.3 Metrics
|
||||
@@ -1398,8 +1512,10 @@ under the request's own spelling of each. `server.default_max_tokens` is `null`
|
||||
| `decode_tokens_total`, `prefill_tokens_total` | |
|
||||
| `decode_tokens_per_second`, `prefill_tokens_per_second` | |
|
||||
| `draft_tokens_total`, `draft_accepted_total`, `draft_acceptance_ratio` | |
|
||||
| `draft_position_reached_total`, `draft_position_acceptance_ratio` | acceptance by position, since start |
|
||||
| `draft_position_reached_total`, `draft_position_accepted_total`, `draft_position_acceptance_ratio` | acceptance by position: the two counters over any window, the ratio since start |
|
||||
| `draft_refills_total`, `draft_refill_tokens_total` | prefix hits ended a drafter window early, and the tokens recomputed (§4.6) |
|
||||
| `decode_rows_unspeculated_total` | rows that never drafted at all |
|
||||
| `draft_depth_adaptive`, `draft_verify_depth_total{depth}` | the adaptive window's mean over the running sequences, and verifies by the drafts they carried; only with `--draft-window adaptive` (§4.6) |
|
||||
| `attn_cached_tokens_total`, `linear_cached_tokens_total` | prefix reuse, both halves |
|
||||
| `linear_checkpoints_written_total`, `linear_prefix_cache_hit_rate` | |
|
||||
| `prefix_cache_evictions_total`, `prefix_cache_ckpt_evictions_total` | |
|
||||
@@ -1483,11 +1599,11 @@ released until it does.
|
||||
| `chat is 501` in the startup line | The container carries no chat template | Re-convert with `--tokenizer`, and check that a `chat_template.jinja` sits beside `tokenizer_config.json` in the checkpoint. Meanwhile use `/v1/completions` |
|
||||
| `does not read '<weight>' encoded <encoding>` at startup | No loaded kernel takes that weight's encoding for the op that reads it | Convert with a recipe that writes an encoding a loaded kernel reads, or load the library that reads it |
|
||||
| Prefix hit rate 0% and every turn re-prefills | The KV pool cannot hold the live sessions, so the cache evicts what the next turn wanted | The cache already has everything the experts can do without: a larger `--host-pool-mib` (RAM permitting), `--kv-cache-dtype fp8`, or fewer/shorter sessions. See §4.3 |
|
||||
| The server dies with no log line, on a request it had been serving fine | A kernel whose code object had never been loaded could not be: the card has no room left. HIP faults inside the launch rather than returning an error, so there is nothing to print | A card that never met `--gpu-headroom-mib` — see §4.3. Raise the headroom past the shortfall startup names. `coredumpctl info` names the kernel; `AMD_LOG_LEVEL=1` prints `HSA_STATUS_ERROR_OUT_OF_RESOURCES` just above the fault |
|
||||
| The server dies with no log line, on a request it had been serving fine | A kernel whose code object had never been loaded could not be: the card has no room left. HIP faults inside the launch rather than returning an error, so there is nothing to print | A card left with too little room for a first launch — see §4.3. Set `--gpu-headroom-mib` to the value the startup warning names. `coredumpctl info` names the kernel; `AMD_LOG_LEVEL=1` prints `HSA_STATUS_ERROR_OUT_OF_RESOURCES` just above the fault |
|
||||
| KV in VRAM stays high with one session and nothing moves | The idle tiers are **off** — they are sized, and with no size nothing is copied | Pass `--prefix-cache-host-mib N` |
|
||||
| `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for |
|
||||
| `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps pinned memory system-wide at `ttm.pages_limit`, half of RAM by default | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under the cap the refusal names, or raise it with the kernel parameter `ttm.pages_limit` |
|
||||
| `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode was seen to refuse any single pin above about 2.5 GiB; a piece failing means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through but on that host also removed peer access between the cards, and every multi-rank kernel requires it. Report the kernel version, the IOMMU mode and the refusal line |
|
||||
| `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode was seen to refuse any single pin above about 2.5 GiB; a piece failing means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through but on that host also removed peer access between the cards, which moves every all-reduce onto the slower host-memory path. Report the kernel version, the IOMMU mode and the refusal line |
|
||||
| `--draft-model is not implemented` | This engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time |
|
||||
| `context_length_exceeded` on a request | The **prompt alone** does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate at all | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it |
|
||||
| `unknown option '--foo'` and the engine exits | Deliberate. A typo in a budget flag is the difference between the plan you asked for and one the planner invented | Check `radiance --help` |
|
||||
|
||||
+1
-1
@@ -232,7 +232,7 @@ not.
|
||||
| `ple_gate` | | device | host |
|
||||
| `qk_norm_rope` | | - | host |
|
||||
| `qk_norm_rope_gate` | | device | - |
|
||||
| `qsa_block_key` | | device | - |
|
||||
| `qsa_block_key` | | device | host |
|
||||
| `qsa_score` | | device | - |
|
||||
| `qsa_select` | | device | - |
|
||||
| `qsa_tail_store` | | device | - |
|
||||
|
||||
+11
-5
@@ -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
|
||||
@@ -1161,11 +1161,11 @@ stages of its sorting network when the runs are a power of two long and fill the
|
||||
over two runs of 1024 where a full sort is 66 -- and the whole network otherwise. A producer that
|
||||
hands it unsorted runs gets a wrong order, not a slow one.
|
||||
|
||||
## Sparse attention (QSA) — device-only
|
||||
## Sparse attention (QSA)
|
||||
|
||||
| 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` |
|
||||
@@ -1173,7 +1173,8 @@ hands it unsorted runs gets a wrong order, not a slow one.
|
||||
|
||||
Five ops decompose one thing: an indexer that scores blocks of key history against the query and
|
||||
hands `attn_paged` a shorter block table. `docs/QSA.md` is that decomposition; these are the
|
||||
schemas, and `arch/common/rad_qsa.h` issues all five.
|
||||
schemas, and `arch/common/rad_qsa.h` issues all five. **`qsa_block_key` has a host kernel in libref
|
||||
and libavx** -- the oracle for libr4d's, YaRN included -- and the other four are **device-only**.
|
||||
|
||||
`qsa_block_key` builds the **compressed key**: one vector per `ratio` tokens of key history, which
|
||||
is what the indexer's block scores are taken against.
|
||||
@@ -1182,6 +1183,11 @@ is what the indexer's block scores are taken against.
|
||||
out[b] = rope( rmsnorm( mean over j<ratio of k[b*ratio + j] ), at position pos0 + b*ratio )
|
||||
```
|
||||
|
||||
The rotation is `rope`'s NeoX ladder over the first `rotary_dim` lanes, with `rope`'s YaRN
|
||||
coefficients (`yarn_factor`, `yarn_low`, `yarn_high`, `yarn_magnitude`) when given -- the
|
||||
attention's own rotary, so a compressed key and the keys it summarises are rotated alike. With
|
||||
YaRN, `scale` must be 1.
|
||||
|
||||
**`M` is BLOCKS and `k` is `ratio` times taller.** Every other op in this document has one output
|
||||
row per input row. A caller that sized `k` at the block count would have every block pool three
|
||||
rows of the next one — plausible numbers and a different model — so libr4d's entry point checks it.
|
||||
|
||||
+3
-1
@@ -103,7 +103,9 @@ op's parameters. `RAD_CEQ(RAD_FACT_P2P, 1)` (`device.p2p`) is how a kernel says
|
||||
another card's memory. On a machine where some pair of the ranks' cards cannot reach each other,
|
||||
such a kernel is not selected. The next row that does not need it takes the op. With no such row,
|
||||
startup stops and the selection table names the fact (`device.p2p == 1, have 0 -- this machine,
|
||||
measured at launch`). Every collective in libr4d carries it. A machine fact is in no geometry, so
|
||||
measured at launch`). Every collective in libr4d carries it, and each has a `_host` twin that
|
||||
requires `device.p2p == 0` and exchanges through pinned host memory, so exactly one of the pair
|
||||
matches any machine. A machine fact is in no geometry, so
|
||||
it changes no tuning key. A tool that selects without an engine has measured nothing, and such a
|
||||
kernel is not selected there either.
|
||||
|
||||
|
||||
+30
@@ -38,6 +38,36 @@ it, and the tiers skip it when they move an entry. Every rank carves the same bl
|
||||
is planned, asked what it could page (`KVManager::paged_tokens`; a rank whose only paged groups are
|
||||
zero limits nobody) and capped at the least before any carves.
|
||||
|
||||
**The attention-zero rank's pools are its own.** The budget resolver derives one split for every
|
||||
card, the dearest rank's -- and an attention-zero rank's cache costs a fraction of its peers' per
|
||||
token (at TP3 on Flash-Next it keeps only the QSA block keys: 2.3 GiB at the worst case where an
|
||||
attention rank's costs 15.2). Under `expert_tiered` with both pools derived, `Engine::plan` gives
|
||||
such a rank a KV pool that pages exactly the common token count (`KVManager::pool_mib_for_tokens`,
|
||||
the inverse of `paged_tokens`: the least whole MiB whose paged split reaches the count, exact
|
||||
because the split is monotone in the budget and its alignment is among the fixed costs) and moves the
|
||||
difference into its weights pool, no further than every one of its weights resident. Both readers
|
||||
of the resolved sizes take the rank's own split -- `Pools::configure` and the planner -- so the
|
||||
grown pool is planned into, and startup refuses a rank whose plan and weights pool disagree, or
|
||||
whose re-sized KV pool pages fewer tokens than it was sized for. The token count, the carve, the
|
||||
loan and the attention ranks' pools are unchanged; a stated `--vram-kv-mib` / `--vram-weights-mib`
|
||||
keeps meaning "this many on every card", and `auto` keeps the common split (a fully resident rank
|
||||
would choose all_vram while its peers spill). `--deterministic` and a device without virtual memory
|
||||
management re-split like any other: the cache does not lend there, and the bytes the rank never
|
||||
pages are as much its experts' as they are under a lending cache. The condition is the cost, not
|
||||
the world: a rank is re-split only where its cache costs less per token than the dearest rank's,
|
||||
which at TP2/TP4 no rank does. A rank that qualifies and keeps the common split names the reason on
|
||||
its `kv: rank N's cache costs ...` line. The pinned host pool is not re-split: every rank allocates
|
||||
its whole `--host-pool-mib`, and a re-split rank whose weights all fit on the card says so
|
||||
(`its pinned host pool holds no weights`). The log line, and the mover on the third rank:
|
||||
|
||||
```
|
||||
kv: rank 2's cache costs 2.27 GiB at the worst case where its dearest peer's costs 15.16 GiB, so its KV pool pages the common 1446302 tokens in 1811 MiB instead of 10881; its weights pool grows 19747 -> 21692 MiB (every weight resident wants 21.18 GiB), and 7125 MiB stay unclaimed
|
||||
I[2] mover: 25142 slab slots (64 shadow), 0 pinned pool slots
|
||||
```
|
||||
|
||||
The settle check's INFO line on that card names the unclaimed MiB and points at this line rather
|
||||
than at the budget's `unusable` line alone.
|
||||
|
||||
Under a smaller attention world the plain even shard over `world` is the wrong cut for every
|
||||
attention projection, so the attention ranks declare **spans** (`rad_weight_shard_span`, the same
|
||||
call the KV replication uses for k/v): q|gate rows and output columns `[attn_rank * n_head,
|
||||
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
# Static YaRN
|
||||
|
||||
Increasing `--max-model-len` reserves a larger serving window; it does not change
|
||||
the model's rotary embeddings. A 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.
|
||||
|
||||
One reader takes every architecture's rotary scaling (`yarn_from`,
|
||||
`arch/common/rad_arch.h`). For the target it reads `text_config.rope_parameters`,
|
||||
then `rope_parameters`, then the legacy `text_config.rope_scaling` and `rope_scaling`,
|
||||
in that order; the first object with `rope_type` (or legacy `type`) is authoritative.
|
||||
A drafter (DFlash2, DSpark) 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. A GGUF's `rope.scaling.*` keys are carried in as the
|
||||
same `rope_scaling` keys when it is read.
|
||||
|
||||
**The factor convention is the config's**, as vLLM and transformers read it:
|
||||
`factor` 2 over `original_max_position_embeddings` 262144 reaches 524288 positions.
|
||||
|
||||
Validated so far: the Qwen3.8 27B and 35B-A3B containers and both Flash-Next
|
||||
variants at factor 2, with retrieval at ~500K tokens, and TP3 perplexity with
|
||||
`--rope-scaling` within roughly ±1% of stock at factor 2. The LLaMA plugins read the
|
||||
same keys and declare the same ops; YaRN there has had no model run.
|
||||
|
||||
## Metadata
|
||||
|
||||
| Key within the rotary object | Meaning |
|
||||
| --- | --- |
|
||||
| `rope_type` | `yarn`; `default`, absent or legacy `mrope` is no scaling; `linear` divides positions by `factor` |
|
||||
| `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` | true/1 (default): floor/ceil correction bounds; false/0: retain fractional bounds |
|
||||
|
||||
Every other type -- `llama3`, `longrope`, `dynamic` -- is refused by name at load,
|
||||
as are the `mscale` and `mscale_all_dim` variants (specify `attention_factor`). A
|
||||
GGUF that sets llama.cpp's YaRN `attn_factor`, `ext_factor` or log multiplier to
|
||||
anything but its neutral value is refused when read. 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.
|
||||
|
||||
## Serve an existing container: `--rope-scaling`
|
||||
|
||||
The same metadata can be written when the container is loaded instead of converted in:
|
||||
|
||||
```sh
|
||||
radiance --model /models/qwen3.8-next-flash-fp8.rad \
|
||||
--rope-scaling yarn:2 --max-model-len 409600
|
||||
```
|
||||
|
||||
`yarn:FACTOR[:ORIG]` sets `rope_type = yarn`, `factor` and `original_max_position_embeddings`
|
||||
(`ORIG`, default the container's own trained length) in the rotary object the reader above
|
||||
takes first -- for a Qwen3.8 container that is `text_config.rope_parameters`, which already says
|
||||
`default`; YaRN written under plain `rope_parameters` would sit behind it and never be read. A
|
||||
drafter gets the same factor over its own trained length. Over a checkpoint's own YaRN
|
||||
the factor is replaced, its trained length kept unless `ORIG` is given, and an explicit
|
||||
`attention_factor` (or `mscale` variant) dropped so the magnitude is derived for the new factor.
|
||||
`none` takes a checkpoint's YaRN off. A linear or other explicit rotary type is refused rather
|
||||
than stacked over. The result is resolved and checked exactly as a converted container's is
|
||||
(`core/format/rope_override.h`, held to `yarn_from` in `tests/yarn_test.cpp`).
|
||||
|
||||
Startup says what the rotary is (`rope: YaRN factor 2 over 262144 trained positions -- the rotary
|
||||
reaches 524288`) and warns when `--max-model-len` is past what it covers -- also with no scaling
|
||||
at all, past the trained length. A persisted prefix cache (`--prefix-cache-dir`) is fingerprinted
|
||||
with the resolved rotary of the target and the drafter, so a store written under a different
|
||||
one -- another `--rope-scaling`, or a container converted with YaRN -- is not reused: every cached
|
||||
key was rotated differently.
|
||||
|
||||
The flag is for trying a factor, or serving a container whose source checkpoints are not at hand;
|
||||
a deployment that settles on one can convert it in as above and drop the flag.
|
||||
|
||||
## Kernel and test contract
|
||||
|
||||
`rope`, `rope_table` and `qsa_block_key` take optional resolved coefficients
|
||||
`yarn_factor`, `yarn_low`, `yarn_high`, `yarn_magnitude` (docs/OPS.md). Absent factor
|
||||
is the original path, with the original op identities. 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.) as vLLM's
|
||||
`YaRNScalingRotaryEmbedding` implements it. `tests/yarn_test.cpp` pins the
|
||||
correction bounds to vLLM's integers (14/22, 28/43, 56/85 for rotary widths 64, 128,
|
||||
256 at factor 2, theta 1e7, 262144 trained positions); `tests/ref_test.cpp` and
|
||||
`r4d_selftest` compare libref and libr4d against a double-precision evaluation of the
|
||||
same formula at positions through 524287, within 8 ulp of each angle -- tight where
|
||||
the ramp sits, loose only in the fastest pairs at long positions, which no f32 rotary
|
||||
places better than its angle's own ulp. libavx is held to libref by `avx_check`, and
|
||||
fused versus unfused HIP rotation is checked byte-for-byte separately.
|
||||
+118
-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)) {
|
||||
@@ -972,3 +987,105 @@ AVX_KERNEL(rope_table) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ qsa_block_key */
|
||||
/* QSA's compressed key (docs/OPS.md): a block's `ratio` rows of k averaged in f32 and rounded to
|
||||
* k's dtype, RMS-normed with gain (wadd + w), then NeoX-rotated over `rotary_dim` at the block's
|
||||
* position, YaRN included. libref's arithmetic in libref's order; what differs is that the angles
|
||||
* of a block come from one `angles` table, and the inverse frequencies are built once a launch. */
|
||||
AVX_KERNEL(qsa_block_key) {
|
||||
const RadTensor* k = rad_arg_in(a, 0);
|
||||
const RadTensor* w = rad_arg_in(a, 1);
|
||||
const RadTensor* page = rad_arg_in(a, 2);
|
||||
const RadTensor* pos = rad_arg_in(a, 3);
|
||||
const RadTensor* out = rad_arg_in(a, 4);
|
||||
if (!k || !w || !out) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
|
||||
const int64_t rot = p_int(a, "rotary_dim", 0), pos0 = p_int(a, "pos0", -1);
|
||||
if (n <= 0 || ratio <= 0 || (pos0 < 0 && !pos)) return RAD_E_INVAL;
|
||||
if (rot < 0 || rot > n || (rot & 1) || rot / 2 > 512) return RAD_E_SHAPE;
|
||||
if (p_int(a, "block_size", ratio) != ratio) return RAD_E_SHAPE;
|
||||
if (k->rank != 2 || out->rank < 2 || out->shape[0] < 1) return RAD_E_SHAPE;
|
||||
const int64_t M = page ? numel(page) : out->shape[0];
|
||||
if (M < 1 || numel(out) / out->shape[0] != n) return RAD_E_SHAPE;
|
||||
if (k->shape[0] != M * ratio || k->shape[1] != n || numel(w) < n) return RAD_E_SHAPE;
|
||||
const bool pos2 = pos && pos->rank == 2;
|
||||
if (pos && (pos2 ? pos->shape[0] < M : numel(pos) < M)) return RAD_E_SHAPE;
|
||||
|
||||
const float eps = p_f32(a, "eps", 1e-6f), wadd = p_f32(a, "wadd", 1.0f);
|
||||
const float theta = p_f32(a, "theta", 10000.0f), rscale = p_f32(a, "scale", 1.0f);
|
||||
static const char* kModes[] = { "neox", "mrope", "imrope" };
|
||||
const int mi = p_enum(a, "mode", kModes, 3, 0);
|
||||
if (mi < 0) return RAD_E_UNSUPPORTED;
|
||||
int64_t sec[3] = {};
|
||||
int n_sec = 0;
|
||||
for (const char* v = p_str(a, "sections", nullptr); v && *v;) {
|
||||
char* e = nullptr;
|
||||
const long long x = std::strtoll(v, &e, 10);
|
||||
if (e == v) break;
|
||||
if (x <= 0 || n_sec >= 3) return RAD_E_SHAPE;
|
||||
sec[n_sec++] = x;
|
||||
v = e;
|
||||
}
|
||||
/* Several components only with a mode, its sections and three columns of `pos`. */
|
||||
const bool mc = mi != 0 && n_sec > 0 && pos2 && pos->shape[1] >= 3;
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f)))
|
||||
return RAD_E_INVAL;
|
||||
const int64_t half = rot / 2;
|
||||
float* invf = inv_freqs(half, rot, theta);
|
||||
int comp[512] = {};
|
||||
if (mc) {
|
||||
int64_t total = 0;
|
||||
for (int c = 0; c < n_sec; ++c) total += sec[c];
|
||||
if (mi == 1 && total != half) return RAD_E_SHAPE;
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
int c = 0;
|
||||
if (mi == 1) {
|
||||
int64_t start = 0;
|
||||
while (c + 1 < n_sec && i >= start + sec[c]) { start += sec[c]; ++c; }
|
||||
} else if (n_sec >= 3) {
|
||||
if (i % 3 == 1 && i < 3 * sec[1]) c = 1;
|
||||
else if (i % 3 == 2 && i < 3 * sec[2]) c = 2;
|
||||
}
|
||||
comp[i] = c;
|
||||
}
|
||||
}
|
||||
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
|
||||
float* gain = (float*)scratch_f32_c((size_t)n);
|
||||
for (int64_t t = 0; t < n; ++t) gain[t] = wadd + ldt(w, offlin(w, t));
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * ratio * n >= AVX_PAR_MIN)
|
||||
for (int64_t b = 0; b < M; ++b) {
|
||||
const int64_t orow = page ? ldi(page, offlin(page, b)) : b;
|
||||
if (orow < 0) continue;
|
||||
float* y = scratch_f32((size_t)n);
|
||||
float* cs = scratch_f32_b((size_t)(rot > 0 ? rot : 1));
|
||||
double ss = 0.0;
|
||||
for (int64_t t = 0; t < n; ++t) {
|
||||
float acc = 0.0f;
|
||||
for (int64_t j = 0; j < ratio; ++j) acc += ldt(k, offlin(k, (b * ratio + j) * n + t));
|
||||
uint64_t tmp = 0;
|
||||
st_elem(&tmp, k->dtype, 0, acc / (float)ratio);
|
||||
y[t] = ld_elem(&tmp, k->dtype, 0);
|
||||
ss += (double)y[t] * y[t];
|
||||
}
|
||||
const float s = 1.0f / std::sqrt((float)(ss / (double)n) + eps);
|
||||
for (int64_t t = 0; t < n; ++t) y[t] = y[t] * s * gain[t];
|
||||
const float div = rscale != 0.0f ? rscale : 1.0f;
|
||||
float pc[3] = {};
|
||||
for (int c = 0; c < (mc ? 3 : 1); ++c)
|
||||
pc[c] = (float)(!pos ? pos0 + b * ratio
|
||||
: ldi(pos, offlin(pos, pos2 ? b * pos->shape[1] + c : b))) / div;
|
||||
if (mc) angles_multi(cs, invf, comp, half, pc);
|
||||
else angles(cs, invf, half, pc[0]);
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const float c = cs[i] * yarn.magnitude, sn = cs[half + i] * yarn.magnitude;
|
||||
const float x0 = y[i], x1 = y[half + i];
|
||||
y[i] = x0 * c - x1 * sn;
|
||||
y[half + i] = x0 * sn + x1 * c;
|
||||
}
|
||||
for (int64_t t = 0; t < n; ++t) stt(out, offlin(out, orow * n + t), y[t]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -206,6 +206,36 @@ 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) });
|
||||
}
|
||||
for (double magnitude : {2.0, (double)NAN}) {
|
||||
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", "neox"),
|
||||
HI("rotary_dim", 64), HS("dtype", "bf16"), HF("yarn_factor", 0),
|
||||
HF("yarn_magnitude", magnitude) });
|
||||
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 1e7), HF("scale", 1),
|
||||
HS("dtype", "f32"), HF("yarn_factor", 0), HF("yarn_magnitude", magnitude) });
|
||||
}
|
||||
/* QSA's compressed key at Flash-Next's geometry (n 128, ratio 4, a 64-wide rotary), stock and
|
||||
* with YaRN, positions drawn up to the block count times the ratio. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64),
|
||||
HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 1),
|
||||
HS("dtype", dt) });
|
||||
add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64),
|
||||
HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 0),
|
||||
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" }) {
|
||||
|
||||
+1
-1
@@ -100,7 +100,7 @@ int avx_isa_force(int level);
|
||||
X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \
|
||||
/* ---- attention */ \
|
||||
X(attn_paged) X(attn_dense) X(kv_store) X(rope) \
|
||||
X(rope_table) X(qk_norm_rope) \
|
||||
X(rope_table) X(qk_norm_rope) X(qsa_block_key) \
|
||||
/* ---- mixture of experts */ \
|
||||
X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \
|
||||
X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \
|
||||
|
||||
+25
-2
@@ -218,13 +218,29 @@ 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") };
|
||||
|
||||
/* QSA's compressed key, libr4d's schema exactly (libr4d/r4d_rows.cpp): `block_size` is `ratio`
|
||||
* spelled for the KV group the block-key store is, `page` and `pos` are optional. */
|
||||
static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("ratio"),
|
||||
P_INT("rotary_dim"), P_INTO("pos0"),
|
||||
P_INTO("block_size"), P_F64("eps"), P_F64("theta"),
|
||||
P_F64O("scale"), P_F64O("wadd"), P_STR("dtype"),
|
||||
P_STRO("mode"), P_STRO("sections"),
|
||||
P_F64O("yarn_factor"), P_F64O("yarn_low"),
|
||||
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page"), OPD_O("pos"),
|
||||
OUT("out") };
|
||||
|
||||
static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("n_head_kv"), P_F64("theta"), P_F64("eps"),
|
||||
P_F64O("scale"), P_STRO("mode"),
|
||||
@@ -506,6 +522,10 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense), "dense varlen attention over cu_seqlens." },
|
||||
{ "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." },
|
||||
{ "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." },
|
||||
{ "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey),
|
||||
"QSA's compressed key: the mean of a block's `ratio` rows rounded to k's dtype, RMS-normed with "
|
||||
"gain (wadd + w), rotated at the block's position with `rope`'s ladder and YaRN; libref's "
|
||||
"arithmetic with the angles from one table a block." },
|
||||
{ "rope", ARR(pRope), ARR(oRope), "rotary embedding in place." },
|
||||
{ "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope), "per-head QK norm then rotary embedding." },
|
||||
{ "scale_rows", ARR(pScaleRows), ARR(oScaleRows),
|
||||
@@ -693,6 +713,9 @@ ROW("avx_kv_store", "kv_store", "attn", "scatter k and v into the paged cache",
|
||||
SIMPLE("avx_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, L(rope)),
|
||||
SIMPLE("avx_rope_table", "rope_table", "attn", "cos/sin at each position's own row", DT_FLOAT,
|
||||
L(rope_table)),
|
||||
SIMPLE("avx_qsa_block_key", "qsa_block_key", "attn",
|
||||
"QSA compressed key: pooled, normed and rotated at the block's position", DT_FLOAT,
|
||||
L(qsa_block_key)),
|
||||
SIMPLE("avx_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary embedding",
|
||||
DT_FLOAT, L(qk_norm_rope)),
|
||||
|
||||
|
||||
@@ -108,6 +108,8 @@ set(R4D_UNITS
|
||||
"r4d_gemm_w4a8_tiled|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}"
|
||||
"r4d_gemm_w4a8_prefill|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}"
|
||||
"r4d_gemm_mxfp4a8_nt_m64|"
|
||||
"r4d_gemm_mxfp4a8_tiled|"
|
||||
"r4d_gemm_mxfp4a8_decode|"
|
||||
# Block-scaled FP8 -- the format Qwen3.8-27B-FP8 ships in.
|
||||
# No -D: the 128x128 block is a property of the checkpoint on disk and not a quantiser choice
|
||||
# like RAD_W4_GROUP, so it is a constant in the source and the entry points reject a mismatch.
|
||||
|
||||
@@ -52,6 +52,8 @@ target architecture. They are reported by the `r4d_*_dims()` accessors in
|
||||
| `gemm_w8a16_nt_m64` | 8-bit weight, f16 activation, skinny |
|
||||
| `gemm_w2a8_nt` | 2-bit weight against int8 activation — the fast draft head |
|
||||
| `gemm_mxfp4a8_nt_m64` | OCP-MXFP4 weight, fp8 activation, skinny |
|
||||
| `gemm_mxfp4a8_decode` | the same operands for the decode band (M ≤ 128): split-K across workgroups with a last-arriver reduction, the partial in the op's scratch |
|
||||
| `gemm_mxfp4a8_tiled` | the prefill sibling: the activation re-tiled into fragment order in the op's scratch and read straight into registers, the weight unpacked once per K slab for a 256-row block |
|
||||
| `attn_decode_h128_gqa4_fp8kv` / `..._bf16kv` | head_dim 128, 4 queries per KV head, sliding window — a block-diffusion drafter's geometry. Decode only; `attn_h128_gqa4_have_prefill()` reports 0 so a caller routes long queries to its own fallback |
|
||||
| `rowtopk_bf16` / `rowtopk_bf16_chunks` | exact per-row top-K over a bf16 matrix, two-stage |
|
||||
| `dflash_conv_t2_g16_bf16` | the drafter's causal conv, two taps, 16 groups |
|
||||
|
||||
+37
-1
@@ -262,6 +262,11 @@ int r4d_p2p_copy2d(long dst, long src, long dpitch, long spitch, long width, lon
|
||||
void r4d_ar_ipc_free(long p);
|
||||
void r4d_ar_ipc_memzero(long p, long size);
|
||||
void r4d_ar_ipc_enable_peer(long peer);
|
||||
// Exchange buffers in pinned, fine-grained HOST memory, for cards that cannot reach each other's
|
||||
// VRAM: every card reads and writes the same host pages over its own link. Zeroed, and the
|
||||
// returned address is valid on every card and on the CPU alike. Startup-only.
|
||||
long r4d_ar_host_alloc(long size);
|
||||
void r4d_ar_host_free(long p);
|
||||
// Exact sum, fp32 accumulate, bf16 / fp16 / fp32 payload (dtype 0 / 1 / 2).
|
||||
void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
|
||||
long seq_ctrs, long slot_stride16, long inp, long out, long n_elem,
|
||||
@@ -547,10 +552,25 @@ void r4d_gemm_w8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, i
|
||||
|
||||
// OCP-MXFP4 weight, fp8 activation. e2m1 elements with one E8M0 exponent per 32 K, folded
|
||||
// against a per-row reference exponent so the inner loop has no rescale; fp8 WMMA.
|
||||
// as_group 0 = one f32 activation scale per row, 128 = one per (row, 128 of K) at row stride as_rs.
|
||||
void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c,
|
||||
int M, int K, int N, int WV, int SK, int MB, int NPW, long stream);
|
||||
int M, int K, int N, int WV, int SK, int MB, int NPW,
|
||||
int as_group, int as_rs, long stream);
|
||||
int r4d_gemm_mxfp4a8_nt_m64_max_m(void);
|
||||
int r4d_gemm_mxfp4a8_nt_m64_group(void);
|
||||
// The same weight tiled for PREFILL: a 256-row block reads A fragments straight from a
|
||||
// FRAGMENT-ORDERED copy of the activation (`at`, written by r4d_mxfp4a8_tile_a, at least
|
||||
// r4d_mxfp4a8_tile_a_bytes long) and unpacks the weight once per K slab. TN (2 or 4, 0 = by M) is
|
||||
// the per-wave column width in 16-column fragments. as_group 0 = one f32 activation scale per row,
|
||||
// 128 = one per (row, 128 of K) at row stride as_rs.
|
||||
void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c,
|
||||
int M, int K, int N, int TN, int as_group, int as_rs, long stream);
|
||||
void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream);
|
||||
long r4d_mxfp4a8_tile_a_bytes(int M, int K);
|
||||
int r4d_gemm_mxfp4a8_tiled_group(void);
|
||||
// The DECODE band (M <= 128) is r4d_rad_gemm_mxfp4a8_decode alone: its split-K partial is the op's
|
||||
// scratch, which only the plugin ABI hands over.
|
||||
int r4d_gemm_mxfp4a8_decode_max_m(void);
|
||||
|
||||
// ---- BLOCK-SCALED FP8: the format a checkpoint ships in ----------------------------------------
|
||||
//
|
||||
@@ -632,6 +652,22 @@ void r4d_moe_gemm_pin_prefill(int form);
|
||||
// every class's K a multiple of 256, a format that folds scale groups). The two are bit-identical,
|
||||
// and r4d_selftest compares their bytes.
|
||||
void r4d_moe_gemm_pin_fk(int pin);
|
||||
// THE RUN-ALIGNED FORM'S COLUMN TILE, pinned for a test: 0 is the launcher's shape rule (the down
|
||||
// projection's 256-column tile wherever the sorted operand, one part, a w4 weight and every class's
|
||||
// width allow it), 1 never that tile, 2 that tile -- refused where the shape cannot take it or the
|
||||
// launch is not the aligned form. Bit-identical, and r4d_selftest compares their bytes.
|
||||
void r4d_moe_gemm_pin_down_tile(int pin);
|
||||
// THE GATHER'S FORM, pinned for a test: 0 is the launcher's rule, 1 a column a thread
|
||||
// (gather_kernel), 2 a wave a token and sixteen bytes a lane (gather_wide_kernel), refused on a
|
||||
// shape it cannot take. Bit-identical, and r4d_selftest compares their bytes.
|
||||
void r4d_moe_gather_pin_form(int form);
|
||||
// THE SORTED OPERAND'S DECODE KERNEL, pinned for a test: 0 is the launcher's rule
|
||||
// (moe_down_dec_kernel on the sorted operand, one part, at most 512 experts, at a column-tile count
|
||||
// set by the routed rows -- kMoeDownDecG2Rows), -1 the (tile, run) form, n > 0 moe_down_dec_kernel
|
||||
// at n column tiles a block, capped at 16 and refused on a shape the kernel does not serve. Inside
|
||||
// the decode form only, which r4d_moe_gemm_pin_prefill(2) pins. Bit-identical, and r4d_selftest
|
||||
// compares their bytes.
|
||||
void r4d_moe_gemm_pin_down_dec(int pin);
|
||||
// THE GATED RESIDUAL READ'S PREFILL TILE, pinned for a test: 0 is the launcher's rule, 1 the decode
|
||||
// tiles' kernels at 128 rows (hc_down_tiled, then hc_up_tiled into `ubuf` and hc_mix), 2 the wide
|
||||
// kernels (which then refuse a shape they are not built for), 3 the PF2 kernels the rule takes from
|
||||
|
||||
+69
-21
@@ -120,6 +120,9 @@ struct ArInst {
|
||||
* that buys nothing but round trips: at a 2048-token prefill chunk the capacity rule asks for
|
||||
* 936 blocks and the tuning rule asks for 24. */
|
||||
int nb_cap = 0;
|
||||
/* Where the exchange buffers live: 0 in each rank's own VRAM, written by its peers over P2P;
|
||||
* 1 in pinned host memory that every card reaches over its own link (build, below). */
|
||||
int host = 0;
|
||||
};
|
||||
|
||||
/* A parameter that may have been declared as a RANGE: init is handed the frozen geometry for one
|
||||
@@ -150,13 +153,14 @@ long align16(long v) { return (v + 15) & ~15L; }
|
||||
* residual that is 40 MiB a slot and 80 MiB for the pair. ONE set serves every op that resolved
|
||||
* to the same (rank, world, dtype, bound) -- see the cache below, which is what keeps a 64-layer
|
||||
* model from building 128 of these. */
|
||||
int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code) {
|
||||
int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, int host) {
|
||||
if (world < 2 || world > R4D_MAX_RANKS) return RAD_E_SHAPE;
|
||||
if (rank < 0 || rank >= world) return RAD_E_INVAL;
|
||||
if (max_numel <= 0) return RAD_E_INVAL;
|
||||
|
||||
in->rank = rank;
|
||||
in->world = world;
|
||||
in->host = host;
|
||||
in->dtype = dtype_code;
|
||||
in->esize = r4d_ar_esize(dtype_code);
|
||||
in->max_numel = (long)max_numel;
|
||||
@@ -196,12 +200,26 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code)
|
||||
* invalidates. libr4d's driver falls back to coarse when fine fails; so does this, because a
|
||||
* deterministic fallback stays symmetric across ranks (same environment, same hardware). */
|
||||
int fine_sc = 1, fine_fl = 1, fine_sq = 1;
|
||||
/* WITHOUT PEER ACCESS THE MAILBOX MOVES TO THE HOST, AND NOTHING ELSE CHANGES. Every kernel in
|
||||
* the family touches another rank only through its scratch slots and its flag words -- its
|
||||
* input, its output and its sequence counters are its own card's -- so with those two in
|
||||
* pinned host memory no card ever addresses another card's VRAM, and the same kernels run on a
|
||||
* machine whose PCIe topology or IOMMU forbids peer traffic. A push then lands in host memory
|
||||
* over the writer's link and the reduce reads it back over the reader's, so a message crosses
|
||||
* two links where P2P crosses one; that is the price, and it is paid only where P2P is absent
|
||||
* (the rows that take this path require device.p2p == 0, r4d_rows.cpp). The sequence counters
|
||||
* stay in VRAM: only their own rank reads them. */
|
||||
R4D_TRY("ar_ipc_alloc",
|
||||
if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
|
||||
sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen);
|
||||
if (!sc) { fine_sc = 0; sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 0, handle, &hlen); }
|
||||
fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen);
|
||||
if (!fl) { fine_fl = 0; fl = r4d_ar_ipc_alloc(flag_words * 4, 0, handle, &hlen); }
|
||||
if (host) {
|
||||
sc = r4d_ar_host_alloc((long)nslots * in->slot_bytes);
|
||||
fl = r4d_ar_host_alloc(flag_words * 4);
|
||||
} else {
|
||||
sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen);
|
||||
if (!sc) { fine_sc = 0; sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 0, handle, &hlen); }
|
||||
fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen);
|
||||
if (!fl) { fine_fl = 0; fl = r4d_ar_ipc_alloc(flag_words * 4, 0, handle, &hlen); }
|
||||
}
|
||||
sq = r4d_ar_ipc_alloc(2L * maxb * 4, 1, handle, &hlen);
|
||||
if (!sq) { fine_sq = 0; sq = r4d_ar_ipc_alloc(2L * maxb * 4, 0, handle, &hlen); });
|
||||
if (!sc || !fl || !sq) return RAD_E_NOMEM;
|
||||
@@ -258,7 +276,7 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code)
|
||||
in->peer_scratch[j] = g_rv.scratch[r];
|
||||
in->peer_flags[j] = g_rv.flags[r];
|
||||
++j;
|
||||
R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)g_rv.dev[r]));
|
||||
if (!host) R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)g_rv.dev[r]));
|
||||
}
|
||||
|
||||
/* Second barrier: no rank may launch until every rank has enabled peer access, or the first
|
||||
@@ -295,8 +313,10 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code)
|
||||
struct CacheKey {
|
||||
int rank, world, dtype;
|
||||
long long numel;
|
||||
int host;
|
||||
bool operator==(const CacheKey& o) const {
|
||||
return rank == o.rank && world == o.world && dtype == o.dtype && numel == o.numel;
|
||||
return rank == o.rank && world == o.world && dtype == o.dtype && numel == o.numel &&
|
||||
host == o.host;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -320,7 +340,7 @@ int acquire(const CacheKey& k, ArInst** out) {
|
||||
* and a rank-keyed entry means no two builders race for the same key. */
|
||||
ArInst* in = new (std::nothrow) ArInst();
|
||||
if (!in) return RAD_E_NOMEM;
|
||||
int rc = build(in, k.rank, k.world, k.numel, k.dtype);
|
||||
int rc = build(in, k.rank, k.world, k.numel, k.dtype, k.host);
|
||||
if (rc != RAD_OK) { delete in; return rc; }
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_cache_mu);
|
||||
@@ -343,8 +363,13 @@ void release(ArInst* in) {
|
||||
}
|
||||
/* Only this rank's own allocations. A peer pointer is the peer's to free, and freeing it here
|
||||
* would be a double free the moment two ranks tear down in either order. */
|
||||
r4d_ar_ipc_free(in->my_scratch);
|
||||
r4d_ar_ipc_free(in->my_flags);
|
||||
if (in->host) {
|
||||
r4d_ar_host_free(in->my_scratch);
|
||||
r4d_ar_host_free(in->my_flags);
|
||||
} else {
|
||||
r4d_ar_ipc_free(in->my_scratch);
|
||||
r4d_ar_ipc_free(in->my_flags);
|
||||
}
|
||||
r4d_ar_ipc_free(in->my_seq);
|
||||
r4d_ar_ipc_free(in->locpack);
|
||||
delete in;
|
||||
@@ -354,8 +379,7 @@ void release(ArInst* in) {
|
||||
|
||||
/* ------------------------------------------------------------------ init / fini */
|
||||
|
||||
extern "C" int r4d_rad_ar_init(const RadParam* p, int n_p, int rank, int world,
|
||||
void** out) {
|
||||
static int ar_init(const RadParam* p, int n_p, int rank, int world, int host, void** out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = nullptr;
|
||||
|
||||
@@ -373,28 +397,35 @@ extern "C" int r4d_rad_ar_init(const RadParam* p, int n_p, int rank, int world,
|
||||
if (numel <= 0) return RAD_E_INVAL;
|
||||
|
||||
ArInst* in = nullptr;
|
||||
int rc = acquire(CacheKey{ rank, world, dt, numel }, &in);
|
||||
int rc = acquire(CacheKey{ rank, world, dt, numel, host }, &in);
|
||||
if (rc != RAD_OK) return rc;
|
||||
*out = in;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_ar_init(const RadParam* p, int n_p, int rank, int world, void** out) {
|
||||
return ar_init(p, n_p, rank, world, 0, out);
|
||||
}
|
||||
extern "C" int r4d_rad_ar_host_init(const RadParam* p, int n_p, int rank, int world, void** out) {
|
||||
return ar_init(p, n_p, rank, world, 1, out);
|
||||
}
|
||||
|
||||
/* The fused all-reduce + norm declares `M`(range) and `n` rather than `numel`: its message is the
|
||||
* post-projection activation. Same world, same buffers, different arithmetic to get the bound. */
|
||||
static int ar_mn_acquire(const RadParam* p, int n_p, int rank, int world, void** out) {
|
||||
static int ar_mn_acquire(const RadParam* p, int n_p, int rank, int world, int host,
|
||||
void** out) {
|
||||
const long long M = pgeti_hi(p, n_p, "M", 0);
|
||||
const long long K = pgeti_hi(p, n_p, "n", 0);
|
||||
if (M <= 0 || K <= 0) return RAD_E_INVAL;
|
||||
|
||||
ArInst* in = nullptr;
|
||||
int rc = acquire(CacheKey{ rank, world, 0 /* bf16 */, M * K }, &in);
|
||||
int rc = acquire(CacheKey{ rank, world, 0 /* bf16 */, M * K, host }, &in);
|
||||
if (rc != RAD_OK) return rc;
|
||||
*out = in;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int world,
|
||||
void** out) {
|
||||
static int ar_ln_init(const RadParam* p, int n_p, int rank, int world, int host, void** out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = nullptr;
|
||||
|
||||
@@ -402,7 +433,15 @@ extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int worl
|
||||
if (ws_param != world) return RAD_E_SHAPE;
|
||||
if (world != 2) return RAD_E_SHAPE; /* the handshake is one peer flag per block */
|
||||
|
||||
return ar_mn_acquire(p, n_p, rank, world, out);
|
||||
return ar_mn_acquire(p, n_p, rank, world, host, out);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int world, void** out) {
|
||||
return ar_ln_init(p, n_p, rank, world, 0, out);
|
||||
}
|
||||
extern "C" int r4d_rad_ar_ln_host_init(const RadParam* p, int n_p, int rank, int world,
|
||||
void** out) {
|
||||
return ar_ln_init(p, n_p, rank, world, 1, out);
|
||||
}
|
||||
|
||||
/* The four-rank ar_hc_write and ar_gather_hc_write. The key is the family's -- {rank, 4, bf16,
|
||||
@@ -413,8 +452,8 @@ extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int worl
|
||||
* (r4d_ar_wide.h), so ops sharing an instance interleave in any order every rank issues them in,
|
||||
* and ops on separate instances touch nothing of each other's. Exact wire only: the rows constrain
|
||||
* `wire` to 0, and a `wire` 6 that reaches this init anyway is refused. */
|
||||
extern "C" int r4d_rad_ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world,
|
||||
void** out) {
|
||||
static int ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world, int host,
|
||||
void** out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = nullptr;
|
||||
|
||||
@@ -423,7 +462,16 @@ extern "C" int r4d_rad_ar_hc_wide_init(const RadParam* p, int n_p, int rank, int
|
||||
if (world != 4) return RAD_E_SHAPE; /* the peer bundle is compiled for four */
|
||||
if (pgeti_hi(p, n_p, "wire", 0) != 0) return RAD_E_UNSUPPORTED;
|
||||
|
||||
return ar_mn_acquire(p, n_p, rank, world, out);
|
||||
return ar_mn_acquire(p, n_p, rank, world, host, out);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world,
|
||||
void** out) {
|
||||
return ar_hc_wide_init(p, n_p, rank, world, 0, out);
|
||||
}
|
||||
extern "C" int r4d_rad_ar_hc_wide_host_init(const RadParam* p, int n_p, int rank, int world,
|
||||
void** out) {
|
||||
return ar_hc_wide_init(p, n_p, rank, world, 1, out);
|
||||
}
|
||||
|
||||
extern "C" void r4d_rad_ar_fini(void* instance) {
|
||||
|
||||
@@ -489,6 +489,29 @@ int r4d_ar_gather_inv(long inv, long sorted, long T, long stream_i) {
|
||||
void r4d_ar_ipc_free(long p) { if (p) (void)hipFree((void*)p); }
|
||||
void r4d_ar_ipc_memzero(long p, long size) { if (p) HIPOK(hipMemset((void*)p, 0, size)); }
|
||||
|
||||
// THE HOST MAILBOX. Coherent so a peer's stores are not held in a CPU cache line this card reads
|
||||
// around, mapped so the cards address it, portable so every card does and not only the one
|
||||
// current at allocation. A card reaches it through the same fine-grained path a peer's VRAM
|
||||
// scratch is reached by, so the kernels' fences mean what they mean there. The address a card
|
||||
// uses must be the CPU's own, because one pointer is published to every rank: a mapping that put
|
||||
// the pages elsewhere on some card would have each rank write where no other rank reads.
|
||||
long r4d_ar_host_alloc(long size) {
|
||||
void* p = nullptr;
|
||||
HIPOK(hipHostMalloc(&p, size, hipHostMallocCoherent | hipHostMallocMapped |
|
||||
hipHostMallocPortable));
|
||||
std::memset(p, 0, (size_t)size);
|
||||
void* d = nullptr;
|
||||
const hipError_t e = hipHostGetDevicePointer(&d, p, 0);
|
||||
if (e != hipSuccess || d != p) {
|
||||
(void)hipHostFree(p);
|
||||
throw std::runtime_error(e != hipSuccess
|
||||
? std::string("host mailbox: no card address: ") + hipGetErrorString(e)
|
||||
: std::string("host mailbox: the card address differs from the CPU address"));
|
||||
}
|
||||
return (long)p;
|
||||
}
|
||||
void r4d_ar_host_free(long p) { if (p) (void)hipHostFree((void*)p); }
|
||||
|
||||
// Enable direct peer access. radiance runs one process with a thread per rank sharing an address
|
||||
// space, so a peer pointer is valid here once this has run and no IPC handle exchange is needed;
|
||||
// see the header of r4d_ar_entry.hip.
|
||||
|
||||
@@ -334,6 +334,16 @@ struct R4dGemmCfg { int wv, sk, mb, npw, nt; };
|
||||
* not compute the GEMM and then pick it. */
|
||||
struct R4dTileCfg { int variant; int bm; int bn; };
|
||||
|
||||
/* The MXFP4 tiled GEMM's column width in 32-column units per wave: TN=2 gives a 256 x 64 block,
|
||||
* TN=4 a 256 x 128 one. Its crossover is a function of M (r4d_gemm_mxfp4a8_tiled.hip carries the
|
||||
* measurement), so 0 -- the default -- decides at issue and a fixed value is for a tuner. */
|
||||
struct R4dMxTileCfg { int tn; };
|
||||
|
||||
/* The MXFP4 decode GEMM's split-K width, K slab and weight-load hint. 0 on each is the rule in
|
||||
* r4d_gemm_mxfp4a8_decode.hip (it needs M and the shape, which exist only at issue); `nt` 1 streams
|
||||
* the weight past L2/MALL, 2 loads it plainly. */
|
||||
struct R4dMxDecCfg { int ks; int bk; int nt; };
|
||||
|
||||
/* Split-KV segment count for the paged decode kernels. 0 is libr4d's own split law, which is
|
||||
* measured (r4d_attn_paged_h256_gqa6.hip carries the table) and reads num_seqs and max_ctx that
|
||||
* only exist at issue -- so it stays the default and the fixed counts are there for a tuner that
|
||||
@@ -375,6 +385,8 @@ extern "C" {
|
||||
void r4d_cfg_gemm (const RadArgs*, struct R4dGemmCfg*);
|
||||
void r4d_cfg_tiled (const RadArgs*, struct R4dTileCfg*);
|
||||
void r4d_cfg_prefill(const RadArgs*, struct R4dTileCfg*);
|
||||
void r4d_cfg_mxfp4_tiled(const RadArgs*, struct R4dMxTileCfg*);
|
||||
void r4d_cfg_mxfp4_decode(const RadArgs*, struct R4dMxDecCfg*);
|
||||
void r4d_cfg_split (const RadArgs*, struct R4dSplitCfg*);
|
||||
void r4d_cfg_ar (const RadArgs*, struct R4dArCfg*);
|
||||
void r4d_cfg_topk (const RadArgs*, struct R4dTopkCfg*);
|
||||
|
||||
@@ -321,6 +321,30 @@ struct GemmOps {
|
||||
long long M, N, K;
|
||||
};
|
||||
|
||||
/* THE MXFP4 GEMMS' ACTIVATION SCALE GRID, read off the operand rather than assumed. One f32 a row
|
||||
* (`[M]` or `[M][1]`: a per-token quantiser) is group 0; one per (row, 128 of K) (`[M][ceil(K/128)]`:
|
||||
* the block-scaled fp8 family's quantisers, which every fused producer in arch/common writes) is
|
||||
* group 128, read at the operand's own row stride. Anything else is refused by shape: a grid read
|
||||
* at the wrong width is an answer that is merely wrong. */
|
||||
static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs) {
|
||||
const RadTensor* s = g.ascale;
|
||||
if (!s || g.M <= 0) return R4D_NO(RAD_E_INVAL);
|
||||
long long cols = 1, rstride = 1;
|
||||
if (s->rank >= 2) {
|
||||
cols = s->shape[s->rank - 1];
|
||||
rstride = s->stride[s->rank - 2];
|
||||
if (s->shape[s->rank - 2] < g.M) return R4D_NO(RAD_E_SHAPE);
|
||||
} else if (s->rank == 1) {
|
||||
if (s->shape[0] < g.M) return R4D_NO(RAD_E_SHAPE);
|
||||
cols = s->shape[0] / g.M;
|
||||
rstride = cols;
|
||||
}
|
||||
const long long kb = (g.K + 127) / 128;
|
||||
if (cols == 1 && (s->rank < 2 || rstride == 1)) { *group = 0; *rs = 1; return RAD_OK; }
|
||||
if (cols == kb && rstride >= kb) { *group = 128; *rs = (int)rstride; return RAD_OK; }
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* Common shape and layout checks. A is [M,K] row-major, C is [M,N] row-major and the weight is
|
||||
* an opaque packed blob whose element count the layout hook owns -- so the weight's SHAPE is not
|
||||
* checked here beyond being present, which is deliberate: the byte count that matters is the one
|
||||
|
||||
@@ -0,0 +1,617 @@
|
||||
// r4d_gemm_mxfp4a8_decode.hip - r4d_gemm_mxfp4a8_decode: the OCP-MXFP4 x fp8 GEMM for the DECODE
|
||||
// band, M <= 128, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T over the same operands, weight
|
||||
// layout and fold as r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_tiled.
|
||||
//
|
||||
// WHY A THIRD MXFP4 KERNEL. At decode the GEMM is a weight stream: a speculative verify step is
|
||||
// a handful of rows against the whole 4-bit trunk, and the only number that matters is how close
|
||||
// the stream runs to the card's DRAM bandwidth. The skinny kernel splits K inside one workgroup
|
||||
// and reads the weight straight into registers, which leaves the narrow projections well short of
|
||||
// it. This one splits K ACROSS workgroups with a fused last-arriver reduction, unpacks the weight
|
||||
// through LDS, gives each block one 16-row A fragment per M tile, and streams the weight with
|
||||
// non-temporal loads.
|
||||
//
|
||||
// THE TILE. A block is DWN = 8 waves over BND = 128 output columns, one 16-column fragment a wave,
|
||||
// and DTM 16-row M fragments -- the SMALLEST that covers M, because a wider tile computes rows
|
||||
// nobody asked for. A K slab of DBK bytes is staged: A (16*DTM rows) and the weight's 128 rows,
|
||||
// unpacked to e4m3 with the block exponent folded in through r4d_mxfp4.h, as the other two MXFP4
|
||||
// kernels fold it.
|
||||
//
|
||||
// SPLIT-K IS NOT OPTIONAL. With one 16-row M fragment the independent N fragments number N/16, so
|
||||
// N=5120 is 320 waves -- 2.5 a SIMD however the N tile is chosen. DKS blocks split the K slabs;
|
||||
// each writes an fp32 partial [DKS][M][N] and the LAST to arrive (an agent-scope counter per column
|
||||
// block) sums them in place, so there is no second launch.
|
||||
//
|
||||
// THE SPLIT, SLAB AND LOAD HINT are a rule measured cell by cell on this kernel -- every split x
|
||||
// slab x hint against the 27B's per-rank shapes at M = 8..128, DRAM-fed -- because no single
|
||||
// fill target fits: the split is the smallest power of two whose grid reaches 48 blocks at M <= 16,
|
||||
// 56 at M <= 96 and 40 above (an unsplit 40-block grid already streams a short-K weight at the
|
||||
// card's rate there, and a split's partial traffic grows with M); a deep K (8192 or more, down at
|
||||
// K=8704) keeps doubling while a split still has 24 or more 128-wide slabs, since 40-odd blocks
|
||||
// do not keep its long slab loop fed; and no split goes past ks*M = 512, where the partials
|
||||
// outweigh what the split buys. The slab is 128 except where LDS per block, (16*DTM + 128) *
|
||||
// (DBK+8) bytes, would cost a wide or deeply split grid its resident blocks (see mxd_plan); a K
|
||||
// that is not a multiple of 128 takes 64 (and a 2-way split widens to 4). Weight loads are non-temporal for weights of 4 MiB or more,
|
||||
// plain below, where the weight is too small to evict anything the split partials need. All three
|
||||
// are tunables (`ks`, `bk`, `nt`) whose 0 is this rule.
|
||||
//
|
||||
// NO STATE IS KEYED ON THE STREAM. The split partial is the op's own scratch -- the core sizes it
|
||||
// from the scratch hook and treats it as read+write, so two ops that could overlap get disjoint
|
||||
// slices -- and the arrival counters are a small block keyed on the OUTPUT buffer (mxd_out_ctr),
|
||||
// zero at entry and left zero by the reducer. A recorded pass is replayed with its recorded
|
||||
// arguments, possibly on another stream than it was recorded on, so a pointer that depended on the
|
||||
// stream would make the replay differ from its recording. Two launches writing the same output are
|
||||
// ordered by that dependency; two that can overlap write different outputs. The row is therefore
|
||||
// concurrent (rad_kernel_concurrent), as gemm_fp8a8_nt_m16 is. A scratch shorter than the split
|
||||
// needs is refused: the hook sizes it for every M of the band, so a short one is a caller's error.
|
||||
//
|
||||
// Every thread fences its partial stores before the counter: a fence on thread 0 alone orders
|
||||
// only thread 0's stores, and the reducer would then read whatever happened to drain.
|
||||
//
|
||||
// TWO ACTIVATION SCALE GRIDS, as in the tiled kernel: one f32 a row, or one a (row, 128 of K). The
|
||||
// per-block form carries each row's accumulator in the current block's scale and rescales it by
|
||||
// s_prev / s_next at each 128 boundary, the ratio computed once a row into LDS from scales loaded a
|
||||
// boundary early; with the accumulator transposed a lane reads one ratio for each of its rows. A split's partial is brought back
|
||||
// to absolute units before it is written, because the splits end in different blocks.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_mxfp4.h"
|
||||
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
|
||||
#define R4D_MXD_DWN 8 // waves per block; the N tile is DWN*16 = 128 wide
|
||||
#define R4D_MXD_MTILE 16
|
||||
#define R4D_MXD_MAX_TM 8 // M <= 128
|
||||
#define R4D_MXD_PAD 8
|
||||
#define R4D_MXD_MAX_KS 16
|
||||
#define R4D_MXD_MAX_N 36864 // the counter block's width; a 27B gate_up at TP=1 is 34816
|
||||
|
||||
typedef int mxd_v2i __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned mxd_u2 __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned mxd_u4 __attribute__((ext_vector_type(4)));
|
||||
typedef float mxd_f4 __attribute__((ext_vector_type(4)));
|
||||
|
||||
template <bool NT, typename T>
|
||||
static __device__ __forceinline__ T mxd_ld(const T* p) {
|
||||
if constexpr (NT) return __builtin_nontemporal_load(p);
|
||||
else return *p;
|
||||
}
|
||||
|
||||
// ---- what both kernels share: the scale grid at a 128 boundary, and the epilogue.
|
||||
//
|
||||
// THE ACCUMULATOR IS C TRANSPOSED. The WMMA takes the weight fragment as its A operand and the
|
||||
// activation fragment as its B operand -- the two fragments have the same register layout, so
|
||||
// this is only an argument order -- and computes C^T: a lane's accumulator for M fragment i holds
|
||||
// ONE row, m = 16i + col, and the eight consecutive columns n0 + 16*wave + kb8 + e. So a row's
|
||||
// activation scale is one value a lane, not eight: the (row, 128) grid's boundary rescale reads
|
||||
// DTM scales instead of 8*DTM, and the epilogue writes each lane's eight outputs as one 16-byte
|
||||
// store (one 32-byte store of partials) instead of eight 2-byte ones.
|
||||
|
||||
// THE (ROW, 128) SCALE GRID, computed once a row: thread t < ROWS owns row t. It loads the next
|
||||
// 128 boundary's two scales -- the block that starts there and the one before it -- a boundary
|
||||
// early, writes the row's ratio s_prev / s_next to LDS at the boundary (published by the staging
|
||||
// barrier), and a lane then reads ONE ratio for each of its rows. A zero block keeps the carried
|
||||
// scale; a zero block before this one sends the carried scale back to the grid, which only an
|
||||
// all-zero activation block ever does.
|
||||
static __device__ __forceinline__ float mxd_ratio(float ns, float np, const float* __restrict__ row,
|
||||
int kb) {
|
||||
return ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(row, kb - 2)) / ns : 1.f;
|
||||
}
|
||||
|
||||
template <int DTM>
|
||||
static __device__ __forceinline__ void mxd_rescale(v8f (&acc)[DTM], const float* sR, int col) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) {
|
||||
const float r = sR[i * 16 + col];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) acc[i][e] *= r;
|
||||
}
|
||||
}
|
||||
|
||||
// The split's result: written straight to C when the accumulator holds the whole K range, else as
|
||||
// an fp32 partial that the last block to arrive on this column block sums. `kb_end` is the block
|
||||
// the split's last slab ends in (ABLK: the scale the accumulators are carried in).
|
||||
template <int DTM, int DKS, bool ABLK>
|
||||
static __device__ __forceinline__ void mxd_epilogue(
|
||||
const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs,
|
||||
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
|
||||
__hip_bfloat16* __restrict__ C, int M, int N, int n0, int wave, int col, int kb8, int ks,
|
||||
int kb_end, unsigned* s_last, float* sR) {
|
||||
constexpr int NTHR = R4D_MXD_DWN * 32, BND = R4D_MXD_DWN * 16;
|
||||
constexpr int ROWS = R4D_MXD_MTILE * DTM;
|
||||
const int tid = threadIdx.x;
|
||||
const int nb = n0 + wave * 16 + kb8; // this lane's eight columns; N % 16 == 0 keeps all or none
|
||||
// Each row's final scale, once a row: the scale the split's accumulators end in (ABLK), or the
|
||||
// row's own. The K loop's closing barrier retired the last ratio reads.
|
||||
if (tid < ROWS) {
|
||||
const int m = tid < M ? tid : M - 1;
|
||||
sR[tid] = ABLK ? r4d_mxfp4_carried(As + (size_t)m * as_rs, kb_end) : As[(size_t)m * as_rs];
|
||||
}
|
||||
__syncthreads();
|
||||
float sc[DTM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) sc[i] = sR[i * 16 + col];
|
||||
if constexpr (DKS == 1) {
|
||||
if (nb < N) {
|
||||
const mxd_u2 rb = *(const mxd_u2*)(Wref + nb);
|
||||
float rf[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) rf[e] = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) {
|
||||
const int m = i * 16 + col;
|
||||
if (m < M) {
|
||||
union { __hip_bfloat16 h[8]; mxd_u4 v; } o;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e)
|
||||
o.h[e] = (__hip_bfloat16)(ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i]);
|
||||
*(mxd_u4*)(C + (size_t)m * N + nb) = o.v;
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (nb < N) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) {
|
||||
const int m = i * 16 + col;
|
||||
if (m < M) {
|
||||
mxd_f4 lo, hi;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; ++e) {
|
||||
lo[e] = ABLK ? acc[i][e] * sc[i] : acc[i][e];
|
||||
hi[e] = ABLK ? acc[i][e + 4] * sc[i] : acc[i][e + 4];
|
||||
}
|
||||
mxd_f4* dst = (mxd_f4*)(P + ((size_t)ks * M + m) * N + nb);
|
||||
dst[0] = lo;
|
||||
dst[1] = hi;
|
||||
}
|
||||
}
|
||||
}
|
||||
// EVERY thread's partial stores are ordered before the counter, then the last arriver reduces.
|
||||
__threadfence();
|
||||
__syncthreads();
|
||||
if (tid == 0)
|
||||
*s_last = __hip_atomic_fetch_add(&cnt[blockIdx.x], 1u, __ATOMIC_ACQ_REL,
|
||||
__HIP_MEMORY_SCOPE_AGENT);
|
||||
__syncthreads();
|
||||
if (*s_last != (unsigned)(DKS - 1)) return;
|
||||
if (tid == 0) cnt[blockIdx.x] = 0u; // left clean for the next launch on this stream
|
||||
__threadfence(); // acquire, before reading the other partials
|
||||
const int nhi = min(n0 + BND, N);
|
||||
for (int nn = n0 + tid; nn < nhi; nn += NTHR) {
|
||||
const float rf = __int_as_float((int)Wref[nn] << 23);
|
||||
for (int m = 0; m < M; ++m) {
|
||||
float sum = 0.f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < DKS; ++k) sum += P[((size_t)k * M + m) * N + nn];
|
||||
C[(size_t)m * N + nn] = (__hip_bfloat16)(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <int DBK, int DKS, int DTM, bool NT, bool ABLK>
|
||||
__global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kernel(
|
||||
const unsigned char* __restrict__ A, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) {
|
||||
constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32;
|
||||
constexpr int ROWS = R4D_MXD_MTILE * DTM;
|
||||
constexpr int STR = DBK + R4D_MXD_PAD;
|
||||
__shared__ unsigned char sA[ROWS * STR];
|
||||
__shared__ unsigned char sW[BND * STR];
|
||||
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
|
||||
__shared__ unsigned s_last;
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int col = lane & 15, kb8 = (lane >> 4) * 8;
|
||||
const int n0 = blockIdx.x * BND;
|
||||
const int ks = blockIdx.z;
|
||||
|
||||
const int slabs = (K + DBK - 1) / DBK;
|
||||
const int spb = (slabs + DKS - 1) / DKS;
|
||||
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
|
||||
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
|
||||
|
||||
v8f acc[DTM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
|
||||
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
|
||||
float ns = 0.f, np = 0.f;
|
||||
if constexpr (ABLK) {
|
||||
// a split that starts mid-block meets its first boundary one slab in
|
||||
const int kb = ((s_lo * DBK) >> 7) + 1;
|
||||
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
|
||||
}
|
||||
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
const int ksteps_g = K / 16;
|
||||
|
||||
for (int s = s_lo; s < s_hi; ++s) {
|
||||
const int k0 = s * DBK;
|
||||
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
|
||||
if constexpr (ABLK) {
|
||||
if (bnd && tid < ROWS) sR[tid] = mxd_ratio(ns, np, asrow, k0 >> 7);
|
||||
}
|
||||
// ---- A: ROWS x DBK bytes, clamped rows, 16 B a thread
|
||||
#pragma unroll
|
||||
for (int off = 0; off < ROWS * DBK; off += NTHR * 16) {
|
||||
const int idx = off + tid * 16;
|
||||
if (idx < ROWS * DBK) {
|
||||
const int r = idx / DBK, c = idx % DBK;
|
||||
const int rc = r < M - 1 ? r : M - 1; // clamp, never predicate
|
||||
*(mxd_u4*)(&sA[r * STR + c]) = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c);
|
||||
}
|
||||
}
|
||||
// ---- W: fragment-order slots, two adjacent rows a thread (an 8 B request), folded to e4m3
|
||||
{
|
||||
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
|
||||
const int kstep0 = k0 / 16;
|
||||
#pragma unroll
|
||||
for (int off = 0; off < NTILES_T * KSTEPS_T * 32; off += NTHR * 2) {
|
||||
const int sl = off + tid * 2;
|
||||
const int lane_ = sl & 31, rest = sl >> 5;
|
||||
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
|
||||
const int r = ntl * 16 + (lane_ & 15), kloc = kst * 16 + (lane_ >> 4) * 8;
|
||||
const int gn = n0 + r;
|
||||
// gn is even and N % 16 == 0: clamping to the last even row keeps the 8 B read aligned and
|
||||
// gc + 1 in bounds; the slot address is recomputed from the clamped row.
|
||||
const int gc = gn < N - 2 ? gn : N - 2;
|
||||
const int lanec = (lane_ & 16) | (gc & 15);
|
||||
const mxd_u2 wv =
|
||||
mxd_ld<NT>((const mxd_u2*)&Wp[((size_t)(gc >> 4) * ksteps_g + kstep0 + kst) * 32 +
|
||||
lanec]);
|
||||
const int blk = (k0 + kst * 16) / R4D_MXFP4_GROUP;
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * N + gc + q]);
|
||||
unsigned int lo, hi;
|
||||
r4d_mxfp4_unpack8(q ? wv[1] : wv[0], d, &lo, &hi);
|
||||
*(mxd_u2*)(&sW[(r + q) * STR + kloc]) = mxd_u2{lo, hi};
|
||||
}
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if constexpr (ABLK) {
|
||||
if (bnd) mxd_rescale(acc, sR, col);
|
||||
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
|
||||
ns = asrow[(k0 >> 7) + 1];
|
||||
np = asrow[k0 >> 7];
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int step = 0; step < DBK / 16; ++step) {
|
||||
const int kk = step * 16 + kb8;
|
||||
mxd_v2i af[DTM], wf;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) {
|
||||
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
|
||||
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
|
||||
}
|
||||
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
|
||||
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i)
|
||||
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
|
||||
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks,
|
||||
kb_end, &s_last, sR);
|
||||
}
|
||||
|
||||
// THE ONE-FRAGMENT FORM (M <= 16), which is every single-sequence verify step. The same tile, fold
|
||||
// and split as above, with two changes that pay only when one M fragment leaves the block waiting
|
||||
// on memory: the NEXT slab's A, codes and exponents are loaded into registers while this slab
|
||||
// computes, so a block keeps its loads in flight across the WMMA phase instead of draining at every
|
||||
// barrier; and a thread takes four adjacent slots, one 16 B load instead of two 8 B ones. Each
|
||||
// row's reference exponent is read once, not once a slab. Bit-identical to the kernel above at
|
||||
// every split: the K order, the fold and the reduction are unchanged.
|
||||
template <int DBK, int DKS, bool NT, bool ABLK>
|
||||
__global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_kernel(
|
||||
const unsigned char* __restrict__ A, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) {
|
||||
constexpr int DTM = 1, VEC = 4;
|
||||
constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32;
|
||||
constexpr int ROWS = R4D_MXD_MTILE * DTM;
|
||||
constexpr int STR = DBK + R4D_MXD_PAD;
|
||||
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
|
||||
constexpr int W_IT = NTILES_T * KSTEPS_T * 32 / (NTHR * VEC);
|
||||
constexpr int A_IT = (ROWS * DBK + NTHR * 16 - 1) / (NTHR * 16);
|
||||
__shared__ unsigned char sA[ROWS * STR];
|
||||
__shared__ unsigned char sW[BND * STR];
|
||||
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
|
||||
__shared__ unsigned s_last;
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int col = lane & 15, kb8 = (lane >> 4) * 8;
|
||||
const int n0 = blockIdx.x * BND;
|
||||
const int ks = blockIdx.z;
|
||||
const int slabs = (K + DBK - 1) / DBK;
|
||||
const int spb = (slabs + DKS - 1) / DKS;
|
||||
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
|
||||
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
|
||||
|
||||
v8f acc[DTM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
|
||||
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
|
||||
float ns = 0.f, np = 0.f;
|
||||
if constexpr (ABLK) {
|
||||
const int kb = ((s_lo * DBK) >> 7) + 1;
|
||||
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
|
||||
}
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
const int ksteps_g = K / 16;
|
||||
|
||||
// per-thread slot geometry, fixed across slabs
|
||||
int s_r[W_IT], s_kst[W_IT], s_kloc[W_IT], s_gc[W_IT], s_lanec[W_IT];
|
||||
int s_ref[W_IT][VEC];
|
||||
#pragma unroll
|
||||
for (int it = 0; it < W_IT; ++it) {
|
||||
const int sl = it * NTHR * VEC + tid * VEC;
|
||||
const int lane_ = sl & 31, rest = sl >> 5;
|
||||
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
|
||||
const int r = ntl * 16 + (lane_ & 15);
|
||||
const int gn = n0 + r;
|
||||
const int gc = gn < N - VEC ? gn : N - VEC;
|
||||
s_r[it] = r; s_kst[it] = kst; s_kloc[it] = kst * 16 + (lane_ >> 4) * 8;
|
||||
s_gc[it] = gc; s_lanec[it] = (lane_ & 16) | (gc & 15);
|
||||
#pragma unroll
|
||||
for (int q = 0; q < VEC; ++q) s_ref[it][q] = (int)Wref[gc + q];
|
||||
}
|
||||
typedef unsigned wv_t __attribute__((ext_vector_type(VEC)));
|
||||
wv_t rw[W_IT];
|
||||
int rd[W_IT][VEC];
|
||||
mxd_u4 ra[A_IT];
|
||||
|
||||
auto load = [&](int s) {
|
||||
const int k0 = s * DBK;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < A_IT; ++j) {
|
||||
const int idx = j * NTHR * 16 + tid * 16;
|
||||
if (idx < ROWS * DBK) {
|
||||
const int r = idx / DBK, c = idx % DBK;
|
||||
const int rc = r < M - 1 ? r : M - 1;
|
||||
ra[j] = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c);
|
||||
}
|
||||
}
|
||||
const int kstep0 = k0 / 16;
|
||||
#pragma unroll
|
||||
for (int it = 0; it < W_IT; ++it) {
|
||||
const size_t slot =
|
||||
((size_t)(s_gc[it] >> 4) * ksteps_g + kstep0 + s_kst[it]) * 32 + s_lanec[it];
|
||||
rw[it] = mxd_ld<NT>((const wv_t*)&Wp[slot]);
|
||||
const int blk = (k0 + s_kst[it] * 16) / R4D_MXFP4_GROUP;
|
||||
#pragma unroll
|
||||
for (int q = 0; q < VEC; ++q) rd[it][q] = (int)Ws[(size_t)blk * N + s_gc[it] + q];
|
||||
}
|
||||
};
|
||||
auto store = [&]() {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < A_IT; ++j) {
|
||||
const int idx = j * NTHR * 16 + tid * 16;
|
||||
if (idx < ROWS * DBK) {
|
||||
const int r = idx / DBK, c = idx % DBK;
|
||||
*(mxd_u4*)(&sA[r * STR + c]) = ra[j];
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int it = 0; it < W_IT; ++it) {
|
||||
#pragma unroll
|
||||
for (int q = 0; q < VEC; ++q) {
|
||||
unsigned int lo, hi;
|
||||
r4d_mxfp4_unpack8(rw[it][q], r4d_mxfp4_fold_d(s_ref[it][q], rd[it][q]), &lo, &hi);
|
||||
*(mxd_u2*)(&sW[(s_r[it] + q) * STR + s_kloc[it]]) = mxd_u2{lo, hi};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (s_lo < s_hi) load(s_lo);
|
||||
for (int s = s_lo; s < s_hi; ++s) {
|
||||
const int k0 = s * DBK;
|
||||
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
|
||||
if constexpr (ABLK) {
|
||||
if (bnd && tid < ROWS) sR[tid] = mxd_ratio(ns, np, asrow, k0 >> 7);
|
||||
}
|
||||
store();
|
||||
__syncthreads();
|
||||
if (s + 1 < s_hi) load(s + 1); // the next slab's loads fly across this slab's WMMAs
|
||||
if constexpr (ABLK) {
|
||||
if (bnd) mxd_rescale(acc, sR, col);
|
||||
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
|
||||
ns = asrow[(k0 >> 7) + 1];
|
||||
np = asrow[k0 >> 7];
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int step = 0; step < DBK / 16; ++step) {
|
||||
const int kk = step * 16 + kb8;
|
||||
mxd_v2i af[DTM], wf;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) {
|
||||
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
|
||||
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
|
||||
}
|
||||
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
|
||||
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i)
|
||||
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
|
||||
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks,
|
||||
kb_end, &s_last, sR);
|
||||
}
|
||||
|
||||
namespace {
|
||||
// THE ARRIVAL COUNTERS, one block an output buffer -- see the header. The counters cannot live in
|
||||
// the scratch: other ops write the arena between two of ours, and the counters must be zero at
|
||||
// entry. So they are a small device allocation of their own, taken once per (device, output) and
|
||||
// kept zero by the reducer, as gemm_fp8a8_nt_m16 keys its split_ctr.
|
||||
unsigned* mxd_out_ctr(const void* out) {
|
||||
static std::mutex mu;
|
||||
static std::map<std::pair<int, const void*>, unsigned*> blocks;
|
||||
int dev = 0;
|
||||
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
const auto key = std::make_pair(dev, out);
|
||||
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
|
||||
const size_t n = R4D_MXD_MAX_N / (R4D_MXD_DWN * 16);
|
||||
unsigned* p = nullptr;
|
||||
if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr;
|
||||
if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess) { (void)hipFree(p); return nullptr; }
|
||||
blocks.emplace(key, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
// THE SPLIT, SLAB AND LOAD HINT A LAUNCH RUNS, from M, the shape and the tunables (0 = the rule).
|
||||
// One function for the launch and the scratch hook, so the partial the hook sizes is the one
|
||||
// written. See the header for the rule and what it was measured on.
|
||||
struct MxdPlan { int ks, bk; bool nt; };
|
||||
MxdPlan mxd_plan(int M, int K, int N, int KS, int BK, int NT) {
|
||||
const int nblk = (N + R4D_MXD_DWN * 16 - 1) / (R4D_MXD_DWN * 16);
|
||||
const int tm = (M + R4D_MXD_MTILE - 1) / R4D_MXD_MTILE;
|
||||
MxdPlan p;
|
||||
int ks = 1;
|
||||
const int fill = M <= 16 ? 48 : (M <= 96 ? 56 : 40);
|
||||
while (ks < R4D_MXD_MAX_KS && nblk * ks < fill && 2 * ks * M <= 512) ks <<= 1;
|
||||
if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them
|
||||
while (ks < R4D_MXD_MAX_KS && (K / 128) / ks >= 24 && 2 * ks * M <= 512) ks <<= 1;
|
||||
p.ks = KS > 0 ? KS : ks;
|
||||
// 64-wide slabs where LDS per block, (16*DTM + 128)*(DBK+8) bytes, costs a wide or deeply split
|
||||
// grid its resident blocks: DTM 4 unsplit on 110+ column blocks, and DTM 8 on those or at a 4-way
|
||||
// split.
|
||||
const bool slab64 = (tm == 4 && p.ks == 1 && nblk >= 110) || (tm == 8 && (nblk >= 110 || p.ks >= 4));
|
||||
p.bk = BK > 0 ? BK : (slab64 ? 64 : 128);
|
||||
p.nt = NT == 1 || (NT == 0 && (long)N * K / 2 >= (4l << 20));
|
||||
if (K % p.bk) { // a slab may not run past K
|
||||
p.bk = 64;
|
||||
if (p.ks == 2) p.ks = 4;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
long mxd_partial_bytes(int M, int N, int ks) {
|
||||
return ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0;
|
||||
}
|
||||
|
||||
void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M, int K, int N,
|
||||
int KS, int BK, int NT, int as_group, int as_rs, long stream, long scratch,
|
||||
long scratch_bytes) {
|
||||
if (M < 1 || M > R4D_MXD_MTILE * R4D_MXD_MAX_TM)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: M must be 1..128");
|
||||
if (N < 16 || N % 16 || N > R4D_MXD_MAX_N)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: N must be a multiple of 16 up to 36864");
|
||||
if (K < 64 || K % 64)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: K must be a multiple of 64");
|
||||
if (as_group != 0 && as_group != 128)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: the activation scale is per row or per "
|
||||
"128 of K");
|
||||
const MxdPlan pl = mxd_plan(M, K, N, KS, BK, NT);
|
||||
const int ks = pl.ks, bk = pl.bk;
|
||||
if (ks != 1 && ks != 2 && ks != 4 && ks != 8 && ks != 16)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: KS must be 1, 2, 4, 8 or 16");
|
||||
if (bk != 64 && bk != 128)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: BK must be 64 or 128");
|
||||
if (scratch_bytes < mxd_partial_bytes(M, N, ks) || (ks > 1 && !scratch))
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: the op's scratch is shorter than the split "
|
||||
"partial; the scratch hook sizes it");
|
||||
float* P = (float*)scratch;
|
||||
unsigned* cnt = mxd_out_ctr((const void*)c);
|
||||
if (!cnt) throw std::runtime_error("r4d gemm_mxfp4a8_decode: split counter alloc failed");
|
||||
const bool ablk = as_group == 128, nt = pl.nt;
|
||||
const int nblk = (N + R4D_MXD_DWN * 16 - 1) / (R4D_MXD_DWN * 16);
|
||||
const int tm = (M + R4D_MXD_MTILE - 1) / R4D_MXD_MTILE;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
dim3 grid(nblk, 1, ks), block(R4D_MXD_DWN * 32);
|
||||
auto Ap = (const unsigned char*)a;
|
||||
auto Sp = (const float*)ascale;
|
||||
auto Wp = (const unsigned char*)wq;
|
||||
auto Zp = (const unsigned char*)ws;
|
||||
auto Rp = (const unsigned char*)wref;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
#define MXD_L(BK_, KS_, TM_, NT_, AB_) \
|
||||
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode_kernel<BK_, KS_, TM_, NT_, AB_>), grid, block, 0, \
|
||||
st, Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs)
|
||||
#define MXD_L1(BK_, KS_, NT_, AB_) \
|
||||
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode1_kernel<BK_, KS_, NT_, AB_>), grid, block, 0, st, \
|
||||
Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs)
|
||||
#define MXD_AB(BK_, KS_, TM_, NT_) \
|
||||
{ if (ablk) MXD_L(BK_, KS_, TM_, NT_, true); else MXD_L(BK_, KS_, TM_, NT_, false); }
|
||||
#define MXD_NT(BK_, KS_, TM_) \
|
||||
{ if (nt) MXD_AB(BK_, KS_, TM_, true) else MXD_AB(BK_, KS_, TM_, false) }
|
||||
#define MXD_AB1(BK_, KS_, NT_) \
|
||||
{ if (ablk) MXD_L1(BK_, KS_, NT_, true); else MXD_L1(BK_, KS_, NT_, false); }
|
||||
#define MXD_NT1(BK_, KS_) { if (nt) MXD_AB1(BK_, KS_, true) else MXD_AB1(BK_, KS_, false) }
|
||||
#define MXD_TM(BK_, KS_) \
|
||||
{ switch (tm) { case 1: MXD_NT1(BK_, KS_) break; case 2: MXD_NT(BK_, KS_, 2) break; \
|
||||
case 3: MXD_NT(BK_, KS_, 3) break; case 4: MXD_NT(BK_, KS_, 4) break; \
|
||||
case 5: MXD_NT(BK_, KS_, 5) break; case 6: MXD_NT(BK_, KS_, 6) break; \
|
||||
case 7: MXD_NT(BK_, KS_, 7) break; default: MXD_NT(BK_, KS_, 8) break; } }
|
||||
#define MXD_KS(BK_) \
|
||||
{ switch (ks) { case 1: MXD_TM(BK_, 1) break; case 2: MXD_TM(BK_, 2) break; \
|
||||
case 4: MXD_TM(BK_, 4) break; case 8: MXD_TM(BK_, 8) break; \
|
||||
default: MXD_TM(BK_, 16) break; } }
|
||||
if (bk == 64) MXD_KS(64) else MXD_KS(128)
|
||||
#undef MXD_KS
|
||||
#undef MXD_TM
|
||||
#undef MXD_NT1
|
||||
#undef MXD_AB1
|
||||
#undef MXD_NT
|
||||
#undef MXD_AB
|
||||
#undef MXD_L1
|
||||
#undef MXD_L
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" int r4d_gemm_mxfp4a8_decode_max_m(void) { return R4D_MXD_MTILE * R4D_MXD_MAX_TM; }
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
extern "C" int r4d_rad_gemm_mxfp4a8_decode(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
if (g.K % 64) return R4D_NO(RAD_E_SHAPE);
|
||||
if (g.M > r4d_gemm_mxfp4a8_decode_max_m() || g.N > R4D_MXD_MAX_N) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL);
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs);
|
||||
if (rc != RAD_OK) return rc;
|
||||
R4dMxDecCfg t;
|
||||
r4d_cfg_mxfp4_decode(a, &t);
|
||||
R4D_TRY("gemm_mxfp4a8_decode",
|
||||
mxd_launch(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
|
||||
r4d_addr(g.bscale), r4d_addr(g.bref), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, t.ks, t.bk, t.nt, as_group, as_rs,
|
||||
(long)(uintptr_t)s, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The core sizes the op's scratch from this. `M` is the band's widest, and a narrower M can split
|
||||
* wider (the fill rule asks for more blocks at M <= 24), so the size is the widest split over the
|
||||
* band times its widest M -- an upper bound on every launch the band can make. */
|
||||
extern "C" int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs* a) {
|
||||
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
|
||||
const long long K = r4d_geti_or(a, "K", 0);
|
||||
if (M < 1 || N < 16 || K < 64 || M > r4d_gemm_mxfp4a8_decode_max_m()) return 0;
|
||||
R4dMxDecCfg t;
|
||||
r4d_cfg_mxfp4_decode(a, &t);
|
||||
int ks = 1;
|
||||
for (int m = 1; m <= (int)M; ++m) {
|
||||
const int k = mxd_plan(m, (int)K, (int)N, t.ks, t.bk, t.nt).ks;
|
||||
if (k > ks) ks = k;
|
||||
}
|
||||
return (int64_t)mxd_partial_bytes((int)M, (int)N, ks);
|
||||
}
|
||||
@@ -68,6 +68,14 @@
|
||||
// The E8M0 scales are left in [K/32][N] order -- a half-wave reads sixteen consecutive bytes of
|
||||
// those already.
|
||||
//
|
||||
// TWO ACTIVATION SCALE GRIDS, as in r4d_gemm_mxfp4a8_tiled.hip: one f32 per row (ABLK=false), or
|
||||
// one per (row, 128 of K) (ABLK=true, the block-scaled fp8 family's grid). With ABLK each wave
|
||||
// carries its partial sums in units of the current 128-block's scale and rescales them by
|
||||
// s_prev / s_next at each block boundary inside its split-K segment. The segments end in
|
||||
// DIFFERENT blocks, so each partial is brought back to absolute units -- multiplied by its own
|
||||
// last scale -- before the LDS reduction adds them, and the epilogue applies only the weight's
|
||||
// reference factor.
|
||||
//
|
||||
// TRAP FOR ANYONE MEASURING THIS KERNEL: a weight of tens of megabytes streamed in a loop is
|
||||
// Infinity-Cache resident on this part, so a bandwidth figure taken that way can read above the
|
||||
// DRAM roofline. It ranks kernels reading the same bytes; it is not achieved DRAM bandwidth.
|
||||
@@ -78,56 +86,36 @@
|
||||
// the last valid row and the store discards it -- which keeps the inner loop branch-free.
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_mxfp4.h"
|
||||
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define R4D_GEMM_MXFP4_MAX_M 64
|
||||
#define R4D_GEMM_MXFP4_GROUP 32 // K per E8M0 exponent, fixed by the OCP MX format
|
||||
#define R4D_GEMM_MXFP4_GROUP R4D_MXFP4_GROUP
|
||||
#define WAVE32 32
|
||||
|
||||
typedef int v2i __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned uint2v __attribute__((ext_vector_type(2)));
|
||||
|
||||
// Folded magnitudes: kMag[d] is the eight e2m1 magnitudes scaled by 2^-d, as packed e4m3 bytes,
|
||||
// low table then high table, indexed by the 3-bit magnitude through v_perm_b32.
|
||||
// Every entry is the round-to-nearest-EVEN e4m3 of that product, which is exact for d <= 8 and
|
||||
// a rounding for d >= 9 -- three entries there (d=9 mag 1.5, d=10 mag 3, d=11 mag 6) are the
|
||||
// same exact tie 1.5*2^-9 and take the even neighbour 2^-8, not the smaller one. They matter
|
||||
// little (such an element is 2.9e-3 of its row's reference) but the table is generated, not
|
||||
// hand-rounded, so it should agree with the hardware's own conversion.
|
||||
__device__ __constant__ unsigned int kMag[16][2] = {
|
||||
{0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u},
|
||||
{0x2c282000u, 0x3c383430u}, {0x24201800u, 0x34302c28u},
|
||||
{0x1c181000u, 0x2c282420u}, {0x14100800u, 0x24201c18u},
|
||||
{0x0c080400u, 0x1c181410u}, {0x06040200u, 0x14100c08u},
|
||||
{0x03020100u, 0x0c080604u}, {0x02010000u, 0x06040302u},
|
||||
{0x01000000u, 0x03020201u}, {0x00000000u, 0x02010100u},
|
||||
{0x00000000u, 0x01000000u}, {0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
|
||||
};
|
||||
|
||||
// Eight e2m1 codes (four packed bytes) -> eight e4m3 bytes in k order, with the block's exponent
|
||||
// difference already folded in.
|
||||
__device__ __forceinline__ v2i r4d_mxfp4_unpack8(unsigned int wv, int dsh) {
|
||||
const unsigned int t0 = kMag[dsh][0], t1 = kMag[dsh][1];
|
||||
const unsigned int ev = wv & 0x0F0F0F0Fu; // low nibble of each byte -> even elements
|
||||
const unsigned int od = (wv >> 4) & 0x0F0F0F0Fu; // high nibble -> odd elements
|
||||
const unsigned int be = __builtin_amdgcn_perm(t1, t0, ev & 0x07070707u) | ((ev & 0x08080808u) << 4);
|
||||
const unsigned int bo = __builtin_amdgcn_perm(t1, t0, od & 0x07070707u) | ((od & 0x08080808u) << 4);
|
||||
// Eight e2m1 codes (four packed bytes) -> the B fragment, eight e4m3 bytes in k order with the
|
||||
// block's exponent difference folded in (r4d_mxfp4.h, shared with the other two MXFP4 kernels).
|
||||
__device__ __forceinline__ v2i r4d_mxfp4_frag8(unsigned int wv, int d) {
|
||||
unsigned int lo, hi;
|
||||
r4d_mxfp4_unpack8(wv, d, &lo, &hi);
|
||||
v2i out;
|
||||
out[0] = (int)__builtin_amdgcn_perm(bo, be, 0x05010400u); // elements 0..3
|
||||
out[1] = (int)__builtin_amdgcn_perm(bo, be, 0x07030602u); // elements 4..7
|
||||
out[0] = (int)lo;
|
||||
out[1] = (int)hi;
|
||||
return out;
|
||||
}
|
||||
|
||||
template <int MT, int NPW>
|
||||
template <int MT, int NPW, bool ABLK>
|
||||
__global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
const unsigned char* __restrict__ A, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int WV, int SK) {
|
||||
int M, int K, int N, int WV, int SK, int as_rs) {
|
||||
extern __shared__ float red[];
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
@@ -161,8 +149,39 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
const int ksteps = K / 16;
|
||||
|
||||
// ABLK: the scale each accumulator row of this lane is carried in -- row (mt0+i)*16 + mhalf + e.
|
||||
float scur[ABLK ? MT : 1][8];
|
||||
if constexpr (ABLK) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) {
|
||||
int r = (mt0 + i) * 16 + mhalf + e;
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
const float s = As[(size_t)r * as_rs + (kbase >> 7)];
|
||||
scur[i][e] = s > 0.f ? s : 1.f;
|
||||
}
|
||||
}
|
||||
|
||||
for (int k = 0; k < Ks; k += 16) {
|
||||
const int kg = kbase + k; // fragment base, both lane halves
|
||||
if constexpr (ABLK) {
|
||||
if (k && (kg & 127) == 0) { // a new 128-wide activation block
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) {
|
||||
int r = (mt0 + i) * 16 + mhalf + e;
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
float s = As[(size_t)r * as_rs + (kg >> 7)];
|
||||
s = s > 0.f ? s : scur[i][e];
|
||||
const float q = scur[i][e] / s;
|
||||
scur[i][e] = s;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) acc[j][i][e] *= q;
|
||||
}
|
||||
}
|
||||
}
|
||||
const int kstep = kg / 16;
|
||||
const int blk = kg / R4D_GEMM_MXFP4_GROUP; // one E8M0 block covers this whole step
|
||||
v2i af[MT];
|
||||
@@ -181,9 +200,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
// wave reads 128 contiguous bytes. In checkpoint order these would be sixteen rows K/2 bytes
|
||||
// apart -- a fully strided read on the operand that dominates traffic.
|
||||
const unsigned int wv = Wp[((size_t)wtile[j] * ksteps + kstep) * WAVE32 + lane];
|
||||
int dsh = (int)wref[j] - (int)Ws[(size_t)blk * N + n];
|
||||
dsh = dsh < 0 ? 0 : (dsh > 15 ? 15 : dsh);
|
||||
const v2i wf = r4d_mxfp4_unpack8(wv, dsh);
|
||||
const v2i wf = r4d_mxfp4_frag8(wv, r4d_mxfp4_fold_d(wref[j], Ws[(size_t)blk * N + n]));
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
acc[j][i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(af[i], wf, acc[j][i]);
|
||||
@@ -199,7 +216,8 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int slot = ((col_local * NPW + j) * SK + ksplit) * 256;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) red[slot + lane * 8 + e] = acc[j][i][e];
|
||||
for (int e = 0; e < 8; e++)
|
||||
red[slot + lane * 8 + e] = ABLK ? acc[j][i][e] * scur[i][e] : acc[j][i][e];
|
||||
}
|
||||
__syncthreads();
|
||||
// One pass over the block's 256-element tiles; every thread takes a stride.
|
||||
@@ -215,7 +233,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
|
||||
C[(size_t)m * N + n] =
|
||||
(__hip_bfloat16)(v * __int_as_float((int)Wref[n] << 23) * As[m]);
|
||||
(__hip_bfloat16)(v * __int_as_float((int)Wref[n] << 23) * (ABLK ? 1.f : As[m]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -225,7 +243,7 @@ extern "C" int r4d_gemm_mxfp4a8_nt_m64_group(void) { return R4D_GEMM_MXFP4_GROUP
|
||||
|
||||
extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c,
|
||||
int M, int K, int N, int WV, int SK, int MB, int NPW,
|
||||
long stream) {
|
||||
int as_group, int as_rs, long stream) {
|
||||
if (M < 1 || M > R4D_GEMM_MXFP4_MAX_M)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: M must be 1..64");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: N must be a multiple of 16");
|
||||
@@ -236,6 +254,9 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l
|
||||
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: MB must be 1..4");
|
||||
if (NPW != 1 && NPW != 2 && NPW != 4 && NPW != 8)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: NPW must be 1, 2, 4 or 8");
|
||||
if (as_group != 0 && as_group != 128)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: the activation scale is per row or per 128 of K");
|
||||
const bool ablk = as_group == 128;
|
||||
const int ntiles = N / 16, mtiles = (M + 15) / 16;
|
||||
const int ncols = WV * NPW;
|
||||
dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
|
||||
@@ -249,8 +270,13 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l
|
||||
auto Rp = (const unsigned char*)wref;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH(MTv, NPv) hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv>), grid, \
|
||||
block, smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK)
|
||||
#define LAUNCH(MTv, NPv) \
|
||||
do { \
|
||||
if (ablk) hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, true>), grid, block, \
|
||||
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \
|
||||
else hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, false>), grid, block, \
|
||||
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \
|
||||
} while (0)
|
||||
#define LAUNCH_MB(NPv) switch (MB) { \
|
||||
case 1: LAUNCH(1, NPv); break; \
|
||||
case 2: LAUNCH(2, NPv); break; \
|
||||
@@ -284,6 +310,9 @@ extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) {
|
||||
* reference and every element would be scaled against zero. */
|
||||
if (!g.bref) return R4D_NO(RAD_E_INVAL);
|
||||
const int group = r4d_gemm_mxfp4a8_nt_m64_group();
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs);
|
||||
if (rc != RAD_OK) return rc;
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, group, BR_FLAT, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
@@ -291,7 +320,7 @@ extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) {
|
||||
r4d_gemm_mxfp4a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
|
||||
r4d_addr(g.bscale), r4d_addr(g.bref), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw,
|
||||
(long)(uintptr_t)s));
|
||||
as_group, as_rs, (long)(uintptr_t)s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
// r4d_gemm_mxfp4a8_tiled.hip - r4d_gemm_mxfp4a8_tiled: the OCP-MXFP4 x fp8 GEMM for PREFILL row
|
||||
// counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the same operands, the same weight
|
||||
// layout and the same fold as r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_decode -- the band
|
||||
// above theirs.
|
||||
//
|
||||
// WHY A SEPARATE KERNEL. The decode kernels give a block at most 128 rows, so at prefill they
|
||||
// would re-read the whole weight ceil(M/128) times. Here a block is a 256 x (32*TN) tile and each
|
||||
// weight byte is unpacked once per K slab into LDS, where all four row-waves of the block read it.
|
||||
//
|
||||
// A COMES STRAIGHT FROM GLOBAL INTO REGISTERS, NOT THROUGH LDS. Staging A through LDS costs a
|
||||
// write, a barrier and a second read of the operand the block uses most, and a WMMA A fragment --
|
||||
// lane l holds row l%16, k-bytes 8*(l/16)..+8 of a 16 x 16 tile -- is 16 rows apart in a row-major
|
||||
// plane, so it cannot be loaded straight from one either. So A is re-tiled first, into the op's
|
||||
// scratch, in FRAGMENT ORDER:
|
||||
//
|
||||
// AT[((m/16) * (K/16) + k/16) * 256 + ((m%16) + 16 * ((k/8)%2)) * 8 + k%8] = A[m][k]
|
||||
//
|
||||
// One 16 x 16 fragment is 256 contiguous bytes and a lane's eight are one aligned 8-byte load, so
|
||||
// every A fragment a wave needs for a slab issues as one clause of global loads off a wave-uniform
|
||||
// base (SGPR, the SADDR form) and is consumed at the WMMAs. The re-tile is one read and one write
|
||||
// of A -- tens of microseconds at a 2048-row chunk against the hundreds the A-direct loop saves on
|
||||
// every large projection -- and it is the op's own, so no producer has to know about the layout.
|
||||
// Rows past M in the last fragment are written as zeros; they only reach accumulators the
|
||||
// epilogue drops.
|
||||
//
|
||||
// THE WEIGHT AND THE FOLD ARE THE SKINNY KERNEL'S. It reads the fragment-order weight that
|
||||
// r4d_rad_layout_mxfp4 stores and folds each block's exponent into the e4m3 value through the
|
||||
// table in r4d_mxfp4.h, so all three MXFP4 kernels produce the same e4m3 byte for every element.
|
||||
// The table is copied to LDS once per block: read from global it would be a dependent load issued
|
||||
// behind the A fragments, and the in-order load counter would make the fold wait for all of them.
|
||||
// 2^(Wref[n]-127) is applied once in the epilogue next to the activation's scale; see
|
||||
// r4d_gemm_mxfp4a8_nt_m64.hip for the fold and its error analysis.
|
||||
//
|
||||
// THE TILE. 8 waves as 4 (M) x 2 (N); a wave owns TM=4 x TN accumulator fragments, so the block
|
||||
// covers BMF = 4*4*16 = 256 rows and BNF = 2*TN*16 columns. The tall tile is for reuse: every
|
||||
// weight byte staged is multiplied against 256 rows. TN is the axis that depends on M. Widening
|
||||
// N halves the column-block count while BMF still masks most of a short M, so TN=4 wins only on
|
||||
// long prompts; on a 17408x5120 weight the two cross near M=2048. Hence tn=0, the default, picks
|
||||
// TN=4 from M >= 2048 and TN=2 below. The K slab is 128 at TN=2 and 64 at TN=4 (and 64 at TN=2
|
||||
// when K is not a multiple of 128): TN=4 holds twice the accumulators, and a 128 slab's A
|
||||
// fragments on top of them would cost occupancy.
|
||||
//
|
||||
// BARRIERS FENCE LDS ONLY. __syncthreads() is a workgroup acquire/release over every address
|
||||
// space, which drains the global load counter at each barrier. Nothing in global memory is
|
||||
// shared between the block's waves, so the barrier is scoped to LDS and the next slab's A loads
|
||||
// stay in flight across it.
|
||||
//
|
||||
// STAGING IS CLAMPED, NEVER PREDICATED. A bounds-predicated load lands in its own exec-mask
|
||||
// region and the compiler then cannot carry a counted s_wait_loadcnt across the merge. Clamped
|
||||
// (a tile past M reads the last real tile, a weight row past N the last aligned group), a slab's
|
||||
// loads issue back to back; the epilogue drops what they computed.
|
||||
//
|
||||
// THE ACCUMULATOR IS C TRANSPOSED. The WMMA takes the weight fragment as its A operand and the
|
||||
// activation fragment as its B operand -- the two have the same register layout, so this is only
|
||||
// an argument order -- and computes C^T: a lane's accumulator for (M fragment i, N fragment j)
|
||||
// holds ONE row and eight consecutive columns. So a row's activation scale is one value a lane
|
||||
// for each of its TM rows, and the epilogue writes each (i, j) as one 16-byte store.
|
||||
//
|
||||
// TWO ACTIVATION SCALE GRIDS. `a_scale` is either one f32 per row (ABLK=false) or one per (row,
|
||||
// 128 of K) (ABLK=true: the block-scaled fp8 family's grid, which every fused producer in
|
||||
// arch/common writes). Per-block scales vary along K and so cannot wait for the epilogue. The
|
||||
// accumulator is carried IN UNITS OF THE CURRENT BLOCK'S SCALE: at each 128 boundary every row's
|
||||
// partial sum is multiplied by s_prev / s_next, and the epilogue applies the last block's scale --
|
||||
// one multiply per accumulator element per 128 of K, ~K/128 fp32 ulps of extra rounding. The
|
||||
// ratio is computed once a row: thread t owns row t of the block, loads the next boundary's two
|
||||
// scales a boundary early (no slab waits on a scale load) and writes the ratio to LDS, and a lane
|
||||
// reads one ratio for each of its TM rows.
|
||||
//
|
||||
// TRAP FOR ANYONE MEASURING THIS KERNEL: the same as the skinny kernel's. A weight of tens of
|
||||
// megabytes streamed in a loop is Infinity-Cache resident on this part, so a bandwidth figure
|
||||
// taken that way reads above the DRAM roofline.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_mxfp4.h"
|
||||
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define R4D_MXT_TM 4 // 16-row fragments per wave
|
||||
#define R4D_MXT_WM 4 // waves along M
|
||||
#define R4D_MXT_WN 2 // waves along N
|
||||
#define R4D_MXT_PAD 8 // LDS row pad: 16 lanes reading rows 64 B apart collide 8 ways
|
||||
#define R4D_MXT_NTHR (R4D_MXT_WM * R4D_MXT_WN * 32)
|
||||
#define R4D_MXT_BMF (R4D_MXT_WM * R4D_MXT_TM * 16)
|
||||
#define R4D_MXT_KUNIT 64 // the narrowest K slab, so K must be a multiple of it
|
||||
#define R4D_MXT_TN4_MIN_M 2048 // tn=0's crossover, see above
|
||||
|
||||
typedef int mxt_v2i __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned mxt_u2 __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned mxt_u4 __attribute__((ext_vector_type(4)));
|
||||
|
||||
static __device__ __forceinline__ void mxt_lds_barrier() {
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local");
|
||||
__builtin_amdgcn_s_barrier();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local");
|
||||
}
|
||||
|
||||
// The re-tile: one thread per 8-byte slot of the fragment-ordered plane, so the writes are
|
||||
// contiguous and each lane reads one 8-byte group of one row.
|
||||
__global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel(
|
||||
const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K,
|
||||
long long slots) {
|
||||
const long long o = (long long)blockIdx.x * 256 + threadIdx.x;
|
||||
if (o >= slots) return;
|
||||
const int ks = K / 16;
|
||||
const int lane = (int)(o & 31);
|
||||
const long long f = o >> 5;
|
||||
const int mt = (int)(f / ks), kst = (int)(f % ks);
|
||||
const int r = mt * 16 + (lane & 15), k = kst * 16 + (lane >> 4) * 8;
|
||||
mxt_u2 v = { 0u, 0u };
|
||||
if (r < M) v = *(const mxt_u2*)(A + (size_t)r * K + k);
|
||||
*(mxt_u2*)(AT + o * 8) = v;
|
||||
}
|
||||
|
||||
template <int TN, int LBK, bool ABLK>
|
||||
__global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
const unsigned char* __restrict__ AT, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int as_rs) {
|
||||
constexpr int TM = R4D_MXT_TM, WN = R4D_MXT_WN, NTHR = R4D_MXT_NTHR, BMF = R4D_MXT_BMF;
|
||||
constexpr int NS = LBK / 16, STR = LBK + R4D_MXT_PAD, BNF = WN * TN * 16;
|
||||
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
|
||||
// 4 weight slots (one 16 B read) wherever the tile has enough of them, else 2 (8 B), else 1.
|
||||
constexpr int WSLOTS = (TOT_SLOTS >= NTHR * 4) ? 4 : (TOT_SLOTS >= NTHR * 2 ? 2 : 1);
|
||||
constexpr int NW = TOT_SLOTS / (NTHR * WSLOTS);
|
||||
static_assert(NW * NTHR * WSLOTS == TOT_SLOTS, "the W tile must split evenly over the block");
|
||||
__shared__ unsigned char sW[BNF * STR];
|
||||
__shared__ unsigned int sMag[32];
|
||||
__shared__ float sR[ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int wm = wave / WN, wn = wave % WN;
|
||||
const int col = lane & 15, kb8 = (lane >> 4) * 8;
|
||||
const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF;
|
||||
const int ksteps = K / 16, Mt = (M + 15) >> 4;
|
||||
|
||||
if (tid < 32) sMag[tid] = (&kMxfp4Mag[0][0])[tid];
|
||||
|
||||
// One A base per M fragment: wave-uniform, so readfirstlane keeps it in an SGPR and every load
|
||||
// takes the SADDR form with a 32-bit lane offset. A tile past M reads the last real one.
|
||||
const unsigned char* abase[TM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
int mt = (m0 >> 4) + wm * TM + i;
|
||||
mt = mt < Mt - 1 ? mt : Mt - 1;
|
||||
abase[i] = AT + (size_t)__builtin_amdgcn_readfirstlane(mt * ksteps * 256);
|
||||
}
|
||||
const unsigned int aoff = (unsigned int)lane * 8;
|
||||
|
||||
// The W slots this thread stages, fixed across slabs: WSLOTS adjacent rows of one (n-tile,
|
||||
// k-step), so the wave reads contiguous bytes; the clamp keeps the vector read aligned.
|
||||
int wrow[NW], wkloc[NW], wrc[NW], wkst[NW], wlanec[NW];
|
||||
unsigned int wref[NW];
|
||||
#pragma unroll
|
||||
for (int it = 0; it < NW; ++it) {
|
||||
const int sl = it * NTHR * WSLOTS + tid * WSLOTS;
|
||||
const int lane_ = sl & 31, rest = sl >> 5;
|
||||
const int kst = rest % NS, ntl = rest / NS;
|
||||
wrow[it] = ntl * 16 + (lane_ & 15);
|
||||
wkloc[it] = kst * 16 + (lane_ >> 4) * 8;
|
||||
const int gn = n0 + wrow[it];
|
||||
wrc[it] = gn < N - WSLOTS ? gn : N - WSLOTS;
|
||||
wlanec[it] = (lane_ & 16) | (wrc[it] & 15);
|
||||
wkst[it] = kst;
|
||||
wref[it] = WSLOTS == 4 ? *(const unsigned int*)(Wref + wrc[it])
|
||||
: WSLOTS == 2 ? *(const unsigned short*)(Wref + wrc[it])
|
||||
: Wref[wrc[it]];
|
||||
}
|
||||
|
||||
v8f acc[TM][TN];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f);
|
||||
|
||||
// ABLK, once a row: thread t owns row m0 + t (BMF == NTHR) and loads the next 128 boundary's two
|
||||
// scales -- the block that starts there and the one before it -- a boundary early.
|
||||
const int trow = m0 + tid < M ? m0 + tid : M - 1;
|
||||
const float* __restrict__ asrow = As + (size_t)trow * as_rs;
|
||||
float ns = 0.f, np = 0.f;
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
mxt_lds_barrier(); // sMag
|
||||
|
||||
for (int k0 = 0; k0 < K; k0 += LBK) {
|
||||
// ABLK: a new 128-wide activation block starts with this slab; each row's ratio goes to LDS,
|
||||
// published by the staging barrier below (sR's previous readers were behind the last slab's
|
||||
// closing barrier). A zero block keeps the carried scale; a zero block before this one sends
|
||||
// the carried scale back to the grid, which only an all-zero activation block ever does.
|
||||
const bool bnd = ABLK && k0 && (k0 & 127) == 0;
|
||||
if constexpr (ABLK) {
|
||||
if (bnd)
|
||||
sR[tid] = ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(asrow, (k0 >> 7) - 2)) / ns : 1.f;
|
||||
}
|
||||
// A fragments for the whole slab, one clause, consumed only at the WMMAs.
|
||||
mxt_v2i af[TM][NS];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int st = 0; st < NS; ++st)
|
||||
af[i][st] = *(const mxt_v2i*)(abase[i] +
|
||||
(aoff + (unsigned int)(k0 * 16) + (unsigned int)(st * 256)));
|
||||
// W slab -> LDS, folded to e4m3.
|
||||
const int kstep0 = k0 / 16;
|
||||
#pragma unroll
|
||||
for (int it = 0; it < NW; ++it) {
|
||||
const unsigned int* src =
|
||||
&Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]];
|
||||
const int blk = (k0 + wkst[it] * 16) / R4D_MXFP4_GROUP;
|
||||
unsigned int wq[WSLOTS], wsw;
|
||||
if constexpr (WSLOTS == 4) {
|
||||
const mxt_u4 v = *(const mxt_u4*)src;
|
||||
wq[0] = v[0]; wq[1] = v[1]; wq[2] = v[2]; wq[3] = v[3];
|
||||
wsw = *(const unsigned int*)(Ws + (size_t)blk * N + wrc[it]);
|
||||
} else if constexpr (WSLOTS == 2) {
|
||||
const mxt_u2 v = *(const mxt_u2*)src;
|
||||
wq[0] = v[0]; wq[1] = v[1];
|
||||
wsw = *(const unsigned short*)(Ws + (size_t)blk * N + wrc[it]);
|
||||
} else {
|
||||
wq[0] = *src;
|
||||
wsw = Ws[(size_t)blk * N + wrc[it]];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int q = 0; q < WSLOTS; ++q) {
|
||||
const int d = r4d_mxfp4_fold_d((int)((wref[it] >> (8 * q)) & 0xFF),
|
||||
(int)((wsw >> (8 * q)) & 0xFF));
|
||||
unsigned int lo, hi;
|
||||
r4d_mxfp4_unpack8_t(wq[q], sMag[d * 2], sMag[d * 2 + 1], &lo, &hi);
|
||||
*(mxt_u2*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = mxt_u2{lo, hi};
|
||||
}
|
||||
}
|
||||
mxt_lds_barrier();
|
||||
|
||||
if constexpr (ABLK) {
|
||||
// Re-express each row's partial sum in the new block's scale: one ratio a lane a row.
|
||||
if (bnd) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
const float r = sR[wm * TM * 16 + i * 16 + col];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) acc[i][j][e] *= r;
|
||||
}
|
||||
}
|
||||
// The next boundary's scales, issued behind this slab's loads and needed a boundary later.
|
||||
if ((k0 & 127) == 0 && k0 + 128 < K) {
|
||||
ns = asrow[(k0 >> 7) + 1];
|
||||
np = asrow[k0 >> 7];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int step = 0; step < NS; ++step) {
|
||||
const int kk = step * 16 + kb8;
|
||||
mxt_v2i wf[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
const unsigned char* p = &sW[(wn * TN * 16 + j * 16 + col) * STR + kk];
|
||||
wf[j][0] = *(const int*)p; wf[j][1] = *(const int*)(p + 4);
|
||||
}
|
||||
// One step's W fragments live at a time: without the fence the compiler hoists every
|
||||
// step's loads above the first WMMA and holds them all.
|
||||
__builtin_amdgcn_sched_barrier(0);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j)
|
||||
acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[j], af[i][step],
|
||||
acc[i][j]);
|
||||
}
|
||||
mxt_lds_barrier();
|
||||
}
|
||||
|
||||
// Epilogue. A lane holds row m0 + 64*wm + 16i + col of M fragment i and eight consecutive columns of N fragment
|
||||
// j, so each (i, j) is one 16-byte store. 2^(Wref[n]-127) is exactly the float whose exponent
|
||||
// field is Wref[n]; N % 16 == 0 keeps a lane's eight columns all inside N or all outside it.
|
||||
float sc[TM];
|
||||
if constexpr (ABLK) {
|
||||
// the scale each row ends in, once a row; the K loop's closing barrier retired the ratio reads
|
||||
sR[tid] = r4d_mxfp4_carried(asrow, (K - 1) >> 7);
|
||||
mxt_lds_barrier();
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) sc[i] = sR[wm * TM * 16 + i * 16 + col];
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
const int m = m0 + wm * TM * 16 + i * 16 + col;
|
||||
sc[i] = As[(size_t)(m < M ? m : M - 1) * as_rs];
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
const int nb = n0 + wn * TN * 16 + j * 16 + kb8;
|
||||
if (nb >= N) continue;
|
||||
const mxt_u2 rb = *(const mxt_u2*)(Wref + nb);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
const int m = m0 + wm * TM * 16 + i * 16 + col;
|
||||
if (m >= M) continue;
|
||||
union { __hip_bfloat16 h[8]; mxt_u4 v; } o;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const float rf = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
|
||||
o.h[e] = (__hip_bfloat16)(acc[i][j][e] * rf * sc[i]);
|
||||
}
|
||||
*(mxt_u4*)(C + (size_t)m * N + nb) = o.v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" int r4d_gemm_mxfp4a8_tiled_group(void) { return R4D_MXFP4_GROUP; }
|
||||
|
||||
extern "C" long r4d_mxfp4a8_tile_a_bytes(int M, int K) {
|
||||
return M < 1 || K < 16 ? 0 : (long)((M + 15) / 16) * 16 * K;
|
||||
}
|
||||
|
||||
extern "C" void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream) {
|
||||
if (M < 1) throw std::runtime_error("r4d mxfp4a8_tile_a: M must be >= 1");
|
||||
if (K < 16 || K % 16) throw std::runtime_error("r4d mxfp4a8_tile_a: K must be a multiple of 16");
|
||||
const long long slots = (long long)((M + 15) / 16) * (K / 16) * 32;
|
||||
hipLaunchKernelGGL(r4d_mxfp4a8_tile_a_kernel, dim3((unsigned)((slots + 255) / 256)), dim3(256), 0,
|
||||
(hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K, slots);
|
||||
}
|
||||
|
||||
extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c,
|
||||
int M, int K, int N, int TN, int as_group, int as_rs,
|
||||
long stream) {
|
||||
if (M < 1) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: M must be >= 1");
|
||||
if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: N must be a multiple of 16");
|
||||
if (K < R4D_MXT_KUNIT || K % R4D_MXT_KUNIT)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_tiled: K must be a multiple of 64");
|
||||
// tn=0: TN=4 from the M crossover on, unless its 128-wide tile leaves the grid short of 128
|
||||
// blocks (a narrow N): there the TN=2 grid's extra blocks win.
|
||||
if (TN == 0)
|
||||
TN = M >= R4D_MXT_TN4_MIN_M && (long)((N + 127) / 128) * ((M + R4D_MXT_BMF - 1) / R4D_MXT_BMF) >= 128
|
||||
? 4 : 2;
|
||||
if (TN != 2 && TN != 4) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: TN must be 2 or 4");
|
||||
if (as_group != 0 && as_group != 128)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_tiled: the activation scale is per row or per 128 of K");
|
||||
const bool ablk = as_group == 128;
|
||||
if (ablk && as_rs < (K + 127) / 128)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_tiled: activation scale rows shorter than ceil(K/128)");
|
||||
const bool wide_slab = TN == 2 && K % 128 == 0;
|
||||
const int bnf = R4D_MXT_WN * TN * 16;
|
||||
dim3 grid((N + bnf - 1) / bnf, (M + R4D_MXT_BMF - 1) / R4D_MXT_BMF), block(R4D_MXT_NTHR);
|
||||
auto Ap = (const unsigned char*)at;
|
||||
auto Sp = (const float*)ascale;
|
||||
auto Wp = (const unsigned char*)wq;
|
||||
auto Zp = (const unsigned char*)ws;
|
||||
auto Rp = (const unsigned char*)wref;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define MXT_LAUNCH(TNv, LBKv, ABv) \
|
||||
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, Sp, \
|
||||
Wp, Zp, Rp, Cp, M, K, N, as_rs)
|
||||
if (TN == 4) { if (ablk) MXT_LAUNCH(4, 64, true); else MXT_LAUNCH(4, 64, false); }
|
||||
else if (wide_slab) { if (ablk) MXT_LAUNCH(2, 128, true); else MXT_LAUNCH(2, 128, false); }
|
||||
else { if (ablk) MXT_LAUNCH(2, 64, true); else MXT_LAUNCH(2, 64, false); }
|
||||
#undef MXT_LAUNCH
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
// The row-major activation is re-tiled into the op's scratch, then the GEMM reads it from there.
|
||||
extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
if (g.K % R4D_MXT_KUNIT) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return R4D_NO(RAD_E_INVAL);
|
||||
/* The per-row reference exponent, as in r4d_rad_gemm_mxfp4a8_m64: without it the fold has no
|
||||
* reference and every element would be scaled against zero. */
|
||||
if (!g.bref) return R4D_NO(RAD_E_INVAL);
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (!a->scratch || a->scratch_bytes < r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K))
|
||||
return R4D_NO(RAD_E_INVAL);
|
||||
R4dMxTileCfg t;
|
||||
r4d_cfg_mxfp4_tiled(a, &t);
|
||||
const long at = (long)(uintptr_t)a->scratch;
|
||||
R4D_TRY("gemm_mxfp4a8_tiled",
|
||||
r4d_mxfp4a8_tile_a(r4d_addr(g.a), at, (int)g.M, (int)g.K, (long)(uintptr_t)s);
|
||||
r4d_gemm_mxfp4a8_tiled(at, r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale),
|
||||
r4d_addr(g.bref), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N,
|
||||
t.tn, as_group, as_rs, (long)(uintptr_t)s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The core sizes the op's scratch from this, at the band's widest M: the fragment-tiled copy of
|
||||
* the activation, whole 16-row fragments. */
|
||||
extern "C" int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs* a) {
|
||||
const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "K", 0);
|
||||
return (int64_t)r4d_mxfp4a8_tile_a_bytes((int)M, (int)K);
|
||||
}
|
||||
+28
-11
@@ -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]);
|
||||
@@ -771,11 +774,12 @@ extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope
|
||||
row_pitch, 0, nullptr, 0, 0, stream);
|
||||
}
|
||||
|
||||
// The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and
|
||||
// `plane` the component pitch of `pos`; plane 0 is the one-component rotary above.
|
||||
extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
|
||||
int rot, int gptj, float theta, float rscale, int row_pitch,
|
||||
int mode, const int* sec, int n_sec, int plane, long stream) {
|
||||
// THE ONE LAUNCH OF rope_kernel. `yarn` with factor 0 is the plain rotary: the kernel's YaRN
|
||||
// blend returns the frequency it was given and the magnitude is not applied, so the C entry points
|
||||
// below and the op without YaRN run the same arithmetic with the same arguments.
|
||||
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot,
|
||||
int gptj, float theta, float rscale, int row_pitch, int mode,
|
||||
const int* sec, int n_sec, int plane, RadYarn yarn, long stream) {
|
||||
if (!qkv || !pos) return -1;
|
||||
if (M <= 0 || head_dim <= 0 || n_rope_heads <= 0) return -2;
|
||||
if (rot <= 0 || rot > head_dim || (rot & 1)) return -3;
|
||||
@@ -787,10 +791,19 @@ 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, yarn);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
// The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and
|
||||
// `plane` the component pitch of `pos`; plane 0 is the one-component rotary above.
|
||||
extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
|
||||
int rot, int gptj, float theta, float rscale, int row_pitch,
|
||||
int mode, const int* sec, int n_sec, int plane, long stream) {
|
||||
return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale, row_pitch,
|
||||
mode, sec, n_sec, plane, RadYarn{}, stream);
|
||||
}
|
||||
|
||||
extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim,
|
||||
int kv_heads, int block_size, int n_blocks,
|
||||
int k_ld, int v_ld, long stream) {
|
||||
@@ -1384,12 +1397,16 @@ 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);
|
||||
/* YaRN over the axial vision rotary, or over a linear position divide, is no model's. */
|
||||
if (yarn.factor != 0.0f && (mc == 4 || rscale != 1.0f)) return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
/* 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,
|
||||
(int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch,
|
||||
mc, sec, n_sec, plane, (long)(uintptr_t)s) == 0 ? RAD_OK
|
||||
: RAD_E_DEVICE;
|
||||
return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
|
||||
(int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch,
|
||||
mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s) == 0 ? RAD_OK
|
||||
: RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ kv_store */
|
||||
|
||||
+827
-73
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,74 @@
|
||||
// Shared device-side machinery for the OCP-MXFP4 GEMMs (r4d_gemm_mxfp4a8_nt_m64, _tiled, _decode):
|
||||
// the folded-magnitude table and the eight-element unpack that reads it. One definition, because
|
||||
// the three kernels must fold every weight element to the same e4m3 byte -- a model whose step
|
||||
// crosses from one row's band into another's must not change what the weight is.
|
||||
//
|
||||
// r4d_gemm_mxfp4a8_nt_m64.hip explains the fold: d = Wref[n] - E8M0[n][blk] is pushed into the
|
||||
// e4m3 value through this table, and 2^(Wref[n]-127) is applied once in the epilogue.
|
||||
#pragma once
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#define R4D_MXFP4_GROUP 32 // K per E8M0 exponent, fixed by the OCP MX format
|
||||
|
||||
// kMxfp4Mag[d] is the eight e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by 2^-d, as packed
|
||||
// e4m3 bytes, low word then high word, indexed by the 3-bit magnitude through v_perm_b32.
|
||||
// Every entry is the round-to-nearest-EVEN e4m3 of that product, which is exact for d <= 8 and a
|
||||
// rounding for d >= 9 -- three entries there (d=9 mag 1.5, d=10 mag 3, d=11 mag 6) are the same
|
||||
// exact tie 1.5*2^-9 and take the even neighbour 2^-8, not the smaller one. They matter little
|
||||
// (such an element is 2.9e-3 of its row's reference), but the table is generated, not hand-rounded,
|
||||
// so it agrees with the hardware's own conversion. d >= 13 is zero: below the row's range.
|
||||
//
|
||||
// Static: each kernel's code object carries its own copy, and no two define the same symbol.
|
||||
static __device__ __constant__ unsigned int kMxfp4Mag[16][2] = {
|
||||
{0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u},
|
||||
{0x2c282000u, 0x3c383430u}, {0x24201800u, 0x34302c28u},
|
||||
{0x1c181000u, 0x2c282420u}, {0x14100800u, 0x24201c18u},
|
||||
{0x0c080400u, 0x1c181410u}, {0x06040200u, 0x14100c08u},
|
||||
{0x03020100u, 0x0c080604u}, {0x02010000u, 0x06040302u},
|
||||
{0x01000000u, 0x03020201u}, {0x00000000u, 0x02010100u},
|
||||
{0x00000000u, 0x01000000u}, {0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
|
||||
};
|
||||
|
||||
// The exponent difference a block is folded at, clamped to the table: a block above its row's
|
||||
// reference cannot occur (the reference is the row's maximum), and one 15 or more below is zero.
|
||||
static __device__ __forceinline__ int r4d_mxfp4_fold_d(int ref, int e8) {
|
||||
const int d = ref - e8;
|
||||
return d < 0 ? 0 : (d > 15 ? 15 : d);
|
||||
}
|
||||
|
||||
// Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) -> eight e4m3 bytes
|
||||
// in k order, word 0 holding elements 0..3 and word 1 elements 4..7, with the block's exponent
|
||||
// difference `d` already folded in. Splitting the nibbles gives the even and odd elements; each is
|
||||
// mapped through the table by a v_perm_b32 indexed with the 3-bit magnitude, the sign rides along
|
||||
// as bit 3 shifted into the e4m3 sign position, and two more v_perm_b32 interleave the halves.
|
||||
//
|
||||
// `_t` takes the table row (t0, t1) the caller already holds -- a kernel that copies the table to
|
||||
// LDS reads it there, off the global load counter its weight and activation loads wait on.
|
||||
static __device__ __forceinline__ void r4d_mxfp4_unpack8_t(unsigned int wv, unsigned int t0,
|
||||
unsigned int t1, unsigned int* lo,
|
||||
unsigned int* hi) {
|
||||
const unsigned int ev = wv & 0x0F0F0F0Fu; // low nibble of each byte -> even elements
|
||||
const unsigned int od = (wv >> 4) & 0x0F0F0F0Fu; // high nibble -> odd elements
|
||||
const unsigned int be = __builtin_amdgcn_perm(t1, t0, ev & 0x07070707u) | ((ev & 0x08080808u) << 4);
|
||||
const unsigned int bo = __builtin_amdgcn_perm(t1, t0, od & 0x07070707u) | ((od & 0x08080808u) << 4);
|
||||
*lo = __builtin_amdgcn_perm(bo, be, 0x05010400u);
|
||||
*hi = __builtin_amdgcn_perm(bo, be, 0x07030602u);
|
||||
}
|
||||
static __device__ __forceinline__ void r4d_mxfp4_unpack8(unsigned int wv, int d,
|
||||
unsigned int* lo, unsigned int* hi) {
|
||||
r4d_mxfp4_unpack8_t(wv, kMxfp4Mag[d][0], kMxfp4Mag[d][1], lo, hi);
|
||||
}
|
||||
|
||||
// THE ACTIVATION SCALE A ROW'S ACCUMULATOR IS CARRIED IN, for the per-(row, 128 of K) grid: the
|
||||
// last non-zero entry of row `row` at or before block `kb`, or 1 when there is none. A block whose
|
||||
// scale is zero has zero codes and adds nothing whichever scale the sum is carried in, so it keeps
|
||||
// the previous one rather than dividing by zero.
|
||||
static __device__ __forceinline__ float r4d_mxfp4_carried(const float* __restrict__ row, int kb) {
|
||||
for (int j = kb; j >= 0; --j) {
|
||||
const float s = row[j];
|
||||
if (s > 0.f) return s;
|
||||
}
|
||||
return 1.f;
|
||||
}
|
||||
@@ -42,6 +42,8 @@ enum {
|
||||
* asks with M=64 to exclude m16. */
|
||||
R4D_PRIO_GEMM_M16 = 60,
|
||||
R4D_PRIO_GEMM_SKINNY = 50,
|
||||
/* The MXFP4 decode row outranks the MXFP4 skinny row, whose band it shares up to N = 36864. */
|
||||
R4D_PRIO_GEMM_MXDEC = 55,
|
||||
/* The skinny m64 row has no upper bound on M, so the tiled bf16 row -- M > 64 only -- has to
|
||||
* outrank it to be reached, and stays below m16 whose band it never enters. */
|
||||
R4D_PRIO_GEMM_BF16_TILED = 55,
|
||||
@@ -167,6 +169,11 @@ int r4d_rad_hc_write_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, in
|
||||
/* -- all-reduce (r4d_ar_entry.hip) -- */
|
||||
int r4d_rad_ar_init(const RadParam*, int, int rank, int world, void** out);
|
||||
void r4d_rad_ar_fini(void*);
|
||||
/* The same three inits with every rank's exchange buffers in pinned host memory: the host twins
|
||||
* of the collective rows (r4d_rows.cpp) take them, and every launch and the fini are shared. */
|
||||
int r4d_rad_ar_host_init(const RadParam*, int, int rank, int world, void** out);
|
||||
int r4d_rad_ar_ln_host_init(const RadParam*, int, int rank, int world, void** out);
|
||||
int r4d_rad_ar_hc_wide_host_init(const RadParam*, int, int rank, int world, void** out);
|
||||
int r4d_rad_ar_oneshot_2rank_exact(const RadArgs*, RadStream);
|
||||
int r4d_rad_ar_gather_2rank (const RadArgs*, RadStream);
|
||||
/* The gather at a wide group's handshake (r4d_ar_gather_Nrank.hip launches it). */
|
||||
@@ -207,6 +214,10 @@ int r4d_rad_gemm_w8a8_m64 (const RadArgs*, RadStream);
|
||||
int r4d_rad_gemm_w8a8_tiled (const RadArgs*, RadStream);
|
||||
int r4d_rad_gemm_w2a8 (const RadArgs*, RadStream);
|
||||
int r4d_rad_gemm_mxfp4a8_m64(const RadArgs*, RadStream);
|
||||
int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs*);
|
||||
int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*);
|
||||
int r4d_rad_dequant_w4 (const RadArgs*, RadStream);
|
||||
int r4d_rad_rowtopk (const RadArgs*, RadStream);
|
||||
int r4d_rad_rowtopk_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
|
||||
|
||||
@@ -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)
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+169
-8
@@ -34,6 +34,8 @@
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#define ROW(a) (a), (int)(sizeof(a) / sizeof((a)[0]))
|
||||
#define NELEM(a) ((int)(sizeof(a) / sizeof((a)[0])))
|
||||
@@ -274,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 },
|
||||
@@ -1094,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 },
|
||||
@@ -1572,6 +1582,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 */
|
||||
@@ -2923,6 +2937,18 @@ static const RadConstraint cGemmNtW8A8[] = {
|
||||
static const RadConstraint cGemmW4A8Tiled[] = {
|
||||
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256), C_IN("dtype", "w4a8 w4a8_asym"),
|
||||
};
|
||||
/* r4d_gemm_mxfp4a8_decode. Entry point: M <= 128, N % 16, K % 64, and N up to its counter block's
|
||||
* 36864. Above the skinny row by priority, so it takes the decode band; the skinny row keeps the
|
||||
* wider N up to M = 64, the tiled row everything else. */
|
||||
static const RadConstraint cGemmMxfp4A8Decode[] = {
|
||||
C_LE("M", 128), C_LE("N", 36864), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
|
||||
};
|
||||
/* r4d_gemm_mxfp4a8_tiled. Entry point: N % 16 (the fragment-order weight), K % 64 (its narrowest
|
||||
* K slab), M >= 1. The decode and skinny rows outrank it in their bands by priority, so the band
|
||||
* starts at 1 rather than at a hand-picked crossover. */
|
||||
static const RadConstraint cGemmMxfp4A8Tiled[] = {
|
||||
C_GE("M", 1), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
|
||||
};
|
||||
/* r4d_gemm_w8a8_tiled. The same kernel at radix 8; the asym arm exists in the .hip but is NOT
|
||||
* declared in r4d.h, so this plugin cannot reach it and `w8a8_asym` is deliberately absent from
|
||||
* the dtype set. */
|
||||
@@ -3042,6 +3068,25 @@ static const RadTunable tGemmPrefill[] = {
|
||||
"compiled tile arm; 0 is BM 128 x BN 256, libr4d's own default" },
|
||||
};
|
||||
|
||||
/* The MXFP4 tiled GEMM's one axis. Both values are compiled arms of one template; 0 is the M
|
||||
* crossover (TN=4 from M >= 2048), which needs M and so cannot be a constant. */
|
||||
static const int64_t kMxTn[] = { 0, 2, 4 };
|
||||
static const RadTunable tGemmMxfp4Tiled[] = {
|
||||
{ "tn", kMxTn, NELEM(kMxTn), 0,
|
||||
"16-column fragments per wave: 2 = 256x64 block, 4 = 256x128. 0 = TN 4 from M >= 2048" },
|
||||
};
|
||||
|
||||
/* The MXFP4 decode GEMM's axes. 0 on each is the kernel's own rule (r4d_gemm_mxfp4a8_decode.hip);
|
||||
* `nt` 1 streams the weight past the caches, 2 loads it plainly. */
|
||||
static const int64_t kMxDecKs[] = { 0, 1, 2, 4, 8, 16 };
|
||||
static const int64_t kMxDecBk[] = { 0, 64, 128 };
|
||||
static const int64_t kMxDecNt[] = { 0, 1, 2 };
|
||||
static const RadTunable tGemmMxfp4Decode[] = {
|
||||
{ "ks", kMxDecKs, NELEM(kMxDecKs), 0, "split-K workgroups a column block. 0 = the fill rule" },
|
||||
{ "bk", kMxDecBk, NELEM(kMxDecBk), 0, "K slab in bytes. 0 = 128, or 64 for a wide unsplit DTM 4" },
|
||||
{ "nt", kMxDecNt, NELEM(kMxDecNt), 0, "weight loads: 1 non-temporal, 2 plain. 0 = by weight size" },
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------------ split-KV attention
|
||||
* 0 is libr4d's measured split law (r4d_attn_paged_h256_gqa6.hip carries the table), which reads
|
||||
* num_seqs and max_ctx -- values that exist only at issue -- so it cannot be a constant and stays
|
||||
@@ -4319,6 +4364,32 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_m64, nullptr, r4d_rad_layout_mxfp4,
|
||||
r4d_rad_relayout_mxfp4 },
|
||||
|
||||
{ "gemm_mxfp4a8_decode", "gemm_nt_q", "gemm",
|
||||
"the OCP-MXFP4 GEMM for the DECODE band: split-K across workgroups with a fused last-arriver "
|
||||
"reduction, the weight unpacked through LDS, streaming weight loads",
|
||||
"M <= 128; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, "
|
||||
"[K/32][N] E8M0 exponents and per-row reference exponent; the split partial in the op's scratch",
|
||||
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K folded "
|
||||
"into the element against a per-row reference, bf16 C, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_MXDEC,
|
||||
ROW(cGemmMxfp4A8Decode), ROW(tGemmMxfp4Decode), nullptr,
|
||||
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_decode, r4d_rad_gemm_mxfp4a8_decode_scratch,
|
||||
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
|
||||
|
||||
{ "gemm_mxfp4a8_tiled", "gemm_nt_q", "gemm",
|
||||
"the OCP-MXFP4 GEMM tiled for PREFILL row counts: the activation re-tiled into fragment order in "
|
||||
"the op's scratch, its fragments read straight into registers, the weight unpacked once per K "
|
||||
"slab into LDS for a 256-row block",
|
||||
"any M; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, "
|
||||
"[K/32][N] E8M0 exponents and per-row reference exponent; the re-tiled activation in the op's "
|
||||
"scratch",
|
||||
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K folded "
|
||||
"into the element against a per-row reference, bf16 C, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_TILED,
|
||||
ROW(cGemmMxfp4A8Tiled), ROW(tGemmMxfp4Tiled), nullptr,
|
||||
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch,
|
||||
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
|
||||
|
||||
/* BAND READ OFF THE ENTRY POINT'S OWN REJECTION TESTS. */
|
||||
{ "gemm_w4a8_prefill", "gemm_nt_q", "gemm",
|
||||
"the 4-bit GEMM for PREFILL row counts, where the matrix pipe rather than the weight stream is "
|
||||
@@ -5067,8 +5138,9 @@ static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_KERNEL,
|
||||
"libr4d",
|
||||
"0.5.0",
|
||||
"the RDNA4 (gfx1201) kernel library: paged and dense attention, gated delta net, P2P "
|
||||
"all-reduce, skinny and tiled quantised GEMM, and the rotate-and-quantise fusions",
|
||||
"the RDNA4 (gfx1201) kernel library: paged and dense attention, gated delta net, "
|
||||
"all-reduce over P2P or a host-memory mailbox, skinny and tiled quantised GEMM, and the "
|
||||
"rotate-and-quantise fusions",
|
||||
"gfx1201",
|
||||
};
|
||||
|
||||
@@ -5082,12 +5154,91 @@ extern "C" const RadOpSchema* rad_kernel_schema_at(int i) {
|
||||
if (i < 0 || i >= rad_kernel_schema_count()) return nullptr;
|
||||
return &kSchemas[i];
|
||||
}
|
||||
/* ================================================================================ the host twins
|
||||
*
|
||||
* A MACHINE WITHOUT PEER ACCESS RUNS THE SAME COLLECTIVES WITH THEIR MAILBOX IN HOST MEMORY. Every
|
||||
* row that takes one of the three all-reduce inits has a twin: the same op, kernel, launch, fini,
|
||||
* priority and tuning axes, `_host` appended to its name, its device.p2p == 1 turned into
|
||||
* device.p2p == 0, and the init that puts every rank's exchange buffers in pinned host memory
|
||||
* (r4d_ar_entry.hip, build). Exactly one of a pair matches any machine, so neither outranks the
|
||||
* other, and a band report names which transport the step runs.
|
||||
*
|
||||
* DERIVED, NOT WRITTEN OUT, so a collective row added to the table above has its twin by being
|
||||
* added and the two cannot drift: the transport is the only thing they differ in. A collective row
|
||||
* that does not require device.p2p == 1 gets no twin, and r4d_selftest fails it for the missing
|
||||
* constraint. */
|
||||
namespace {
|
||||
|
||||
struct HostTwin {
|
||||
RadKernelInfo info;
|
||||
std::string name, computes, shape;
|
||||
std::vector<RadConstraint> c;
|
||||
};
|
||||
|
||||
RadInitFn host_init_for(RadInitFn f) {
|
||||
if (f == r4d_rad_ar_init) return r4d_rad_ar_host_init;
|
||||
if (f == r4d_rad_ar_ln_init) return r4d_rad_ar_ln_host_init;
|
||||
if (f == r4d_rad_ar_hc_wide_init) return r4d_rad_ar_hc_wide_host_init;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::string replaced(std::string s, const char* from, const char* to) {
|
||||
const size_t at = s.find(from);
|
||||
if (at != std::string::npos) s.replace(at, std::strlen(from), to);
|
||||
return s;
|
||||
}
|
||||
|
||||
const std::vector<HostTwin>& host_twins() {
|
||||
static const std::vector<HostTwin> v = [] {
|
||||
std::vector<HostTwin> t;
|
||||
for (const RadKernelInfo& k : kKernels) {
|
||||
const RadInitFn init = host_init_for(k.init);
|
||||
if (!init) continue;
|
||||
HostTwin h;
|
||||
h.c.assign(k.constraints, k.constraints + k.n_constraints);
|
||||
int p2p = 0;
|
||||
for (RadConstraint& c : h.c)
|
||||
if (!std::strcmp(c.key, RAD_FACT_P2P) && c.op == RAD_C_EQ && c.ival == 1) {
|
||||
c.ival = 0;
|
||||
++p2p;
|
||||
}
|
||||
if (p2p != 1) continue;
|
||||
h.info = k;
|
||||
h.info.init = init;
|
||||
h.name = std::string(k.name) + "_host";
|
||||
h.computes = k.computes;
|
||||
if (h.computes.find("over P2P IPC scratch") != std::string::npos)
|
||||
h.computes = replaced(h.computes, "over P2P IPC scratch",
|
||||
"through a pinned host-memory mailbox");
|
||||
else
|
||||
h.computes += ", exchanged through a pinned host-memory mailbox";
|
||||
h.shape = replaced(replaced(k.shape, "all peer-accessible", "no peer access needed"),
|
||||
"peer-accessible", "no peer access needed");
|
||||
t.push_back(std::move(h));
|
||||
}
|
||||
/* The strings are pointed into only once the vector has stopped growing. */
|
||||
for (HostTwin& h : t) {
|
||||
h.info.name = h.name.c_str();
|
||||
h.info.computes = h.computes.c_str();
|
||||
h.info.shape = h.shape.c_str();
|
||||
h.info.constraints = h.c.data();
|
||||
h.info.n_constraints = (int)h.c.size();
|
||||
}
|
||||
return t;
|
||||
}();
|
||||
return v;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
extern "C" int rad_kernel_count(void) {
|
||||
return (int)(sizeof(kKernels) / sizeof(kKernels[0]));
|
||||
return (int)(sizeof(kKernels) / sizeof(kKernels[0])) + (int)host_twins().size();
|
||||
}
|
||||
extern "C" const RadKernelInfo* rad_kernel_at(int i) {
|
||||
const int base = (int)(sizeof(kKernels) / sizeof(kKernels[0]));
|
||||
if (i < 0 || i >= rad_kernel_count()) return nullptr;
|
||||
return &kKernels[i];
|
||||
if (i < base) return &kKernels[i];
|
||||
return &host_twins()[(size_t)(i - base)].info;
|
||||
}
|
||||
|
||||
/* WHICH ROWS TOUCH NOTHING BUT THEIR OPERANDS AND SCRATCH (rad_abi.h). Nothing on an R4D launch
|
||||
@@ -5100,11 +5251,13 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) {
|
||||
* gemm_w8a8_tiled
|
||||
* every collective the peer flags and exchange buffers the all-reduces own
|
||||
*
|
||||
* gemm_fp8a8_nt_m16's finisher counters are keyed on the stream AND the output, and
|
||||
* gemm_fp8a8_nt_m16's finisher counters are keyed on the stream AND the output;
|
||||
* gemm_mxfp4a8_decode's split partial is the op's scratch and its arrival counters are keyed on the
|
||||
* output alone, so no argument depends on the stream a pass is recorded or replayed on; and
|
||||
* router_gemm_topk_scatter_bf16's arrival counter is its op instance's (taken at init, one a
|
||||
* declared op and band), so two launches that could run at once never share them, and both rows
|
||||
* are concurrent. A row added with state of its own that the stream's order protects belongs in
|
||||
* this list. */
|
||||
* declared op and band). Two launches that could run at once never share any of them, so all three
|
||||
* rows are concurrent. A row added with state of its own that the stream's order protects belongs
|
||||
* in this list. */
|
||||
extern "C" int rad_kernel_concurrent(int i) {
|
||||
const RadKernelInfo* k = rad_kernel_at(i);
|
||||
if (!k) return 0;
|
||||
@@ -5179,6 +5332,14 @@ extern "C" void r4d_cfg_tiled(const RadArgs* a, R4dTileCfg* out) {
|
||||
extern "C" void r4d_cfg_prefill(const RadArgs* a, R4dTileCfg* out) {
|
||||
tile_bmbn(TUNE(a, tGemmPrefill, "tile"), 1, out);
|
||||
}
|
||||
extern "C" void r4d_cfg_mxfp4_decode(const RadArgs* a, R4dMxDecCfg* out) {
|
||||
out->ks = TUNE(a, tGemmMxfp4Decode, "ks");
|
||||
out->bk = TUNE(a, tGemmMxfp4Decode, "bk");
|
||||
out->nt = TUNE(a, tGemmMxfp4Decode, "nt");
|
||||
}
|
||||
extern "C" void r4d_cfg_mxfp4_tiled(const RadArgs* a, R4dMxTileCfg* out) {
|
||||
out->tn = TUNE(a, tGemmMxfp4Tiled, "tn");
|
||||
}
|
||||
extern "C" void r4d_cfg_split(const RadArgs* a, R4dSplitCfg* out) {
|
||||
out->splits = TUNE(a, tAttnSplit, "splits");
|
||||
}
|
||||
|
||||
+1350
-97
File diff suppressed because it is too large.
Load diff
+102
-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,17 +584,106 @@ 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;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ qsa_block_key */
|
||||
/* The QSA indexer's compressed key (docs/OPS.md, docs/QSA.md): for each of M blocks,
|
||||
*
|
||||
* pooled = mean of the block's `ratio` rows of k, accumulated in f32 and ROUNDED TO k's dtype
|
||||
* normed = pooled * rsqrt(mean(pooled^2) + eps) * (wadd + w)
|
||||
* out = NeoX rotary of normed's first `rotary_dim` lanes at the block's position, the rest
|
||||
* passed through, rounded once at the store
|
||||
*
|
||||
* The rounding after the mean is the reference model's (`.float().mean(dim=1).to(dtype)`) and is
|
||||
* part of the answer. The block's position is `pos[b]` (a [>= M, 1 or 3] list carries a block's
|
||||
* components side by side, read under `mode` mrope/imrope and `sections`), or `pos0 + b*ratio`
|
||||
* without one. `page[b]`, when given, is the output row, and a negative entry writes nothing. The
|
||||
* rotary is `rope`'s ladder with YaRN's blend and magnitude when the coefficients are given. */
|
||||
int ref_qsa_block_key(const RadArgs* a, RadStream) {
|
||||
const RadTensor* k = t_in(a, 0);
|
||||
const RadTensor* w = t_in(a, 1);
|
||||
const RadTensor* page = t_in(a, 2);
|
||||
const RadTensor* pos = t_in(a, 3);
|
||||
const RadTensor* out = t_in(a, 4);
|
||||
if (!k || !w || !out) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
|
||||
const int64_t rot = p_int(a, "rotary_dim", 0), pos0 = p_int(a, "pos0", -1);
|
||||
if (n <= 0 || n > REF_HD_MAX || ratio <= 0 || (pos0 < 0 && !pos)) return RAD_E_INVAL;
|
||||
if (rot < 0 || rot > n || (rot & 1)) return RAD_E_SHAPE;
|
||||
if (p_int(a, "block_size", ratio) != ratio) return RAD_E_SHAPE;
|
||||
if (k->rank != 2 || out->rank < 2 || out->shape[0] < 1) return RAD_E_SHAPE;
|
||||
const int64_t M = page ? numel(page) : out->shape[0];
|
||||
if (M < 1 || numel(out) / out->shape[0] != n) return RAD_E_SHAPE;
|
||||
if (k->shape[0] != M * ratio || k->shape[1] != n || numel(w) < n) return RAD_E_SHAPE;
|
||||
const bool pos2 = pos && pos->rank == 2;
|
||||
if (pos && (pos2 ? pos->shape[0] < M : numel(pos) < M)) return RAD_E_SHAPE;
|
||||
|
||||
const float eps = p_f32(a, "eps", 1e-6f), wadd = p_f32(a, "wadd", 1.0f);
|
||||
const float theta = p_f32(a, "theta", 10000.0f), rscale = p_f32(a, "scale", 1.0f);
|
||||
static const char* kModes[] = { "neox", "mrope", "imrope" };
|
||||
const int mi = p_enum(a, "mode", kModes, 3, 0);
|
||||
if (mi < 0) return RAD_E_UNSUPPORTED;
|
||||
const int mode = mi == 1 ? ROPE_MROPE : mi == 2 ? ROPE_IMROPE : ROPE_NEOX;
|
||||
int64_t sec[8] = {};
|
||||
const int n_sec = rope_sections(a, sec);
|
||||
if (n_sec < 0 || n_sec > 3) return RAD_E_SHAPE;
|
||||
/* Several components only with a mode, its sections and three columns of `pos`; otherwise
|
||||
* every frequency reads the block's one position, which every mode reads as NeoX. */
|
||||
const bool mc = mode != ROPE_NEOX && n_sec > 0 && pos2 && pos->shape[1] >= 3;
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f)))
|
||||
return RAD_E_INVAL;
|
||||
RopeFreq f;
|
||||
RAD_REF_TRY(rope_freqs(mc ? mode : ROPE_NEOX, rot, theta, sec, mc ? n_sec : 0, &f));
|
||||
for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t b = 0; b < M; ++b) {
|
||||
const int64_t orow = page ? ld_int(page->dtype, page->data, offlin(page, b)) : b;
|
||||
if (orow < 0) continue;
|
||||
float x[REF_HD_MAX], y[REF_HD_MAX];
|
||||
double ss = 0.0;
|
||||
for (int64_t t = 0; t < n; ++t) {
|
||||
float acc = 0.0f;
|
||||
for (int64_t j = 0; j < ratio; ++j) acc += ldt(k, offlin(k, (b * ratio + j) * n + t));
|
||||
uint64_t tmp = 0;
|
||||
st_dt(k->dtype, &tmp, 0, acc / (float)ratio);
|
||||
x[t] = ld_dt(k->dtype, &tmp, 0);
|
||||
ss += (double)x[t] * x[t];
|
||||
}
|
||||
const float inv = 1.0f / std::sqrt((float)(ss / (double)n) + eps);
|
||||
for (int64_t t = 0; t < n; ++t) y[t] = x[t] * inv * (wadd + ldt(w, offlin(w, t)));
|
||||
float p[3] = {};
|
||||
for (int c = 0; c < (mc ? 3 : 1); ++c) {
|
||||
const int64_t bp = !pos ? pos0 + b * ratio
|
||||
: ld_int(pos->dtype, pos->data,
|
||||
offlin(pos, pos2 ? b * pos->shape[1] + c : b));
|
||||
p[c] = (float)bp / (rscale != 0.0f ? rscale : 1.0f);
|
||||
}
|
||||
const int64_t half = rot / 2;
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const float ang = p[f.comp[i]] * f.inv[i];
|
||||
const float c = std::cos(ang) * yarn.magnitude, s = std::sin(ang) * yarn.magnitude;
|
||||
const float x0 = y[i], x1 = y[half + i];
|
||||
y[i] = x0 * c - x1 * s;
|
||||
y[half + i] = x0 * s + x1 * c;
|
||||
}
|
||||
for (int64_t t = 0; t < n; ++t) stt(out, offlin(out, orow * n + t), y[t]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -115,6 +115,7 @@ int ref_kv_store (const RadArgs*, RadStream);
|
||||
int ref_rope (const RadArgs*, RadStream);
|
||||
int ref_rope_table (const RadArgs*, RadStream);
|
||||
int ref_qk_norm_rope (const RadArgs*, RadStream);
|
||||
int ref_qsa_block_key (const RadArgs*, RadStream);
|
||||
|
||||
/* ---- mixture of experts */
|
||||
int ref_router_topk (const RadArgs*, RadStream);
|
||||
@@ -229,6 +230,7 @@ REF_SHAPE_FN(ref_kv_store);
|
||||
REF_SHAPE_FN(ref_rope);
|
||||
REF_SHAPE_FN(ref_rope_table);
|
||||
REF_SHAPE_FN(ref_qk_norm_rope);
|
||||
REF_SHAPE_FN(ref_qsa_block_key);
|
||||
|
||||
REF_SHAPE_FN(ref_router_topk);
|
||||
REF_SHAPE_FN(ref_moe_scatter);
|
||||
|
||||
+27
-2
@@ -278,16 +278,32 @@ 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") };
|
||||
|
||||
/* QSA's compressed key, libr4d's schema exactly (libr4d/r4d_rows.cpp): `block_size` is `ratio`
|
||||
* spelled for the KV group the block-key store is, `page` and `pos` are optional. */
|
||||
static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("ratio"),
|
||||
P_INT("rotary_dim"), P_INTO("pos0"),
|
||||
P_INTO("block_size"), P_F64("eps"), P_F64("theta"),
|
||||
P_F64O("scale"), P_F64O("wadd"), P_STR("dtype"),
|
||||
P_STRO("mode"), P_STRO("sections"),
|
||||
P_F64O("yarn_factor"), P_F64O("yarn_low"),
|
||||
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page"), OPD_O("pos"),
|
||||
OUT("out") };
|
||||
|
||||
static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("n_head_kv"), P_F64("theta"), P_F64("eps"),
|
||||
P_F64O("scale"), P_STRO("mode"), P_INTO("rotary_dim"),
|
||||
@@ -747,6 +763,12 @@ static const RadOpSchema kSchemas[] = {
|
||||
"cos/sin for the positions a step names, at each position's own row of a [max_ctx, rot] plane: "
|
||||
"rot values a row, cos for the first half and sin for the second. The angles are `rope`'s "
|
||||
"exactly. A row no position names is not written; a negative position writes nothing." },
|
||||
{ "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey),
|
||||
"QSA's compressed key, one vector per `ratio` rows of k: the block's mean accumulated in f32 and "
|
||||
"rounded to k's dtype, RMS-normed with gain (wadd + w), then NeoX-rotated over `rotary_dim` at "
|
||||
"the block's position -- `pos[b]` (with `mode` mrope/imrope and `sections`, a [>= M, 3] list's "
|
||||
"three components) or `pos0 + b*ratio` -- with YaRN's blend and magnitude when given. `page[b]`, "
|
||||
"when given, is the output row; a negative entry writes nothing." },
|
||||
{ "rope", ARR(pRope), ARR(oRope),
|
||||
"Rotary embedding in place over the q and k heads of a fused [q|k|v] row; the v heads are left "
|
||||
"alone. `mode` is \"neox\" or \"gptj\", or a multi-component form: \"mrope\" (contiguous "
|
||||
@@ -1080,6 +1102,9 @@ SIMPLE("ref_moe_gemm_q_mod4", "moe_gemm_q_mod4", "moe",
|
||||
SIMPLE("ref_moe_gather", "moe_gather", "moe", "weighted scatter back to token order", DT_FLOAT,
|
||||
ref_moe_gather),
|
||||
SIMPLE("ref_rope_table", "rope_table", "attn", "cos/sin at each position's own row", DT_FLOAT, ref_rope_table),
|
||||
SIMPLE("ref_qsa_block_key", "qsa_block_key", "attn",
|
||||
"QSA compressed key: pooled, normed and rotated at the block's position", DT_FLOAT,
|
||||
ref_qsa_block_key),
|
||||
SIMPLE("ref_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, ref_row_topk),
|
||||
SIMPLE("ref_row_topk_merge", "row_topk_merge", "moe", "the global top-R of the gathered per-rank candidate sets", DT_FLOAT, ref_row_topk_merge),
|
||||
SIMPLE("ref_logit_rerank", "logit_rerank", "moe", "R candidates a row rescored exactly against the full-precision head", DT_FLOAT, ref_logit_rerank),
|
||||
|
||||
@@ -1040,6 +1040,23 @@ int ref_rope_table_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
|
||||
return o.finish("rope_table", operand, out);
|
||||
}
|
||||
|
||||
int ref_qsa_block_key_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
const int64_t n = gi(p, n_p, "n", 0);
|
||||
const int64_t r = gi(p, n_p, "ratio", 0);
|
||||
if (M <= 0 || n <= 0 || r <= 0) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { M * r, n }); /* k -- `ratio` rows a block */
|
||||
o.t((uint32_t)RAD_F32, { n }); /* w -- the norm gain */
|
||||
/* page: absent, so the write is contiguous. A drawn page list may repeat an entry, and two
|
||||
* blocks onto one row is a race whose winner the comparison would then measure. */
|
||||
o.skip();
|
||||
o.t_idx({ M }, M * r, -1, 0); /* pos -- each block's first-token position */
|
||||
o.t(D, { M, n }); /* out */
|
||||
return o.finish("qsa_block_key", operand, out);
|
||||
}
|
||||
|
||||
/* ================================================================== mixture of experts */
|
||||
|
||||
int ref_scale_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
|
||||
@@ -152,6 +152,21 @@ if(RAD_HIP_FOUND AND TARGET r4d_selftest)
|
||||
ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home")
|
||||
endif()
|
||||
|
||||
# ================================================================== the device layer without SVM
|
||||
#
|
||||
# A KERNEL DRIVER WITHOUT THE SVM API PINS HOST MEMORY ANOTHER WAY, and a machine with it never
|
||||
# takes that way. ROCr's thunk maps a locked range in place only through the KFD's SVM API; without
|
||||
# it (a KVM guest whose amdgpu registered no device memory with HMM) the backend allocates a pinned
|
||||
# range whole from the host pool (core/device/aql.cpp, "pinned host memory, in pieces"). HSA_USE_SVM=0
|
||||
# is the thunk's own switch for that driver, so device_test runs a second time under it and the
|
||||
# path is held on every machine with a card. On the host backend both runs are the same run.
|
||||
if(RAD_HIP_FOUND AND TARGET device_test)
|
||||
add_test(NAME device_test_nosvm COMMAND device_test)
|
||||
set_tests_properties(device_test_nosvm PROPERTIES
|
||||
SKIP_RETURN_CODE 77
|
||||
ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home;HSA_USE_SVM=0")
|
||||
endif()
|
||||
|
||||
# ================================================================== the host kernels
|
||||
#
|
||||
# rad-avx-check holds libavx to libref, op for op and at every ISA level the machine executes, and
|
||||
|
||||
@@ -306,6 +306,8 @@ extern "C" void* rad_buf_ptr (RadCtx* c, rad_buf b) { (void)c; return (void
|
||||
#include "../arch/qwen35_bf16/qwen35_bf16.cpp"
|
||||
/* And the production architecture, for its sizing declare (RadBuildCtx::shape_probe). */
|
||||
#include "../arch/qwen4exp_fp8/qwen4exp_fp8.cpp"
|
||||
/* And the LLaMA family, for how it reads its rotary scaling. */
|
||||
#include "../arch/llama_fp8/llama_fp8.cpp"
|
||||
/* The PLE block on its own: no architecture in this file declares it, and what its step() hands
|
||||
* the two windowed ops is a contract of its own (rad_block_ple.h). */
|
||||
#include <arch/rad_block_ple.h>
|
||||
@@ -550,6 +552,86 @@ 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);
|
||||
}
|
||||
|
||||
/* THE LLAMA FAMILY READS ITS ROTARY SCALING THROUGH THE SAME READER. A Llama 3.1 checkpoint says
|
||||
* `rope_type: llama3` with a factor of 8; read as a bare factor that is a linear position divide
|
||||
* by 8 and fluent nonsense, so it is refused by name at declare. Linear stays linear and YaRN
|
||||
* reaches the rope op. */
|
||||
TEST(llama_reads_its_rotary_scaling_by_type) {
|
||||
(void)&llama_fp8::step; /* included for its declare; nothing here runs a step */
|
||||
(void)&llama_fp8::probe;
|
||||
auto declare = [](const char* type, const char* factor, RadBuilder* b) {
|
||||
const char* keys[] = {"rope_scaling.rope_type", "rope_scaling.factor",
|
||||
"rope_scaling.original_max_position_embeddings"};
|
||||
const char* vals[] = {type, factor, "8192"};
|
||||
RadModelMeta m{};
|
||||
m.arch_id = "llama"; m.name = "test-llama"; m.quant = "fp8_e4m3";
|
||||
m.n_layers = 2; m.n_embd = 1024; m.n_head = 8; m.n_head_kv = 2; m.head_dim = 128;
|
||||
m.n_ff = 2048; m.n_vocab = 32000; m.n_ctx_train = 8192;
|
||||
m.rms_eps = 1e-5f; m.rope_theta = 5e5f; m.rope_scale = 1.0f;
|
||||
m.n_kv = type ? 3 : 0; m.kv_key = keys; m.kv_val = vals;
|
||||
RadBuildCtx c = build_ctx();
|
||||
return llama_fp8::declare(b, &m, &c);
|
||||
};
|
||||
for (const char* refused : {"llama3", "longrope", "dynamic"}) {
|
||||
RadBuilder b;
|
||||
CHECK_EQ(declare(refused, "8", &b), RAD_E_UNSUPPORTED);
|
||||
}
|
||||
{
|
||||
RadBuilder b;
|
||||
CHECK_OK(declare("linear", "2", &b));
|
||||
CHECK(count_op(b, "rope") > 0);
|
||||
for (const auto& op : b.ops) if (op.op == "rope") {
|
||||
CHECK_EQ(pflt(&op, "scale"), 2.0);
|
||||
CHECK(!param(&op, "yarn_factor"));
|
||||
}
|
||||
}
|
||||
{
|
||||
RadBuilder b;
|
||||
CHECK_OK(declare("yarn", "4", &b));
|
||||
CHECK(count_op(b, "rope") > 0);
|
||||
for (const auto& op : b.ops) if (op.op == "rope") {
|
||||
CHECK_EQ(pflt(&op, "scale"), 1.0);
|
||||
CHECK_EQ(pflt(&op, "yarn_factor"), 4.0);
|
||||
}
|
||||
}
|
||||
{
|
||||
RadBuilder b;
|
||||
CHECK_OK(declare(nullptr, "", &b));
|
||||
for (const auto& op : b.ops) if (op.op == "rope") {
|
||||
CHECK_EQ(pflt(&op, "scale"), 1.0);
|
||||
CHECK(!param(&op, "yarn_factor"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(the_alternation_puts_full_attention_at_3_and_7) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = qwen35_meta();
|
||||
@@ -1544,6 +1626,35 @@ RadModelMeta qwen4exp_meta() {
|
||||
* 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
|
||||
* 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) {
|
||||
RadModelMeta meta = qwen4exp_meta();
|
||||
RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
|
||||
|
||||
@@ -918,6 +918,77 @@ TEST(the_generated_grammar_accepts_what_the_vendored_one_accepts) {
|
||||
log_set_level(Log::Warn);
|
||||
}
|
||||
|
||||
/* A REQUIRED CALL IS THE WHOLE REPLY: from the generation prompt the sampler feeds it, the
|
||||
* reasoning block and then the calls, with no prose before them and nothing after them -- so a
|
||||
* complete grammar admits only the end of the turn and the reply stops at the last call. A named
|
||||
* function admits that function alone, and `parallel_tool_calls: false` one call. */
|
||||
TEST(a_required_call_grammar_is_the_whole_reply) {
|
||||
log_set_level(Log::Error);
|
||||
static const SimpleVocab vocab = [] {
|
||||
SimpleVocab v;
|
||||
for (int c = 32; c < 127; ++c) v.add(std::string(1, (char)c));
|
||||
v.add("\n");
|
||||
return v;
|
||||
}();
|
||||
int checked = 0;
|
||||
for (const Model& m : models()) {
|
||||
Bench* b = bench(m, ChatRequest{});
|
||||
if (!b || b->prompt().grammar.empty()) continue;
|
||||
const std::string gp = b->prompt().generation_prompt;
|
||||
auto grammar = [&](bool parallel, const std::string& only) {
|
||||
ChatGrammarRequest gq;
|
||||
gq.tools = &agent_tools();
|
||||
gq.generation_prompt = gp;
|
||||
gq.parallel_tool_calls = parallel;
|
||||
gq.require_call = true;
|
||||
gq.only_tool = only;
|
||||
ChatGrammar g;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_grammar(b->format(), gq, &g, &why));
|
||||
CHECK(!g.lazy);
|
||||
CHECK(g.trigger_words.empty());
|
||||
return g.text;
|
||||
};
|
||||
/* 1 complete, 0 admitted but unfinished or refused. The sampler feeds the generation
|
||||
* prompt first (SamplingParams::grammar_prefix), so the reply is read after it. */
|
||||
auto admits = [&](const std::string& gbnf, const std::string& reply) {
|
||||
std::unique_ptr<GbnfGrammar> gr;
|
||||
std::string err;
|
||||
if (GbnfGrammar::create(gbnf, "root", &vocab, false, {}, {}, &gr, &err) < 0) return -1;
|
||||
if (gr->accept_str(gp) < 0 || gr->accept_str(reply) < 0) return 0;
|
||||
return gr->complete() ? 1 : 0;
|
||||
};
|
||||
const std::string any = grammar(true, ""), one = grammar(false, ""),
|
||||
read = grammar(true, "read");
|
||||
const std::string T = "Thinking it over.\n</think>\n\n";
|
||||
const std::string bash = C(m, "bash", { { "command", "ls" } });
|
||||
const std::string rd = C(m, "read", { { "path", "/a" } });
|
||||
|
||||
CHECK_EQ(admits(any, T + bash), 1);
|
||||
CHECK_EQ(admits(any, T + bash + "\n" + rd), 1);
|
||||
CHECK_EQ(admits(any, T + "The answer is 42."), 0);
|
||||
CHECK_EQ(admits(any, T + "Checking.\n" + bash), 0);
|
||||
CHECK_EQ(admits(any, T + bash + "\nDone now."), 0);
|
||||
CHECK_EQ(admits(any, T), 0);
|
||||
CHECK_EQ(admits(one, T + bash), 1);
|
||||
CHECK_EQ(admits(one, T + bash + "\n" + rd), 0);
|
||||
CHECK_EQ(admits(read, T + rd), 1);
|
||||
CHECK_EQ(admits(read, T + bash), 0);
|
||||
|
||||
ChatGrammarRequest gq;
|
||||
gq.tools = &agent_tools();
|
||||
gq.require_call = true;
|
||||
gq.only_tool = "nope";
|
||||
ChatGrammar g;
|
||||
std::string why;
|
||||
CHECK(chat_format_grammar(b->format(), gq, &g, &why) == RAD_E_INVAL);
|
||||
CHECK(why.find("nope") != std::string::npos);
|
||||
++checked;
|
||||
}
|
||||
CHECK(checked > 0);
|
||||
log_set_level(Log::Warn);
|
||||
}
|
||||
|
||||
/* ================================================================== the description */
|
||||
|
||||
TEST(the_derived_formats_are_the_ones_in_service) {
|
||||
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user