From 4703da4363489564c7a2909b48bf30c343bd77bb Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Sat, 26 Sep 2026 22:15:04 +0200 Subject: [PATCH] generate: min_p and the penalties ride the GEN line The sampled chain's last two gaps close: `min_p` and the llama.cpp penalty set (repeat/freq/present over a history window) are live end to end - GEN keys, per-request params, and the token history the penalties count over. - GEN accepts min_p=F penalty_last_n=N penalty_repeat=F penalty_freq=F penalty_present=F between max_new and the ids (the server's spelling); the engine clamps defensively (min_p to 0..1, a negative last_n to 0) and skips what it does not know, as before. - min_p cuts the top_k survivors to the prefix with p >= min_p * p_max - in logits, sel_logit >= sel_logit[0] + logf(min_p) - before top_p, so the two cuts compose; 0 disables, and the head always survives, so the kept count never reaches zero. - the penalties need the token history: the serve loop uploads the last penalty_last_n tokens - the consumed tail plus the fed-back head, which joins consumed_seq only after the window commits - into one device row before every window. A request without penalties hands the sampler a null row and takes the byte-for-byte neutral path (no upload, nothing handed over). Verified: sampler_parity grows a full-chain host reference (the Philox draw transcribed host-side) and fixtures for the sampled chain with penalties and for min_p at 0/0.5/0.9 - the kernel matches the reference on all of them, and each fixture first asserts it can SEE the feature before asserting the kernel matches. On the IQ3_XXS artifact, same seed: a request with neutral penalty keys is token-identical to one without them; a six-copy prompt that loops 24/24 on one token clean produces 24 distinct tokens with repeat 1.5 + present 0.5; min_p 0.9 changes the pick. --- include/strata/core/verify.hpp | 11 ++ include/strata/kernels/sampler.hpp | 11 +- src/core/verify.cpp | 2 +- src/kernels/cuda/sampler.cu | 26 +++- src/kernels/sampler_parity.cpp | 210 +++++++++++++++++++++++++++++ src/program/generate.cpp | 42 +++++- 6 files changed, 286 insertions(+), 16 deletions(-) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index f82b423d..7bdf6ae1 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -67,6 +67,15 @@ public: draw_counter_ = 0; // each request's sampling starts its own draw sequence } + /// 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. + void set_history(const int32_t* history, int history_len) { + hist_d_ = history; + hist_len_ = history_len; + } + /// 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); @@ -98,6 +107,8 @@ private: return s; }(); ///< greedy by default; per-request via set_sampling uint64_t draw_counter_ = 0; ///< advanced by T on every sampled window; reset by set_sampling + const int32_t* hist_d_ = nullptr; ///< penalty-history row (set_history); null = no penalties apply + int hist_len_ = 0; bool 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.hpp index 32a5ded9..d528e363 100644 --- a/include/strata/kernels/sampler.hpp +++ b/include/strata/kernels/sampler.hpp @@ -1,12 +1,10 @@ // include/strata/kernels/sampler.hpp - the sampler chain, host-callable (P2.S2). // -// penalties -> top_k -> top_p -> temperature -> pick +// penalties -> top_k -> min_p -> top_p -> temperature -> penalties -> pick // -// The ORDER is specified in docs/sampling.md, transcribed from llama.cpp's own chain. Two facts there are -// easy to get backwards: temperature comes AFTER the truncation filters, and penalties come AFTER temperature. -// -// PENALTIES ARE NOT IMPLEMENTED YET: they need the token history, which is not in this signature, so a caller -// passing a non-zero `penalty_last_n` gets a loud failure rather than a silently unpenalised sample. +// 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). #pragma once #include @@ -16,6 +14,7 @@ namespace strata::kernels { struct SamplerParams { int top_k = 20; // 0 disables the filter float top_p = 0.95f; // 1.0 disables the filter + float 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 int min_keep = 1; // top_p keeps at least this many int penalty_last_n = 0; // 0 disables; the window over `history` to count occurrences in diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 7e7010cf..5ed90345 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -800,7 +800,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, SamplerParams sp = sampling_; sp.counter = draw_counter_; draw_counter_ += (uint64_t) T; - sample_tokens(head_logits_, T, (int) n_vocab_, nullptr, 0, sp, m_out_, cs_); + sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_); const cudaError_t sm = cudaMemcpyAsync(h_out_, m_out_, (size_t) T * sizeof(int32_t), cudaMemcpyDeviceToHost, cs_); if (sm != cudaSuccess || cudaStreamSynchronize(cs_) != cudaSuccess) { diff --git a/src/kernels/cuda/sampler.cu b/src/kernels/cuda/sampler.cu index 04883b81..2d4d79df 100644 --- a/src/kernels/cuda/sampler.cu +++ b/src/kernels/cuda/sampler.cu @@ -1,6 +1,6 @@ // src/kernels/cuda/sampler.cu - P2.S2: the sampler chain, in the order docs/sampling.md settles. // -// penalties -> top_k -> top_p -> temperature -> pick +// penalties -> top_k -> min_p -> top_p -> temperature -> penalties -> pick // // THE ORDER IS THE WHOLE CONTENT OF THIS FILE. `docs/sampling.md` transcribes it from llama.cpp's own chain // (`common/sampling.cpp` L357/360/375/381/399) and the two facts that are easy to get backwards are that @@ -217,22 +217,34 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, in __syncthreads(); } + // ---- min_p: keep the descending prefix whose probability is at least `min_p` of the top token's. The + // kept list is in selection order (descending), so the survivors are a PREFIX and the cut composes with + // top_p's below. In logit space the threshold is `sel_logit[0] + logf(min_p)` - equivalent to + // `p >= min_p * p_max` without the overflow an exp of raw logits risks. 0 disables, and the head itself + // always survives (`expf(0) == 1 >= min_p` for min_p in 0..1), so the count never reaches zero. + int n_minp = k; + if (p.min_p > 0.0f) { + const float thresh = sel_logit[0] + logf(p.min_p); + for (int i = 0; i < k; ++i) + if (sel_logit[i] < thresh) { n_minp = i; break; } + } + // ---- top_p over the survivors, in descending order (which the selection produced), then temperature and // one Philox draw. Every thread computes the same chain redundantly over `sel_*` - the arithmetic is the // serial kernel's, instruction for instruction - so they agree on `pick` and thread 0 writes it. - int n_keep = k; + int n_keep = n_minp; float mx = sel_logit[0]; - for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]); + for (int i = 1; i < n_minp; ++i) mx = fmaxf(mx, sel_logit[i]); if (p.top_p < 1.0f) { double sum = 0.0; - for (int i = 0; i < k; ++i) sum += exp((double) sel_logit[i] - (double) mx); + for (int i = 0; i < n_minp; ++i) sum += exp((double) sel_logit[i] - (double) mx); double cum = 0.0; - int cut = k; - for (int i = 0; i < k; ++i) { + int cut = n_minp; + for (int i = 0; i < n_minp; ++i) { cum += exp((double) sel_logit[i] - (double) mx) / sum; if (cum >= (double) p.top_p) { cut = i + 1; break; } } - if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; + if (cut < p.min_keep) cut = p.min_keep < n_minp ? p.min_keep : n_minp; n_keep = cut; } auto scaled = [&](int i) { diff --git a/src/kernels/sampler_parity.cpp b/src/kernels/sampler_parity.cpp index 6eb7df06..899fea4c 100644 --- a/src/kernels/sampler_parity.cpp +++ b/src/kernels/sampler_parity.cpp @@ -12,6 +12,7 @@ #include +#include #include #include #include @@ -126,6 +127,139 @@ int run(const char* name, const std::vector& logits, int n_tokens, const return bad; } +// The Philox draw, host side - a transcription of the kernel's `philox_uniform` so the SAMPLED pick (not +// just the greedy argmax) can be pinned against a reference. `__umulhi(a, b)` is the high half of a 32x32 +// multiply, spelled `(uint32_t)(((uint64_t) a * b) >> 32)` here. +struct PhiloxRound { + uint32_t& c0; uint32_t& c1; uint32_t& c2; uint32_t& c3; + void step(uint32_t k0, uint32_t k1) const { + const uint32_t hi0 = (uint32_t) (((uint64_t) 0x9E3779B9u * c0) >> 32); + const uint32_t hi1 = (uint32_t) (((uint64_t) 0xBB67AE85u * c2) >> 32); + const uint32_t lo0 = 0x9E3779B9u * c0; + const uint32_t lo1 = 0xBB67AE85u * c2; + const uint32_t n0 = hi1 ^ c1 ^ k0; + const uint32_t n1 = lo1; + const uint32_t n2 = hi0 ^ c3 ^ k1; + const uint32_t n3 = lo0; + c0 = n0; c1 = n1; c2 = n2; c3 = n3; + } +}; + +float host_philox_uniform(uint64_t seed, uint64_t counter) { + uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32); + uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32); + PhiloxRound r{c0, c1, c2, c3}; + for (int i = 0; i < 10; ++i) r.step((uint32_t) i, 0u); + return (float) (c0 >> 8) * (1.0f / 16777216.0f); +} + +// The full SAMPLED chain, host side - the kernel's `sampler_kernel` in serial form: penalties on the raw +// logits during the top_k selection (ties to the lowest index), the min_p prefix cut, top_p's cut in double, +// then penalties AGAIN on the temperature-scaled survivors (docs/sampling.md's after-temperature pass), and +// one Philox draw at (seed, counter + row). +int sampled_reference(const std::vector& l, const std::vector& 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; + return logit; + }; + 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; + std::vector sel_ids; + std::vector sel_logit; + std::vector taken((size_t) nv, 0); + for (int i = 0; i < k; ++i) { + 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)); + if (best < 0 || s > bv) { best = v; bv = s; } + } + taken[(size_t) best] = 1; + sel_ids.push_back(best); sel_logit.push_back(bv); + } + int n_minp = (int) sel_ids.size(); + if (p.min_p > 0.0f) { + const float thresh = sel_logit[0] + std::log(p.min_p); + for (int i = 0; i < (int) sel_ids.size(); ++i) + if (sel_logit[(size_t) i] < thresh) { n_minp = i; break; } + } + int n_keep = n_minp; + if (p.top_p < 1.0f) { + double sum = 0.0; + for (int i = 0; i < n_minp; ++i) sum += std::exp((double) sel_logit[(size_t) i] - (double) sel_logit[0]); + double cum = 0.0; + int cut = n_minp; + for (int i = 0; i < n_minp; ++i) { + cum += std::exp((double) sel_logit[(size_t) i] - (double) sel_logit[0]) / sum; + if (cum >= (double) p.top_p) { cut = i + 1; break; } + } + if (cut < p.min_keep) cut = p.min_keep < n_minp ? p.min_keep : n_minp; + n_keep = cut; + } + const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; + auto scaled = [&](int i) { return penal(sel_logit[(size_t) i] * inv_t, count(sel_ids[(size_t) i])); }; + float smx = scaled(0); + for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i)); + double sum = 0.0; + for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx); + const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row); + double cum = 0.0; + int pick = sel_ids[(size_t) (n_keep - 1)]; + for (int i = 0; i < n_keep; ++i) { + cum += std::exp((double) scaled(i) - (double) smx) / sum; + if ((double) u < cum) { pick = sel_ids[(size_t) i]; break; } + } + return pick; +} + +// Survivors after the min_p + top_p cuts, in the sampled chain - the quantity an order or a threshold +// actually changes, used to assert a fixture can SEE the feature before asserting the kernel matches. +int sampled_cut(const std::vector& l, const std::vector& hist, const strata::kernels::SamplerParams& p) { + 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; + return logit; + }; + 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; + std::vector sel; + std::vector taken((size_t) nv, 0); + for (int i = 0; i < k; ++i) { + 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)); + if (best < 0 || s > bv) { best = v; bv = s; } + } + taken[(size_t) best] = 1; sel.push_back(bv); + } + int n_minp = (int) sel.size(); + if (p.min_p > 0.0f) { + const float thresh = sel[0] + std::log(p.min_p); + for (int i = 0; i < (int) sel.size(); ++i) + if (sel[(size_t) i] < thresh) { n_minp = i; break; } + } + if (p.top_p >= 1.0f) return n_minp; + double sum = 0.0; + for (int i = 0; i < n_minp; ++i) sum += std::exp((double) sel[(size_t) i] - (double) sel[0]); + double cum = 0.0; + int cut = n_minp; + for (int i = 0; i < n_minp; ++i) { + cum += std::exp((double) sel[(size_t) i] - (double) sel[0]) / sum; + if (cum >= (double) p.top_p) { cut = i + 1; break; } + } + if (cut < p.min_keep) cut = p.min_keep < n_minp ? p.min_keep : n_minp; + return cut; +} + } // namespace int main(int argc, char** argv) { @@ -326,6 +460,82 @@ int main(int argc, char** argv) { bad += run("T=1 greedy=true is the argmax", l, NT3, p2, want); } + // ---- fixture 6: PENALTIES IN THE SAMPLED CHAIN. Fixture 4 pins the greedy (argmax) path; the sampled + // chain applies penalties a SECOND time - after the temperature scaling, on the survivors - so it gets its + // own reference (the full chain with the host Philox) and its own observability check: with the penalties + // on, the history row's favourite must LOSE a pick it would win penalty-free. + { + const int NV2 = 8, NT2 = 2; + strata::kernels::SamplerParams p; + p.top_k = 5; p.top_p = 0.9f; p.temperature = 0.8f; p.seed = 9; p.counter = 0; + p.penalty_last_n = 4; p.penalty_repeat = 3.0f; p.penalty_freq = 0.2f; p.penalty_present = 0.6f; + + std::vector l((size_t) NV2 * NT2, -8.0f); + std::vector hist((size_t) NT2 * 4, -1); + for (int t = 0; t < NT2; ++t) { + float* row = l.data() + (size_t) t * NV2; + row[0] = 9.0f; row[1] = 4.5f; row[2] = 4.4f; row[3] = 4.3f; // token 0 leads clean (9 vs 4.5) + hist[(size_t) t * 4 + 0] = 0; // and falls to 2.2/2.0 penalised + hist[(size_t) t * 4 + 1] = t == 1 ? 0 : -1; // (repeat 3, freq, presence) + } + std::vector want((size_t) NT2), clean((size_t) NT2); + strata::kernels::SamplerParams clean_p = p; + clean_p.penalty_last_n = 0; clean_p.penalty_repeat = 1.0f; + clean_p.penalty_freq = 0.0f; clean_p.penalty_present = 0.0f; + for (int t = 0; t < NT2; ++t) { + const std::vector row(l.begin() + (size_t) t * NV2, l.begin() + (size_t) (t + 1) * NV2); + const std::vector h(hist.begin() + (size_t) t * 4, hist.begin() + (size_t) (t + 1) * 4); + want[(size_t) t] = sampled_reference(row, h, p, t); + clean[(size_t) t] = sampled_reference(row, h, clean_p, t); + } + const bool visible = want[0] != clean[0] || want[1] != clean[1]; + std::printf(" %-34s %s (penalised picks %d/%d, clean %d/%d)\n", + "sampled penalties are observable", visible ? "yes" : "*** NO ***", want[0], want[1], + clean[0], clean[1]); + if (!visible) ++bad; + else bad += run("sampled chain: penalties + top_k/p", l, NT2, p, want, hist, 4); + } + + // ---- fixture 7: MIN_P. The cut is a PREFIX of the descending top_k list (logit >= max + log(min_p)), + // so the fixture asserts the survivor count moves with the threshold (the observability half) and that + // the kernel's pick equals the reference's through the full sampled chain (the correctness half). + { + const int NV3 = 8, NT3 = 2; + std::vector l((size_t) NV3 * NT3, -8.0f); + for (int t = 0; t < NT3; ++t) { + float* row = l.data() + (size_t) t * NV3; + row[0] = 4.0f; row[1] = 3.5f; row[2] = 3.2f; row[3] = 3.1f; // gaps keep the cut off the + row[4] = 2.0f; // logf/rounding knife edge + } + strata::kernels::SamplerParams base; + base.top_k = 6; base.top_p = 1.0f; base.temperature = 0.9f; base.seed = 77; + + int c0 = 0, c05 = 0, c09 = 0; + for (int t = 0; t < NT3; ++t) { + const std::vector row(l.begin() + (size_t) t * NV3, l.begin() + (size_t) (t + 1) * NV3); + strata::kernels::SamplerParams q = base; q.min_p = 0.0f; + c0 += sampled_cut(row, {}, q); + q.min_p = 0.5f; c05 += sampled_cut(row, {}, q); + q.min_p = 0.9f; c09 += sampled_cut(row, {}, q); + } + const bool visible = c0 > c05 && c05 > c09 && c09 >= NT3; + std::printf(" %-34s %s (survivors: min_p 0 -> %d, 0.5 -> %d, 0.9 -> %d)\n", + "min_p cut is observable", visible ? "yes" : "*** NO ***", c0, c05, c09); + if (!visible) ++bad; + + for (float mp : {0.0f, 0.5f, 0.9f}) { + strata::kernels::SamplerParams q = base; q.min_p = mp; + std::vector want((size_t) NT3); + for (int t = 0; t < NT3; ++t) { + const std::vector row(l.begin() + (size_t) t * NV3, l.begin() + (size_t) (t + 1) * NV3); + want[(size_t) t] = sampled_reference(row, {}, q, t); + } + char name[64]; + std::snprintf(name, sizeof name, "sampled chain: min_p=%.1f", (double) mp); + bad += run(name, l, NT3, q, want); + } + } + // 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.cpp index 059cffd6..7fd462c9 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1966,6 +1966,16 @@ 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). + constexpr int kPenaltyWindowCap = 4096; + int32_t* d_hist = nullptr; + std::vector hist_stage((size_t) kPenaltyWindowCap, -1); + if (cudaMalloc(&d_hist, (size_t) kPenaltyWindowCap * sizeof(int32_t)) != cudaSuccess) { + std::fprintf(stderr, "strata serve: the penalty-history allocation failed\n"); + return 1; + } strata::core::Verifier ver; strata::core::VerifyHits vh; vh.d_res = thits.d_res; @@ -2154,11 +2164,14 @@ int main(int argc, char** argv) { } char* endp = nullptr; const long long max_new = std::strtoll(line.c_str() + (geni ? 5 : 4), &endp, 10); - // optional sampling keys between max_new and the ids: temperature=F, top_p=F, top_k=N, - // seed=N (text requests only). Absent keys keep today's behavior: greedy. + // optional sampling keys between max_new and the ids: temperature=F, top_p=F, top_k=N, min_p=F, + // penalty_last_n=N, penalty_repeat=F, penalty_freq=F, penalty_present=F, seed=N (text requests + // only). Absent keys keep today's behavior: greedy, no penalties. float req_temperature = 0.0f, req_top_p = 1.0f; int req_top_k = 20; // the sampler's own default; the sampled path REQUIRES top_k in 1..64 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; if (!geni && endp != nullptr) { for (;;) { while (*endp == ' ') ++endp; @@ -2173,6 +2186,11 @@ int main(int argc, char** argv) { if (key == "temperature") req_temperature = fv; else if (key == "top_p") req_top_p = fv; else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1); + else if (key == "min_p") req_min_p = fv; + else if (key == "penalty_last_n") req_penalty_last_n = std::atoi(tok.c_str() + eq + 1); + 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 == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10); // unknown keys are skipped: the ids start at the first token without '=' } @@ -2417,8 +2435,15 @@ int main(int argc, char** argv) { req_sp.top_k = req_top_k; req_sp.seed = req_seed ? req_seed : (unsigned long long) std::chrono::steady_clock::now().time_since_epoch().count(); + req_sp.min_p = std::clamp(req_min_p, 0.0f, 1.0f); + req_sp.penalty_last_n = std::max(req_penalty_last_n, 0); + req_sp.penalty_repeat = req_penalty_repeat; + req_sp.penalty_freq = req_penalty_freq; + req_sp.penalty_present = req_penalty_present; req_sp.counter = 0; ver.set_sampling(req_sp); + const int hist_n = std::min(req_sp.penalty_last_n, kPenaltyWindowCap); + ver.set_history(hist_n > 0 ? d_hist : nullptr, hist_n); bool cancelled = false; tr("prompt start", n - 1); // The prompt is read in two parts when it has a turn boundary past `resume`: up to the last <|im_start|> @@ -2498,6 +2523,19 @@ int main(int argc, char** argv) { drive.d.experts = 0; 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(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); + } tr("window", p, T); if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err) || drive.d.failed) { std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str());