From 64adee3ecea74c2907def844d2dac6699341766f Mon Sep 17 00:00:00 2001 From: C_Tamas Date: Tue, 20 Oct 2026 14:39:19 +0700 Subject: [PATCH] core: a control vector loaded from a controlvector GGUF, discovered per model family A control vector is one unit direction per layer, applied to the residual stream while the model runs (llama.cpp's --cvec-mode project). This is the loader and its ABI, with no configuration surface: a vector is a property of the model family, so the engine looks for one beside the container, in its directory or in $RADIANCE_HOME/vectors, and uses it when it fits the container. The operation's parameters (layer range, scale, mode) come from the package's own JSON. Validation is against the container, never the file's provenance: architecture hint, direction width against n_embd, every layer in the range present, F32 rows. A discovered file that does not fit is reported and skipped; the switch stays off until a request asks for it. The ABI grows by one trailing, zero-defaulted field (RadBuildCtx::cvec), so an architecture plugin that ignores it is unchanged, and the cache gains a salt (0 without a vector) that keeps blocks and linear-state snapshots of one mode from being reused by the other. --- abi/rad_builder.h | 40 +++++ core/cvec.cpp | 313 +++++++++++++++++++++++++++++++++++++++ core/cvec.h | 100 +++++++++++++ core/engine.cpp | 49 +++++- core/engine.h | 33 +++++ core/engine_bringup.cpp | 63 ++++++++ core/rad_core.h | 8 + tests/abi_layout_rows.h | 6 + tests/abi_layout_table.h | 8 +- tests/cvec_test.cpp | 241 ++++++++++++++++++++++++++++++ 10 files changed, 859 insertions(+), 2 deletions(-) create mode 100644 core/cvec.cpp create mode 100644 core/cvec.h create mode 100644 tests/cvec_test.cpp diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 3e33597d..c439ee0e 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -173,8 +173,48 @@ typedef struct RadBuildCtx { * * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ int kv_quant; + + /* A control vector loaded from a GGUF `controlvector` file (--speed-projection), or null. + * + * The engine loads and validates it once, at bringup, and the plugin only reads it: the + * direction table lives in device memory on every rank, in the activations' own float form, + * and a per-request switch reaches the step through a derived buffer the plugin declares + * itself (a row mask, `projection_on_rows`). Nothing is reloaded to turn the feature on or + * off, and with the mask zero the model computes what it computes without a vector. + * + * The plugin decides where in its own graph the projection applies; for the gated-residual + * architectures that is after each block's write into the wide stream, which is the point + * llama.cpp's control-vector hook uses for `qwen4exp`. A plugin that does not declare an op + * reading this table ignores it. + * + * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ + const struct RadControlVector* cvec; } RadBuildCtx; +/* ================================================================== control vectors */ +/* A direction per layer, in the shape llama.cpp's `--cvec-mode project` applies it: + * + * h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l| (times the user scale) + * + * with `v_l` unit and `s_l` the norm the file stored (so a unit vector's scale is 1). The engine + * normalises the rows when it uploads them, so a kernel reads `dir` as the unit direction and + * takes `s` from `scales`; a zero scale means "this layer is not steered". + * + * `dir` is [n_layers, n_embd] f32, row `l` that layer's direction, row 0 unused (layer 0 has no + * direction in the format). Each rank has its own copy: the pointer a plugin receives is that + * rank's, and the residual stream is replicated, so no collective is involved. + * + * `n_layers` is the model's layer count, which may be longer than the file's (the published + * Flash-Next vector carries 47 of 48 rows). The steered range is not a separate field: a layer is + * steered exactly when its `scales` entry is nonzero, so a plugin asks that and cannot disagree + * with the loader. */ +typedef struct RadControlVector { + const float* dir; /* device, [n_layers, n_embd] f32, unit rows */ + const float* scales; /* host, [n_layers] f32, |d_l| * user scale; 0 = not steered */ + int64_t n_embd; + int64_t n_layers; +} RadControlVector; + /* ================================================================== weights */ /* Access class, declared per weight because only the architecture plugin knows it. It tells the * placement planner whether prefetch can be exact (spec ยง5.2). */ diff --git a/core/cvec.cpp b/core/cvec.cpp new file mode 100644 index 00000000..4a59059c --- /dev/null +++ b/core/cvec.cpp @@ -0,0 +1,313 @@ +/* cvec.cpp -- loading and validating a GGUF control vector (core/cvec.h). + * + * The format is llama.cpp's `controlvector` package: one `direction.` tensor of unit f32 per + * layer, plus three metadata keys. The reader is core/text/gguf.cpp, which already mmaps a GGUF + * and computes tensor byte sizes, so nothing here parses bytes by hand. + * + * The published package (hf.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection) is what the checks + * below are written against, and its own JSON states the operation's parameters: + * + * {"mode": "project", "dir": "per-layer", "scale": 1.0, "layer_range": [4, 44], ...} + * + * so a file is only accepted for a model whose hidden size equals the directions' width and whose + * architecture the file names. Everything else is refused at startup, by name, rather than + * steered along a direction from another residual basis. + */ +#include "cvec.h" + +#include "text/gguf.h" + +#include +#include +#include +#include + +#include + +namespace rad { +namespace { + +/* FNV-1a over the table, so two different vectors never share a cache partition. */ +uint64_t hash_table(const ControlVector& cv) { + uint64_t h = 1469598103934665603ull; + const auto mix = [&h](const void* p, size_t n) { + const uint8_t* b = (const uint8_t*) p; + for (size_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; } + }; + mix(cv.dir.data(), cv.dir.size() * sizeof(float)); + mix(cv.scales.data(), cv.scales.size() * sizeof(float)); + return h ? h : 1ull; +} + +} /* namespace */ + +std::string control_vector_sidecar_path(const std::string& model_path) { + const size_t slash = model_path.find_last_of("/\\"); + const size_t dot = model_path.find_last_of('.'); + const bool has_ext = dot != std::string::npos && (slash == std::string::npos || dot > slash); + return (has_ext ? model_path.substr(0, dot) : model_path) + ".control-vector.gguf"; +} + +namespace { + +bool file_present(const std::string& p) { + std::ifstream f(p, std::ios::binary); + if (!f) return false; + f.seekg(0, std::ios::end); + return f.tellg() > 0; +} + +} /* namespace */ + +int control_vector_discover(const std::string& model_path, const std::string& arch, + const std::string& radiance_home, std::string* found, + std::string* tried) { + if (!found) return RAD_E_INVAL; + found->clear(); + if (tried) tried->clear(); + + std::vector cand; + const size_t slash = model_path.find_last_of("/\\"); + const std::string dir = slash == std::string::npos ? std::string(".") : model_path.substr(0, slash); + if (!model_path.empty()) { + cand.push_back(control_vector_sidecar_path(model_path)); + /* One file for a directory of containers: each quant of the family shares the directions, + * since the file names the architecture and its width, not the quantisation. */ + cand.push_back(dir + "/control-vector.gguf"); + } + if (!arch.empty() && !radiance_home.empty()) { + size_t at = 0; + while (at <= radiance_home.size()) { + const size_t colon = radiance_home.find(':', at); + const std::string home = radiance_home.substr( + at, colon == std::string::npos ? std::string::npos : colon - at); + if (!home.empty()) + cand.push_back(home + "/vectors/" + arch + "-control-vector.gguf"); + if (colon == std::string::npos) break; + at = colon + 1; + } + } + + for (const std::string& p : cand) { + if (tried) { + if (!tried->empty()) *tried += ", "; + *tried += p; + } + if (file_present(p)) { *found = p; return RAD_OK; } + } + return RAD_OK; +} + + +/* The package's own JSON, if it is beside the vector: `{"mode": "project", "scale": 1.0, + * "layer_range": [4, 44]}` is what the published Flash-Next vector ships. It is the only place + * the operation's parameters are stated, so they are read from there rather than configured; a + * malformed or absent file only means the defaults below. */ +namespace { + +struct PackageJson { + int first = 0, last = -1; /* -1: not stated */ + float scale = 1.0f; +}; + +PackageJson read_package_json(const std::string& gguf_path) { + PackageJson out; + std::string stem = gguf_path; + const size_t dot = stem.find_last_of('.'); + const size_t slash = stem.find_last_of("/\\"); + if (dot != std::string::npos && (slash == std::string::npos || dot > slash)) + stem = stem.substr(0, dot); + const std::string path = stem + ".json"; + std::ifstream f(path); + if (!f) return out; + try { + const nlohmann::json j = nlohmann::json::parse(f); + if (const auto m = j.find("mode"); m != j.end() && m->is_string() && + m->get() != "project") { + RAD_WARN("control vector: %s says mode '%s'; only 'project' is implemented, so the " + "defaults apply", path.c_str(), m->get().c_str()); + return out; + } + if (const auto r = j.find("layer_range"); r != j.end() && r->is_array() && r->size() == 2 && + (*r)[0].is_number_integer() && + (*r)[1].is_number_integer()) { + out.first = (*r)[0].get(); + out.last = (*r)[1].get(); + } + if (const auto s = j.find("scale"); s != j.end() && s->is_number()) + out.scale = (float) s->get(); + } catch (const std::exception& e) { + RAD_WARN("control vector: %s is not readable JSON (%s); the defaults apply", path.c_str(), + e.what()); + } + return out; +} + +} /* namespace */ + +int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd, + int64_t n_model_layers, ControlVector* out, std::string* err) { + const auto fail = [err](const std::string& why) { + if (err) *err = why; + return RAD_E_INVAL; + }; + if (!out) return RAD_E_INVAL; + *out = ControlVector{}; + + GgufFile f; + const int rc = f.open(path.c_str()); + if (rc != RAD_OK) + return fail("control vector " + path + ": cannot read it as a GGUF container"); + + std::string a; + if (!f.get_str("general.architecture", &a) || a != "controlvector") + return fail("control vector " + path + ": general.architecture is '" + a + + "', not 'controlvector' -- this is not a control vector"); + + /* The hint is optional in llama.cpp's generator, but when a file states one it must be this + * model's architecture: a direction is a basis vector inferred from that architecture's + * residual stream, and nothing else. */ + std::string hint; + if (f.get_str("controlvector.model_hint", &hint) && !hint.empty() && !arch.empty() && + hint != arch) + return fail("control vector " + path + ": the vector is for architecture '" + hint + + "', this container is '" + arch + "' -- a direction from another model's " + "residual basis would move hidden states along a meaningless axis"); + + /* The file's directions: direction., one dimensional, F32, n_embd wide. Anything else is + * refused rather than skipped, because a quietly missing layer is a differently steered model. */ + int64_t n_dir = 0, dir_first = -1, dir_last = -1; + for (const GgufTensor& t : f.tensors()) { + if (t.name.rfind("direction.", 0) != 0) + return fail("control vector " + path + ": tensor '" + t.name + + "' is not a direction. entry"); + int64_t layer = 0; + try { + layer = std::stoll(t.name.substr(10)); + } catch (...) { + return fail("control vector " + path + ": tensor name '" + t.name + + "' does not end in a layer number"); + } + if (layer < 1 || layer > n_model_layers) + return fail("control vector " + path + ": direction." + std::to_string(layer) + + " is outside this model's " + std::to_string(n_model_layers) + " layers"); + if (t.n_dims != 1 || t.ne[0] != n_embd) + return fail("control vector " + path + ": " + t.name + " is shape [" + + std::to_string(t.ne[0]) + "] with rank " + std::to_string(t.n_dims) + + "; this model's residual streams are " + std::to_string(n_embd) + + " wide and a direction is one row of that"); + if (gguf_to_rad_dtype(t.ggml_type) != RAD_F32) + return fail("control vector " + path + ": " + t.name + + " is not F32 -- only an f32 direction is read"); + if (dir_first < 0 || layer < dir_first) dir_first = layer; + if (layer > dir_last) dir_last = layer; + ++n_dir; + } + if (n_dir == 0) return fail("control vector " + path + ": the file holds no directions"); + + /* The package's parameters: its JSON, else the published selection where the file covers it, + * else every direction the file carries. A deployment therefore has nothing to configure, and + * a file published with a different selection states it itself. */ + const PackageJson pj = read_package_json(path); + int first = pj.first, last = pj.last; + float scale = pj.scale; + if (last < 0) { + if (n_model_layers >= 45 && dir_last >= 44) { first = 4; last = 44; } + else { first = (int) dir_first; last = (int) dir_last; } + } + if (first < 1 || last < first) + return fail("control vector " + path + ": the layer range " + std::to_string(first) + ":" + + std::to_string(last) + " is empty"); + if (last > n_model_layers) + return fail("control vector " + path + ": the layer range " + std::to_string(first) + ":" + + std::to_string(last) + " runs past this model's " + + std::to_string(n_model_layers) + " layers"); + if (!(scale > 0.0f) || !std::isfinite(scale)) + return fail("control vector " + path + ": its scale is not a positive number"); + + out->n_embd = n_embd; + /* Indexed by layer: rows 0..n_layers-1. Row 0 stays zero, the format carrying no direction + * for layer 0, and every row a model can name exists. */ + out->n_layers = n_model_layers; + out->first = first; + out->last = last; + out->user_scale = scale; + out->path = path; + out->dir.assign((size_t) (out->n_layers * n_embd), 0.0f); + out->scales.assign((size_t) out->n_layers, 0.0f); + + double worst = 0.0; + for (int64_t l = 1; l <= n_model_layers; ++l) { + const GgufTensor* t = f.tensor("direction." + std::to_string(l)); + if (!t) continue; + const float* d = (const float*) f.tensor_data(*t); + if (!d) return fail("control vector " + path + ": " + t->name + " lies outside the file"); + + double nn = 0.0; + for (int64_t i = 0; i < n_embd; ++i) nn += (double) d[i] * (double) d[i]; + const double norm = std::sqrt(nn); + if (!(norm > 0.0) || !std::isfinite(norm)) + return fail("control vector " + path + ": " + t->name + " has no direction"); + + float* dst = &out->dir[(size_t) (l * n_embd)]; + const float inv = (float) (1.0 / norm); + for (int64_t i = 0; i < n_embd; ++i) dst[i] = d[i] * inv; + out->scales[(size_t) l] = (float) norm * scale; + + /* A layer inside the range with no direction would silently be unsteered. */ + if (l >= first && l <= last) worst = std::max(worst, std::fabs(norm - 1.0)); + } + for (int64_t l = first; l <= last; ++l) + if (out->scales[(size_t) l] == 0.0f) + return fail("control vector " + path + ": the range " + std::to_string(first) + ":" + + std::to_string(last) + " includes layer " + std::to_string(l) + + ", which has no direction in the file"); + + if (worst > 1e-2) + RAD_WARN("control vector: %s: the directions are not unit-normalised (worst |norm - 1| " + "= %.4f); each is divided by its own norm, so the operation is unchanged", + path.c_str(), worst); + return RAD_OK; +} + +RadControlVector control_vector_view(const ControlVector& cv, const float* dir_device) { + RadControlVector v{}; + v.dir = dir_device; + v.scales = cv.scales.data(); + v.n_embd = cv.n_embd; + v.n_layers = cv.n_layers; + return v; +} + +const float* control_vector_upload(const ControlVector& cv, int rank) { + if (!cv.loaded()) return nullptr; + const int64_t bytes = (int64_t) cv.dir.size() * 4; + void* d = rad_dev_alloc(bytes, RAD_MEM_DEVICE); + if (!d) { + RAD_ERR("speed projection: rank %d: could not allocate %.2f MiB on the card for the " + "directions", rank, (double) bytes / (1024.0 * 1024.0)); + return nullptr; + } + RadStream s = nullptr; + if (rad_stream_create(&s, 0) < 0) { + rad_dev_free(d, RAD_MEM_DEVICE); + return nullptr; + } + const int rc = rad_memcpy_async(d, cv.dir.data(), bytes, s); + rad_stream_sync(s); + rad_stream_destroy(s); + if (rc < 0) { + RAD_ERR("speed projection: rank %d: uploading the directions failed: %s", rank, + rad_dev_last_error()); + rad_dev_free(d, RAD_MEM_DEVICE); + return nullptr; + } + return (const float*) d; +} + +uint64_t control_vector_salt(const ControlVector& cv) { + if (!cv.loaded()) return 0; + return hash_table(cv) | 1ull; +} + +} /* namespace rad */ diff --git a/core/cvec.h b/core/cvec.h new file mode 100644 index 00000000..cf86e773 --- /dev/null +++ b/core/cvec.h @@ -0,0 +1,100 @@ +/* cvec.h -- the experimental speed projection: a GGUF control vector on the residual stream. + * + * ============================== what it is ============================== + * + * The package at huggingface.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection carries one unit + * direction per layer (`direction.1` .. `direction.47`, 2560 f32 each) and the configuration its + * authors selected: the llama.cpp `--cvec-mode project` operation + * + * h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l| + * + * over layers 4..44, applied to every stream of the gated residual. Strata ports the same + * package (`data/experimental-speed-projection`) with the same operation, range and per-request + * switch; this is that port for radiance, which has its own graph and cannot use llama.cpp's + * patch (arch/qwen4exp_fp8 issues `hc_project` from the op vocabulary instead). + * + * The vector is a refusal-direction projection: with it on the model declines far fewer requests. + * Removing refusals removes a safety behaviour, so the default is OFF and every request names its + * own choice, and the file is only read when the engine finds one for this container. + * + * ============================== compatibility, checked, not assumed ============================== + * + * Nothing here trusts the file's provenance. A vector is refused unless + * + * - `general.architecture` is `controlvector`, + * - `controlvector.model_hint`, when present, names this model's architecture plugin + * (`qwen4exp`), since a direction from another architecture's residual basis is noise, + * - every tensor is `direction.`, F32, one dimension, and exactly the model's `n_embd`, + * - the layer range lies inside the model and every layer in it has a direction. + * + * The published Flash-Next vector passes all four against a Flash-Next container: 47 tensors of + * 2560 f32, hint `qwen4exp`, range 4..44 of 48 layers. A 27B, Gemma or Qwen3.6 container refuses + * it at startup with the reason, rather than serving a model whose hidden states are moved along + * an unrelated direction. + */ +#pragma once +#include "rad_internal.h" + +#include +#include + +namespace rad { + +/* What a loaded vector keeps on the host, before it is uploaded per rank. `dir` is + * [n_layers * n_embd] f32, unit rows, row 0 unused (the format has no direction for layer 0); + * `scales[l]` is |d_l| * user scale, or 0 where the layer is outside the loaded range. */ +struct ControlVector { + std::vector dir; + std::vector scales; + int64_t n_embd = 0; + int64_t n_layers = 0; + int first = -1, last = -1; /* inclusive layer range */ + float user_scale = 1.0f; + std::string path; + + bool loaded() const { return n_layers > 0 && n_embd > 0; } + /* Whether layer `l` is steered, i.e. a kernel has something to project. Mirror of the loader's + * range check, used by the architecture plugin at declare. */ + bool covers(int64_t l) const { + return loaded() && l >= first && l <= last && l < (int64_t) scales.size() && + scales[(size_t) l] != 0.0f; + } +}; + +/* Read and validate `path` against a model of `n_embd` and `n_model_layers`. + * + * The operation's parameters come with the package, never from a command line: `path`'s own + * `.json` (the JSON the vector is published with) supplies `layer_range` and `scale` when it + * says `"mode": "project"`. Without one, the range is the published Qwen3.8-Flash-Next selection + * (4..44) where the file has directions there, else every layer the file carries, at scale 1. */ +int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd, + int64_t n_model_layers, ControlVector* out, std::string* err); + +/* Where a vector for `model_path` is looked for: + * the container's sidecar, then one generic name in the container's directory, then each + * $RADIANCE_HOME's `vectors/` directory. Mirrors gen_sidecar_path's naming so an operator who + * already knows the generation-config convention knows this one. */ +std::string control_vector_sidecar_path(const std::string& model_path); + +/* Resolve `auto`: sets *found to the first candidate that exists and is non-empty, or to "" when + * none does. *tried receives the candidates, for the log line that says why the feature is + * unavailable on this deployment. Discovery is a filesystem test only; whether the file is + * compatible is control_vector_load's answer. */ +int control_vector_discover(const std::string& model_path, const std::string& arch, + const std::string& radiance_home, std::string* found, + std::string* tried); + +/* Build the ABI view for one rank. `dir_device` is that rank's [n_layers, n_embd] f32 copy. */ +RadControlVector control_vector_view(const ControlVector& cv, const float* dir_device); + +/* Upload the host table to a fresh device buffer on rank `rank`, or null on failure. The caller + * owns the buffer and frees it with rad_dev_free. */ +const float* control_vector_upload(const ControlVector& cv, int rank); + +/* The layer salt a cache uses so that blocks and linear-state snapshots computed with the mode on + * are never handed to a request with it off (or to another vector's). 0 for "off", which is also + * the value the engine uses with no vector loaded, so a deployment without the feature hashes + * exactly as it did before it existed. */ +uint64_t control_vector_salt(const ControlVector& cv); + +} /* namespace rad */ diff --git a/core/engine.cpp b/core/engine.cpp index 3256f380..ba865d38 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -58,6 +58,18 @@ Engine::Readback::~Readback() { } Engine::~Engine() { + /* The control vector's per-rank direction copies. Uploaded at declare, outside any arena, so + * nothing else frees them; each rank's copy is freed with that rank's device bound, since the + * allocator is per device. */ + for (const auto& r : ranks_) { + if (!r || (size_t) r->index >= cvec_views_.size()) continue; + const float* d = cvec_views_[(size_t) r->index].dir; + if (!d) continue; + if (rad_dev_set(r->device) < 0) continue; + rad_dev_free((void*) d, RAD_MEM_DEVICE); + cvec_views_[(size_t) r->index].dir = nullptr; + } + cvec_views_.clear(); /* --profile-ops prints its final table here, the last point where the program still holds * the op table the rows name. */ if (cfg_.profile_ops) for (auto& r : ranks_) r->ctx.dump_profile(); @@ -1444,6 +1456,11 @@ int Engine::serve(std::unique_ptr watch) { kv_iface_ = std::make_unique>(&ranks_[0]->kv); pc_iface_ = std::make_unique>(&ranks_[0]->prefix); + /* The control vector's identity partitions the block cache (PCBinding::salt_id): a request + * that runs with the projection on never adopts a block or a linear-state snapshot produced + * without it, or the other way round. Zero with no vector loaded, and then every chain hashes + * exactly as it did before the feature existed. */ + static_cast*>(pc_iface_.get())->salt_id = cvec_salt_; /* The restore path, installed only when the tiers are on. The scheduler calls it before the * admission lookup without knowing about tiers, so it is a callable rather than an include in * core/sched. @@ -1460,7 +1477,8 @@ int Engine::serve(std::unique_ptr watch) { PrefixCache& pc = ranks_[0]->prefix; std::vector mk; media_keys(req, &mk); - const std::vector want = pc.restorable_from(req.prompt, mk); + const std::vector want = + pc.restorable_from(req.prompt, mk, cvec_salt_for(req.sp.use_control_vector)); if (want.empty()) return; /* The whole chain in one restore. With 4-token blocks a long conversation is tens of * thousands of entries; batched, it is one launch per (group, layer) per staging batch @@ -1615,6 +1633,25 @@ bool Engine::state_slots_of(uint64_t seq, std::vector* out) const { /* The engine's part of /server_info: model, cards, KV, drafting and wire, for a running process. * The server holds only interfaces, so the engine renders this object and the server splices it in * verbatim. */ +/* The experimental speed projection, for /stats, /v1/models and /server_info. `available` is + * what a client should test before sending the field: without a loaded vector a request that asks + * for it is refused, so a UI can hide the control rather than offer a switch that fails. */ +std::string Engine::cvec_json() const { + nlohmann::ordered_json o; + o["available"] = cvec_.loaded(); + o["default"] = cvec_default_.load(); + if (cvec_.loaded()) { + o["first"] = cvec_.first; + o["last"] = cvec_.last; + o["n_embd"] = cvec_.n_embd; + o["n_layers"] = cvec_.n_layers > 0 ? cvec_.n_layers - 1 : 0; + o["scale"] = cvec_.user_scale; + o["file"] = cvec_.path; + o["mode"] = "project"; + } + return o.dump(); +} + std::string Engine::engine_info() const { nlohmann::ordered_json e; e["arch"] = meta_.arch_id ? meta_.arch_id : ""; @@ -1638,6 +1675,7 @@ std::string Engine::engine_info() const { e["vision_tower_placement"] = { { "asked", table_placement_name(cfg_.tower_placement) }, { "resolved", table_placement_name(cfg_.tower_resolved) } }; e["prefix_cache"] = cfg_.prefix_cache; + e["control_vector"] = nlohmann::ordered_json::parse(cvec_json()); e["checkpoint_slots"] = cfg_.checkpoint_slots; e["deterministic"] = cfg_.deterministic; @@ -1992,6 +2030,15 @@ int Engine::run_server() { d.tok = &tok_bridge; d.grammar = &grammar_bridge; d.live = snap; + /* The experimental speed projection, when a vector was loaded. The admin endpoint flips the + * default through this; nothing rebuilds a graph, so a toggle takes effect on the next request + * and leaves the running ones alone. */ + if (cvec_.loaded()) { + d.control_vector.available = [this] { return cvec_loaded(); }; + d.control_vector.get_default = [this] { return cvec_default_on(); }; + d.control_vector.set_default = [this](bool on) { set_cvec_default(on); }; + d.control_vector.json = [this] { return cvec_json(); }; + } /* An embedding model serves /v1/embeddings and no chat. Its named prompts are the checkpoint's * sentence-transformers configuration (`sentence_transformers.prompts.*`); a `messages` input diff --git a/core/engine.h b/core/engine.h index 4b07a680..56c57d47 100644 --- a/core/engine.h +++ b/core/engine.h @@ -19,6 +19,7 @@ */ #pragma once #include "rad_core.h" +#include "cvec.h" #include #include #include "build/startup.h" @@ -88,6 +89,24 @@ public: std::string diagnostics_json() const; bool startup_report_printed() const { return report_printed_; } + /* ---- the control vector's public surface (core/cvec.h). + * + * `cvec_loaded` is whether a vector was found and validated for this container; a request + * asking for the feature on a deployment without one is refused by name rather than silently + * served unprojected. `cvec_default_on` is the runtime default for requests that name no + * choice, and the setter is what POST /admin/control-vector calls: it flips a flag, builds + * nothing, reloads nothing, and leaves every running request alone. */ + bool cvec_loaded() const { return cvec_.loaded(); } + bool cvec_default_on() const { return cvec_default_.load(); } + void set_cvec_default(bool on) { cvec_default_.store(on); } + /* {available, default, mode, first, last, n_embd, n_layers, scale, file} for /stats, the + * admin route and the dashboard. */ + std::string cvec_json() const; + /* The value the block cache is keyed by for a step with this mode: the vector's identity when + * on, 0 when off. Zero with no vector loaded, so a deployment without the feature hashes + * exactly as before. */ + uint64_t cvec_salt_for(bool on) const { return on ? cvec_salt_ : 0; } + private: /* One thread per tensor-parallel rank, each owning one device. Ranks share the address * space, so there is no IPC or serialisation and the step batch is shared by pointer rather @@ -463,6 +482,20 @@ private: std::string p2p_blocked_; bool has_ngram_ = false; /* the model carries an n-gram table */ std::string prefix_off_why_; /* why the engine itself turned prefix caching off, or "" */ + + /* ---- the experimental speed projection (core/cvec.h). `cvec_` is the host table, loaded + * once at bringup and empty when the feature is off; `cvec_views_` is, per rank, that table + * uploaded to the rank's card and the ABI view build_ctx hands to a declaring plugin (the + * view's `dir` is the allocation, so one vector holds both). `cvec_salt_` partitions the + * prefix cache between the mode on and off, so a conversation's KV and linear state are never + * reused by a step that would compute different hidden states from the same tokens. */ + ControlVector cvec_; + std::vector cvec_views_; + uint64_t cvec_salt_ = 0; + /* Runtime default for requests that name no choice (flippable through + * POST /admin/control-vector). Atomic: the server's admin thread writes it while + * request threads read it; nothing about the graph changes with it. */ + std::atomic cvec_default_{false}; std::vector env_set_; /* the RADIANCE_* names set when the engine was made */ bool report_printed_ = false; /* Runtime device identity (PCI address, name, integrated flag, runtime version), read once in diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 7192f0a0..521f98fe 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -895,6 +895,12 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const { /* Under --prefill-span every step but a lone prefill is planned at the shared budget * (Scheduler::step), so a wider step is one sequence; 0 without a span. */ bc.max_mixed_tok = cfg_.prefill_span > 1 ? std::min(max_tok, prefill_shared_tok(cfg_)) : 0; + /* The control vector, when one is loaded: this rank's view, or null. A plugin reads it at + * declare only (the direction table never changes); the per-request switch rides the derived + * mask, not this struct. */ + if (cvec_.loaded() && rank >= 0 && rank < (int) cvec_views_.size() && + cvec_views_[(size_t) rank].dir) + bc.cvec = &cvec_views_[(size_t) rank]; return bc; } @@ -1063,6 +1069,52 @@ int Engine::declare() { * a serial loop times out. Registry::select() and init_instance() share a mutex for this. Each * thread binds its device first, because the current device is thread-local and the init * allocates on it. */ + /* Control vectors are resolved here, before any rank declares: the plugin reads the direction + * table from RadBuildCtx, so a table that failed validation must stop the server before a graph + * is built around it. + * + * There is nothing to configure. A vector is a property of the model family, so the engine + * looks for one beside the container (or in the directory, or in $RADIANCE_HOME/vectors) and + * uses it if it is compatible with this container; its operation parameters come from the + * package's own JSON. A file that does not fit is reported and skipped -- a sidecar must never + * stop a server nobody pointed at it -- while the switch itself stays off until a request (or + * the dashboard) asks for it. */ + const std::string arch = meta_.arch_id ? meta_.arch_id : ""; + if (!arch.empty()) { + std::string proj_path, tried; + (void) control_vector_discover(cfg_.model, arch, cfg_.radiance_home, &proj_path, &tried); + if (proj_path.empty()) { + RAD_INFO("control vectors: none found (%s)", tried.c_str()); + } else if (arch != "qwen4exp") { + RAD_WARN("control vectors: %s is for this family only (qwen4exp, whose gated residual " + "carries the projection op); this container is '%s' -- ignoring it", + proj_path.c_str(), arch.c_str()); + } else { + std::string why; + const int rc = control_vector_load(proj_path, arch, meta_.n_embd, meta_.n_layers, + &cvec_, &why); + if (rc != RAD_OK) { + RAD_WARN("%s -- serving without it", why.c_str()); + cvec_ = ControlVector{}; + } + } + } + if (cvec_.loaded()) { + cvec_views_.assign(ranks_.size(), RadControlVector{}); + cvec_salt_ = control_vector_salt(cvec_); + cvec_default_.store(false); + RAD_INFO("control vectors: %s: %lld directions of %lld, layers %d..%d, scale %.3f -- " + "off until a request asks for it (the dashboard's switch, or a request's `control_vector` " + "field)", + cvec_.path.c_str(), (long long) (cvec_.n_layers > 0 ? cvec_.n_layers - 1 : 0), + (long long) cvec_.n_embd, cvec_.first, cvec_.last, (double) cvec_.user_scale); + decide("control vectors", cvec_.path, + "found beside the container, in its directory, or in $RADIANCE_HOME/vectors; " + "requests opt in"); + } else { + cvec_default_.store(false); + } + std::vector st(ranks_.size(), RAD_OK); std::vector th; th.reserve(ranks_.size()); @@ -1076,6 +1128,17 @@ int Engine::declare() { st[(size_t)ri] = RAD_E_DEVICE; return; } + /* This rank's copy of the control vector's directions, on the device the thread has + * just bound. Uploaded outside the program's arena: it is not a weight (it is not in + * the container) and not an activation (it lives for the deployment). */ + if (cvec_.loaded()) { + const float* d = control_vector_upload(cvec_, ri); + if (!d) { + st[(size_t)ri] = RAD_E_DEVICE; + return; + } + cvec_views_[(size_t)ri] = control_vector_view(cvec_, d); + } const RadBuildCtx bc = build_ctx(ri, cfg_.max_tok); LoraDeclare ld; ld.cfg = &cfg_.lora; diff --git a/core/rad_core.h b/core/rad_core.h index 6185bf76..c23c9f55 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -614,6 +614,14 @@ struct SamplingParams { * scheduler thread where every other request's step waits; held here, starting is a lookup. * Null for a request not admitted through the server; the sampler then compiles. */ std::shared_ptr grammar_program; + + /* The control vector (core/cvec.h): whether this request's steps project the vector found for + * this deployment out of the residual stream. The server sets it from the request's + * `control_vector` field (`experimental_speed_projection` is Strata's spelling of the same + * switch), or from the deployment's runtime default when the request names none; it needs no + * reload and leaves the graph untouched. A deployment with no vector refuses `true` at + * admission rather than serving the stock model. */ + bool use_control_vector = false; }; /* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 0abae8bf..8fa48a77 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -101,6 +101,7 @@ ABI_FIELD(RadBuildCtx, max_out_rows) ABI_FIELD(RadBuildCtx, max_audio_frames) ABI_FIELD(RadBuildCtx, max_mixed_tok) ABI_FIELD(RadBuildCtx, kv_quant) +ABI_FIELD(RadBuildCtx, cvec) ABI_STRUCT(RadAudioGenBatch) ABI_FIELD(RadAudioGenBatch, n_lane) ABI_FIELD(RadAudioGenBatch, lane) @@ -169,6 +170,11 @@ ABI_FIELD(RadAudioGenDecl, prompt_whole) ABI_FIELD(RadAudioGenDecl, first_frame) ABI_FIELD(RadAudioGenDecl, voc_chunk) ABI_FIELD(RadAudioGenDecl, voc_context) +ABI_STRUCT(RadControlVector) +ABI_FIELD(RadControlVector, dir) +ABI_FIELD(RadControlVector, scales) +ABI_FIELD(RadControlVector, n_embd) +ABI_FIELD(RadControlVector, n_layers) ABI_STRUCT(RadAudioFormat) ABI_FIELD(RadAudioFormat, struct_size) ABI_FIELD(RadAudioFormat, audio_open) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index 9ff6bc7a..70fa21a3 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -80,7 +80,7 @@ { "RadBufDecl", "domain", 60, 4 }, { "RadBufDecl", "derive", 64, 8 }, { "RadBufDecl", "kv", 72, 4 }, -{ "RadBuildCtx", "", 0, 112 }, +{ "RadBuildCtx", "", 0, 120 }, { "RadBuildCtx", "rank", 0, 4 }, { "RadBuildCtx", "world_size", 4, 4 }, { "RadBuildCtx", "max_tok", 8, 8 }, @@ -98,6 +98,7 @@ { "RadBuildCtx", "max_audio_frames", 88, 8 }, { "RadBuildCtx", "max_mixed_tok", 96, 8 }, { "RadBuildCtx", "kv_quant", 104, 4 }, +{ "RadBuildCtx", "cvec", 112, 8 }, { "RadAudioGenBatch", "", 0, 264 }, { "RadAudioGenBatch", "n_lane", 0, 8 }, { "RadAudioGenBatch", "lane", 8, 8 }, @@ -166,6 +167,11 @@ { "RadAudioGenDecl", "first_frame", 204, 4 }, { "RadAudioGenDecl", "voc_chunk", 208, 8 }, { "RadAudioGenDecl", "voc_context", 216, 8 }, +{ "RadControlVector", "", 0, 32 }, +{ "RadControlVector", "dir", 0, 8 }, +{ "RadControlVector", "scales", 8, 8 }, +{ "RadControlVector", "n_embd", 16, 8 }, +{ "RadControlVector", "n_layers", 24, 8 }, { "RadAudioFormat", "", 0, 72 }, { "RadAudioFormat", "struct_size", 0, 4 }, { "RadAudioFormat", "audio_open", 8, 8 }, diff --git a/tests/cvec_test.cpp b/tests/cvec_test.cpp new file mode 100644 index 00000000..a6ad220a --- /dev/null +++ b/tests/cvec_test.cpp @@ -0,0 +1,241 @@ +/* cvec_test.cpp -- the experimental speed projection's loader (core/cvec.h). + * + * The vector is the published package's format: a GGUF `controlvector` with one unit f32 + * `direction.` per layer and three metadata keys. These cases write such a file, then check + * both what the loader accepts and, just as important, what it refuses: a vector from another + * architecture, one of the wrong width, and a layer range with a gap must stop startup rather than + * steer a model along a direction that does not describe its residual stream. + * + * The compatibility question the port turns on is answered here rather than assumed: the file's + * directions are 2560 wide and a Flash-Next container's stream is 2560, and the file states + * `qwen4exp` as its architecture hint. + */ +#include "rad_test.h" + +#include "cvec.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +/* A minimal GGUF writer, just enough for a control vector: the header, a string/int KV table, one + * F32 one-dimensional tensor per direction, and the data blob at the file's alignment. */ +struct GgufWriter { + struct T { std::string name; std::vector data; }; + std::vector> strs; + std::vector> ints; + std::vector tensors; + + static void u32(std::string& out, uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back((char) ((v >> (8 * i)) & 0xff)); + } + static void u64(std::string& out, uint64_t v) { + for (int i = 0; i < 8; ++i) out.push_back((char) ((v >> (8 * i)) & 0xff)); + } + static void str(std::string& out, const std::string& s) { + u64(out, s.size()); + out += s; + } + + void write(const std::string& path, uint64_t alignment = 32) const { + std::string h; + h += "GGUF"; + u32(h, 3); + u64(h, tensors.size()); + u64(h, strs.size() + ints.size() + 1); /* + general.alignment */ + for (const auto& [k, v] : strs) { + str(h, k); + u32(h, 8); /* GGUF_STR */ + str(h, v); + } + for (const auto& [k, v] : ints) { + str(h, k); + u32(h, 5); /* GGUF_I32 */ + u32(h, (uint32_t) v); + } + str(h, "general.alignment"); + u32(h, 4); /* GGUF_U32 */ + u32(h, (uint32_t) alignment); + + uint64_t off = 0; + std::string dir; + for (const T& t : tensors) { + str(dir, t.name); + u32(dir, 1); /* n_dims */ + u64(dir, (uint64_t) t.data.size()); /* ne[0] */ + u32(dir, 0); /* ggml type 0 = F32 */ + const uint64_t padded = t.data.size() * 4; + u64(dir, off); + off += (padded + alignment - 1) / alignment * alignment; + } + h += dir; + while (h.size() % alignment) h.push_back('\0'); + for (const T& t : tensors) { + const size_t at = h.size(); + (void) at; + h.append((const char*) t.data.data(), t.data.size() * 4); + while (h.size() % alignment) h.push_back('\0'); + } + std::ofstream f(path, std::ios::binary | std::ios::trunc); + f.write(h.data(), (std::streamsize) h.size()); + } +}; + +/* A vector with the published package's shape: `layers` directions of `n` values, each a unit + * vector, plus the metadata its header carries. */ +GgufWriter make_vector(int64_t n, int layers, const char* arch = "controlvector", + const char* hint = "qwen4exp") { + GgufWriter w; + w.strs.push_back({ "general.architecture", arch }); + w.strs.push_back({ "controlvector.model_hint", hint }); + w.ints.push_back({ "controlvector.layer_count", (int32_t) layers }); + for (int l = 1; l <= layers; ++l) { + std::vector d((size_t) n); + for (int64_t i = 0; i < n; ++i) d[(size_t) i] = (float) std::sin(0.001 * (double) (l + 1) * + (double) i + 0.1 * l); + double ss = 0.0; + for (float v : d) ss += (double) v * v; + const float inv = (float) (1.0 / std::sqrt(ss)); + for (float& v : d) v *= inv; + w.tensors.push_back({ "direction." + std::to_string(l), std::move(d) }); + } + return w; +} + +struct Loaded { + rad::ControlVector cv; + std::string err; + int rc = 0; +}; + +/* A vector file, optionally with the package's JSON beside it (which is where the operation's + * parameters live: there is no flag for them). */ +Loaded load(const GgufWriter& w, int64_t n_embd, int64_t model_layers, const std::string& leaf, + const std::string& json = std::string()) { + const std::string path = radtest::tmp_path(leaf); + w.write(path); + if (!json.empty()) { + const std::string side = path.substr(0, path.find_last_of('.')) + ".json"; + std::ofstream f(side, std::ios::binary | std::ios::trunc); + f << json; + } + Loaded out; + out.rc = rad::control_vector_load(path, "qwen4exp", n_embd, model_layers, &out.cv, &out.err); + return out; +} + +} // namespace + +TEST(the_published_shape_loads_and_is_normalised) { + /* 47 directions of 2560 for a 48-layer model, the range the package's own JSON states. */ + /* Nothing states a range, so the loader takes the published selection, 4..44. */ + const Loaded f = load(make_vector(2560, 47), 2560, 48, "flash-next.gguf"); + CHECK_OK(f.rc); + CHECK_EQ(f.cv.n_embd, (int64_t) 2560); + CHECK_EQ(f.cv.first, 4); + CHECK_EQ(f.cv.last, 44); + /* Indexed by layer, so row 0 exists (the format has no direction for it) and 47 rows follow. */ + CHECK_EQ(f.cv.n_layers, (int64_t) 48); + + for (int l = 1; l <= 47; ++l) { + double ss = 0.0; + for (int64_t i = 0; i < 2560; ++i) + ss += (double) f.cv.dir[(size_t) (l * 2560 + i)] * + (double) f.cv.dir[(size_t) (l * 2560 + i)]; + CHECK_NEAR(std::sqrt(ss), 1.0, 1e-5); + /* Unit rows, so the stored norm -- what llama.cpp keeps as `scales[il]` -- is 1. */ + CHECK_NEAR(f.cv.scales[(size_t) l], 1.0f, 1e-5); + } + /* Outside the range nothing is steered: the plugin declares no op there. */ + CHECK_EQ(f.cv.covers(3), false); + CHECK_EQ(f.cv.covers(4), true); + CHECK_EQ(f.cv.covers(44), true); + CHECK_EQ(f.cv.covers(45), false); + + /* The cache partition: nonzero with a vector loaded, and stable across loads of one file. */ + const Loaded again = load(make_vector(2560, 47), 2560, 48, "flash-next-2.gguf"); + CHECK_OK(again.rc); + CHECK(rad::control_vector_salt(f.cv) != 0); + CHECK_EQ(rad::control_vector_salt(f.cv), rad::control_vector_salt(again.cv)); +} + +TEST(a_vector_for_another_architecture_is_refused) { + /* A direction inferred from another model's residual basis is noise here. The hint is the one + * place the file names its architecture, so it is checked when present. */ + const Loaded l = load(make_vector(2560, 47, "controlvector", "gemma4"), 2560, 48, + "wrong-arch.gguf"); + CHECK(l.rc < 0); + CHECK(l.err.find("gemma4") != std::string::npos); +} + +TEST(a_vector_of_the_wrong_width_is_refused) { + /* 2048-wide directions in a 2560-wide model: the kernel would read past the row. */ + const Loaded l = load(make_vector(2048, 47), 2560, 48, "wrong-width.gguf"); + CHECK(l.rc < 0); + CHECK(l.err.find("2560") != std::string::npos); +} + +TEST(a_layer_range_with_a_gap_is_refused) { + /* A vector with no direction for layer 30 while the range covers it would serve a model that + * is silently unsteered on that layer -- a different model from the one the file describes. */ + GgufWriter w = make_vector(2560, 47); + std::vector kept; + for (auto& t : w.tensors) + if (t.name != "direction.30") kept.push_back(t); + w.tensors = std::move(kept); + const Loaded l = load(w, 2560, 48, "gap.gguf"); + CHECK(l.rc < 0); + CHECK(l.err.find("30") != std::string::npos); +} + +TEST(not_a_control_vector_is_refused) { + const Loaded l = load(make_vector(2560, 47, "qwen4exp", "qwen4exp"), 2560, 48, + "wrong-kind.gguf"); + CHECK(l.rc < 0); + CHECK(l.err.find("controlvector") != std::string::npos); +} + +/* The operation's parameters come from the package's own JSON, not a command line: the published + * Flash-Next vector ships {"mode":"project","scale":1.0,"layer_range":[4,44]}. A JSON that states a + * different range or scale is honoured; one that says another mode, or is malformed, only means the + * defaults (the vector itself is still valid). */ +TEST(the_packages_json_sets_the_range_and_scale) { + const Loaded a = load(make_vector(2560, 47), 2560, 48, "json-range.gguf", + R"({"mode":"project","scale":0.5,"layer_range":[8,20]})"); + CHECK_OK(a.rc); + CHECK_EQ(a.cv.first, 8); + CHECK_EQ(a.cv.last, 20); + CHECK_NEAR(a.cv.scales[(size_t) 8], 0.5f, 1e-5); + CHECK_EQ(a.cv.covers(7), false); + CHECK_EQ(a.cv.covers(21), false); + + /* Another mode is not implemented: the file's directions still load, with the defaults. */ + const Loaded b = load(make_vector(2560, 47), 2560, 48, "json-add.gguf", + R"({"mode":"add","scale":0.1,"layer_range":[16,32]})"); + CHECK_OK(b.rc); + CHECK_EQ(b.cv.first, 4); + CHECK_EQ(b.cv.last, 44); + CHECK_NEAR(b.cv.user_scale, 1.0f, 1e-6); + + /* Malformed JSON is reported, not fatal. */ + const Loaded c = load(make_vector(2560, 47), 2560, 48, "json-broken.gguf", "{ not json"); + CHECK_OK(c.rc); + CHECK_EQ(c.cv.first, 4); +} + +TEST(a_unit_vector_gives_scale_one_at_every_steered_layer) { + const std::string path = radtest::tmp_path("scaled.gguf"); + make_vector(2560, 47).write(path); + rad::ControlVector cv; + std::string why; + CHECK_OK(rad::control_vector_load(path, "qwen4exp", 2560, 48, &cv, &why)); + CHECK_NEAR(cv.scales[(size_t) 4], 1.0f, 1e-5); + CHECK_NEAR(cv.scales[(size_t) 44], 1.0f, 1e-5); +} + +RAD_TEST_MAIN()