server: a control_vector request field, its admin switch and the Model-view panel

The field is per request, with the deployment's runtime default when absent, and a deployment with
no vector refuses 'true' by name rather than serving the stock model. Strata's
`experimental_speed_projection` is accepted as an alias.

The dashboard's Model view carries a "Control vectors" panel with the switch for that default;
GET/POST /admin/control-vector is its endpoint, behind the API key like every other route. The state
is in /stats and /server_info. Nothing here reloads the model: the directions are uploaded once and
each step carries a per-request mask.

The panel stays visible when the page has no API key, with the reason, instead of disappearing --
a control that vanishes because the page has not signed in reads exactly like a build without the
feature.
This commit is contained in:
C_Tamas authored and StillDeadcode committed 2026-10-21 09:26:17 +02:00
1 parent 66c6d71254
commit 6f26cdb5f4
7 files changed
+312 -3

No files matched your search

+127 -2
View File
@@ -30,6 +30,47 @@ namespace server {
* Derived rates are the page's job: they are counter differences over wall time, and only the
* browser holds both ends of its poll interval. Computing them here would need per-client state. */
/* ------------------------------------------------------------------ /admin/control-vector
*
* The control vector's runtime switch (core/cvec.h). Turning it on for the next
* request costs a boolean: the direction table was uploaded at startup and the per-request mask
* is a derived buffer the core fills every step, so there is nothing to rebuild and nothing to
* reload. The engine's own log records the load; this records the flip, because a deployment's
* answer to "was that text produced with the vector" should not depend on a browser's memory.
*
* GET reports the state (and is what the Model view renders); POST takes {"enabled": true|false}
* and answers with the same object. A deployment with no vector loaded answers 404 on both: it has
* no such feature, and its requests refuse `control_vector: true` by name. */
HttpResponse Server::handle_control_vector(const HttpRequest& req) {
const bool have = deps_.control_vector.available && deps_.control_vector.available();
if (!have)
return error_response(err_not_implemented(
"this deployment found no control vector for its model; there is nothing to switch"),
req.peer);
if (req.method == "POST") {
json body;
try {
body = json::parse(req.body.empty() ? "{}" : req.body);
} catch (const std::exception& e) {
return error_response(err_bad("body", std::string("not JSON: ") + e.what()), req.peer);
}
const auto it = body.find("enabled");
if (it == body.end() || !it->is_boolean())
return error_response(err_bad("enabled", "a boolean is required"), req.peer);
const bool on = it->get<bool>();
if (deps_.control_vector.set_default) deps_.control_vector.set_default(on);
RAD_INFO("control vector: default %s by an admin request%s", on ? "ON" : "OFF",
req.peer.empty() ? "" : (" from " + req.peer).c_str());
} else if (req.method != "GET") {
return HttpResponse::json_body(405, err_bad("method", "GET or POST").dump());
}
metrics_.observe_http(200);
return HttpResponse::json_body(
200, deps_.control_vector.json ? deps_.control_vector.json() : std::string("{}"));
}
/* ------------------------------------------------------------------ /sessions
*
* A separate route, not a /stats field: /stats is polled every second, while a stored session
@@ -124,6 +165,16 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
json o;
o["model"] = opt_.model_id;
o["version"] = opt_.version;
/* The control vector (core/cvec.h), when this deployment has one: `available` is what a UI
* tests before offering the control, `default` what a request that names no choice runs. The
* dashboard's own control asks /admin/control-vector, which also reports this. */
if (deps_.control_vector.json) {
try {
o["control_vector"] = json::parse(deps_.control_vector.json());
} catch (const std::exception&) {
/* A malformed snapshot is not worth failing /stats over; the field is omitted. */
}
}
o["uptime_s"] = unix_now() - started_at_;
/* Seconds this process took to come up, the cost of a restart; 0 before the server listens. */
o["startup_s"] = startup_s_;
@@ -643,7 +694,8 @@ th + th, td + td { padding-left:14px; }
it as a dot, because on a server with long-lived agent clients the second group is most of the
table and none of it needs reading to understand the first. */
#view-sess .cell { height:auto; padding-bottom:12px; }
#view-sess .panel + .panel { margin-top:14px; }
/* Stacked panels in one view are 14px apart, the same gap the strip's own margin-bottom gives. */
#view-sess .panel + .panel, #view-model .panel + .panel { margin-top:14px; }
.stbl td, .stbl th { width:1%; }
/* The two text columns take the slack and read left to right; the figures stay narrow. */
.stbl .l { text-align:left; width:auto; }
@@ -1177,6 +1229,22 @@ nav button.on { color:var(--fg); background:var(--track); }
<div id="view-model" hidden>
<div class="strip" id="gstrip"></div>
<!-- The control vector (core/cvec.h): one direction per layer, projected out of the residual
stream at run time. Shown only on a deployment that found one; flipping it needs no
reload, and every request that names its own choice overrides it. -->
<section class="panel" id="cvpanel" hidden>
<div class="phead">
<span class="cap">Control vectors</span>
<span class="aside" id="cvsum"></span>
</div>
<div class="pbody">
<label class="cvrow">
<input id="cvbox" type="checkbox">
<span id="cvlabel">Apply the control vector to new requests</span>
</label>
<div class="aside" id="cvnote"></div>
</div>
</section>
<section class="panel">
<div class="phead">
<span class="cap">Kernel libraries</span>
@@ -1232,6 +1300,10 @@ $("key").addEventListener("change", (e) => {
e.target.hidden = true;
identify();
poll();
/* The Model view's controls are fetched on demand, so a key entered after the tab was opened
* has to re-ask: otherwise the control-vector panel stays in its "sign in" state until the
* tab is left and re-opened. */
loadControlVector();
});
const HIST = 120; /* 60s of history at the 500ms poll */
@@ -2829,7 +2901,7 @@ function show(which) {
$("tab-dash").className = (model || sess) ? "" : "on";
$("tab-sess").className = sess ? "on" : "";
$("tab-model").className = model ? "on" : "";
if (model) loadGraph();
if (model) { loadGraph(); loadControlVector(); }
if (sess) loadSessions();
window.scrollTo(0, 0);
const h = model ? "#model" : sess ? "#sessions" : "#";
@@ -2985,6 +3057,59 @@ async function identify() {
} catch (err) { /* the header simply keeps its placeholder */ }
}
/* THE SPEED PROJECTION, asked when the Model view opens. It is not a polled value: it changes only
* when this page (or an admin call) flips it, and a control that silently reverted under the
* reader would be worse than one that is a second old. A deployment without a control vector
* answers 404 and the panel stays hidden. */
async function loadControlVector() {
/* THREE OUTCOMES, and only one of them hides the panel:
* 404 this deployment has no control vector -- there is no such control, so it is omitted;
* 200 the vector is loaded -- show the switch and its state;
* anything else (most often 401, the page has no API key yet) -- the feature may well be
* there, so SAY that instead of hiding the control. A control that silently disappears
* because the page has not signed in reads exactly like a build without the feature. */
try {
const r = await api("admin/control-vector");
if (r.status === 404) { $("cvpanel").hidden = true; return; }
if (!r.ok) throw new Error(String(r.status));
const p = await r.json();
$("cvpanel").hidden = false;
$("cvbox").disabled = false;
$("cvbox").checked = !!p.default;
$("cvsum").textContent = "layers " + p.first + "\u2013" + p.last + " \u00b7 " + p.mode +
" \u00b7 scale " + p.scale;
$("cvnote").textContent = "Applies to new requests only; a request's own control_vector " +
"field wins. It removes a safety behaviour.";
} catch (e) {
$("cvpanel").hidden = false;
$("cvbox").disabled = true;
$("cvbox").checked = false;
$("cvsum").textContent = "";
$("cvnote").textContent =
"Sign in with the API key (the field in the header) to read or change this: the vector " +
"is present on this deployment, but its state needs the key.";
}
}
$("cvbox").addEventListener("change", async (e) => {
const want = e.target.checked;
e.target.disabled = true;
try {
const r = await fetch("admin/control-vector", {
method: "POST", cache: "no-store",
headers: Object.assign({ "Content-Type": "application/json" },
apiKey ? { Authorization: "Bearer " + apiKey } : {}),
body: JSON.stringify({ enabled: want }),
});
if (!r.ok) throw new Error(String(r.status));
const p = await r.json();
$("cvbox").checked = !!p.default;
} catch (err) {
e.target.checked = !want; // the server kept the old value
} finally {
e.target.disabled = false;
}
});
async function poll() {
/* A background tab watches nothing, and neither does the Model view -- which is static. */
if (document.hidden || $("view-dash").hidden) return;
+12
View File
@@ -240,6 +240,7 @@ const char* kAcceptedCommon[] = {
"dry_sequence_breakers", "samplers",
"grammar", "json_schema", "priority", "logprobs", "ignore_eos",
"timings_per_token", "return_progress", "session_id", "n_probs",
"control_vector", "experimental_speed_projection",
};
const char* kAcceptedChat[] = {
@@ -842,6 +843,17 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
/* ignore_eos: generate to max_tokens whatever the model emits. See Request::ignore_eos. */
if (!get_bool(b, "ignore_eos", &r->ignore_eos, err)) return RAD_E_INVAL;
/* The control vector (core/cvec.h): an opt-in per request, and the only place an API client
* turns it on when the deployment's default is off. `control_vector` is the field's name;
* `experimental_speed_projection` is Strata's spelling of the same switch, kept as an alias so
* a client written against that reports what it means. */
for (const char* key : { "control_vector", "experimental_speed_projection" }) {
if (!b.contains(key)) continue;
bool on = false;
if (!get_bool(b, key, &on, err)) return RAD_E_INVAL;
r->control_vector = on ? 1 : 0;
}
/* stop: a string or an array of strings. Bounded in count and length because every stop
* string is searched in each piece of generated text (by the decoder and the server's scan),
* so per-token cost is count x longest. OpenAI allows four; the bounds are far above that
+5
View File
@@ -94,6 +94,11 @@ struct OaiRequest {
int n = 1;
SamplingParams sp;
/* The experimental speed projection, tri-state: -1 the request named no choice (the engine's
* runtime default applies), 0 it asked for the stock model, 1 for the loaded control vector.
* Parsed from `control_vector` (or Strata's `experimental_speed_projection`); a deployment
* with no vector refuses 1 rather than silently serving the stock model. */
int control_vector = -1;
int32_t max_tokens = 0;
std::vector<std::string> stop;
/* How many of `stop` the client sent; the rest are the chat format's end-of-turn markers.
+26
View File
@@ -204,6 +204,12 @@ void Server::register_routes() {
router_.get ("/stats", [this](const HttpRequest& q) { return handle_stats(q); });
router_.get ("/graph", [this](const HttpRequest& q) { return handle_graph(q); });
router_.get ("/sessions", [this](const HttpRequest& q) { return handle_sessions(q); });
/* The control vector's switch, for the dashboard's Model view and for automation: a
* deployment with no vector found answers 404 here. */
router_.get ("/admin/control-vector",
[this](const HttpRequest& q) { return handle_control_vector(q); });
router_.post("/admin/control-vector",
[this](const HttpRequest& q) { return handle_control_vector(q); });
}
/* Workers beyond the admission ceiling. A generation holds its connection's worker for its whole
@@ -460,6 +466,25 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
}
}
/* The control vector: the request's own choice, else the deployment's runtime default. A
* deployment with no vector refuses the on state by name -- serving the stock model while the
* client believes it asked for the vector would be a silent lie about what produced the text.
* (Naming: `control_vector` is the field, `experimental_speed_projection` its alias.) */
bool projection_on = false;
{
const bool named = r.control_vector >= 0;
projection_on = named
? (r.control_vector == 1)
: (deps_.control_vector.get_default && deps_.control_vector.get_default());
if (projection_on &&
!(deps_.control_vector.available && deps_.control_vector.available())) {
*err = err_bad("control_vector",
"this deployment found no control vector for its model; the stock model "
"is what it serves");
return RAD_E_INVAL;
}
}
int idx = 0;
std::vector<Request> rqs;
rqs.reserve(r.prompts.size() * (size_t)r.n);
@@ -482,6 +507,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
Request rq;
rq.prompt = r.prompts[p].tokens;
rq.sp = r.sp;
rq.sp.use_control_vector = projection_on;
/* Distinct seeds per choice, or `n` identical completions. An offset suffices: the
* sampler's stream is seeded, not chained. */
rq.sp.seed = r.sp.seed + (uint64_t)k;
+17
View File
@@ -48,6 +48,19 @@ struct Deps {
* (liveview.h), so the terminal and the web page agree. Absent, the dashboard shows only the
* scheduler's metrics and omits the cards. */
LiveView::Source live;
/* The control vector (core/cvec.h), as the server sees it: whether the engine found one for
* this container, the runtime default for requests that name no choice, and the switch the
* admin endpoint flips. Absent (the function members null) means the feature does not exist on
* this deployment: a request that asks for it is refused by name, and the dashboard shows no
* control. Nothing here reloads the model. */
struct ControlVectorSwitch {
std::function<bool()> available;
std::function<bool()> get_default;
std::function<void(bool)> set_default;
std::function<std::string()> json;
};
ControlVectorSwitch control_vector;
};
struct ServerOptions {
@@ -312,6 +325,10 @@ private:
HttpResponse handle_stats(const HttpRequest& req);
HttpResponse handle_graph(const HttpRequest& req);
HttpResponse handle_sessions(const HttpRequest& req);
/* The control vector's runtime switch (dashboard.cpp): GET reports the state, POST
* {"enabled": bool} sets the default for requests that name no choice. Guarded by the API key
* like every other route but the health probes and the page. */
HttpResponse handle_control_vector(const HttpRequest& req);
HttpResponse error_response(const ApiError& e, const std::string& peer,
ApiShape shape = ApiShape::OpenAI);
+59 -1
View File
@@ -1435,7 +1435,63 @@ radiance --model krea-2-turbo-fp8.rad --lora-dir /loras --lora film=/loras/film-
- `POST /v1/load_lora_adapter {"lora_name": "x", "lora_path": "/file.safetensors"}` adds a file
under a name; unload removes it and frees the slots of every combination using it.
### 4.10 Every flag
### 4.10 Control vectors
A **control vector** is a small GGUF file holding one direction per layer; applied while the model
runs, it moves every token's residual stream off that direction. radiance implements llama.cpp's
`--cvec-mode project` operation for it (`hc_project`, `docs/OPS.md`), which is what the published
package for Qwen3.8-Flash-Next was tuned for:
**The switch is present whenever a compatible vector is there — there is nothing to pass on the
command line.** The engine looks, in order, at:
1. `<container without its extension>.control-vector.gguf` beside the model, and
2. `control-vector.gguf` in the container's directory (one file serves a directory of quants of
the family), then
3. `<home>/vectors/<architecture>-control-vector.gguf` for each `--radiance-home`, i.e.
`…/vectors/qwen4exp-control-vector.gguf`.
So a deployment that drops the file beside its Flash-Next container offers the Model-view switch and
the `control_vector` request field with nothing else to configure; every quantisation of the family
shares it, because the file names the architecture and the width, not the quant. The operation's
parameters come from the package's own JSON (`layer_range`, `scale`, `mode`), so there is no flag for
them either: a file that does not fit this container is reported and skipped, never served. The
default for *requests* stays off in all cases.
- **Only a compatible container accepts it.** The file must be a GGUF `controlvector` whose
`controlvector.model_hint` (when present) is this model's architecture (`qwen4exp`), whose
directions are exactly the model's `--n-embd` wide, and whose range lies inside its layers.
Anything else stops startup with the reason: a direction from another model's residual basis
would move hidden states along a meaningless axis.
- **It is off until a request asks for it.** The dashboard's Model view flips the default for
requests that name no choice, and a request's own `control_vector` field always wins. **No
switch reloads the model**: the directions are uploaded once at startup and each step carries a
per-request row mask.
- **A request without it computes exactly what it computes with no vector loaded** — the op skips
a disabled row without reading or writing it.
- **Conversations are partitioned.** Blocks and linear-state snapshots computed with the vector
on are keyed differently from those computed without it, so switching modes in one conversation
recomputes instead of reusing hidden states that belonged to the other mode. A runtime LoRA
adapter (§4.9.1) and a control vector are independent: both enter the prefix cache's key, so
neither's KV is ever shared with the other's.
- Cost: 41 extra launches per trunk step at Flash-Next's 48 layers (range 4..44), each a dot
product and a subtract per residual stream. On two RX 9070s that is not measurable: prefill of a
7.9K-token prompt 2.09 s without the vector, 2.08 s with it; decode of 5,000-token answers
(three runs each, alternating, temperature 0, ignore_eos) medians 150.1 tok/s without it and
151.3 tok/s with it. The spread around those medians -- 139 to 154 tok/s -- is speculative
acceptance, which follows the text the model writes and not the vector, and a session's first run
reads lower still (91 tok/s at 17% acceptance) while the cold caches fill. The MTP draft head is
not steered; the trunk verifies every token, so the text is the vector's.
- For the vector shipped for Qwen3.8-Flash-Next it is a refusal-direction projection: it removes a
safety behaviour, and the default stays off for that reason. With it on, a request that asks the
model for its system prompt gets it, and tone/policy refusals stop -- so a deployment that exposes
the API beyond one user should leave the default off and control who may set the field.
The published vector, its JSON and the llama.cpp patches it was built against are at
`huggingface.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection`; the operation and the range
(`4..44`, scale `1.0`, per-layer) are the package's own selected configuration.
### 4.11 Every flag
`radiance --help` prints these. Grouped by purpose:
@@ -1448,6 +1504,7 @@ radiance --model krea-2-turbo-fp8.rad --lora-dir /loras --lora film=/loras/film-
| `--radiance-home DIRS` | where `kernels/`, `architectures/` and `quantizers/` live; homes separated by `:` are searched in order, the first winning (§1.5) |
| `--kernels LIST` | the kernel libraries to use, separated by `,` or `:`, first wins; a library not named is not loaded. Default: every library found |
**Batch shape**
| flag | default | |
@@ -1976,6 +2033,7 @@ passes but not launches (the UNet runs once per image and branch), so two take t
| `timings_per_token`, `return_progress` | llama-server's: `timings` on every chunk, and `prompt_progress` chunks while the prompt is read |
| `samplers` | llama-server's sampler order, names or letters. A stage it leaves out is off. The chain here is penalties, DRY, top-k, top-p, min-p, typical, XTC, with temperature first (the default) or last (llama-server's default), so a list in either order is honoured and any other is refused by name |
| `session_id` | OpenRouter's conversation id: labels the conversation on `/sessions` and the dashboard |
| `control_vector` | `true` applies the control vector this deployment found to this request's steps, `false` leaves them on the stock model; absent takes the deployment's runtime default (off unless flipped in the dashboard's Model view). `experimental_speed_projection` is Strata's spelling of the same field and is accepted as an alias. A deployment with no vector refuses `true` by name. On a compatible container (Qwen3.8-Flash-Next), a refusal-direction vector makes the model decline far fewer requests -- that is a safety behaviour removed, and you own what it writes (§4.10, "Control vectors") |
| `logprobs`, `top_logprobs`, `n_probs` | each generated token's logprob and up to 20 alternatives (§5.12). Chat: `logprobs: true` with `top_logprobs` alternatives (0 when absent); completions: `logprobs: N`; any endpoint: llama-server's `n_probs: N`, which wins. Not with `echo` (the prompt's logprobs are not computed) |
| `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 |
+66
View File
@@ -4523,6 +4523,61 @@ int status_with(Fixture& f, const std::string& ep, const std::string& key, const
} /* namespace */
/* The experimental speed projection: absent, the engine's default applies; an explicit `true` on a
* deployment with no vector is refused by name (serving the stock model while the client believes
* otherwise would be a silent lie), and on one with a vector it reaches the engine's request. */
TEST(the_control_vector_field_overrides_the_default_or_is_refused) {
const json body = json::parse(R"({"messages":[{"role":"user","content":"hi"}],
"max_tokens":4,
"control_vector":true})");
{
/* No vector loaded: refused, naming the field. */
Fixture f;
HttpResponse r = f.post("/v1/chat/completions", body.dump());
if (r.streaming()) drain(r);
f.sched.join_all();
CHECK_EQ(r.status, 400);
CHECK(r.body.find("control_vector") != std::string::npos);
}
{
/* A vector loaded, default off: the request's own choice wins and reaches the engine. */
bool def = false;
Fixture f(Fixture::Tweak{ [&](ServerOptions&, Deps& d) {
d.control_vector.available = [] { return true; };
d.control_vector.get_default = [&def] { return def; };
d.control_vector.set_default = [&def](bool on) { def = on; };
d.control_vector.json = [&def] {
return std::string("{\"available\":true,\"default\":") +
(def ? "true" : "false") + "}";
};
} });
HttpResponse r = f.post("/v1/chat/completions", body.dump());
if (r.streaming()) drain(r);
f.sched.join_all();
CHECK_EQ(r.status, 200);
CHECK(f.sched.last_sp.use_control_vector);
/* The same request naming nothing runs the default, which the admin route flips. */
def = true;
HttpResponse r2 = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],
"max_tokens":4})");
if (r2.streaming()) drain(r2);
f.sched.join_all();
CHECK_EQ(r2.status, 200);
CHECK(f.sched.last_sp.use_control_vector);
const HttpResponse g = f.get("/admin/control-vector");
CHECK_EQ(g.status, 200);
CHECK(g.body.find("\"default\":true") != std::string::npos);
const HttpResponse p = f.post("/admin/control-vector", R"({"enabled":false})");
CHECK_EQ(p.status, 200);
CHECK(!def);
/* Refuses a body that names no boolean rather than guessing. */
CHECK_EQ(f.post("/admin/control-vector", R"({"enabled":"yes"})").status, 400);
}
}
/* The policy oai.cpp's lists state, key by key, on every endpoint: a guarded key is served at its
* neutral value and refused by name at any other (a 200 means every answer-changing field was
* honoured); an inert key and an unknown one are accepted and ignored; an accepted key with a
@@ -4534,6 +4589,12 @@ TEST(every_request_key_is_served_refused_or_ignored_as_its_list_says) {
Fixture f(Fixture::Tweak{ [&](ServerOptions& o, Deps& d) {
d.embed = &emb;
o.supports_logprobs = true;
/* This deployment has a control vector, so `control_vector: true` is served rather
* than refused; the refusal on a deployment without one is its own case below. */
d.control_vector.available = [] { return true; };
d.control_vector.get_default = [] { return false; };
d.control_vector.set_default = [](bool) {};
d.control_vector.json = [] { return std::string("{\"available\":true}"); };
} });
emb.tpl = &f.tmpl;
f.sched.embedding = { 1.0f, 2.0f, 3.0f, 4.0f };
@@ -4639,6 +4700,11 @@ TEST(every_request_key_is_served_refused_or_ignored_as_its_list_says) {
{ "input", { "yo", none } }, { "encoding_format", { "base64", none } },
{ "dimensions", { 2, none } }, { "image_tokens", { 70, none } },
{ "prompt_name", { "query", none } },
/* The control vector is accepted by every text endpoint under its own name and under
* Strata's spelling; its semantic refusal (a deployment with no vector) happens at
* submission, not parsing, so a parse test sees 200 here. */
{ "control_vector", { true, none } },
{ "experimental_speed_projection", { true, none } },
};
/* logprobs is spelled per endpoint: true on chat, a count on completions. */
auto value_for = [&](const std::string& key, const std::string& ep) -> Valid {