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.
This commit is contained in:
C_Tamas authored and StillDeadcode committed 2026-10-21 09:26:17 +02:00
1 parent aa12f79579
commit 64adee3ece
10 files changed
+859 -2

No files matched your search

+313
View File
@@ -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.<l>` 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 <algorithm>
#include <cmath>
#include <cstring>
#include <fstream>
#include <nlohmann/json.hpp>
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<std::string> 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<std::string>() != "project") {
RAD_WARN("control vector: %s says mode '%s'; only 'project' is implemented, so the "
"defaults apply", path.c_str(), m->get<std::string>().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<int>();
out.last = (*r)[1].get<int>();
}
if (const auto s = j.find("scale"); s != j.end() && s->is_number())
out.scale = (float) s->get<double>();
} 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.<l>, 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.<layer> 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 */
+100
View File
@@ -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.<l>`, 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 <string>
#include <vector>
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<float> dir;
std::vector<float> 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
* `<stem>.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 */
+48 -1
View File
@@ -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<StallWatch> watch) {
kv_iface_ = std::make_unique<KVBinding<KVManager>>(&ranks_[0]->kv);
pc_iface_ = std::make_unique<PCBinding<PrefixCache>>(&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<PCBinding<PrefixCache>*>(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<StallWatch> watch) {
PrefixCache& pc = ranks_[0]->prefix;
std::vector<MMContentKey> mk;
media_keys(req, &mk);
const std::vector<BlockHash> want = pc.restorable_from(req.prompt, mk);
const std::vector<BlockHash> 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<int32_t>* 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
+33
View File
@@ -19,6 +19,7 @@
*/
#pragma once
#include "rad_core.h"
#include "cvec.h"
#include <map>
#include <set>
#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<RadControlVector> 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<bool> cvec_default_{false};
std::vector<std::string> 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
+63
View File
@@ -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<int> st(ranks_.size(), RAD_OK);
std::vector<std::thread> 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;
+8
View File
@@ -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<const GbnfProgram> 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