radiance 1.2.1

- A checkpoint restore that found its snapshot slot given back stopped the engine (#33): a
  snapshot handed to an admission is now kept until its step has run, a lost one re-prefills
  that request instead, and a failed restore names the check and the rank.
- The headroom warning had no fixed point (#32): it now checks the room left for a kernel's first
  launch and names the --gpu-headroom-mib value that clears it.
- reasoning_effort (#31): the levels the chat template takes are probed at startup and published
  in /server_info; a level outside them is a 400 on `reasoning_effort` with `supported`;
  --reasoning-effort-map rewrites a client's level.
- rad-convert reads published quantised releases (#29): AMD Quark MXFP4 byte for byte, and
  AutoRound (auto_round:auto_gptq) / GPTQ int4 and int8, with Flash-Next checkpoints that ship
  their experts one by one.
- tool_choice "required" and a named function are served by a call grammar for the whole reply.
This commit is contained in:
Deadcode committed 2026-10-07 10:14:00 +02:00
1 parent e95d397288
commit d23c3e0d17
37 files changed
+1595 -147

No files matched your search

+1 -1
View File
@@ -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.2.0 LANGUAGES C CXX)
project(radiance VERSION 1.2.1 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
+25
View File
@@ -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,
+6 -6
View File
@@ -520,8 +520,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
@@ -1205,8 +1205,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 +1367,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);
+30 -1
View File
@@ -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.",
+9 -1
View File
@@ -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
+22
View File
@@ -123,6 +123,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"
@@ -480,6 +484,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))
+28 -4
View File
@@ -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()) {
+46 -26
View File
@@ -757,7 +757,8 @@ int Engine::read_checkpoint_metadata() {
/* ================================================================== 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. */
@@ -3332,18 +3333,29 @@ 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);
* 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 (auto& r : ranks_) {
LogRank lr(r->index);
RadDeviceProps props{};
@@ -3351,29 +3363,37 @@ int Engine::start() {
/* 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
+286 -9
View File
@@ -432,10 +432,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 +736,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 +811,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 +994,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 +1031,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 +1065,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 +1110,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 +1119,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 */
+47 -5
View File
@@ -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);
+46 -10
View File
@@ -1338,6 +1338,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 +1355,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 +1387,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;
+2
View File
@@ -435,6 +435,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
+10 -1
View File
@@ -740,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
@@ -793,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);
@@ -841,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()) {
@@ -969,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;
}
+12 -3
View File
@@ -54,6 +54,7 @@
#include "mem/kv.h"
#include "rad_core.h"
#include <algorithm>
#include <cstdint>
#include <list>
#include <memory>
@@ -325,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. */
@@ -339,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
@@ -435,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_;
+3
View File
@@ -756,6 +756,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;
+6
View File
@@ -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 */
@@ -307,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
+16 -1
View File
@@ -1263,8 +1263,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
+3
View File
@@ -555,6 +555,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);
@@ -597,6 +598,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
View File
@@ -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();
+4
View File
@@ -373,10 +373,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
+76 -24
View File
@@ -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()) {
+32
View File
@@ -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 */
};
@@ -147,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.
@@ -196,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
+46
View File
@@ -69,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;
@@ -196,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;
@@ -203,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,)"
+11
View File
@@ -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
View File
@@ -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;
}
+1
View File
@@ -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
View File
@@ -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
View File
@@ -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 {
@@ -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
+65 -16
View File
@@ -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
@@ -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
@@ -543,16 +570,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.
@@ -874,6 +903,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
@@ -993,6 +1040,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` |
@@ -1235,9 +1283,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` |
@@ -1397,8 +1445,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
@@ -1506,7 +1555,7 @@ 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` |
+71
View File
@@ -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) {
+285
View File
@@ -10,6 +10,7 @@
#include "format/checkpoint.h"
#include "rad_plugin.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -335,3 +336,287 @@ TEST(what_is_not_served_as_it_is_says_why) {
}
RAD_TEST_MAIN()
/* ================================================================== imported quantisations */
namespace {
/* A GPTQ-packed weight as auto_gptq's packer writes it: code (row n, column k) is the signed value
* `q[n][k]`, stored unsigned with zero point 2^(bits-1) as field k % (32/bits) of int32 word
* [k / (32/bits), n]; `qzeros` holds the v1 zero point (less one) in every field; `scales` is
* f16 [K / group, N]. */
struct Gptq {
std::vector<std::vector<int>> q; /* [N][K] signed codes */
std::vector<float> scale; /* [G * N], row g of the scale tensor first */
int64_t N = 0, K = 0, group = 0;
int bits = 4;
};
Gptq make_gptq(int64_t N, int64_t K, int64_t group, int bits, int seed) {
Gptq g;
g.N = N; g.K = K; g.group = group; g.bits = bits;
const int lo = -(1 << (bits - 1)), span = 1 << bits;
g.q.assign((size_t)N, std::vector<int>((size_t)K));
uint32_t x = 2463534242u ^ (uint32_t)seed;
for (auto& row : g.q)
for (int& v : row) {
x ^= x << 13; x ^= x >> 17; x ^= x << 5;
v = lo + (int)(x % (uint32_t)span);
}
/* f16 scales with low mantissa bits set and both signs, so the bf16 rounding and the sign
* are both seen. */
for (int64_t i = 0; i < (K / group) * N; ++i)
g.scale.push_back((i % 3 == 1 ? -1.0f : 1.0f) * (0.0123f + 0.00071f * (float)i));
return g;
}
void add_gptq(std::vector<T>* ts, const std::string& base, const Gptq& g, bool with_gidx = false) {
const int64_t per = 32 / g.bits, G = g.K / g.group;
T qw{ base + ".qweight", "I32", { g.K / per, g.N }, {} };
qw.bytes.assign((size_t)(g.K / per * g.N * 4), 0);
for (int64_t n = 0; n < g.N; ++n)
for (int64_t k = 0; k < g.K; ++k) {
const uint32_t u = (uint32_t)(g.q[(size_t)n][(size_t)k] + (1 << (g.bits - 1)));
uint32_t* w = (uint32_t*)qw.bytes.data() + (k / per) * g.N + n;
*w |= u << ((k % per) * g.bits);
}
T sc{ base + ".scales", "F16", { G, g.N }, {} };
sc.bytes.resize((size_t)(G * g.N * 2));
for (int64_t i = 0; i < G * g.N; ++i) rad_store_f32(sc.bytes.data(), RAD_F16, i, g.scale[(size_t)i]);
T qz{ base + ".qzeros", "I32", { G, g.N * g.bits / 32 }, {} };
qz.bytes.resize((size_t)(G * g.N * g.bits / 32 * 4));
for (size_t i = 0; i < qz.bytes.size() / 4; ++i)
((uint32_t*)qz.bytes.data())[i] = g.bits == 4 ? 0x77777777u : 0x7f7f7f7fu;
ts->push_back(qw);
ts->push_back(sc);
ts->push_back(qz);
if (with_gidx) {
T gi{ base + ".g_idx", "I32", { g.K }, {} };
gi.bytes.resize((size_t)g.K * 4);
for (int64_t k = 0; k < g.K; ++k) ((int32_t*)gi.bytes.data())[k] = (int32_t)(k / g.group);
ts->push_back(gi);
}
}
/* The scale the f16 tensor actually holds. */
float f16_of(float v) {
uint16_t h;
rad_store_f32(&h, RAD_F16, 0, v);
return rad_load_f32(&h, RAD_F16, 0);
}
const char* kAutoRound =
"{\"model_type\":\"qwen4_exp\",\"quantization_config\":{\"quant_method\":\"auto-round\","
"\"packing_format\":\"auto_round:auto_gptq\",\"bits\":4,\"group_size\":128,\"sym\":true}}";
} /* namespace */
/* AUTOROUND'S GPTQ EXPORT IS IMPORTED: gate and up -- each its own GPTQ-packed int4 weight --
* become one `i4*bf16[1x128]` weight whose codes are the shipped ones, signed, row by row, and
* whose scales are the shipped f16 ones rounded to bf16. Read as f32 it is the shipped value:
* the code times the f16 scale. Codeberg #29. */
TEST(an_autoround_int4_weight_is_imported_as_its_codes_and_scales) {
const Gptq gate = make_gptq(8, 256, 128, 4, 1), up = make_gptq(16, 256, 128, 4, 2);
std::vector<T> ts;
add_gptq(&ts, "e.0.gate_proj", gate);
add_gptq(&ts, "e.0.up_proj", up, /*with_gidx=*/true);
const std::string dir = write_checkpoint(ts, kAutoRound);
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
CHECK(ck.imports() == Checkpoint::Import::Gptq);
CHECK_EQ(ck.meta().quant, std::string("auto-round"));
Program prog;
prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "e.0.gate_proj.weight", "e.0.up_proj.weight" }));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK);
CHECK(!w.trivial);
REQUIRE(w.imported);
CHECK_EQ(w.rows, (int64_t)24);
CHECK_EQ(w.cols, (int64_t)256);
REQUIRE_EQ(w.enc.n_planes, 2);
CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_I4);
CHECK_EQ(w.enc.plane[1].dtype, (uint32_t)RAD_BF16);
CHECK_EQ(w.enc.plane[1].block[0], (int64_t)1);
CHECK_EQ(w.enc.plane[1].block[1], (int64_t)128);
CHECK(rad_enc_valid(&w.enc));
/* every row, both pieces: codes, scales and the f32 value */
std::vector<uint8_t> codes((size_t)(24 * 128)), scales((size_t)(24 * 2 * 2));
REQUIRE_EQ(ckpt_plane_rows(w, 0, 0, 24, codes.data(), &why), RAD_OK);
REQUIRE_EQ(ckpt_plane_rows(w, 1, 0, 24, scales.data(), &why), RAD_OK);
std::vector<float> f((size_t)(24 * 256));
REQUIRE_EQ(ckpt_rows_f32(w, 0, 24, f.data(), &why), RAD_OK);
int bad_code = 0, bad_scale = 0, bad_f = 0;
for (int64_t r = 0; r < 24; ++r) {
const Gptq& g = r < 8 ? gate : up;
const int64_t n = r < 8 ? r : r - 8;
for (int64_t k = 0; k < 256; ++k) {
const int q = g.q[(size_t)n][(size_t)k];
if ((int)rad_load_f32(codes.data(), RAD_I4, r * 256 + k) != q) ++bad_code;
const float s = f16_of(g.scale[(size_t)((k / 128) * g.N + n)]);
if (f[(size_t)(r * 256 + k)] != (float)q * s) ++bad_f;
}
for (int64_t c = 0; c < 2; ++c) {
const float s = f16_of(g.scale[(size_t)(c * g.N + n)]);
if (rad_load_f32(scales.data(), RAD_BF16, r * 2 + c) !=
rad_load_f32(std::vector<uint16_t>{ rad_f32_to_bf16(s) }.data(), RAD_BF16, 0))
++bad_scale;
}
}
CHECK_EQ(bad_code, 0);
CHECK_EQ(bad_scale, 0);
CHECK_EQ(bad_f, 0);
/* a part of the plane, from the middle of the second piece */
std::vector<uint8_t> part(128);
REQUIRE_EQ(ckpt_plane_rows(w, 0, 13, 1, part.data(), &why), RAD_OK);
CHECK_EQ(std::memcmp(part.data(), codes.data() + 13 * 128, 128), 0);
remove_checkpoint(dir);
}
/* AN INT8 PER-CHANNEL WEIGHT (one scale a row, g_idx all zero) is `i8*bf16[1x128]` with its row's
* scale in every block. */
TEST(a_gptq_int8_per_channel_weight_repeats_its_scale) {
const Gptq g = make_gptq(4, 384, 384, 8, 3);
std::vector<T> ts;
add_gptq(&ts, "o_proj", g, /*with_gidx=*/true);
const std::string dir = write_checkpoint(ts, kAutoRound);
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
Program prog;
prog.name_map.push_back(map("o", RAD_MAP_COPY, { "o_proj.weight" }));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "o", false, &w, &why), RAD_OK);
REQUIRE(w.imported);
CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_I8);
std::vector<uint8_t> codes(4 * 384), scales(4 * 3 * 2);
REQUIRE_EQ(ckpt_plane_rows(w, 0, 0, 4, codes.data(), &why), RAD_OK);
REQUIRE_EQ(ckpt_plane_rows(w, 1, 0, 4, scales.data(), &why), RAD_OK);
int bad = 0;
for (int64_t n = 0; n < 4; ++n) {
for (int64_t k = 0; k < 384; ++k)
if ((int8_t)codes[(size_t)(n * 384 + k)] != g.q[(size_t)n][(size_t)k]) ++bad;
for (int c = 0; c < 3; ++c)
if (rad_load_f32(scales.data(), RAD_BF16, n * 3 + c) !=
rad_load_f32(scales.data(), RAD_BF16, n * 3))
++bad;
}
CHECK_EQ(bad, 0);
remove_checkpoint(dir);
}
/* WHAT AN IMPORT CANNOT READ IT REFUSES BY NAME: an asymmetric zero point, an act-order group
* index, a group narrower than the served 128, and a packing it does not know. */
TEST(an_import_refuses_what_it_cannot_read) {
auto refused = [](void (*edit)(std::vector<T>*), const char* config, const char* expect) {
Gptq g = make_gptq(8, 256, 128, 4, 4);
std::vector<T> ts;
add_gptq(&ts, "x", g, true);
edit(&ts);
const std::string dir = write_checkpoint(ts, config);
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
Program prog;
prog.name_map.push_back(map("x", RAD_MAP_COPY, { "x.weight" }));
CkptWeight w;
std::string why;
const int rc = ckpt_resolve(ck, prog, "x", false, &w, &why);
CHECK(rc < 0);
CHECK(why.find(expect) != std::string::npos);
remove_checkpoint(dir);
};
refused([](std::vector<T>* ts) { (*ts)[2].bytes[0] = 0x76; }, kAutoRound, "symmetric");
refused([](std::vector<T>* ts) { ((int32_t*)(*ts)[3].bytes.data())[0] = 1; }, kAutoRound,
"act-order");
/* group 64: four scale rows for 256 columns */
{
Gptq g = make_gptq(8, 256, 64, 4, 5);
std::vector<T> ts;
add_gptq(&ts, "x", g);
const std::string dir = write_checkpoint(ts, kAutoRound);
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
Program prog;
prog.name_map.push_back(map("x", RAD_MAP_COPY, { "x.weight" }));
CkptWeight w;
std::string why;
CHECK(ckpt_resolve(ck, prog, "x", false, &w, &why) < 0);
CHECK(why.find("multiple of 128") != std::string::npos);
remove_checkpoint(dir);
}
/* AutoRound's own packing is another layout, and the checkpoint is not imported at all. */
{
const std::string dir = write_checkpoint(
{ bf16("y", { 2, 2 }, 0) },
"{\"model_type\":\"qwen4_exp\",\"quantization_config\":{\"quant_method\":"
"\"auto-round\",\"packing_format\":\"auto_round\"}}");
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
CHECK(ck.imports() == Checkpoint::Import::None);
CHECK(ck.import_refusal().find("auto_round:auto_gptq") != std::string::npos);
remove_checkpoint(dir);
}
}
/* QUARK'S MXFP4 IS `fp4_e2m1*e8m0[1x32]` BYTE FOR BYTE, and so trivial: the U8 codes and U8
* exponents are the planes, gate and up join along rows, and the f32 value is the e2m1 code times
* 2^(e - 127). */
TEST(a_quark_mxfp4_weight_is_its_codes_and_exponents) {
const int64_t K = 64;
auto codes = [&](const std::string& n, int64_t N, int seed) {
T t{ n, "U8", { N, K / 2 }, {} };
for (int64_t i = 0; i < N * K / 2; ++i) t.bytes.push_back((uint8_t)((i * 37 + seed) & 0xff));
return t;
};
auto exps = [&](const std::string& n, int64_t N, int seed) {
T t{ n, "U8", { N, K / 32 }, {} };
for (int64_t i = 0; i < N * K / 32; ++i) t.bytes.push_back((uint8_t)(120 + (i + seed) % 9));
return t;
};
const T g = codes("g.weight", 2, 1), gs = exps("g.weight_scale", 2, 1);
const T u = codes("u.weight", 3, 5), us = exps("u.weight_scale", 3, 4);
const std::string dir = write_checkpoint(
{ g, gs, u, us, bf16("n.weight", { 4 }, 1.0f) },
"{\"model_type\":\"qwen3_5\",\"quantization_config\":{\"quant_method\":\"quark\","
"\"global_quant_config\":{\"weight\":{\"dtype\":\"fp4\",\"qscheme\":\"per_group\","
"\"group_size\":32,\"scale_format\":\"e8m0\"}},\"layer_quant_config\":{}}}");
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
CHECK(ck.imports() == Checkpoint::Import::QuarkMx);
Program prog;
prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "g.weight", "u.weight" }));
prog.name_map.push_back(map("n", RAD_MAP_COPY, { "n.weight" }));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK);
REQUIRE(w.trivial);
CHECK(!w.imported);
CHECK_EQ(w.rows, (int64_t)5);
CHECK_EQ(w.cols, K);
REQUIRE_EQ(w.enc.n_planes, 2);
CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_FP4E2M1);
CHECK_EQ(w.enc.plane[1].dtype, (uint32_t)RAD_E8M0);
CHECK_EQ(w.enc.plane[1].block[1], (int64_t)32);
CHECK(rad_enc_valid(&w.enc));
std::vector<uint8_t> cp(5 * K / 2), sp(5 * K / 32);
REQUIRE_EQ(ckpt_plane_rows(w, 0, 0, 5, cp.data(), &why), RAD_OK);
REQUIRE_EQ(ckpt_plane_rows(w, 1, 0, 5, sp.data(), &why), RAD_OK);
CHECK_EQ(std::memcmp(cp.data(), g.bytes.data(), g.bytes.size()), 0);
CHECK_EQ(std::memcmp(cp.data() + g.bytes.size(), u.bytes.data(), u.bytes.size()), 0);
CHECK_EQ(std::memcmp(sp.data() + gs.bytes.size(), us.bytes.data(), us.bytes.size()), 0);
std::vector<float> f((size_t)K);
REQUIRE_EQ(ckpt_rows_f32(w, 3, 1, f.data(), &why), RAD_OK); /* u's row 1 */
int bad = 0;
for (int64_t k = 0; k < K; ++k) {
const uint8_t b = u.bytes[(size_t)(K / 2 + k / 2)];
const float code = rad_fp4e2m1_to_f32((uint8_t)(k % 2 ? b >> 4 : b & 15));
const float sc = std::ldexp(1.0f, (int)us.bytes[(size_t)(K / 32 + k / 32)] - 127);
if (f[(size_t)k] != code * sc) ++bad;
}
CHECK_EQ(bad, 0);
/* an excluded layer is a plain tensor */
REQUIRE_EQ(ckpt_resolve(ck, prog, "n", false, &w, &why), RAD_OK);
CHECK(w.trivial && rad_enc_is(&w.enc, "plain"));
remove_checkpoint(dir);
}
+80
View File
@@ -1332,6 +1332,86 @@ TEST(checkpoint_retention_is_budgeted_and_keeps_the_tip) {
CHECK(has_512);
}
/* A SNAPSHOT A LOOKUP HANDED OUT THIS STEP KEEPS ITS SLOT until the next step begins. The
* admission it was handed to restores from the slot ahead of the step, and a later admission in
* the same step reserves its own checkpoint -- which, on a full store, runs retention and then
* evicts. Either taking the handed snapshot leaves the restore naming a slot the store gave back,
* and the engine stopped on it ("could not restore ... from checkpoint slot 1: invalid
* argument"). Geometric backoff over {64..512} releases 192, so the hit is made to land there. */
TEST(a_snapshot_handed_out_this_step_survives_retention) {
Fixture f;
CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/8));
const auto a = tok_run(4242, 16 * 33);
publish(f, 1, a, 16 * 32);
BlockHash parent;
std::vector<BlockHash> hs;
for (int b = 0; b < 33; ++b) {
parent = chain_block_hash(parent, a.data() + b * 16, 16, nullptr, 0, b * 16);
hs.push_back(parent);
}
std::vector<int32_t> slot_at(9, -1);
for (int i = 1; i <= 8; ++i) {
CHECK_OK(f.pc.reserve_checkpoint(1, i * 64, hs[i * 4 - 1], &slot_at[(size_t)i]));
f.pc.commit_checkpoint(hs[i * 4 - 1]);
}
CHECK_EQ(f.kv.free_checkpoint_slots(), 0ll);
/* A prompt that leaves the chain after 200 tokens: the deepest snapshot under it is 192. */
f.pc.begin_step();
auto b = a;
b.resize(16 * 20);
for (int i = 200; i < (int)b.size(); ++i) b[(size_t)i] = 900000 + i;
std::vector<std::vector<int32_t>> hit;
const CacheHit h = f.pc.lookup(b, {}, &hit);
REQUIRE_EQ(h.n_linear_tokens, 192);
REQUIRE_EQ(h.checkpoint_slot, slot_at[3]);
/* The same step's next reservation finds the store full. */
BlockHash other = hs[3];
other.lo ^= 0x5eedull;
int32_t s9 = -1;
CHECK_OK(f.pc.reserve_checkpoint(2, 64, other, &s9));
CHECK(s9 >= 0);
CHECK(s9 != h.checkpoint_slot);
CHECK(f.kv.checkpoint_held(h.checkpoint_slot));
bool kept_192 = false;
for (int64_t p : f.pc.checkpoints(1)) if (p == 192) kept_192 = true;
CHECK(kept_192);
}
/* AND THE EVICTION AFTER RETENTION passes it over too. With one slot, the handed snapshot is the
* only thing a reservation could take, so the reservation is refused instead: that chunk goes
* without a checkpoint, and the restore still has its state. */
TEST(a_snapshot_handed_out_this_step_is_not_evicted) {
Fixture f;
CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/1));
const auto a = tok_run(5151, 16 * 9);
publish(f, 1, a, 16 * 8);
BlockHash parent;
std::vector<BlockHash> hs;
for (int b = 0; b < 9; ++b) {
parent = chain_block_hash(parent, a.data() + b * 16, 16, nullptr, 0, b * 16);
hs.push_back(parent);
}
int32_t s1 = -1;
CHECK_OK(f.pc.reserve_checkpoint(1, 64, hs[3], &s1));
f.pc.commit_checkpoint(hs[3]);
f.pc.begin_step();
std::vector<std::vector<int32_t>> hit;
const CacheHit h = f.pc.lookup(a, {}, &hit);
REQUIRE_EQ(h.checkpoint_slot, s1);
int32_t s2 = -1;
CHECK_EQ(f.pc.reserve_checkpoint(1, 128, hs[7], &s2), RAD_E_FULL);
CHECK(f.kv.checkpoint_held(s1));
CHECK_EQ(f.pc.stats().ckpt_evictions, 0ll);
f.pc.begin_step();
CHECK_OK(f.pc.reserve_checkpoint(1, 128, hs[7], &s2));
}
TEST(a_dead_sessions_tip_is_evictable_so_the_slot_pool_cannot_wedge) {
/* One checkpoint each from more DISTINCT sessions than there are slots. Every one of them is
* its session's tip, so a rule that made a tip unevictable would wedge the pool here: the
+34
View File
@@ -280,6 +280,11 @@ struct FakeKV : IKVManager {
it->second.dirty[(size_t)g] = INT64_MAX;
return d;
}
/* Snapshot slots the store has given back; every other slot is held. */
std::vector<int32_t> ck_gone;
bool checkpoint_held(int32_t slot) const override {
return std::find(ck_gone.begin(), ck_gone.end(), slot) == ck_gone.end();
}
/* Blocks an elastic pool has handed back to the card: still carved and free, but not
* available to hand out until the pool grows again. free_blocks() is bounded by that and
* held_blocks() is not, which is the difference an elastic pool presents. */
@@ -876,6 +881,35 @@ TEST(a_hit_with_no_checkpoint_slot_reuses_nothing) {
CHECK_EQ(f.sch.metrics().linear_cached_tokens, 0);
}
/* A RESTORE FROM A SLOT THE STORE GAVE BACK IS NEVER BUILT. The cache keeps a handed-out snapshot
* until the step that restores it has run, so this is a guard: a step that finds one is abandoned,
* the request gives its hit back and goes to the queue, and the next step prefills it from a fresh
* lookup rather than the engine stopping on the restore. */
TEST(a_restore_from_a_slot_the_store_gave_back_is_prefilled_again) {
Fixture f;
f.build();
CHECK_OK(f.start());
f.pc.seed(304);
f.pc.lin = 256;
f.pc.src = 3;
f.kv.ck_gone = {3};
const int64_t free_before = f.kv.free_blocks(0);
const uint64_t a = f.submit(1000, 8);
CHECK(f.sch.step() == nullptr);
CHECK_EQ(f.sch.find(a)->n_computed, 0);
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Waiting);
CHECK_EQ(f.kv.free_blocks(0), free_before); /* the adopted blocks went back */
/* The next lookup finds no snapshot, and the request runs from zero. */
f.pc.src = -1;
f.kv.ck_gone.clear();
const RadBatch* b = f.sch.step();
REQUIRE(b != nullptr);
CHECK_EQ(b->ctx_lens[0], 0);
CHECK_EQ(f.sch.plan().e[0].ckpt_restore, -1);
}
TEST(a_hit_that_no_checkpoint_covers_replays_from_zero) {
Fixture f;
f.build();
+153 -17
View File
@@ -103,6 +103,14 @@ struct FakeChatTemplate : IChatTemplate {
if (why) *why = "the template does not take " + refuse_kwarg;
return RAD_E_UNSUPPORTED;
}
/* And one with a set of its own, as Qwen3.8's xhigh|medium|low. */
if (!efforts.empty() && opt.template_kwargs.count("reasoning_effort")) {
const std::string& v = opt.template_kwargs.at("reasoning_effort");
if (std::find(efforts.begin(), efforts.end(), v) == efforts.end()) {
if (why) *why = "Jinja Exception: Unexpected reasoning effort " + v;
return RAD_E_UNSUPPORTED;
}
}
std::string s;
if (!tools.empty()) s += "[tools:" + std::to_string(tools.size()) + "]";
if (!opt.enable_thinking) s += "[nothink]";
@@ -143,6 +151,7 @@ struct FakeChatTemplate : IChatTemplate {
std::shared_ptr<IReplyParser> real_parser;
std::string refusal;
std::string refuse_kwarg;
std::vector<std::string> efforts; /* JSON text, as the template context carries them */
/* The reasoning block a render reports. FakeTokenizer makes a one-byte marker one token. */
std::string think_open, think_close;
bool think_starts_open = false;
@@ -845,23 +854,6 @@ TEST(unsupported_parameters_are_400_and_name_themselves) {
CHECK_EQ(r3.status, 400);
CHECK(r3.body.find("temperature") != std::string::npos);
/* A forced tool choice is refused rather than approximated: the template's forced-call
* grammar does not terminate, so honouring it would mean a reply that runs to max_tokens. */
HttpResponse r4 = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],
"tools":[{"type":"function","function":{"name":"f"}}],
"tool_choice":"required"})");
CHECK_EQ(r4.status, 400);
CHECK(r4.body.find("tool_choice") != std::string::npos);
/* ...and the object form is the same refusal, not a different one. */
HttpResponse r4b = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],
"tools":[{"type":"function","function":{"name":"f"}}],
"tool_choice":{"type":"function","function":{"name":"f"}}})");
CHECK_EQ(r4b.status, 400);
CHECK(r4b.body.find("tool_choice") != std::string::npos);
/* logprobs without sampler support is refused rather than answered with nulls. */
HttpResponse r5 = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],
@@ -1275,6 +1267,109 @@ TEST(a_template_default_the_template_refuses_is_found_before_a_caller_sends_one)
CHECK(kw_why.empty() && eff_why.empty());
}
/* AN EFFORT THE TEMPLATE REFUSES IS NAMED AS ONE. The template's own set is probed at startup, a
* request outside it is answered as OpenAI answers an unsupported value -- `reasoning_effort`,
* `unsupported_value`, the set in `supported` -- and /server_info publishes the set beforehand.
* Codeberg #31: the 400 blamed `messages` and carried the set only inside a Jinja traceback. */
TEST(an_effort_the_template_refuses_is_answered_with_the_set_it_takes) {
Fixture f;
f.tmpl.efforts = { "\"xhigh\"", "\"medium\"", "\"low\"" };
const std::vector<std::string> set = f.srv->probe_reasoning_efforts();
REQUIRE_EQ(set.size(), 3u);
CHECK_EQ(set[0], std::string("low"));
CHECK_EQ(set[1], std::string("medium"));
CHECK_EQ(set[2], std::string("xhigh"));
OaiLimits lim = f.limits();
lim.reasoning_efforts = set;
for (const char* extra : { R"("reasoning_effort":"high")",
R"("chat_template_kwargs":{"reasoning_effort":"high"})" }) {
OaiRequest r;
ApiError e;
const std::string body =
std::string(R"({"messages":[{"role":"user","content":"hi"}],)") + extra + "}";
CHECK(parse_chat_request(body, f.odeps(), lim, &r, &e) < 0);
CHECK_EQ(e.status, 400);
CHECK_EQ(e.param, std::string("reasoning_effort"));
CHECK_EQ(e.code, std::string("unsupported_value"));
CHECK(!has(e.message, "Jinja"));
CHECK(has(e.message, "'xhigh'"));
const json env = json::parse(e.dump());
REQUIRE(env["error"]["supported"].is_array());
CHECK_EQ(env["error"]["supported"].size(), 5u);
CHECK_EQ(env["error"]["supported"][0].get<std::string>(), std::string("none"));
CHECK_EQ(env["error"]["supported"][4].get<std::string>(), std::string("xhigh"));
}
chat_with(f, lim, R"("reasoning_effort":"xhigh")");
chat_with(f, lim, R"("reasoning_effort":"none")");
const json j = json::parse(f.srv->router().call("GET", "/server_info").body);
const json& caps = j["capabilities"]["reasoning_efforts"];
REQUIRE(caps.is_array());
CHECK_EQ(caps.size(), 5u);
CHECK_EQ(caps[2].get<std::string>(), std::string("low"));
}
/* A TEMPLATE THAT TAKES ANY WORD has no set to publish or to refuse with, and a template that
* refuses for another reason keeps blaming `messages` with its own sentence. */
TEST(a_template_that_takes_any_effort_publishes_no_set) {
Fixture f;
CHECK(f.srv->probe_reasoning_efforts().empty());
const json j = json::parse(f.srv->router().call("GET", "/server_info").body);
CHECK(j["capabilities"]["reasoning_efforts"].is_null());
f.tmpl.refuse_kwarg = "custom";
OaiLimits lim = f.limits();
lim.reasoning_efforts = { "low" };
OaiRequest r;
ApiError e;
CHECK(parse_chat_request(R"({"messages":[{"role":"user","content":"hi"}],
"reasoning_effort":"low","chat_template_kwargs":{"custom":1}})",
f.odeps(), lim, &r, &e) < 0);
CHECK_EQ(e.param, std::string("messages"));
CHECK(has(e.message, "does not take custom"));
}
/* --reasoning-effort-map: the deployment's word replaces the request's before the template sees
* it, in either spelling; a word mapped to "none" turns thinking off; a target the template
* refuses is found at startup. */
TEST(a_mapped_effort_reaches_the_template_as_the_deployments_word) {
Fixture f;
f.tmpl.efforts = { "\"xhigh\"", "\"medium\"", "\"low\"" };
OaiLimits lim = f.limits();
lim.reasoning_effort_map = { { "high", "xhigh" }, { "minimal", "low" }, { "max", "none" } };
chat_with(f, lim, R"("reasoning_effort":"high")");
CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"), std::string("\"xhigh\""));
chat_with(f, lim, R"("chat_template_kwargs":{"reasoning_effort":"high"})");
CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"), std::string("\"xhigh\""));
chat_with(f, lim, R"("reasoning_effort":"medium")");
CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"), std::string("\"medium\""));
chat_with(f, lim, R"("reasoning_effort":"max")");
CHECK(!f.tmpl.last_opt.enable_thinking);
CHECK(!f.tmpl.last_opt.template_kwargs.count("reasoning_effort"));
/* The map is read before "none" and "minimal" are, so it can name either. */
chat_with(f, lim, R"("reasoning_effort":"minimal")");
CHECK(f.tmpl.last_opt.enable_thinking);
CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"), std::string("\"low\""));
auto check = [&](const std::map<std::string, std::string>& m) {
FakeScheduler sched;
FakeTokenizer tok;
Deps d;
d.sched = &sched;
d.tok = &tok;
d.chat = &f.tmpl;
ServerOptions o;
o.reasoning_effort_map = m;
Server srv(d, o);
const json j = json::parse(srv.router().call("GET", "/server_info").body);
CHECK_EQ(j["request_defaults"]["reasoning_effort_map"].size(), m.size());
return srv.check_reasoning_effort_map();
};
CHECK(check({ { "high", "xhigh" }, { "max", "none" } }).empty());
CHECK(has(check({ { "high", "ultra" } }), "high=ultra"));
}
TEST(server_info_reports_what_a_request_that_leaves_a_field_out_gets) {
FakeScheduler sched;
FakeTokenizer tok;
@@ -1358,6 +1453,47 @@ TEST(parallel_tool_calls_false_reaches_the_template) {
CHECK_EQ(f.tmpl.last_n_tools, 1);
}
/* A forced choice reaches the template as "required", with the function it names; the grammar
* that holds the reply to it is built from that (chatparse_test). */
TEST(a_forced_tool_choice_reaches_the_template) {
Fixture f;
f.sched.reply = "TOOL:a:{}";
HttpResponse r = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"max_tokens":128,
"tools":[{"type":"function","function":{"name":"a"}}],
"tool_choice":"required"})");
CHECK_EQ(r.status, 200);
CHECK_EQ(f.tmpl.last_opt.tool_choice, std::string("required"));
CHECK(f.tmpl.last_opt.tool_name.empty());
HttpResponse r2 = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"max_tokens":128,
"tools":[{"type":"function","function":{"name":"a"}},
{"type":"function","function":{"name":"b"}}],
"tool_choice":{"type":"function","function":{"name":"b"}}})");
CHECK_EQ(r2.status, 200);
CHECK_EQ(f.tmpl.last_opt.tool_choice, std::string("required"));
CHECK_EQ(f.tmpl.last_opt.tool_name, std::string("b"));
CHECK_EQ(f.tmpl.last_n_tools, 2);
}
/* What cannot be forced is a 400 naming tool_choice: a call with no tools, a function the request
* does not offer, and a call that would have to share the whole reply with a document. */
TEST(a_forced_tool_choice_that_cannot_be_kept_is_refused) {
Fixture f;
auto refused = [&](const std::string& body) {
HttpResponse r = f.post("/v1/chat/completions", body);
return r.status == 400 && r.body.find("tool_choice") != std::string::npos;
};
CHECK(refused(R"({"messages":[{"role":"user","content":"hi"}],"tool_choice":"required"})"));
CHECK(refused(R"({"messages":[{"role":"user","content":"hi"}],
"tools":[{"type":"function","function":{"name":"a"}}],
"tool_choice":{"type":"function","function":{"name":"zz"}}})"));
CHECK(refused(R"({"messages":[{"role":"user","content":"hi"}],
"tools":[{"type":"function","function":{"name":"a"}}],
"tool_choice":"required","response_format":{"type":"json_object"}})"));
}
/* A grammar the compiler cannot run is a 400 at admission, not a request that dies mid-stream. */
TEST(a_grammar_that_cannot_be_run_is_refused_at_the_door) {
Fixture f;
+21 -7
View File
@@ -462,12 +462,22 @@ int main(int argc, char** argv) {
/* ---------------------------------------------------------------- plugins */
LoadedPlugins plugins;
if (rad_tools_load_plugins(home, hierarchy, meta.arch, meta.quant, &plugins) < 0) {
const bool imported = ck.imports() != Checkpoint::Import::None;
if (!ck.import_refusal().empty())
RAD_ERR("quantisation '%s' cannot be imported: %s", meta.quant.c_str(),
ck.import_refusal().c_str());
if (rad_tools_load_plugins(home, hierarchy, meta.arch, meta.quant, &plugins, imported) < 0) {
RAD_ERR("rad-convert runs the architecture plugin's declare: its name map says which "
"checkpoint tensors make each weight, and the kernels it resolves are what the "
"recipe is checked against");
return 1;
}
/* AN IMPORTED QUANTISATION IS RECORDED AS THE DESCRIPTOR OF THE PLUGIN THAT SERVES IT: every
* weight states its own encoding in the container, and the engine selects by exact match. */
if (imported) {
meta.quant = plugins.arch_quant;
meta.finish();
}
Registry& reg = rad_tools_registry();
std::deque<Compiled> compiled;
std::map<const RecipeRule*, const Compiled*> by_rule;
@@ -530,7 +540,7 @@ int main(int argc, char** argv) {
const RadQuantWeight qw = quant_weight(L, nullptr);
const int st = L.rule->q->encoding(L.rule->params.data(), (int)L.rule->params.size(),
&qw, &L.enc);
if (st == RAD_E_UNSUPPORTED && L.src.trivial) {
if (st == RAD_E_UNSUPPORTED && (L.src.trivial || L.src.imported)) {
/* declined -- a norm under a pattern meant for matrices -- and kept as it is */
L.rule = nullptr;
L.enc = L.src.enc;
@@ -541,7 +551,7 @@ int main(int argc, char** argv) {
L.status = RAD_E_FORMAT;
L.why = r->quantizer + " answered with a malformed encoding";
}
} else if (!L.src.trivial) {
} else if (!L.src.trivial && !L.src.imported) {
L.status = RAD_E_UNSUPPORTED;
L.why = "no recipe rule matches it, and its checkpoint form is not one the engine "
"serves as it is: " + L.src.why;
@@ -666,10 +676,12 @@ int main(int argc, char** argv) {
std::sort(plan.begin(), plan.end(), plan_less);
{
int64_t n_q = 0, n_kept = 0;
for (const Logical* L : plan) (L->rule ? n_q : n_kept)++;
int64_t n_q = 0, n_kept = 0, n_imp = 0;
for (const Logical* L : plan) (L->rule ? n_q : L->src.imported ? n_imp : n_kept)++;
RAD_INFO("plan %zu weight(s): %lld quantised by the recipe, %lld kept as the "
"checkpoint holds them", plan.size(), (long long)n_q, (long long)n_kept);
"checkpoint holds them%s", plan.size(), (long long)n_q, (long long)n_kept,
n_imp ? fmt(", %lld imported from its packed codes", (long long)n_imp).c_str()
: "");
for (const auto& c : compiled) {
int64_t n = 0;
for (const Logical* L : plan) if (L->rule == &c) ++n;
@@ -976,7 +988,9 @@ int main(int argc, char** argv) {
for (int k = 0; k < L.enc.n_planes; ++k) {
const std::vector<const SrcTensor*>& src = k == 0 ? L.src.pieces : L.src.scales;
const int64_t pb = w.plane_bytes(idx, k);
if (L.src.concat_dim == 0 || src.size() == 1) {
/* An imported weight is re-laid row by row (ckpt_plane_rows); its bytes are not
* the plane's. */
if (!L.src.imported && (L.src.concat_dim == 0 || src.size() == 1)) {
int64_t off = 0;
for (const SrcTensor* s : src) {
if (w.write_plane(idx, k, off, s->data, s->bytes) != RAD_OK)