Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Engine 0.1.19: penalties on every drafted token; the CLI samples; sampler hardening
Niko1221de71982be9b5
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 6c628552b..a24b68803 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -8,7 +8,7 @@# written against sm_120 (RTX 5000 / Blackwell) and silently building for an older arch would produce a# binary that runs and is wrong about its own performance, which is the worst of both outcomes.cmake_minimum_required(VERSION 3.24)-project(strata VERSION 0.1.18 LANGUAGES CXX)+project(strata VERSION 0.1.19 LANGUAGES CXX)add_compile_definitions(STRATA_VERSION="${PROJECT_VERSION}")# issue #31: release builds keep a PDB beside the exe (not shipped in it), so a minidump from a stalled engine can# be read back to the exact source linediff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 7b436fc67..b823de76f 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -308,7 +308,9 @@ engine arguments. The run config's optional `sampling` block sets the defaults fblock at all a request without sampling keys decodes greedy. The penalties (`presence_penalty`, `frequency_penalty`,`repetition_penalty`, with `penalty_last_n` capping how many recent tokens they count over, default 64 when anypenalty is set) ride the same path; they count the tokens the request has consumed, so a repetition penalty-suppresses what the model itself just said, not the prompt alone.+suppresses what the model itself just said, not the prompt alone. Since engine 0.1.19 they apply to every token+the speculative decoding checks at once, exactly as if it decoded one token at a time (before, only the first of+each batch got them). `top_k` keeps at most 64 candidates: `0` ("off") or anything above 64 uses all 64.---diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hppindex bc9b32e3c..bf48b5b80 100644--- a/include/strata/core/verify.hpp+++ b/include/strata/core/verify.hpp@@ -71,14 +71,20 @@ public:sampling_ = sp; // row t of a window at pos0 draws Philox(seed, pos0 + t): see run()}- /// The penalty-history row for `sampling_.penalty_last_n`: ONE row of `history_len` int32 slots, most- /// recent token LAST, unused front slots -1 (the kernel reads only the tail window). Null disables the- /// penalties entirely - the neutral run's sampling call is byte-for-byte what it was. The engine- /// re-uploads the request's tail before every window; the pointer must stay alive across the request.+ /// 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+ /// row 0 alone (before 0.1.19) left the drafted rows with unwritten histories. Null disables the penalties+ /// entirely - the neutral run's sampling call is byte-for-byte what it was. The engine re-uploads the rows+ /// before every window; the buffer must hold kVerifyMaxT rows and stay alive across the request.void set_history(const int32_t* history, int history_len) {hist_d_ = history;hist_len_ = history_len;}+ /// Off: `run` skips the request's head sampling and `out` is the recorded greedy pick. For windows whose+ /// picks are discarded - a prompt read through windows commits every token - so they cost no sampler launch+ /// or sync and never read a history staged for another position.+ void set_head_sampling(bool on) { head_sampling_ = on; }/// Keep the first `n_keep` (1..T) tokens of the last window; advances `ss.ple_prev` by them.bool commit(int n_keep, std::string& err);@@ -112,6 +118,7 @@ private:}(); ///< greedy by default; per-request via set_samplingconst int32_t* hist_d_ = nullptr; ///< penalty-history row (set_history); null = no penalties applyint hist_len_ = 0;+ bool head_sampling_ = true; ///< set_head_samplingbool capture_commit(std::string& err);bool record_window(int T, cudaStream_t cs, std::string& err);diff --git a/include/strata/kernels/sampler.hpp b/include/strata/kernels/sampler.hppindex d528e3637..955625879 100644--- a/include/strata/kernels/sampler.hpp+++ b/include/strata/kernels/sampler.hpp@@ -1,18 +1,19 @@// include/strata/kernels/sampler.hpp - the sampler chain, host-callable (P2.S2).//-// penalties -> top_k -> min_p -> top_p -> temperature -> penalties -> pick+// penalties -> top_k -> top_p -> min_p -> temperature -> pick//-// The ORDER is specified in docs/sampling.md, transcribed from llama.cpp's own chain. Three facts there are-// easy to get backwards: temperature comes AFTER the truncation filters, penalties come AFTER temperature as-// well as before the selection, and min_p cuts BEFORE top_p (both on the pre-temperature logits).+// llama.cpp's default chain (issue #53): ONE penalties stage, first, and temperature AFTER the truncation filters;+// top_p cuts before min_p. `src/kernels/cuda/sampler.cu` has the details and `sampler_parity` pins them.#pragma once+#include <algorithm>+#include <cstddef>#include <cstdint>namespace strata::kernels {struct SamplerParams {- int top_k = 20; // 0 disables the filter+ int top_k = 20; // sampled path: 1..64 as given; 0 (off) or more than 64 keep the widest list, 64float top_p = 0.95f; // 1.0 disables the filterfloat min_p = 0.0f; // 0 disables; keeps tokens with p >= min_p * p_max (a prefix of the top_k list)float temperature = 1.0f; // <= 0 means greedy@@ -34,9 +35,29 @@ struct SamplerParams {// reported by whatever synchronising call happens NEXT, which will be somewhere else entirely and will name a// buffer that has nothing to do with it. A sticky async fault does not know where it came from.//-// `history` is (n_tokens, history_len) int32, the most recent tokens for each row with any unused slots set to-// -1; only the last `p.penalty_last_n` of each row are counted. Pass nullptr and 0 when no penalties apply.+// `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.+// 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);+// 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.+// `tail` is what the state consumed before the window, `window[0]` the fed-back token and `window[1..]` the+// drafts: row t is exactly the history plain decode counts when it picks the token after `window[t]`, so drafting+// cannot change which tokens are penalised. Row 0 alone is the single row the engine staged before 0.1.19.+inline void penalty_rows(const int32_t* tail, int64_t n_tail, const int32_t* window, int T, int h, int32_t* out) {+ for (int t = 0; t < T; ++t) {+ int32_t* row = out + (size_t) t * (size_t) h;+ const int64_t avail = n_tail + t + 1; // tail + window[0..t]+ const int take = (int) std::min<int64_t>(h, avail);+ std::fill(row, row + (h - take), -1);+ for (int j = 0; j < take; ++j) {+ const int64_t i = avail - take + j; // index into (tail, window)+ row[h - take + j] = i < n_tail ? tail[i] : window[i - n_tail];+ }+ }+}+} // namespace strata::kernelsdiff --git a/serve/server.py b/serve/server.pyindex b0a2f3126..dbfda5e67 100644--- a/serve/server.py+++ b/serve/server.py@@ -234,8 +234,9 @@ class StrataEngine:if isinstance(tp, (int, float)) and float(tp) < 1.0:keys += f" top_p={float(tp)!r}"tk = sampling.get("top_k")- if isinstance(tk, int) and 1 <= tk <= 64:- keys += f" top_k={tk}" # the engine's sampled path takes 1..64; outside it keeps its 20+ if isinstance(tk, int) and not isinstance(tk, bool) and tk >= 0:+ # the engine's sampled path keeps at most 64 candidates: 0 ("off") and wider lists get all 64+ keys += f" top_k={tk if 1 <= tk <= 64 else 64}"mp = sampling.get("min_p")if isinstance(mp, (int, float)) and 0.0 < float(mp) <= 1.0:keys += f" min_p={float(mp)!r}"diff --git a/serve/test_server.py b/serve/test_server.pyindex 14dacc066..5b2b03b10 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -14,7 +14,7 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1]))from serve.frontend import ChatTemplate # noqa: E402-from serve.server import CTX_SLACK, ByteTokenizer, EngineDied, MockEngine, Service, serve # noqa: E402+from serve.server import CTX_SLACK, ByteTokenizer, EngineDied, MockEngine, Service, StrataEngine, serve # noqa: E402ROOT = Path(__file__).resolve().parents[1]CTX = 4096@@ -236,6 +236,27 @@ class ClientShapes(unittest.TestCase):self.assertEqual([m["role"] for m in msgs], ["system", "user"])+class SamplingKeys(unittest.TestCase):+ """The GEN line's sampling keys: top_k 0 ("off") or wider than the engine's 64 get the widest list, 64 (they used+ to fall back to the engine default 20); a penalty always carries its window."""++ def keys(self, **sampling):+ return StrataEngine.sampling_keys(sampling).split()++ def test_top_k(self):+ self.assertIn("top_k=10", self.keys(temperature=0.7, top_k=10))+ self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=64))+ self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=0))+ self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=100))+ for bad in (-1, True, 2.5, "20"):+ self.assertFalse([k for k in self.keys(temperature=0.7, top_k=bad) if k.startswith("top_k=")], bad)++ def test_penalty_window(self):+ self.assertIn("penalty_last_n=64", self.keys(presence_penalty=1.5))+ self.assertIn("penalty_last_n=4096", self.keys(repetition_penalty=1.1, penalty_last_n=4096))+ self.assertFalse([k for k in self.keys(temperature=0.7) if k.startswith("penalty")])++class GpuChoice(unittest.TestCase):"""Issue #51: the config's \"gpu\" reaches the engine as CUDA_VISIBLE_DEVICES, numbered like nvidia-smi."""diff --git a/setup.py b/setup.pyindex 1122c3630..0f09c18e6 100644--- a/setup.py+++ b/setup.py@@ -57,7 +57,7 @@ PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip"# the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packagesCUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"]MIN_DRIVER = 580 # CUDA 13.0-MIN_ENGINE = (0, 1, 17) # v0.1.17: one sampler penalties stage (#53); v0.1.16: the Coder (PR #54)+MIN_ENGINE = (0, 1, 19) # v0.1.19: penalties on every drafted token; v0.1.17: one penalties stage (#53)PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"]MODELS = {diff --git a/src/core/verify.cpp b/src/core/verify.cppindex 4dfddf39c..72fccd5e3 100644--- a/src/core/verify.cpp+++ b/src/core/verify.cpp@@ -845,7 +845,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,// the POSITION it samples, not to how the text was cut into windows, so a seed replays the same text whatever// the drafts were. Exact: a rejected row's draw is discarded, and no kept decision depends on a reused draw.const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f;- if (sampled || hist_d_ != nullptr) {+ 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_);diff --git a/src/kernels/cuda/sampler.cu b/src/kernels/cuda/sampler.cuindex 3e711c100..76a7873e5 100644--- a/src/kernels/cuda/sampler.cu+++ b/src/kernels/cuda/sampler.cu@@ -116,7 +116,8 @@ __global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vofor (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) atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));+ 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));__syncthreads();}auto hit_count = [&](int v) -> int {@@ -200,7 +201,8 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, infor (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) atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));+ 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));__syncthreads();}auto hit_count = [&](int v) -> int {@@ -208,14 +210,11 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, inreturn history_count(hrow, hlen, v);};+ // 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.const int KMAX = 64;- int k = p.top_k > 0 ? (p.top_k < KMAX ? p.top_k : KMAX) : 0;- if (k <= 0) {- if (threadIdx.x == 0)- std::printf("sampler: the sampled path needs top_k in 1..%d (got %d); greedy needs no filters\n",- KMAX, p.top_k);- return; // leave out[t] unwritten rather than returning an uninitialised token- }+ int k = (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX;+ if (k > n_vocab) k = n_vocab;// ---- top_k: k rounds of a block argmax over the not-yet-taken. `sel_*` holds the kept ids and their// raw logits in selection order: descending by value, ties to the lower index, which is the order thediff --git a/src/kernels/sampler_parity.cpp b/src/kernels/sampler_parity.cppindex 587ae333c..4a7d5901f 100644--- a/src/kernels/sampler_parity.cpp+++ b/src/kernels/sampler_parity.cpp@@ -107,6 +107,9 @@ int run(const char* name, const std::vector<float>& logits, int n_tokens, constcheck(cudaMalloc(&d_l, logits.size() * sizeof(float)), "malloc logits");check(cudaMalloc(&d_o, (size_t) n_tokens * sizeof(int)), "malloc out");check(cudaMemcpy(d_l, logits.data(), logits.size() * sizeof(float), cudaMemcpyHostToDevice), "copy");+ // -1 in every output slot first: a row the kernel leaves unwritten can never match (a verify window reads+ // every row, so "no output" is a wrong answer, not a skipped one)+ check(cudaMemset(d_o, 0xFF, (size_t) n_tokens * sizeof(int)), "fill out");int* d_h = nullptr;if (hist_len > 0) {check(cudaMalloc(&d_h, hist.size() * sizeof(int)), "malloc hist");@@ -167,8 +170,8 @@ int sampled_reference(const std::vector<float>& l, const std::vector<int>& hist,};auto count = [&](int v) { int c = 0; for (int h : hist) if (h == v) ++c; return c; };const int nv = (int) l.size();- const int KMAX = 64;- const int k = p.top_k > 0 ? (p.top_k < KMAX ? p.top_k : KMAX) : 0;+ const int KMAX = 64; // 1..64 as given; 0 (off) and wider keep the widest list, 64+ const int k = std::min(nv, (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX);std::vector<int> sel_ids;std::vector<float> sel_logit;std::vector<char> taken((size_t) nv, 0);@@ -230,7 +233,7 @@ int sampled_cut(const std::vector<float>& l, const std::vector<int>& hist, constauto count = [&](int v) { int c = 0; for (int h : hist) if (h == v) ++c; return c; };const int nv = (int) l.size();const int KMAX = 64;- const int k = p.top_k > 0 ? (p.top_k < KMAX ? p.top_k : KMAX) : 0;+ const int k = std::min(nv, (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX);std::vector<float> sel;std::vector<char> taken((size_t) nv, 0);for (int i = 0; i < k; ++i) {@@ -647,6 +650,173 @@ int main(int argc, char** argv) {bad += run("stale history, last_n=0 (greedy)", l, NT, gp, gwant, hist, 8);}+ // ---- fixture 12: ONE HISTORY PER ROW (engine 0.1.19). A verify window samples T rows, and row t's pick+ // follows the drafts 1..t: its penalties must count them. The engine used to stage row 0 alone, so rows+ // 1..T-1 read slots nobody wrote. Here every row gets `penalty_rows`' history and is pinned against a+ // per-row scalar reference; the fixture first asserts it can SEE the difference - with row 0's history+ // copied to every row (the nearest well-defined stand-in for the old staging) some row must pick differently.+ // Row t's own newest token (window[t]) is its favourite by a margin the presence penalty overturns.+ {+ auto greedy_pen = [](const std::vector<float>& l, const std::vector<int>& hist,+ const strata::kernels::SamplerParams& p) {+ int best = 0; float bv = 0; bool first = true;+ for (int v = 0; v < (int) l.size(); ++v) {+ int c = 0; for (int h : hist) if (h == v) ++c;+ float s = l[(size_t) v];+ if (c > 0) {+ if (s <= 0.0f) s *= p.penalty_repeat; else s /= p.penalty_repeat;+ s -= (float) c * p.penalty_freq + p.penalty_present;+ }+ if (first || s > bv) { bv = s; best = v; first = false; }+ }+ return best;+ };+ std::mt19937 rng(12); std::normal_distribution<float> g(0.0f, 1.0f);+ const int TAIL = 5000; // longer than the widest window below+ std::vector<int32_t> tail((size_t) TAIL);+ for (auto& v : tail) v = (int32_t) (rng() % NV);+ int observable = 0, rows_checked = 0;+ for (int T : {1, 2, 4, 8}) {+ for (int H : {1, 64, 1024, 4096}) {+ std::vector<int32_t> window((size_t) T);+ for (int t = 0; t < T; ++t) window[(size_t) t] = (int32_t) (100 + 37 * t); // distinct, in range+ std::vector<int32_t> rows((size_t) T * H);+ strata::kernels::penalty_rows(tail.data(), TAIL, window.data(), T, H, rows.data());+ std::vector<float> l((size_t) T * NV);+ for (auto& v : l) v = g(rng);+ for (int t = 0; t < T; ++t) l[(size_t) t * NV + window[(size_t) t]] = 5.0f;+ strata::kernels::SamplerParams gp;+ gp.greedy = true; gp.temperature = 0.0f; gp.top_k = 0; gp.top_p = 1.0f;+ gp.penalty_last_n = H; gp.penalty_present = 4.0f;+ strata::kernels::SamplerParams sp2;+ sp2.top_k = 20; sp2.top_p = 0.9f; sp2.temperature = 0.7f; sp2.seed = 1000 + (uint64_t) H;+ sp2.counter = 77; sp2.penalty_last_n = H; sp2.penalty_present = 4.0f; sp2.penalty_repeat = 1.1f;+ std::vector<int> gwant((size_t) T), swant((size_t) T), rows_int(rows.begin(), rows.end());+ for (int t = 0; t < T; ++t) {+ const std::vector<float> lr(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV);+ const std::vector<int> own(rows.begin() + (size_t) t * H, rows.begin() + (size_t) (t + 1) * H);+ const std::vector<int> row0(rows.begin(), rows.begin() + H);+ gwant[(size_t) t] = greedy_pen(lr, own, gp);+ swant[(size_t) t] = sampled_reference(lr, own, sp2, t);+ if (t > 0 && greedy_pen(lr, row0, gp) != gwant[(size_t) t]) ++observable;+ ++rows_checked;+ }+ char name[64];+ std::snprintf(name, sizeof name, "per-row history T=%d H=%d greedy", T, H);+ bad += run(name, l, T, gp, gwant, rows_int, H);+ std::snprintf(name, sizeof name, "per-row history T=%d H=%d sampled", T, H);+ bad += run(name, l, T, sp2, swant, rows_int, H);+ }+ }+ std::printf(" %-34s %s (%d drafted rows pick differently with row 0's history, of %d rows)\n",+ "per-row histories are observable", observable > 0 ? "yes" : "*** NO ***", observable,+ rows_checked);+ if (observable == 0) ++bad;+ }++ // ---- fixture 13: HISTORY IDS OUTSIDE THE VOCABULARY ARE IGNORED. The bitmap is sized for n_vocab bits;+ // an id >= n_vocab used to set a bit past its end (a shared-memory write out of bounds - compute-sanitizer+ // memcheck reports it). They can never be a candidate, so the result equals the reference without them.+ {+ std::mt19937 rng(13); std::normal_distribution<float> g(0.0f, 1.0f);+ const int H = 16;+ std::vector<float> l((size_t) NV * NT);+ for (auto& v : l) v = g(rng);+ std::vector<int> hist((size_t) NT * H, -1), valid_only((size_t) NT * H, -1);+ const int junk[] = {NV, NV + 1000, 0x7fffffff, -5, 1 << 20};+ for (int t = 0; t < NT; ++t) {+ for (int j = 0; j < H; ++j) {+ const bool bogus = j % 3 == 0;+ const int v = bogus ? junk[(size_t) (j / 3) % 5] : (int) (rng() % NV);+ hist[(size_t) t * H + j] = v;+ if (!bogus) valid_only[(size_t) t * H + j] = v;+ }+ l[(size_t) t * NV + hist[(size_t) t * H + 1]] = 4.0f; // a penalised favourite, so penalties matter+ }+ strata::kernels::SamplerParams gp;+ gp.greedy = true; gp.temperature = 0.0f; gp.top_k = 0; gp.top_p = 1.0f;+ gp.penalty_last_n = H; gp.penalty_present = 3.0f;+ strata::kernels::SamplerParams sp2 = gp;+ sp2.greedy = false; sp2.temperature = 0.8f; sp2.top_k = 20; sp2.top_p = 0.95f; sp2.seed = 13;+ std::vector<int> gwant((size_t) NT), swant((size_t) NT);+ for (int t = 0; t < NT; ++t) {+ const std::vector<float> lr(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV);+ const std::vector<int> ok(valid_only.begin() + (size_t) t * H, valid_only.begin() + (size_t) (t + 1) * H);+ { // the greedy reference with the penalty (reference_pick has none)+ int best = 0; float bv = 0; bool first = true;+ for (int v = 0; v < NV; ++v) {+ int c = 0; for (int h : ok) if (h == v) ++c;+ float s = lr[(size_t) v];+ if (c > 0) { if (s <= 0.0f) s *= gp.penalty_repeat; else s /= gp.penalty_repeat; s -= gp.penalty_present; }+ if (first || s > bv) { bv = s; best = v; first = false; }+ }+ gwant[(size_t) t] = best;+ }+ swant[(size_t) t] = sampled_reference(lr, ok, sp2, t);+ }+ bad += run("out-of-vocab history ids (greedy)", l, NT, gp, gwant, hist, H);+ bad += run("out-of-vocab history ids (sampled)", l, NT, sp2, swant, hist, H);+ }++ // ---- fixture 14: THE top_k CONTRACT. 1..64 as given; 0 ("off") and anything wider use the widest list the+ // kernel keeps, 64 - and every row is written (the sampled kernel used to print an error for 0 and leave the+ // row unwritten, which a verify window then read as a token; `run` pre-fills -1 so that fails here).+ {+ std::mt19937 rng(14); std::normal_distribution<float> g(0.0f, 1.0f);+ std::vector<float> l((size_t) NV * NT);+ for (auto& v : l) v = g(rng) * 0.3f; // flat: the 64-wide list matters to the draw+ strata::kernels::SamplerParams p64;+ p64.top_k = 64; p64.top_p = 1.0f; p64.temperature = 1.5f; p64.seed = 14;+ std::vector<int> want((size_t) NT);+ for (int t = 0; t < NT; ++t)+ want[(size_t) t] = sampled_reference({l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV},+ {}, p64, t);+ bad += run("sampled top_k=64", l, NT, p64, want);+ strata::kernels::SamplerParams p0 = p64; p0.top_k = 0;+ bad += run("sampled top_k=0 means 64", l, NT, p0, want);+ strata::kernels::SamplerParams p100 = p64; p100.top_k = 100;+ bad += run("sampled top_k=100 means 64", l, NT, p100, want);+ strata::kernels::SamplerParams pneg = p64; pneg.top_k = -3;+ bad += run("sampled top_k=-3 means 64", l, NT, pneg, want);+ }++ // ---- fixture 15: `penalty_rows`, host only, against the plain definition: row t = the last h tokens of+ // tail + window[0..t], -1 padded in front. Covers a tail shorter than, equal to and longer than h, and row 0+ // equal to the single row the engine staged before 0.1.19.+ {+ int wrong = 0, cases = 0;+ for (int n_tail : {0, 1, 5, 63, 64, 65, 300}) {+ for (int T : {1, 3, 8}) {+ for (int h : {1, 4, 64, 100}) {+ std::vector<int32_t> tail((size_t) n_tail), window((size_t) T);+ for (int i = 0; i < n_tail; ++i) tail[(size_t) i] = 1000 + i;+ for (int i = 0; i < T; ++i) window[(size_t) i] = 5000 + i;+ std::vector<int32_t> rows((size_t) T * h, 12345);+ strata::kernels::penalty_rows(tail.data(), n_tail, window.data(), T, h, rows.data());+ for (int t = 0; t < T; ++t) {+ std::vector<int32_t> seq(tail);+ seq.insert(seq.end(), window.begin(), window.begin() + t + 1);+ std::vector<int32_t> expect((size_t) h, -1);+ const int take = (int) std::min<size_t>((size_t) h, seq.size());+ for (int j = 0; j < take; ++j) expect[(size_t) (h - take + j)] = seq[seq.size() - take + j];+ if (!std::equal(expect.begin(), expect.end(), rows.begin() + (size_t) t * h)) ++wrong;+ ++cases;+ }+ // row 0 = the old single-row staging: consumed tail, then the fed-back head last+ std::vector<int32_t> old((size_t) h, -1);+ const int take0 = (int) std::min<int64_t>(h, (int64_t) n_tail + 1);+ for (int j = 0; j < take0 - 1; ++j) old[(size_t) (h - take0 + j)] = tail[(size_t) (n_tail - (take0 - 1) + j)];+ old[(size_t) (h - 1)] = window[0];+ if (!std::equal(old.begin(), old.end(), rows.begin())) ++wrong;+ ++cases;+ }+ }+ }+ std::printf(" %-34s %s (%d of %d rows differ)\n", "penalty_rows layout", wrong ? "*** WRONG ***" : "matches",+ wrong, cases);+ bad += wrong;+ }+// A continuous stream and individual decode calls consume the same draw counters.{constexpr int count = 32, vocab = 16;diff --git a/src/program/generate.cpp b/src/program/generate.cppindex d84d86476..7a8c6eb47 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -26,6 +26,7 @@#include "strata/kernels/ngram.hpp"#include "strata/kernels/s2_expert_grouped.hpp"#include "strata/kernels/sampler.hpp"+#include "strata/kernels/verify_kernels.hpp"#include "strata/kernels/shared_expert.hpp"#include "strata/kernels/native_moe.hpp"#include "strata/kernels/native_gdn.hpp"@@ -1825,6 +1826,16 @@ int main(int argc, char** argv) {sp.top_k = o.top_k;sp.top_p = o.top_p;sp.temperature = o.temperature;+ // what this run actually samples with (the speculative loop below gets the same parameters); serve samples+ // per request instead+ if (!o.serve) {+ if (sp.greedy || sp.temperature <= 0.0f)+ std::fprintf(stderr, "strata generate: sampling greedy\n");+ else+ std::fprintf(stderr, "strata generate: sampling temperature=%g top_k=%d top_p=%g seed=%llu\n",+ (double) sp.temperature, sp.top_k > 0 && sp.top_k < 64 ? sp.top_k : 64, (double) sp.top_p,+ (unsigned long long) sp.seed);+ }std::FILE* dump = nullptr;const int64_t dump_positions = (int64_t) o.tokens.size() - 1 + o.max_new;@@ -2337,13 +2348,15 @@ int main(int argc, char** argv) {return 1;}mem_mark("the head and the prompt path");- // the penalty-history buffer: ONE row, the request's last `penalty_last_n` tokens, -1 padded in- // front. Allocated once at the cap; a request without penalties gets a null row and takes the- // byte-for-byte neutral path (no upload, no buffer handed to the sampler).+ // the penalty-history buffer: one row per verify-window row (`penalty_rows`), each the last+ // `penalty_last_n` tokens that row's pick follows, -1 padded in front. Allocated once at the cap for+ // the widest window; a request without penalties gets a null buffer and takes the byte-for-byte+ // neutral path (no upload, no buffer handed to the sampler).constexpr int kPenaltyWindowCap = 4096;+ constexpr size_t kHistSlots = (size_t) kPenaltyWindowCap * (size_t) strata::kernels::kVerifyMaxT;int32_t* d_hist = nullptr;- std::vector<int32_t> hist_stage((size_t) kPenaltyWindowCap, -1);- if (cudaMalloc(&d_hist, (size_t) kPenaltyWindowCap * sizeof(int32_t)) != cudaSuccess) {+ std::vector<int32_t> hist_stage(kHistSlots, -1);+ if (cudaMalloc(&d_hist, kHistSlots * sizeof(int32_t)) != cudaSuccess) {std::fprintf(stderr, "strata serve: the penalty-history allocation failed\n");return 1;}@@ -2854,6 +2867,12 @@ int main(int argc, char** argv) {};// tokens [a, b) through the windows: commit all of them, then give the draft layer their residualsauto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool {+ // every token is committed and the picks are discarded: no head sampling (see set_head_sampling)+ struct NoHeadSampling {+ strata::core::Verifier& v;+ explicit NoHeadSampling(strata::core::Verifier& x) : v(x) { v.set_head_sampling(false); }+ ~NoHeadSampling() { v.set_head_sampling(true); }+ } no_head_sampling(ver);std::vector<int32_t> win((size_t) S), outw((size_t) S), nxt((size_t) S);for (int64_t q = a; q < b;) {if (stop_req.load()) { e = "cancelled"; return false; }@@ -3041,17 +3060,14 @@ int main(int argc, char** argv) {drive.d.failed = false;apply_pending(false);if (hist_n > 0) {- // the tail the penalties count over: the tokens the state has consumed plus the fed-back- // head `x` (it joins `consumed` only after this window commits). Most recent LAST,- // -1 in the unused front slots - the sampler's row layout.- const int64_t avail = (int64_t) consumed.size() + 1;- const int take = (int) std::min<int64_t>(hist_n, avail);- std::fill(hist_stage.begin(), hist_stage.begin() + hist_n, -1);- for (int j = 0; j < take - 1; ++j)- hist_stage[(size_t) (hist_n - take + j)] =- consumed[(size_t) ((int64_t) consumed.size() - (take - 1) + j)];- hist_stage[(size_t) (hist_n - 1)] = (int32_t) x;- cudaMemcpy(d_hist, hist_stage.data(), (size_t) hist_n * sizeof(int32_t), cudaMemcpyHostToDevice);+ // the tails the penalties count over, ONE PER ROW: the tokens the state has consumed, the+ // fed-back head `x` (it joins `consumed` only after this window commits), then the drafts+ // before that row - what plain decode would have counted there. (Until 0.1.19 only row 0+ // was staged, and the drafted rows read unwritten slots.)+ strata::kernels::penalty_rows(consumed.data(), (int64_t) consumed.size(), window.data(), T,+ hist_n, hist_stage.data());+ cudaMemcpy(d_hist, hist_stage.data(), (size_t) T * (size_t) hist_n * sizeof(int32_t),+ cudaMemcpyHostToDevice);}tr("window", p, T);if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err) || drive.d.failed) {@@ -3475,8 +3491,9 @@ int main(int argc, char** argv) {}int next = 0;- // Teacher-forced prompt rows consume no generation draws.- sp.counter = (uint64_t) produced.size();+ // The draw is Philox(seed, position), as in a verify window (row t at pos0 draws pos0 + t): a seed gives+ // the same text whether a token comes from this path or from the speculative loop below.+ sp.counter = (uint64_t) pos;strata::kernels::sample_tokens(d_logits, 1, (int) n_vocab, nullptr, 0, sp, d_next, token_stream);if (cudaMemcpyAsync(&next, d_next, sizeof(int), cudaMemcpyDeviceToHost,(cudaStream_t) token_stream) != cudaSuccess ||@@ -3572,6 +3589,7 @@ int main(int argc, char** argv) {return 1;}mem_mark("the verifier and the drafter's binding");+ ver.set_sampling(sp); // the CLI's own sampling (until 0.1.19 this loop was always greedy); no penalties herever.set_split(o.spec_split);// auto: the copy kernel for every pack. DMA (the native packs' default until 0.1.13) has the host call// cudaMemcpyAsync + cudaLaunchHostFunc inside a verify window while the GPU spins on the flag they raise;