Author SHA1 Message Date
lotherk 430af49f84 frontend: print the engine's prompt and decode progress as it happens
The engine reports progress (PP) and tokens (T) over its stdout, but the
front end logged only the start and end of a request.  A 154k-token prompt
is minutes of silence that reads as a hung request.  Now a line every
STRATA_PROGRESS seconds (default 5, 0 = off): prompt processing from the
engine's own PP lines, and decoding from the token count.
2026-10-15 11:55:32 +01:00
lotherk 4ad0206b1f serve: capture the verify windows up front, not on the first request
cudaGraphInstantiate allocates device memory for each window size's exec and the
exec is never freed (measured ~22-26 MiB per size on a GTX 1070 Ti, 2026-10-15).
serve captured each size lazily, on the first request that used it, so that
memory came out of - and could outrun - the reserve the auto-cache had been sized
against.  A serve planned down to its last ~150 MiB therefore captured the sizes
its first requests asked for and then failed the next

    strata serve: verify: instantiate: out of memory

mid-request, which took the engine and the front end down with it (the container
restarted).  This is not the sampler or the Qwen3.6 port: the DRY work adds ~4 KB
of device arrays and a 128 KB history row, and the lazy capture predates both.

Every size 1..max_t the serve path can ask for is now captured right after the
verifier is bound (after set_split / set_pcie_mode, which the recorded graph
depends on).  That makes the cost part of what the serve free-VRAM check sees and
bounds it before any request runs: a size that does not fit is reported at
startup, naming the knobs that make room, instead of killing a request.

Seen on kontron.local: a GTX 1070 Ti (sm_61) serving Flash-Next Coder IQ1_M with
--ctx 131072 --vram-cap 7680.  There the window graphs need ~135 MiB and the plan
left 135 MiB free; --vram-reserve-mib 700 (which skips #496's lowering to 300)
leaves ~630 MiB and all six fit.  The cap itself is honoured: the blocker held
back the 424 MiB it should.
2026-10-15 09:29:23 +01:00
lotherk c8c3ca492c Sampler: DRY anti-repetition penalty, exposed end to end
The sampler chain gains llama.cpp's dry stage (penalties -> DRY -> top_k -> ...): a token that would extend a
repeat longer than dry_allowed_length over the last dry_penalty_last_n history tokens loses
dry_multiplier * dry_base^(repeat - allowed_length), with tokenized restart sequences capping the scan.

- kernels/cuda/sampler.cu: dry_window/dry_build/apply_dry in the greedy, old, one-block, split and coupled
  penalize kernels; the DRY window is the same history row the penalties count, clamped to kDryWindowCap=512;
  the membership bitmap spans the wider of the two windows and gates both.  Off (the default) the neutral path
  is unchanged: shmem 0, the cluster argmax still runs, the parity fixtures pin every path against a host
  reference (sampler_parity, 19 fixtures).
- include/strata/kernels/sampler.hpp: the dry_* fields, DryBreakers (device flat/off), dry_enabled.
- verify / mtp: Verifier::set_breakers and MtpDrafter::set_draft_breakers thread the tokenized breakers to the
  head sampling and the captured coupled-draft graph (stable device arrays).
- generate.cpp (engine): dry_multiplier / dry_base / dry_allowed_length / dry_penalty_last_n / dry_breakers GEN
  keys; the breaker arrays are allocated once at the cap on the head device, the request refills them; a
  DRY-only request still stages history (the wider of the two windows).
- front end: --dry-multiplier / --dry-base / --dry-allowed-length / --dry-penalty-last-n / --dry-breakers
  defaults and dry_* / dry_sequence_breakers request fields; the front end tokenizes the restart sequences
  (the engine has no tokenizer) and sends them as ids.  The defaults are llama.cpp's: multiplier 0.8, base
  1.75, allowed length 2, window 256, breakers newline, colon, quote, asterisk when unset.
2026-10-14 22:44:58 +01:00
12 changed files with 774 additions and 118 deletions

No files matched your search

+3 -2
View File
@@ -60,9 +60,10 @@ cache.
| | |
| --- | --- |
| Endpoints | `POST /v1/chat/completions` (streaming or not), `GET /v1/models`, `GET /health`, on `127.0.0.1:8080` |
| Options | `--ctx N` (32768), `--threads N` (default: physical cores, or half the CPU quota in a container), `--host`, `--port`, `--mmproj PATH`, `--vision-tokens N` (1024), `--fit-max-tokens` / `--no-fit-max-tokens` (default: on); engine flags after `--`: `--kv fp16\|q4_0\|int8`, `--vram-cap MiB` and `--ram-cap GiB` (plan as a smaller card or host), `--expert-cache N`, `--prompt-cache N` (checkpoints kept between requests) |
| Options | `--ctx N` (32768), `--threads N` (default: physical cores, or half the CPU quota in a container), `--host`, `--port`, `--mmproj PATH`, `--vision-tokens N` (1024), `--fit-max-tokens` / `--no-fit-max-tokens` (default: on); sampling defaults (a request's own fields win): `--temperature F` (0, greedy), `--top-k N` (1..64), `--top-p F`, `--min-p F`, `--repeat-last-n N`, `--repeat-penalty F`, `--presence-penalty F`, `--frequency-penalty F`, `--dry-multiplier F`, `--dry-base F`, `--dry-allowed-length N`, `--dry-penalty-last-n N`, `--dry-breakers LIST`, `--seed N`; engine flags after `--`: `--kv fp16\|q4_0\|int8`, `--vram-cap MiB` and `--ram-cap GiB` (plan as a smaller card or host), `--expert-cache N`, `--prompt-cache N` (checkpoints kept between requests) |
| Context | a request whose `max_tokens` would run past `--ctx` has it shortened to the room left; with `--no-fit-max-tokens` it is refused (400) instead |
| Sampling | greedy unless `temperature` > 0 |
| Sampling | greedy unless the effective `temperature` > 0; `temperature`, `top_p`, `top_k` (1..64), `min_p`, `seed`, `presence_penalty`, `frequency_penalty`, `repeat_penalty` and `repeat_last_n` per request, else the launch defaults; a penalty with a zero window uses 64 (`repeat_last_n` / the alias `penalty_last_n`) |
| DRY | llama.cpp's `dry` anti-repetition sampler, on when `dry_multiplier` and `dry_penalty_last_n` are both set (per request, else `--dry-multiplier` / `--dry-penalty-last-n`): a token that would extend a repeat longer than `dry_allowed_length` loses `dry_multiplier * dry_base^(repeat - allowed_length)` over the last `dry_penalty_last_n` tokens. `dry_sequence_breakers` / `--dry-breakers` (literal strings, `\|`-separated; default newline, `:`, `"`, `*`) restart the repeat count. Applies in greedy and sampled mode; the front end tokenizes the breakers (the engine has no tokenizer) |
| Reasoning | returned as `reasoning_content`; `"reasoning_effort": "none"` turns it off |
| Tools | OpenAI format (`tools`, `tool_calls`) |
| Images | with `--mmproj`, OpenAI `image_url` parts holding a base64 `data:image/...` URL (PNG, JPEG, BMP or GIF), several per message |
+50 -1
View File
@@ -152,8 +152,57 @@ int main(int argc, char** argv) {
assert(server.prepare(request, budgeted, error));
assert(!budgeted.thinking && budgeted.reasoning_budget == 0);
request.erase("reasoning_effort");
// Sampling header: the launch-time defaults, overridden by a request's own fields; greedy is preserved;
// penalties apply even in greedy and get llama.cpp's 64-token window when none is set.
{
const common_json empty = common_json::parse_no_throw(R"({"messages":[]})");
Options neutral;
assert(sampling_keys(empty, neutral, server.vocab).empty()); // greedy, no penalties: exactly the old header
Options tuned = neutral;
tuned.temperature = 0.7; tuned.top_p = 0.9; tuned.top_k = 40; tuned.min_p = 0.05;
tuned.repeat_penalty = 1.05; tuned.presence_penalty = 0.3; tuned.frequency_penalty = 0.2;
tuned.repeat_last_n = 256; tuned.seed = 42;
const std::string k = sampling_keys(empty, tuned, server.vocab);
for (const char* s : {" temperature=0.7", " top_p=0.9", " top_k=40", " seed=42", " min_p=0.05",
" penalty_repeat=1.05", " penalty_present=0.3", " penalty_freq=0.2",
" penalty_last_n=256"})
assert(k.find(s) != std::string::npos);
// a request's own fields win; the ones it omits keep the launch default
const common_json override_body = common_json::parse_no_throw(
R"({"messages":[],"temperature":0.2,"top_k":8,"repeat_penalty":1.1,"repeat_last_n":512})");
const std::string ko = sampling_keys(override_body, tuned, server.vocab);
for (const char* s : {" temperature=0.2", " top_k=8", " top_p=0.9", " penalty_repeat=1.1",
" penalty_last_n=512"})
assert(ko.find(s) != std::string::npos);
// the greedy path honors penalties too, so a penalty applies with no temperature
const common_json penalty_body = common_json::parse_no_throw(R"({"messages":[],"presence_penalty":0.5})");
const std::string kp = sampling_keys(penalty_body, neutral, server.vocab);
assert(kp.find("temperature") == std::string::npos);
assert(kp.find(" penalty_present=0.5") != std::string::npos);
assert(kp.find(" penalty_last_n=64") != std::string::npos);
// DRY: emitted only when the multiplier and the window are both set; the default breakers are tokenized
// here (the engine has no tokenizer) and encoded as ids; a request's own list wins.
Options dry = neutral;
dry.dry_multiplier = 0.8; dry.dry_base = 1.75; dry.dry_allowed_length = 2; dry.dry_penalty_last_n = 256;
const std::string kd = sampling_keys(empty, dry, server.vocab);
for (const char* s : {" dry_multiplier=0.8", " dry_base=1.75", " dry_allowed_length=2",
" dry_penalty_last_n=256", " dry_breakers="})
assert(kd.find(s) != std::string::npos);
assert(sampling_keys(empty, neutral, server.vocab).find("dry_") == std::string::npos);
const common_json dry_body = common_json::parse_no_throw(
R"({"messages":[],"dry_multiplier":0.5,"dry_penalty_last_n":128,"dry_sequence_breakers":["\n"]})");
const std::string kb = sampling_keys(dry_body, neutral, server.vocab);
assert(kb.find(" dry_multiplier=0.5") != std::string::npos);
assert(kb.find(" dry_penalty_last_n=128") != std::string::npos);
assert(kb.find(" dry_breakers=") != std::string::npos);
}
llama_model_free(server.model);
std::puts("PASS: omitted parallel_tool_calls uses the model capability; explicit false remains honored; "
"tool arguments parse in any order; the answer streams as it grows and tool calls arrive whole; "
"reasoning_budget_tokens and its message override the command line");
"reasoning_budget_tokens and its message override the command line; the sampling header honors the "
"launch defaults, a request's overrides, greedy and the penalty window");
}
+38 -1
View File
@@ -9,6 +9,7 @@
#include <mutex>
#include <string>
#include <vector>
#include <chrono>
#include <csignal>
#include <unistd.h>
@@ -80,6 +81,26 @@ public:
}
req += '\n';
if (!send(req)) { r.error = "the engine is not running"; return r; }
// Live progress (llama.cpp prints while it works; the engine does not). The engine is silent for the whole
// of a long prompt - a 154k-token prompt is minutes at a few tens of tokens a second - and a request that is
// merely slow then reads as hung. One stderr line per STRATA_PROGRESS seconds (default 5, 0 = off), between
// the request's start line and the engine's own end-of-request summary, which is unchanged.
static const double progress_s = [] {
const char* v = std::getenv("STRATA_PROGRESS");
if (v == nullptr) return 5.0;
const double x = std::atof(v);
return x > 0.0 ? x : 0.0;
}();
auto last_report = std::chrono::steady_clock::now();
auto decode_t0 = last_report;
long long pp_done = 0, pp_total = (long long) ids.size(), n_out = 0;
auto report_ok = [&]() -> bool {
if (progress_s <= 0.0) return false;
const auto now = std::chrono::steady_clock::now();
if (std::chrono::duration<double>(now - last_report).count() < progress_s) return false;
last_report = now;
return true;
};
bool stopped = false;
std::string callback_error;
std::string line;
@@ -98,6 +119,22 @@ public:
send("STOP\n");
}
}
if (++n_out == 1) decode_t0 = std::chrono::steady_clock::now();
if (report_ok()) {
const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - decode_t0).count();
std::fprintf(stderr, "unbiased-strata: decoding: %lld tokens, %.1f tok/s\n",
n_out, s > 0.0 ? (double) n_out / s : 0.0);
}
} else if (line.rfind("PP ", 0) == 0) {
long long done = 0, total = 0;
double ms = 0.0, tps = 0.0;
std::sscanf(line.c_str(), "PP %lld %lld %lf %lf", &done, &total, &ms, &tps);
if (done > 0) pp_done = done;
if (total > 0) pp_total = total;
if (report_ok())
std::fprintf(stderr, "unbiased-strata: prompt processing: %lld/%lld (%.1f%%), %.1f tok/s\n",
pp_done, pp_total,
pp_total > 0 ? 100.0 * (double) pp_done / (double) pp_total : 0.0, tps);
} else if (line.rfind("DONE ", 0) == 0) {
char finish[32] = {0};
std::sscanf(line.c_str(), "DONE %lld %lld %lf %lf %31s %lld %lld", &r.produced, &r.prompt_n, &r.prompt_ms,
@@ -117,7 +154,7 @@ public:
r.error = line.size() > 4 ? line.substr(4) : "the engine reported an error";
return r;
}
// PP (prompt progress), RESUME, REUSED and INFO lines need no action here
// RESUME, REUSED and INFO lines need no action here (PP is reported above)
}
alive_ = false;
r.error = "the engine exited during the request";
+145 -29
View File
@@ -19,6 +19,7 @@
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstdlib>
@@ -74,6 +75,25 @@ struct Options {
double ram_cap_gib = 0.0; // --ram-cap: bounds the engine's RAM expert tier and pinned arena
long long reasoning_budget = 0; // cap the thinking of every request (0: no cap; a request can set its own)
std::string reasoning_budget_message = kDefaultReasoningBudgetMessage; // injected before the end tag
// Sampling defaults: a request's own fields win over these. Temperature <= 0 keeps the documented default
// (greedy) and emits no filters, exactly as before; the rest are the engine's own neutral values, so an
// unconfigured front end changes nothing.
double temperature = 0.0; // > 0 samples; 0 (default) is greedy
double top_p = 0.95;
long long top_k = 20; // the engine's sampler takes 1..64
double min_p = 0.0; // 0 disables
long long repeat_last_n = 0; // penalty window; 0 with a penalty set falls back to 64
double repeat_penalty = 1.0; // 1.0 disables
double presence_penalty = 0.0; // 0.0 disables
double frequency_penalty = 0.0; // 0.0 disables
// DRY (llama.cpp's `dry` sampler): breaks looping generations by penalising a token that would extend a
// repeat longer than `dry_allowed_length`. Off unless the multiplier and the window are both set.
double dry_multiplier = 0.0; // 0.0 disables
double dry_base = 1.75; // the exponent base (>= 1)
long long dry_allowed_length = 2; // repeats of this length or less are free
long long dry_penalty_last_n = 0; // the DRY window in tokens (0 disables)
std::vector<std::string> dry_breakers; // restart sequences; empty uses "\n", ":", "\"", "*"
long long seed = -1; // -1: a fresh random seed per request
std::vector<std::string> extra; // after `--`: passed to the engine as they are
};
@@ -100,9 +120,28 @@ void usage() {
" --port N port to listen on (default 8080)\n"
" --vram-cap MIB emulate a smaller card: the engine uses at most MIB of VRAM (a 1080 Ti as 6 GB: 5722)\n"
" --ram-cap GIB bound the engine's RAM expert tier and pinned arena to GIB\n\n"
"Sampling defaults (a request's own temperature/top_p/top_k/min_p/seed/presence_penalty/\n"
"frequency_penalty/repeat_penalty/repeat_last_n wins; greedy unless the effective temperature is > 0):\n"
" --temperature F sampling temperature (default 0 = greedy)\n"
" --top-k N top-k shortlist, 1..64 (default 20)\n"
" --top-p F nucleus probability, 0..1 (default 0.95)\n"
" --min-p F min-p floor, 0..1 (default 0, off)\n"
" --repeat-last-n N repetition-penalty window in tokens (default 0; a penalty set here or in a\n"
" request forces at least 64)\n"
" --repeat-penalty F repetition penalty, > 0 (default 1.0, off)\n"
" --presence-penalty F presence penalty (default 0.0, off)\n"
" --frequency-penalty F frequency penalty (default 0.0, off)\n"
" --dry-multiplier F DRY repetition penalty; 0 disables (default 0.0)\n"
" --dry-base F DRY exponent base, >= 1 (default 1.75)\n"
" --dry-allowed-length N free repeat length before DRY applies (default 2)\n"
" --dry-penalty-last-n N the DRY window in tokens; 0 disables (default 0)\n"
" --dry-breakers LIST restart sequences as literal text separated by '|' (default \n:|\"|*)\n"
" --seed N sampling seed (default: a fresh random seed per request)\n\n"
"Serves POST /v1/chat/completions (OpenAI style, with streaming), GET /v1/models and GET /health (with the\n"
"engine's expert tiers and per-token counters: VRAM slots, RAM copies, mapped experts, hits, warm hints,\n"
"major page faults).\n");
"major page faults).\n"
"STRATA_PROGRESS=SECONDS prints a prompt-processing/decoding line to stderr every SECONDS while a request\n"
"runs (default 5; 0 turns it off).\n");
}
bool file_exists(const std::string& p) {
@@ -172,6 +211,75 @@ struct Prepared {
long long max_new = 0;
};
/// The sampling keys of one request's engine header: the launch-time defaults (`opt`) with the request's own
/// OpenAI / llama.cpp fields winning. Greedy is preserved: an effective temperature <= 0 emits no temperature
/// and no filters, and the penalties and their window are emitted only when a penalty is actually set (a
/// non-neutral value). The order is fixed, so the header is reproducible for a given input.
std::string sampling_keys(const common_json& body, const Options& opt, const llama_vocab* vocab) {
auto number = [&](const char* key, double fallback) {
return body.contains(key) && body.at(key).is_number() ? body.at(key).get<double>() : fallback;
};
auto integer = [&](const char* key, long long fallback) {
return body.contains(key) && body.at(key).is_number() ? body.at(key).get<long long>() : fallback;
};
auto text = [](double v) { char b[32]; std::snprintf(b, sizeof b, "%g", v); return std::string(b); };
std::string keys;
const double temperature = number("temperature", opt.temperature);
if (temperature > 0.0) {
const double top_p = number("top_p", opt.top_p);
const long long top_k = std::max(1LL, std::min(64LL, integer("top_k", opt.top_k)));
const double min_p = number("min_p", opt.min_p);
const unsigned long long seed = body.contains("seed") && body.at("seed").is_number()
? (unsigned long long) body.at("seed").get<long long>()
: (opt.seed >= 0 ? (unsigned long long) opt.seed : (unsigned long long) std::random_device{}());
keys += " temperature=" + text(temperature) + " top_p=" + text(top_p) +
" top_k=" + std::to_string(top_k) + " seed=" + std::to_string(seed);
if (min_p > 0.0) keys += " min_p=" + text(min_p);
}
// llama.cpp's names: presence_penalty, frequency_penalty, repeat_penalty; repeat_last_n is the window.
const double penalty_repeat = number("repeat_penalty", opt.repeat_penalty);
const double penalty_freq = number("frequency_penalty", opt.frequency_penalty);
const double penalty_present = number("presence_penalty", opt.presence_penalty);
if (penalty_repeat != 1.0 || penalty_freq != 0.0 || penalty_present != 0.0) {
if (penalty_repeat != 1.0) keys += " penalty_repeat=" + text(penalty_repeat);
if (penalty_freq != 0.0) keys += " penalty_freq=" + text(penalty_freq);
if (penalty_present != 0.0) keys += " penalty_present=" + text(penalty_present);
// a penalty with a zero window is a no-op in the sampler, so give it llama.cpp's default of 64
const long long window = integer("repeat_last_n", integer("penalty_last_n", opt.repeat_last_n));
keys += " penalty_last_n=" + std::to_string(window > 0 ? window : 64);
}
// DRY (llama.cpp's `dry`): emitted only when it is actually on (multiplier and window both set). The restart
// sequences are tokenized here - the engine has no tokenizer - and sent as ids ("id,id|id|...", sequences by
// '|'); a request's own `dry_sequence_breakers` array wins over the launch-time list, else llama.cpp's default.
const double dry_multiplier = number("dry_multiplier", opt.dry_multiplier);
const long long dry_window = integer("dry_penalty_last_n", opt.dry_penalty_last_n);
if (dry_multiplier != 0.0 && dry_window != 0) {
const double dry_base = number("dry_base", opt.dry_base);
const long long dry_allowed = std::max(0LL, integer("dry_allowed_length", opt.dry_allowed_length));
std::vector<std::string> breakers = opt.dry_breakers;
if (body.contains("dry_sequence_breakers") && body.at("dry_sequence_breakers").is_array()) {
breakers.clear();
for (const auto& e : body.at("dry_sequence_breakers"))
if (e.is_string()) breakers.push_back(e.get<std::string>());
}
if (breakers.empty()) breakers = {"\n", ":", "\"", "*"};
std::string enc;
for (const std::string& s : breakers) {
if (s.empty()) continue;
const std::vector<llama_token> ids = common_tokenize(vocab, s, /*add_special=*/false, /*parse_special=*/true);
if (ids.empty()) continue;
if (!enc.empty()) enc += '|';
for (size_t k = 0; k < ids.size(); ++k) { if (k) enc += ','; enc += std::to_string((long long) ids[k]); }
}
keys += " dry_multiplier=" + text(dry_multiplier) + " dry_base=" + text(dry_base) +
" dry_allowed_length=" + std::to_string(dry_allowed) +
" dry_penalty_last_n=" + std::to_string(dry_window);
if (!enc.empty()) keys += " dry_breakers=" + enc;
}
return keys;
}
/// The parse of one response as its text grows: what has been published, and what to publish next.
///
/// Reasoning and answer text are published as they arrive. Tool calls are published once, from the parse of the
@@ -376,34 +484,8 @@ struct Server {
p.max_new = max_new;
p.stream = body.value("stream", false);
// sampling: greedy unless the request sets a temperature above zero
std::string keys;
const double temperature = body.contains("temperature") && body.at("temperature").is_number()
? body.at("temperature").get<double>() : 0.0;
if (temperature > 0.0) {
const double top_p = body.contains("top_p") && body.at("top_p").is_number() ? body.at("top_p").get<double>() : 0.95;
long long top_k = body.contains("top_k") && body.at("top_k").is_number() ? body.at("top_k").get<long long>() : 20;
top_k = std::max(1LL, std::min(64LL, top_k)); // the engine's sampler takes 1..64
unsigned long long seed;
if (body.contains("seed") && body.at("seed").is_number()) seed = (unsigned long long) body.at("seed").get<long long>();
else seed = std::random_device{}();
char b[160];
std::snprintf(b, sizeof b, " temperature=%g top_p=%g top_k=%lld seed=%llu", temperature, top_p, top_k, seed);
keys += b;
if (body.contains("min_p") && body.at("min_p").is_number()) {
std::snprintf(b, sizeof b, " min_p=%g", body.at("min_p").get<double>());
keys += b;
}
}
for (const auto& kv : {std::pair<const char*, const char*>{"presence_penalty", "penalty_present"},
std::pair<const char*, const char*>{"frequency_penalty", "penalty_freq"},
std::pair<const char*, const char*>{"repeat_penalty", "penalty_repeat"}})
if (body.contains(kv.first) && body.at(kv.first).is_number()) {
char b[64];
std::snprintf(b, sizeof b, " %s=%g", kv.second, body.at(kv.first).get<double>());
keys += b;
if (keys.find("penalty_last_n") == std::string::npos) keys += " penalty_last_n=64";
}
// sampling: the launch-time defaults with the request's own fields winning (see sampling_keys)
const std::string keys = sampling_keys(body, opt, vocab);
// The header's parts are kept so a continuation (a thinking budget wrap-up) can rebuild it with a smaller
// max_new; the assembled header is byte-for-byte the one this fork always sent.
p.gen_prefix = p.images ? "GENI " : "GEN ";
@@ -749,6 +831,30 @@ bool parse_args(int argc, char** argv, Options& o) {
else if (a == "--threads") o.threads = std::atoi(next("--threads").c_str());
else if (a == "--vram-cap") o.vram_cap_mib = std::atoll(next("--vram-cap").c_str());
else if (a == "--ram-cap") o.ram_cap_gib = std::atof(next("--ram-cap").c_str());
else if (a == "--temperature" || a == "--temp") o.temperature = std::atof(next("--temperature").c_str());
else if (a == "--top-k") o.top_k = std::atoll(next("--top-k").c_str());
else if (a == "--top-p") o.top_p = std::atof(next("--top-p").c_str());
else if (a == "--min-p") o.min_p = std::atof(next("--min-p").c_str());
else if (a == "--repeat-last-n") o.repeat_last_n = std::atoll(next("--repeat-last-n").c_str());
else if (a == "--repeat-penalty") o.repeat_penalty = std::atof(next("--repeat-penalty").c_str());
else if (a == "--presence-penalty") o.presence_penalty = std::atof(next("--presence-penalty").c_str());
else if (a == "--frequency-penalty") o.frequency_penalty = std::atof(next("--frequency-penalty").c_str());
else if (a == "--dry-multiplier") o.dry_multiplier = std::atof(next("--dry-multiplier").c_str());
else if (a == "--dry-base") o.dry_base = std::atof(next("--dry-base").c_str());
else if (a == "--dry-allowed-length") o.dry_allowed_length = std::atoll(next("--dry-allowed-length").c_str());
else if (a == "--dry-penalty-last-n") o.dry_penalty_last_n = std::atoll(next("--dry-penalty-last-n").c_str());
else if (a == "--dry-breakers") {
const std::string list = next("--dry-breakers");
o.dry_breakers.clear();
for (size_t p = 0; p <= list.size();) {
const size_t bar = list.find('|', p);
const size_t end = bar == std::string::npos ? list.size() : bar;
o.dry_breakers.push_back(list.substr(p, end - p));
if (bar == std::string::npos) break;
p = bar + 1;
}
}
else if (a == "--seed") o.seed = std::atoll(next("--seed").c_str());
else if (a == "--") {
for (++i; i < argc; ++i) {
const std::string e = argv[i];
@@ -769,6 +875,16 @@ bool parse_args(int argc, char** argv, Options& o) {
std::fprintf(stderr, "unbiased-strata: --reasoning-budget-tokens must be 0 or more (0: no budget)\n\n");
return false;
}
if (!std::isfinite(o.temperature) || !std::isfinite(o.top_p) || !std::isfinite(o.min_p) ||
!std::isfinite(o.repeat_penalty) || !std::isfinite(o.presence_penalty) || !std::isfinite(o.frequency_penalty) ||
!std::isfinite(o.dry_multiplier) || !std::isfinite(o.dry_base) ||
o.repeat_penalty <= 0.0 || o.top_p <= 0.0 || o.top_p > 1.0 || o.min_p < 0.0 || o.min_p > 1.0 ||
o.repeat_last_n < 0 || o.dry_base < 1.0 || o.dry_allowed_length < 0 || o.dry_penalty_last_n < 0) {
std::fprintf(stderr, "unbiased-strata: sampling options must be finite (--repeat-penalty positive, "
"--top-p/--min-p in 0..1, --repeat-last-n 0 or more, --dry-base >= 1, "
"--dry-allowed-length/--dry-penalty-last-n 0 or more)\n\n");
return false;
}
return !o.model.empty() && !o.pack.empty() && !o.mtp.empty();
}
+4
View File
@@ -80,6 +80,9 @@ public:
/// the target's Philox draw for the verifying row, and `probs` is the draft's probability under that chain; a
/// greedy one keeps the argmax drafts and their graphs. A no-op when the switch is off.
void set_draft_sampling(const strata::kernels::SamplerParams& sp);
/// Coupled mode: the request's DRY sequence breakers (device pointers, alive across the request), used by the
/// draft chain so a drafted token follows the same DRY rule the verifying row's sample does. Empty for none.
void set_draft_breakers(const strata::kernels::DryBreakers& br) { draft_br_ = br; }
/// Coupled mode with penalties: the history the next draft() chain starts from - what the session holds after the
/// window's commit (`tail`) and the window's pick at its last accepted row (`next`, the next window's row 0).
void set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next);
@@ -157,6 +160,7 @@ private:
bool coupled_rec_ = false; ///< record_forward: the full layer ends in the coupled sampler (draft coupled_j_)
int coupled_j_ = 0;
strata::kernels::SamplerParams *h_cparams_ = nullptr, *m_cparams_ = nullptr, *cparams_ = nullptr;
strata::kernels::DryBreakers draft_br_ = {}; ///< set_draft_breakers: the coupled chain's DRY breakers
int32_t *h_chist_ = nullptr, *m_chist_ = nullptr, *cring_ = nullptr, *dinv_ = nullptr;
void* cscratch_ = nullptr;
const float* f32(const char* name) const;
+16
View File
@@ -89,6 +89,13 @@ public:
/// One window: `tokens[0..T)` at positions pos0.., the pool served per layer; `out[t]` = argmax after token t.
/// The PLE rows are gathered here from `ss.ple_prev` and the tokens. Captures the T-token graph on first use.
bool run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, std::string& err);
/// Capture the T-token window graph NOW instead of on its first `run`. cudaGraphInstantiate allocates device
/// memory per window size and the exec is never freed (measured ~22-26 MiB per size on a GTX 1070 Ti,
/// 2026-10-15), so a size captured lazily spent the reserve one request at a time until an instantiate ran out
/// mid-request and the engine died. `serve` captures every size it can ask for (1..max_t) up front; `run` still
/// captures any size that was missed. False with `err` when the capture fails (the buffers or the exec did not
/// fit). Set `set_split`/`set_pcie_mode` first: the recorded graph depends on them.
bool capture_window(int T, std::string& err) { return capture(T, err); }
/// Diagnostics: row `t` of the last window's head logits (n_vocab floats) to the host. Valid after run().
bool copy_logits(int t, float* host) const;
int64_t vocab() const { return next_ ? next_->vocab() : n_vocab_; }
@@ -100,6 +107,14 @@ public:
if (next_) next_->set_sampling(sp);
}
/// The DRY restart sequences (tokenized; device pointers) the head's sampler uses. Only the last stage
/// holds the head, so this forwards down a layer split like set_sampling; null (`n == 0`) is the default and
/// leaves the sampler byte-for-byte neutral. The buffers must stay alive across the request.
void set_breakers(const strata::kernels::DryBreakers& b) {
br_ = b;
if (next_) next_->set_breakers(b);
}
/// The penalty histories for `sampling_.penalty_last_n`: ONE ROW PER WINDOW ROW, T rows of `history_len`
/// int32 slots at that stride (`strata::kernels::penalty_rows` builds them), most recent token LAST, unused
/// front slots -1 (the kernel reads only the tail window). Row t follows the window's drafts 1..t - staging
@@ -260,6 +275,7 @@ private:
const int32_t* hist_d_ = nullptr; ///< penalty-history row (set_history); null = no penalties apply
int hist_len_ = 0;
bool head_sampling_ = true; ///< set_head_sampling
strata::kernels::DryBreakers br_ = {}; ///< DRY sequence breakers for the head's sampling (set_breakers)
int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split)
std::atomic<bool> released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows
bool all_resident_ = false; ///< 100% of experts in [lb_, le_) resident in VRAM: zero-doorbell graph
+37 -3
View File
@@ -25,8 +25,39 @@ struct SamplerParams {
uint64_t seed = 0; // drives Philox, which is counter-based on (seed, token index)
uint64_t counter = 0; // absolute draw index of row 0; advance across decode calls
bool greedy = false;
// DRY (llama.cpp's `dry` sampler, applied straight after the penalties above): a token that would EXTEND a
// repeat longer than `dry_allowed_length` loses `dry_multiplier * dry_base^(repeat - allowed_length)`, over
// the last `dry_penalty_last_n` history tokens. Restart sequences cap the repeat length. `dry_multiplier`
// 0, `dry_base` < 1, or `dry_penalty_last_n` 0 disables it (llama.cpp's `dry_enabled`). Only the last
// `kDryWindowCap` window tokens are examined; a longer `dry_penalty_last_n` is clamped there.
float dry_multiplier = 0.0f;
float dry_base = 1.75f;
int dry_allowed_length = 2;
int dry_penalty_last_n = 0; // 0 disables; the window over `history`, the same row the penalties count
};
// The DRY Z-algorithm runs in DEVICE SHARED memory, one window per row: the cap bounds that window (and the
// sequence-breaker scan). llama.cpp's default is 256; the engine's penalty window may be wider (up to 4096).
constexpr int kDryWindowCap = 512;
// DRY sequence breakers, tokenized (llama.cpp's `dry_processed_breakers`): `n` restart sequences, sequence k is
// `flat[off[k] .. off[k+1])`, its head `flat[off[k]]` and its tail the rest. A head with an empty tail is a
// single-token sequence and is never penalised. DEVICE pointers; `n == 0` means no breakers.
struct DryBreakers {
const int* flat = nullptr;
const int* off = nullptr;
int n = 0;
};
// `dry_enabled` (llama.cpp's condition): the multiplier, the base and a non-zero window must all agree. Both the
// host launch path and the device kernels call it, so it is host-and-device (the header is not CUDA-only).
#if defined(__CUDACC__)
__host__ __device__
#endif
inline bool dry_enabled(const SamplerParams& p) {
return p.dry_multiplier != 0.0f && p.dry_base >= 1.0f && p.dry_penalty_last_n != 0;
}
// logits (n_tokens, n_vocab) -> one sampled token id per row in `out`.
//
// **`logits` AND `out` ARE DEVICE POINTERS.** This is a CUDA kernel launch, not a host function, and nothing
@@ -37,10 +68,12 @@ struct SamplerParams {
//
// `history` is (n_tokens, history_len) int32 - ONE ROW PER TOKEN ROW, at a stride of `history_len` - the most
// recent tokens that row's pick follows, with any unused slots set to -1; only the last `p.penalty_last_n` of
// each row are counted, and ids outside [0, n_vocab) are ignored. Pass nullptr and 0 when no penalties apply.
// each row are counted, and ids outside [0, n_vocab) are ignored. DRY counts over the last `p.dry_penalty_last_n`
// of the SAME row; `breakers` are its tokenized restart sequences (a head with an empty tail is a single-token
// sequence and is never penalised), `n == 0` for none. Pass history nullptr and 0 when no penalties apply.
// A verify window's rows need DIFFERENT histories: row t follows the window's drafts 1..t (`penalty_rows`).
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
const SamplerParams& p, int* out, void* stream);
const SamplerParams& p, int* out, void* stream, const DryBreakers& breakers = DryBreakers{});
// The greedy pick (no penalties) on a thread-block cluster of 8 CTAs per row (sm_90+, CUDA; S19): the same token as
// sample_tokens' one-block argmax, which takes it unless STRATA_ARGMAX_MULTI=0. False (nothing launched) where it
@@ -63,7 +96,8 @@ void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapp
// the id to ring[cap + j].
void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
void* scratch, int32_t* out_id, float* out_prob, void* stream);
void* scratch, int32_t* out_id, float* out_prob, void* stream,
const DryBreakers& breakers = DryBreakers{});
// The penalty-history rows of a verify window, on the host: row t of `out` (T rows of `h` slots) is the last `h`
// tokens of `tail[0..n_tail)` followed by `window[0..t]`, most recent LAST, -1 in the unused front slots.
+4 -2
View File
@@ -772,7 +772,8 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri
// coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft
// (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer)
coupled_draft_sample(head_logits_, (int) nv, sub ? dvocab_ : nullptr, sub ? dinv_ : nullptr, (int) n_vocab_,
cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs);
cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs,
draft_br_);
return true;
}
SamplerParams sp;
@@ -985,7 +986,8 @@ bool MtpDrafter::record_forward_qwen36(int T, int step_row0, cudaStream_t cs, st
emit("result_output", head_logits_, T * nv);
if (coupled_rec_) {
coupled_draft_sample(head_logits_, (int) nv, sub ? dvocab_ : nullptr, sub ? dinv_ : nullptr, (int) n_vocab_,
cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs);
cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs,
draft_br_);
return true;
}
SamplerParams sp;
+1 -1
View File
@@ -1659,7 +1659,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
if (head_sampling_ && (sampled || hist_d_ != nullptr)) {
SamplerParams sp = sampling_;
sp.counter = (uint64_t) pos0;
sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_);
sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_, br_);
if (cudaStreamSynchronize(cs_) != cudaSuccess) { // m_out_ is the mapped h_out_: synced, it is readable
err = "verify: the head sampling failed";
return false;
+239 -70
View File
@@ -80,6 +80,113 @@ __device__ __forceinline__ float apply_penalties(float logit, int count, const S
return logit;
}
// ---- DRY (llama.cpp's `dry` sampler): a token that would EXTEND a repeat longer than `dry_allowed_length`
// loses `dry_multiplier * dry_base^(repeat - allowed_length)`. `dry_build` is `llama_sampler_dry_apply`'s
// steps 1-3 (the restart-sequence scan, the reverse Z-algorithm, and the per-token maximum repeat), run once per
// row on ONE thread into shared memory; `apply_dry` is step 4, consulted per candidate.
//
// The window is the last `p.dry_penalty_last_n` tokens of the row, the SAME row the penalties count, with the
// `-1` padding `penalty_rows` writes in front dropped (`rat(0)` is then the most recent real token, as in
// llama.cpp's `last_tokens.rat`). `br` is `dry_processed_breakers`: sequence k is flat[off[k] .. off[k+1]).
struct DryShared {
int n; // tokens in `tok`/`len`
int drep[kDryWindowCap]; // step 2: the repeat length at each reversed position
int tok[kDryWindowCap]; // step 3: a token that would extend a repeat ...
int len[kDryWindowCap]; // ... and its longest such repeat length (the max over positions)
};
// The trailing window of the padded history row: `dlen` real tokens ending at the row's end, `drow` their base.
__device__ __forceinline__ void dry_window(const int* base, int history_len, int dry_last_n, const int*& drow,
int& dlen) {
int d = dry_last_n < history_len ? dry_last_n : history_len;
if (d > kDryWindowCap) d = kDryWindowCap;
if (d < 0) d = 0;
drow = base + history_len - d;
while (d > 0 && drow[0] == -1) { ++drow; --d; } // drop the -1 padding (a real id is never negative)
dlen = d;
}
__device__ void dry_build(DryShared& d, const int* hrow, int hlen, int dlen, const SamplerParams& p,
const DryBreakers& br) {
d.n = 0;
if (!dry_enabled(p) || dlen <= p.dry_allowed_length) return;
const int nb = br.n;
const int* bf = br.flat;
const int* bo = br.off;
auto rat = [&](int x) -> int { return hrow[hlen - 1 - x]; };
// Step 1: the nearest restart sequence (a head token with its tail tokens closer to the end) bounds the
// longest repeat we care about.
int rep_limit = dlen;
for (int i = 0; i < dlen; ++i) {
const int token = rat(i);
int longest = -1;
for (int b = 0; b < nb; ++b) {
if (bf[bo[b]] != token) continue;
const int sl = bo[b + 1] - bo[b] - 1;
if (sl > longest && sl <= i) {
bool match = true;
for (int off = 0; off < sl; ++off)
if (bf[bo[b] + 1 + off] != rat(i - off - 1)) { match = false; break; }
if (match) longest = sl;
}
}
if (longest >= 0) { rep_limit = i - longest; break; }
}
if (rep_limit < p.dry_allowed_length) return;
// Step 2: the reverse Z-algorithm, suffix length capped at `rep_limit`.
const int last = dlen - 1;
int rt = 0, lt = 0;
for (int k = 1; k < dlen; ++k) {
if (k > rt) {
int n = 0;
while (n + k < dlen && rat(n) == rat(n + k)) ++n;
d.drep[last - k] = n < rep_limit ? n : rep_limit;
if (n > 0) { lt = k; rt = k + n - 1; }
} else {
const int pp = k - lt, rpl = rt - k + 1;
if (d.drep[last - pp] < rpl) {
d.drep[last - k] = d.drep[last - pp] < rep_limit ? d.drep[last - pp] : rep_limit;
} else {
int i = rt + 1;
while (i < dlen && rat(i) == rat(i - k)) ++i;
const int n = (i - k) < rep_limit ? (i - k) : rep_limit;
d.drep[last - k] = n;
lt = k;
rt = i - 1;
}
}
}
// Step 3: each position whose repeat is long enough names the next token, which would extend it.
for (int i = 0; i < dlen - 1; ++i) {
const int repeat_len = d.drep[i];
if (repeat_len < p.dry_allowed_length) continue;
const int token = rat(dlen - 2 - i);
int j = 0;
for (; j < d.n; ++j) if (d.tok[j] == token) break;
if (j == d.n) { d.tok[d.n] = token; d.len[d.n] = repeat_len; ++d.n; }
else if (d.len[j] < repeat_len) d.len[j] = repeat_len;
}
}
__device__ __forceinline__ float apply_dry(float s, int v, const SamplerParams& p, const DryShared& d,
const DryBreakers& br) {
if (d.n <= 0) return s;
int rep = -1;
for (int j = 0; j < d.n; ++j) if (d.tok[j] == v) { rep = d.len[j]; break; }
if (rep < 0) return s;
// A single-token restart sequence (an empty tail) is never penalised.
for (int b = 0; b < br.n; ++b)
if (br.flat[br.off[b]] == v && br.off[b + 1] - br.off[b] == 1) return s;
int exp = rep - p.dry_allowed_length;
int max_exp = 0;
if (p.dry_base > 1.000001f) max_exp = (int) (88.7228391f / logf(p.dry_base)); // overflow guard
if (max_exp > 0 && exp > max_exp) exp = max_exp;
return s - p.dry_multiplier * powf(p.dry_base, (float) exp);
}
/// **THE GREEDY ARGMAX, ONE BLOCK PER TOKEN, COVERING THE VOCABULARY.**
///
/// **WHY THIS IS A SEPARATE KERNEL AND NOT A BRANCH.** `sampler_kernel` is launched as a grid over TOKENS
@@ -101,47 +208,57 @@ __device__ __forceinline__ float apply_penalties(float logit, int count, const S
/// SMALLER index - the same total order, so `sampler_parity` and C1 see no change.
__global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vocab,
const int* __restrict__ history, int history_len, const SamplerParams p,
int pmin, int plen, int* __restrict__ out) {
int pmin, int plen, int* __restrict__ out, const DryBreakers br) {
const int t = blockIdx.x;
const float* l = logits + (size_t) t * n_vocab;
(void) pmin;
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
const int* hbase = history ? history + (size_t) t * history_len : nullptr;
const int* hrow = hbase;
int hlen = 0;
if (hrow) {
if (hbase) {
hlen = plen < history_len ? plen : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the window is the TAIL
hrow += history_len - hlen; // the penalty window is the TAIL
}
const int* drow = nullptr;
int dlen = 0;
if (hbase) dry_window(hbase, history_len, p.dry_penalty_last_n, drow, dlen);
// PENALTY MEMBERSHIP AS A BITMAP. The history touches at most `hlen` tokens of a quarter-million
// vocabulary, but the naive `history_count` per candidate per argmax round costs O(k x n_vocab x hlen)
// integer compares (~318 M per token at k=20, hlen=64 - measured 45 -> 31 tok/s on a real workload).
// A shared bitmap gives an O(1) membership test, and only the (at most hlen) hits pay the count scan;
// the counts - and therefore every sampled value - are exactly what the per-candidate scan produced.
// The bitmap spans the WIDEST of the penalty and DRY windows, so it also gates the DRY lookup.
extern __shared__ unsigned int penal_bits[];
const int bits_words = (int) ((n_vocab + 31) / 32);
// The gate needs a NON-EMPTY WINDOW (`hlen > 0`): the launch sizes the shared bitmap only when penalties
// are on, so a caller handing over a history buffer with `penalty_last_n == 0` must not touch it.
const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
const int wlen = hlen > dlen ? hlen : dlen;
const int* wrow = (hbase && wlen > 0) ? hbase + history_len - wlen : nullptr;
// The gate needs a NON-EMPTY WINDOW (`wlen > 0`): the launch sizes the shared bitmap only when penalties or
// DRY are on, so a caller handing over a history buffer with `penalty_last_n == 0` must not touch it.
const bool use_bits = wrow != nullptr && bits_words > 0;
if (use_bits) {
for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < hlen; i += blockDim.x)
if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
for (int i = threadIdx.x; i < wlen; i += blockDim.x)
if (wrow[i] >= 0 && wrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[wrow[i] >> 5], 1u << (wrow[i] & 31));
__syncthreads();
}
auto hit_count = [&](int v) -> int {
if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
return history_count(hrow, hlen, v);
};
__shared__ DryShared g_dry;
if (threadIdx.x == 0) dry_build(g_dry, drow, dlen, dlen, p, br);
__syncthreads();
// `n_vocab` is the "no candidate" index: it loses every comparison to a real one, so a thread with no
// elements contributes nothing rather than contributing a bogus zero.
float bv = __int_as_float(0xff800000); // -inf
int best = n_vocab;
for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
const float s = apply_penalties(l[v], hit_count(v), p);
float s = l[v];
if (use_bits && (penal_bits[v >> 5] & (1u << (v & 31)))) {
s = apply_penalties(s, history_count(hrow, hlen, v), p);
s = apply_dry(s, v, p, g_dry, br);
}
if (s > bv) { bv = s; best = v; }
}
for (int off = 16; off > 0; off >>= 1) {
@@ -278,7 +395,7 @@ __global__ void __launch_bounds__(kAmThreads) sampler_greedy_cluster_kernel(cons
/// 1/64 of FP32. The kernels after this one remove both and select the same list in the same order.
__global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, int n_tokens,
const int* __restrict__ history, int history_len, const SamplerParams p,
int* __restrict__ out) {
int* __restrict__ out, const DryBreakers br) {
const int t = blockIdx.x;
if (t >= n_tokens) return;
const float* l = logits + (size_t) t * n_vocab;
@@ -289,32 +406,38 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, in
// The penalty window is the last `penalty_last_n` entries of this row's history (disabled at this
// launch: `sample_tokens` refuses a non-zero `penalty_last_n` without a history buffer).
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
const int* hbase = history ? history + (size_t) t * history_len : nullptr;
const int* hrow = hbase;
int hlen = 0;
if (hrow) {
if (hbase) {
hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the window is the TAIL
hrow += history_len - hlen; // the penalty window is the TAIL
}
const int* drow = nullptr;
int dlen = 0;
if (hbase) dry_window(hbase, history_len, p.dry_penalty_last_n, drow, dlen);
// the membership bitmap, as in `sampler_greedy_kernel` - see the cost note there. The gate needs an
// NON-EMPTY WINDOW too: the launch sizes the bitmap only when penalties are on, so a caller that hands over
// a stale history buffer with `penalty_last_n == 0` must not touch it.
// NON-EMPTY WINDOW too: the launch sizes the bitmap only when penalties or DRY are on, so a caller that hands
// over a stale history buffer with `penalty_last_n == 0` must not touch it. The bitmap spans the widest of
// the penalty and DRY windows, so it gates the DRY lookup too.
extern __shared__ unsigned int penal_bits[];
const int bits_words = (int) ((n_vocab + 31) / 32);
const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
const int wlen = hlen > dlen ? hlen : dlen;
const int* wrow = (hbase && wlen > 0) ? hbase + history_len - wlen : nullptr;
const bool use_bits = wrow != nullptr && bits_words > 0;
if (use_bits) {
for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < hlen; i += blockDim.x)
if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
for (int i = threadIdx.x; i < wlen; i += blockDim.x)
if (wrow[i] >= 0 && wrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[wrow[i] >> 5], 1u << (wrow[i] & 31));
__syncthreads();
}
auto hit_count = [&](int v) -> int {
if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
return history_count(hrow, hlen, v);
};
__shared__ DryShared g_dry;
if (threadIdx.x == 0) dry_build(g_dry, drow, dlen, dlen, p, br);
__syncthreads();
// top_k in 1..64 is taken as given; 0 ("off") and anything wider mean the widest shortlist the kernel
// keeps, 64. Every row writes out[t]: a verify window reads all of them.
@@ -338,7 +461,11 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, in
bool taken = false;
for (int j = 0; j < i; ++j) if (sel_ids[j] == v) { taken = true; break; }
if (taken) continue;
const float s = apply_penalties(l[v], hit_count(v), p);
float s = l[v];
if (use_bits && (penal_bits[v >> 5] & (1u << (v & 31)))) {
s = apply_penalties(s, history_count(hrow, hlen, v), p);
s = apply_dry(s, v, p, g_dry, br);
}
if (s > bv) { bv = s; best = v; }
}
for (int off = 16; off > 0; off >>= 1) {
@@ -524,33 +651,38 @@ __device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, in
/// 0 runs the tail. `STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split path cannot run.
__global__ void __launch_bounds__(1024)
sampler_one_block_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history,
int history_len, const SamplerParams p, int* __restrict__ out) {
int history_len, const SamplerParams p, int* __restrict__ out, const DryBreakers br) {
const int t = blockIdx.x;
const float* l = logits + (size_t) t * n_vocab;
// the penalty window and its membership bitmap, exactly as in `sampler_kernel`
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
const int* hbase = history ? history + (size_t) t * history_len : nullptr;
const int* hrow = hbase;
int hlen = 0;
if (hrow) {
if (hbase) {
hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the window is the TAIL
hrow += history_len - hlen; // the penalty window is the TAIL
}
const int* drow = nullptr;
int dlen = 0;
if (hbase) dry_window(hbase, history_len, p.dry_penalty_last_n, drow, dlen);
extern __shared__ unsigned int penal_bits[];
const int bits_words = (int) ((n_vocab + 31) / 32);
const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
const int wlen = hlen > dlen ? hlen : dlen;
const int* wrow = (hbase && wlen > 0) ? hbase + history_len - wlen : nullptr;
const bool use_bits = wrow != nullptr && bits_words > 0;
if (use_bits) {
for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < hlen; i += blockDim.x)
if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
for (int i = threadIdx.x; i < wlen; i += blockDim.x)
if (wrow[i] >= 0 && wrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[wrow[i] >> 5], 1u << (wrow[i] & 31));
__syncthreads();
}
auto hit_count = [&](int v) -> int {
if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
return history_count(hrow, hlen, v);
};
__shared__ DryShared g_dry;
if (threadIdx.x == 0) dry_build(g_dry, drow, dlen, dlen, p, br);
__syncthreads();
const int k = sampled_k(p.top_k, n_vocab);
__shared__ int sel_ids[kSelMax];
@@ -565,7 +697,11 @@ sampler_one_block_kernel(const float* __restrict__ logits, int n_vocab, const in
float bv = __int_as_float(0xff800000); // -inf
int best = n_vocab;
for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
const float s = apply_penalties(l[v], hit_count(v), p);
float s = l[v];
if (use_bits && (penal_bits[v >> 5] & (1u << (v & 31)))) {
s = apply_penalties(s, history_count(hrow, hlen, v), p);
s = apply_dry(s, v, p, g_dry, br);
}
if ((s < prev_v || (s == prev_v && v > prev_i)) && s > bv) { bv = s; best = v; }
}
for (int off = 16; off > 0; off >>= 1) {
@@ -659,33 +795,44 @@ __device__ __forceinline__ void warp_merge_lists(const int2* lists, int nl, int
/// (row-major: row t, block b, entry i at `(t * n_blocks + b) * k + i`, as (id, value bits)).
__global__ void __launch_bounds__(kSplitWarps * 32)
sampler_split_part_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history,
int history_len, const SamplerParams p, int k, int n_blocks, int2* __restrict__ cand) {
int history_len, const SamplerParams p, int k, int n_blocks, int2* __restrict__ cand,
const DryBreakers br) {
const int t = blockIdx.y;
const float* l = logits + (size_t) t * n_vocab;
const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
const int blo = (int) blockIdx.x * kSplitBlockSpan;
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
const int* hbase = history ? history + (size_t) t * history_len : nullptr;
const int* hrow = hbase;
int hlen = 0;
if (hrow) {
if (hbase) {
hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the window is the TAIL
hrow += history_len - hlen; // the penalty window is the TAIL
}
const int* drow = nullptr;
int dlen = 0;
if (hbase) dry_window(hbase, history_len, p.dry_penalty_last_n, drow, dlen);
const int wlen = hlen > dlen ? hlen : dlen;
const int* wrow = (hbase && wlen > 0) ? hbase + history_len - wlen : nullptr;
// The membership bitmap of THIS BLOCK'S 4,096 logits (512 bytes, not the vocabulary's 31 KB): the same test,
// and a hit pays the same exact count over the whole window.
// and a hit pays the same exact count over the whole window. It spans the widest of the penalty and DRY
// windows, so it also gates the DRY lookup.
__shared__ unsigned int bits[kSplitBlockSpan / 32];
const bool use_bits = hrow != nullptr && hlen > 0;
const bool use_bits = wrow != nullptr;
if (use_bits) {
for (int w = threadIdx.x; w < kSplitBlockSpan / 32; w += blockDim.x) bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < hlen; i += blockDim.x) {
const int h = hrow[i];
for (int i = threadIdx.x; i < wlen; i += blockDim.x) {
const int h = wrow[i];
if (h >= 0 && h < n_vocab && h >= blo && h - blo < kSplitBlockSpan)
atomicOr(&bits[(h - blo) >> 5], 1u << ((h - blo) & 31));
}
__syncthreads();
}
__shared__ DryShared g_dry;
if (threadIdx.x == 0) dry_build(g_dry, drow, dlen, dlen, p, br);
__syncthreads();
// This warp's logits, penalised: `apply_penalties` with a zero count returns the logit unchanged, so only the
// bitmap's hits go through it. Past the vocabulary: -inf, which no round picks.
@@ -700,8 +847,10 @@ sampler_split_part_kernel(const float* __restrict__ logits, int n_vocab, const i
#pragma unroll
for (int j = 0; j < kSplitPerLane; ++j) {
const int v = lo + 32 * j + lane, b = v - blo;
if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31))))
if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31)))) {
s[j] = apply_penalties(s[j], history_count(hrow, hlen, v), p);
s[j] = apply_dry(s[j], v, p, g_dry, br);
}
}
}
@@ -783,23 +932,34 @@ __global__ void coupled_stage_kernel(const SamplerParams* __restrict__ mp, const
/// subset has no logit here. Each distinct token is penalised once: the entry whose `atomicOr` sets its bit does it.
__global__ void coupled_penalize_kernel(float* __restrict__ logits, int nv, const int* __restrict__ id_to_sub,
int id_vocab, const SamplerParams* __restrict__ dp, const int* __restrict__ ring,
int cap, int j) {
int cap, int j, const DryBreakers br) {
const SamplerParams p = *dp;
const int h = strata::core::coupled_hist_len(p.penalty_last_n, cap);
if (h <= 0) return;
const int* hrow = ring + strata::core::coupled_hist_start(cap, j, h);
const int hd = strata::core::coupled_hist_len(p.dry_penalty_last_n, cap);
const int wlen = h > hd ? h : hd;
const int* hrow = ring + strata::core::coupled_hist_start(cap, j, h); // the penalty sub-window
const int* drow = ring + cap + j - hd; // the DRY sub-window (dropping -1 padding)
int dlen = hd;
while (dlen > 0 && drow[0] == -1) { ++drow; --dlen; }
__shared__ DryShared g_dry;
if (threadIdx.x == 0) dry_build(g_dry, drow, dlen, dlen, p, br);
if (wlen <= 0) { __syncthreads(); return; }
const int* wrow = ring + cap + j - wlen; // the union: both lookups are gated by it
extern __shared__ unsigned int seen[];
const int words = (nv + 31) / 32;
for (int w = threadIdx.x; w < words; w += blockDim.x) seen[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < h; i += blockDim.x) {
const int v = hrow[i];
for (int i = threadIdx.x; i < wlen; i += blockDim.x) {
const int v = wrow[i];
if (v < 0 || v >= id_vocab) continue;
const int s = id_to_sub != nullptr ? id_to_sub[v] : v;
if (s < 0 || s >= nv) continue;
const unsigned bit = 1u << (s & 31);
if (atomicOr(&seen[s >> 5], bit) & bit) continue;
logits[s] = apply_penalties(logits[s], history_count(hrow, h, v), p);
float x = logits[s];
x = apply_penalties(x, history_count(hrow, h, v), p);
x = apply_dry(x, v, p, g_dry, br);
logits[s] = x;
}
}
@@ -975,14 +1135,22 @@ bool sample_greedy_cluster(const float* logits, int n_tokens, int n_vocab, int*
}
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
const SamplerParams& p, int* out, void* stream) {
const SamplerParams& p, int* out, void* stream, const DryBreakers& breakers) {
if (n_tokens <= 0 || n_vocab <= 0) return;
if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) {
const bool has_hist = history != nullptr && history_len > 0;
if (p.penalty_last_n > 0 && !has_hist) {
std::fprintf(stderr, "sample_tokens: penalty_last_n %d needs a history (got %p, len %d)\n",
p.penalty_last_n, (const void*) history, history_len);
std::exit(1);
}
const unsigned shmem = (history != nullptr && history_len > 0 && p.penalty_last_n > 0)
if (dry_enabled(p) && !has_hist) {
std::fprintf(stderr, "sample_tokens: dry_penalty_last_n %d needs a history (got %p, len %d)\n",
p.dry_penalty_last_n, (const void*) history, history_len);
std::exit(1);
}
// The bitmap spans the widest of the penalty and DRY windows, so it is sized (and the cluster kernel, which
// needs shmem == 0, is disabled) when EITHER is on.
const unsigned shmem = (has_hist && (p.penalty_last_n > 0 || dry_enabled(p)))
? (unsigned) ((n_vocab + 31) / 32) * sizeof(unsigned) // the penalty bitmap
: 0;
if (p.greedy || p.temperature <= 0.0f) {
@@ -996,12 +1164,12 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi
const int gthreads = 1024;
if (!(multi && shmem == 0 && sample_greedy_cluster(logits, n_tokens, n_vocab, out, stream)))
sampler_greedy_kernel<<<(unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream>>>(
logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out);
logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out, breakers);
} else if (sampled_path() == SampledPath::Old) {
// The same block-per-token shape: the selection's k argmax rounds reduce inside the block. See
// `sampler_kernel`'s header for what the old one-thread-per-token launch cost.
sampler_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>(
logits, n_vocab, n_tokens, history, history_len, p, out);
logits, n_vocab, n_tokens, history, history_len, p, out, breakers);
} else {
// The split top_k by default: stage 1 over (61 blocks x rows) for 248,320 logits, stage 2 one warp per
// row. The one-block kernel when asked for, or when the split cannot run: a wider vocabulary than the merge
@@ -1017,12 +1185,12 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi
if (scratch != nullptr) {
sampler_split_part_kernel<<<dim3((unsigned) n_blocks, (unsigned) n_tokens), kSplitWarps * 32, 0,
(cudaStream_t) stream>>>(logits, n_vocab, history, history_len, p, k,
n_blocks, scratch);
n_blocks, scratch, breakers);
sampler_split_merge_kernel<<<(unsigned) n_tokens, 32, 0, (cudaStream_t) stream>>>(
scratch, n_blocks, n_vocab, p, k, out);
} else {
sampler_one_block_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>(
logits, n_vocab, history, history_len, p, out);
logits, n_vocab, history, history_len, p, out, breakers);
}
}
const cudaError_t e = cudaGetLastError();
@@ -1058,20 +1226,21 @@ void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapp
void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
void* scratch, int32_t* out_id, float* out_prob, void* stream) {
void* scratch, int32_t* out_id, float* out_prob, void* stream, const DryBreakers& breakers) {
const cudaStream_t s = (cudaStream_t) stream;
const int n_blocks = coupled_blocks(nv), kpart = coupled_kpart(nv);
if (nv <= 0 || n_blocks > kSplitMaxBlocks || scratch == nullptr) {
std::fprintf(stderr, "coupled_draft_sample: %d logits need scratch and at most %d blocks\n", nv, kSplitMaxBlocks);
std::exit(1);
}
coupled_penalize_kernel<<<1, 1024, (unsigned) ((nv + 31) / 32) * sizeof(unsigned), s>>>(logits, nv, id_to_sub,
id_vocab, params, ring, cap, j);
coupled_penalize_kernel<<<1, 1024, (unsigned) ((nv + 31) / 32) * sizeof(unsigned), s>>>(
logits, nv, id_to_sub, id_vocab, params, ring, cap, j, breakers);
coupled_check("coupled_penalize");
// the selection of the split sampler, unchanged: every 4,096-logit block's first `kpart` (the widest list,
// since the request's top_k is only known on the device), penalties already applied above
// since the request's top_k is only known on the device), penalties and DRY already applied above (the null
// history here keeps the split kernel from applying them a second time)
sampler_split_part_kernel<<<dim3((unsigned) n_blocks, 1u), kSplitWarps * 32, 0, s>>>(
logits, nv, nullptr, 0, SamplerParams{}, kpart, n_blocks, (int2*) scratch);
logits, nv, nullptr, 0, SamplerParams{}, kpart, n_blocks, (int2*) scratch, DryBreakers{});
coupled_check("coupled_draft split part");
coupled_merge_kernel<<<1, 32, 0, s>>>((const int2*) scratch, n_blocks, nv, kpart, params, step_rec, sub_to_id, ring,
cap, j, out_id, out_prob);
+156 -8
View File
@@ -20,6 +20,7 @@
#include <limits>
#include <random>
#include <string>
#include <unordered_map>
#include <vector>
namespace {
@@ -31,6 +32,65 @@ void check(cudaError_t e, const char* what) {
}
}
// ---- DRY host reference, transcribed from llama.cpp's `llama_sampler_dry_apply` (Step 1 restart sequences,
// then a NAIVE repeat-length computation in place of the Z-algorithm: an independent check of the device's
// Z-array). `hist` is the row, oldest to newest; only its last `dry_penalty_last_n` entries are read. The
// result is token -> maximum repeat length, from which Step 4 subtracts `multiplier * base^(len - allowed)`.
std::unordered_map<int, int> host_dry_map(const std::vector<int>& hist, const strata::kernels::SamplerParams& p,
const std::vector<std::vector<int>>& breakers) {
std::unordered_map<int, int> out;
if (!strata::kernels::dry_enabled(p)) return out;
const int dlen = (int) std::min<size_t>((size_t) std::max(p.dry_penalty_last_n, 0), hist.size());
if (dlen <= p.dry_allowed_length) return out;
auto rat = [&](int x) { return hist[(size_t) (dlen - 1 - x)]; }; // rat(0) is the newest token
int rep_limit = dlen;
for (int i = 0; i < dlen; ++i) {
const int token = rat(i);
int longest = -1;
for (const auto& s : breakers) {
if (s.empty() || s[0] != token) continue;
const int sl = (int) s.size() - 1; // the tail length (head already matched)
if (sl > longest && sl <= i) {
bool match = true;
for (int off = 0; off < sl; ++off)
if (s[(size_t) (1 + off)] != rat(i - off - 1)) { match = false; break; }
if (match) longest = sl;
}
}
if (longest >= 0) { rep_limit = i - longest; break; }
}
if (rep_limit < p.dry_allowed_length) return out;
const int last = dlen - 1;
std::vector<int> drep((size_t) dlen, 0);
for (int k = 1; k < dlen; ++k) {
int n = 0;
while (n + k < dlen && rat(n) == rat(n + k)) ++n;
drep[(size_t) (last - k)] = std::min(n, rep_limit);
}
for (int i = 0; i < dlen - 1; ++i) {
const int repeat_len = drep[(size_t) i];
if (repeat_len >= p.dry_allowed_length) {
const int token = rat(dlen - 2 - i);
auto it = out.find(token);
if (it == out.end() || it->second < repeat_len) out[token] = repeat_len;
}
}
return out;
}
bool host_single_token_breaker(int id, const std::vector<std::vector<int>>& breakers) {
for (const auto& s : breakers) if (s.size() == 1 && s[0] == id) return true;
return false;
}
float host_dry_penalty(int repeat_len, const strata::kernels::SamplerParams& p) {
int max_exponent = 0;
if (p.dry_base > 1.000001f) max_exponent = (int) (88.7228391f / std::log(p.dry_base));
int e = repeat_len - p.dry_allowed_length;
if (max_exponent > 0 && e > max_exponent) e = max_exponent;
return p.dry_multiplier * std::pow(p.dry_base, (float) e);
}
// The host reference for the specified order: top_k -> top_p -> temperature -> argmax.
// `temp_first` swaps the first and last stages, which is the intuitive-but-wrong order.
int reference_pick(const std::vector<float>& l, const strata::kernels::SamplerParams& p, bool temp_first) {
@@ -102,7 +162,8 @@ int reference_cut(const std::vector<float>& l, const strata::kernels::SamplerPar
}
int run(const char* name, const std::vector<float>& logits, int n_tokens, const strata::kernels::SamplerParams& p,
const std::vector<int>& want, const std::vector<int>& hist = {}, int hist_len = 0) {
const std::vector<int>& want, const std::vector<int>& hist = {}, int hist_len = 0,
const std::vector<std::vector<int>>* breakers = nullptr) {
float* d_l = nullptr;
int* d_o = nullptr;
check(cudaMalloc(&d_l, logits.size() * sizeof(float)), "malloc logits");
@@ -116,8 +177,27 @@ int run(const char* name, const std::vector<float>& logits, int n_tokens, const
check(cudaMalloc(&d_h, hist.size() * sizeof(int)), "malloc hist");
check(cudaMemcpy(d_h, hist.data(), hist.size() * sizeof(int), cudaMemcpyHostToDevice), "copy hist");
}
// The DRY breakers as the device wants them: a flat id array plus `n + 1` offsets.
strata::kernels::DryBreakers br;
int* d_bf = nullptr;
int* d_bo = nullptr;
std::vector<int> flat, off;
if (breakers != nullptr && !breakers->empty()) {
off.push_back(0);
for (const auto& s : *breakers) {
for (int id : s) flat.push_back(id);
off.push_back((int) flat.size());
}
check(cudaMalloc(&d_bf, flat.size() * sizeof(int)), "malloc breakers flat");
check(cudaMemcpy(d_bf, flat.data(), flat.size() * sizeof(int), cudaMemcpyHostToDevice), "copy breakers flat");
check(cudaMalloc(&d_bo, off.size() * sizeof(int)), "malloc breakers off");
check(cudaMemcpy(d_bo, off.data(), off.size() * sizeof(int), cudaMemcpyHostToDevice), "copy breakers off");
br.flat = d_bf;
br.off = d_bo;
br.n = (int) breakers->size();
}
strata::kernels::sample_tokens(d_l, n_tokens, (int) (logits.size() / n_tokens), d_h, hist_len, p, d_o,
nullptr);
nullptr, br);
std::vector<int> got((size_t) n_tokens);
check(cudaMemcpy(got.data(), d_o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back");
int bad = 0;
@@ -128,6 +208,8 @@ int run(const char* name, const std::vector<float>& logits, int n_tokens, const
cudaFree(d_l);
cudaFree(d_o);
if (d_h) cudaFree(d_h);
if (d_bf) cudaFree(d_bf);
if (d_bo) cudaFree(d_bo);
return bad;
}
@@ -162,11 +244,18 @@ float host_philox_uniform(uint64_t seed, uint64_t counter) {
// the top_k list, the min_p prefix cut on its survivors, the temperature, and one Philox draw at
// (seed, counter + row). One penalties stage (issue #53: this reference used to repeat the kernel's second one).
int sampled_reference(const std::vector<float>& l, const std::vector<int>& hist,
const strata::kernels::SamplerParams& p, int row) {
auto penal = [&](float logit, int count) {
if (count <= 0) return logit;
if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat;
logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
const strata::kernels::SamplerParams& p, int row,
const std::vector<std::vector<int>>* breakers = nullptr) {
const std::unordered_map<int, int> dry = breakers ? host_dry_map(hist, p, *breakers)
: std::unordered_map<int, int>{};
auto penal = [&](float logit, int count, int v) {
if (count > 0) {
if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat;
logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
}
const auto it = dry.find(v);
if (it != dry.end() && !(breakers && host_single_token_breaker(v, *breakers)))
logit -= host_dry_penalty(it->second, p);
return logit;
};
auto count = [&](int v) { int c = 0; for (int h : hist) if (h == v) ++c; return c; };
@@ -180,7 +269,7 @@ int sampled_reference(const std::vector<float>& l, const std::vector<int>& hist,
int best = -1; float bv = 0;
for (int v = 0; v < nv; ++v) {
if (taken[(size_t) v]) continue;
const float s = penal(l[(size_t) v], count(v));
const float s = penal(l[(size_t) v], count(v), v);
if (best < 0 || s > bv) { best = v; bv = s; }
}
taken[(size_t) best] = 1;
@@ -996,6 +1085,65 @@ int main(int argc, char** argv) {
bad += wrong;
}
// ---- fixture 19: DRY (llama.cpp's `dry` sampler). A window of the last `dry_penalty_last_n` tokens is
// scanned for repeats; a token that would EXTEND a repeat longer than `dry_allowed_length` loses
// `mult * base^(len - allowed)`. The window here is 7 9 7 9 7 9 (newest last): the longest repeat is 4 and
// the token that continues it is 7, so token 7 is penalised 1.0 * 1.75^2 = 3.0625 and loses to token 9.
// Two breaker cases pin Step 1: the single-token breaker [7] makes 7 a restart head and it is NOT penalised
// (llama.cpp's empty tail rule); the multi-token breaker [9, 7] caps `rep_limit` at 1 so DRY does nothing.
{
const int W = 6, NVd = 16;
const std::vector<int> win = {7, 9, 7, 9, 7, 9};
std::vector<float> row((size_t) NVd, -8.0f);
row[7] = 5.0f; row[9] = 4.5f; row[3] = 4.0f;
strata::kernels::SamplerParams p;
p.greedy = true; p.temperature = 0.0f; p.top_k = 0; p.top_p = 1.0f;
p.penalty_last_n = 0; // DRY only, so the reference's count scan cannot interfere
p.dry_multiplier = 1.0f; p.dry_base = 1.75f; p.dry_allowed_length = 2; p.dry_penalty_last_n = W;
const std::vector<std::vector<int>> none = {};
const std::vector<std::vector<int>> single = {{7}};
const std::vector<std::vector<int>> multi = {{9, 7}};
auto greedy_dry = [&](const std::vector<std::vector<int>>& br) {
const std::unordered_map<int, int> map = host_dry_map(win, p, br);
int best = 0; float bv = 0; bool first = true;
for (int v = 0; v < NVd; ++v) {
float s = row[(size_t) v];
const auto it = map.find(v);
if (it != map.end() && !host_single_token_breaker(v, br)) s -= host_dry_penalty(it->second, p);
if (first || s > bv) { bv = s; best = v; first = false; }
}
return best;
};
const int d_none = greedy_dry(none), d_single = greedy_dry(single), d_multi = greedy_dry(multi);
const bool observable = d_none == 9 && d_single == 7 && d_multi == 7;
std::printf(" %-34s %s (dry %d, single-token breaker %d, multi-token breaker %d)\n",
"DRY changes the pick", observable ? "yes" : "*** NO ***", d_none, d_single, d_multi);
if (!observable) ++bad;
else {
bad += run("DRY: no breakers (greedy)", row, 1, p, {d_none}, win, W, &none);
bad += run("DRY: single-token breaker", row, 1, p, {d_single}, win, W, &single);
bad += run("DRY: multi-token breaker", row, 1, p, {d_multi}, win, W, &multi);
}
// The sampled chain over the same window: the full chain with the host Philox must match draw for draw.
// Every row carries the same window, so the history buffer is 64 rows of it (the kernel reads one row
// per sampled row at a stride of `history_len`).
const int NTd = 64;
std::vector<float> l((size_t) NVd * NTd);
std::vector<int> hrows((size_t) NTd * W);
for (int t = 0; t < NTd; ++t) {
std::copy(row.begin(), row.end(), l.begin() + (size_t) t * NVd);
std::copy(win.begin(), win.end(), hrows.begin() + (size_t) t * W);
}
strata::kernels::SamplerParams sp = p;
sp.greedy = false; sp.temperature = 1.0f; sp.top_k = 4; sp.top_p = 1.0f; sp.seed = 19; sp.counter = 0;
std::vector<int> want((size_t) NTd);
for (int t = 0; t < NTd; ++t) want[(size_t) t] = sampled_reference(row, win, sp, t, &none);
bad += run("DRY: sampled chain", l, NTd, sp, want, hrows, W, &none);
}
// A continuous stream and individual decode calls consume the same draw counters.
{
constexpr int count = 32, vocab = 16;
+81 -1
View File
@@ -5405,6 +5405,20 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata serve: the penalty-history allocation failed\n");
return 1;
}
// DRY's tokenized sequence breakers: device arrays on the head's device, allocated once (the pointers must
// stay put for the captured coupled-draft graph) and refilled per request from the request's `dry_breakers`.
constexpr int kDryBreakersCap = 64; // restart sequences a request may name
constexpr int kDryFlatCap = 1024; // token ids over all of them
int32_t* d_dry_flat = nullptr;
int32_t* d_dry_off = nullptr;
{
const strata::core::OnDevice on_h(hist_dev);
if (cudaMalloc(&d_dry_flat, kDryFlatCap * sizeof(int32_t)) != cudaSuccess ||
cudaMalloc(&d_dry_off, (kDryBreakersCap + 1) * sizeof(int32_t)) != cudaSuccess) {
std::fprintf(stderr, "strata serve: the DRY-breaker allocation failed\n");
return 1;
}
}
strata::core::Verifier ver;
strata::core::VerifyHits vh;
vh.d_res = thits.d_res;
@@ -5514,6 +5528,30 @@ int main(int argc, char** argv) {
// issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy
// kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests).
ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2);
// ---- CAPTURE EVERY WINDOW SIZE HERE, NOT ON THE FIRST REQUEST THAT USES IT. cudaGraphInstantiate
// allocates device memory per size and the exec is never freed (measured ~22-26 MiB per size on a GTX
// 1070 Ti, 2026-10-15); a size captured lazily drew on the reserve the cache had been sized against, and a
// request that needed a size not yet captured died with "verify: instantiate: out of memory" and took the
// engine down with it. Doing it here makes that cost part of what the free-VRAM check below sees and bounds
// it before any request runs; a size that does not fit is reported now, with the way to make room.
{
const int win_max_t = std::max(o.spec, o.batch);
const int64_t kWindowGraphMib = 32; // one exec per size; 26 MiB measured on the 1070 Ti, rounded up
for (int T = 1; T <= win_max_t; ++T) {
for (int st = 0; st < n_stages; ++st) {
std::string cerr;
if (!stage_ver(st).capture_window(T, cerr)) {
std::fprintf(stderr, "strata serve: %s\n", cerr.c_str());
std::fprintf(stderr, "strata serve: the verify window needs one captured graph per size "
"(1..%d), about %lld MiB of VRAM beyond its buffers; it does not fit "
"beside this cache - lower --max-context, raise --vram-reserve-mib, or "
"close other programs that use the GPU\n",
win_max_t, (long long) win_max_t * (long long) kWindowGraphMib);
return 1;
}
}
}
}
std::vector<int64_t> cur;
// ---- the conversation cache (see ConvCheckpoint). `live` is what the session holds right now: the tokens
// it has consumed, so a request that starts with exactly them continues without any copy. `checks` are the
@@ -6631,6 +6669,11 @@ int main(int argc, char** argv) {
unsigned long long req_seed = 0;
float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f;
int req_penalty_last_n = 0;
// DRY (llama.cpp's `dry` sampler): `dry_breakers` is the tokenizer's restart sequences, sequences
// separated by '|' and their ids by ',' (the front end tokenizes them; this engine has no tokenizer).
float req_dry_multiplier = 0.0f, req_dry_base = 1.75f;
int req_dry_allowed_length = 2, req_dry_penalty_last_n = 0;
std::string req_dry_breakers;
int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent)
// tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of
// the missed experts and the draft-probability floor, for this request only
@@ -6656,6 +6699,11 @@ int main(int argc, char** argv) {
else if (key == "penalty_repeat") req_penalty_repeat = fv;
else if (key == "penalty_freq") req_penalty_freq = fv;
else if (key == "penalty_present") req_penalty_present = fv;
else if (key == "dry_multiplier") req_dry_multiplier = fv;
else if (key == "dry_base") req_dry_base = fv;
else if (key == "dry_allowed_length") req_dry_allowed_length = std::atoi(tok.c_str() + eq + 1);
else if (key == "dry_penalty_last_n") req_dry_penalty_last_n = std::atoi(tok.c_str() + eq + 1);
else if (key == "dry_breakers") req_dry_breakers = tok.substr(eq + 1);
else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10);
else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0);
else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0);
@@ -7329,15 +7377,47 @@ int main(int argc, char** argv) {
req_sp.penalty_repeat = req_penalty_repeat;
req_sp.penalty_freq = req_penalty_freq;
req_sp.penalty_present = req_penalty_present;
req_sp.dry_multiplier = req_dry_multiplier;
req_sp.dry_base = req_dry_base;
req_sp.dry_allowed_length = std::max(req_dry_allowed_length, 0);
req_sp.dry_penalty_last_n = std::max(req_dry_penalty_last_n, 0);
req_sp.counter = 0;
ver.set_sampling(req_sp);
mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise)
// DRY's tokenized breakers, parsed from "id,id|id|...": flatten the sequences and upload them. The
// device arrays are stable (allocated once), so the captured coupled-draft graph keeps valid pointers.
std::vector<int32_t> dry_flat, dry_off(1, 0);
if (!req_dry_breakers.empty()) {
for (size_t p = 0; p < req_dry_breakers.size() && (int) dry_off.size() <= kDryBreakersCap;) {
const size_t bar = req_dry_breakers.find('|', p);
const size_t end = bar == std::string::npos ? req_dry_breakers.size() : bar;
for (size_t q = p; q < end && (int) dry_flat.size() < kDryFlatCap;) {
const size_t comma = req_dry_breakers.find(',', q);
const size_t e2 = (comma == std::string::npos || comma > end) ? end : comma;
if (e2 > q) dry_flat.push_back(std::atoi(req_dry_breakers.substr(q, e2 - q).c_str()));
q = comma == std::string::npos || comma >= end ? end : comma + 1;
}
dry_off.push_back((int32_t) dry_flat.size());
p = bar == std::string::npos ? req_dry_breakers.size() : bar + 1;
}
}
strata::kernels::DryBreakers req_br;
if (!dry_flat.empty() && dry_off.size() > 1) {
const strata::core::OnDevice on_h(hist_dev);
cudaMemcpy(d_dry_flat, dry_flat.data(), (size_t) dry_flat.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
cudaMemcpy(d_dry_off, dry_off.data(), (size_t) dry_off.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
req_br = strata::kernels::DryBreakers{d_dry_flat, d_dry_off, (int) dry_off.size() - 1};
}
ver.set_breakers(req_br);
mtp.set_draft_breakers(req_br);
drive.d.pcie_num = std::max(0, std::min(256, (int) (req_pcie_frac * 256.0 + 0.5)));
// a layer split: CUDA0's share as asked; a later GPU keeps its own (its link) unless the request sets one
for (int st = 0; st < split_drive.n; ++st)
split_drive.pcie_num[st] = (st == 0 || split_same || req_pcie_frac != o.pcie_frac)
? drive.d.pcie_num : pcie_num_of(stages[(size_t) st - 1]->pcie_frac);
const int hist_n = std::min(req_sp.penalty_last_n, kPenaltyWindowCap);
// DRY builds its window from the same history row the penalties count, so a DRY-only request (no
// penalties) still stages history, sized to the wider of the two windows.
const int hist_n = std::min(std::max(req_sp.penalty_last_n, req_sp.dry_penalty_last_n), kPenaltyWindowCap);
ver.set_history(hist_n > 0 ? d_hist : nullptr, hist_n);
bool cancelled = false;
tr("prompt start", n - 1);