feat(sampler-ref): CPU reference of the Original sampler chain with host-oracle fixtures

New pure-Rust crate leleka-sampler-ref: Philox draw, penalties -> top_k ->
top_p -> min_p -> temperature -> inverse-CDF pick, greedy argmax, coupled-draft
counter/ring math, penalty_rows, exact-match acceptance, and the request-level
SamplingParams validation with the Original's GEN defaults and wire keys.

Golden fixtures come from compiling the Original's sampler_parity.cpp host
reference (included unmodified) and sampler/coupled_draft headers with clang++
(-ffp-contract=off), plus the verbatim StrataEngine.sampling_keys lifted from
server.py. No GPU, no speed or quality claim.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 14:42:51 +02:00
co-authored by Claude Sonnet 5.5
parent 8651f784ef
commit 45bad22b88
16 changed files with 3228 additions and 2 deletions
Generated
+7
View File
@@ -1052,6 +1052,13 @@ dependencies = [
"sha2",
]
[[package]]
name = "leleka-sampler-ref"
version = "0.1.0"
dependencies = [
"serde_json",
]
[[package]]
name = "leleka-tokenizer"
version = "0.1.0"
+2 -2
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "control-plane", "desktop-core"]
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "crates/sampler-ref", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/sampler-ref", "control-plane", "desktop-core"]
[workspace.package]
edition = "2024"
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "leleka-sampler-ref"
version = "0.1.0"
description = "Pure Rust CPU reference of the Original Strata sampler chain, Philox draw and coupled-draft counter math"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dev-dependencies]
serde_json = "1"
[lints]
workspace = true
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Rebuild the host oracle and regenerate the committed fixtures. macOS or Linux, clang++ or g++, no CUDA.
# crates/sampler-ref/oracle/build_oracle.sh [output_dir]
# -ffp-contract=off pins the host float evaluation to separate IEEE operations (no FMA), which is the
# contract the Rust reference documents. Compile flags are echoed into the fixture header.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
root=$(cd "$here/../../.." && pwd)
out=${1:-"$here/../tests/fixtures"}
bin=${TMPDIR:-/tmp}/leleka_sampler_oracle.$$
${CXX:-clang++} -std=c++17 -O1 -ffp-contract=off -fno-fast-math -Wno-unused-function -Wno-unused-variable \
-I "$root/engine/strata/include" -I "$here/stub" "$here/gen_fixtures.cpp" -o "$bin"
mkdir -p "$out"
"$bin" "$out/sampler_oracle.json"
rm -f "$bin"
+479
View File
@@ -0,0 +1,479 @@
// Golden-fixture generator for the Rust CPU sampler reference (crates/sampler-ref).
//
// WHAT THIS RUNS. The Original's own host-side logic, not a re-implementation:
// * `engine/strata/src/kernels/sampler_parity.cpp` is #included UNMODIFIED (its `main` renamed, a
// header-only stub standing in for <cuda_runtime.h>) so that `host_philox_uniform`,
// `sampled_reference`, `mirror_select`, `mirror_pick`, `sampled_k` are the Original's code;
// * `strata/kernels/sampler.hpp` (`penalty_rows`) and `strata/core/coupled_draft.hpp`
// (`coupled_draft_cell/counter`, `coupled_hist_len/start`, `coupled_hist_base`) are the Original's headers.
// The only code written here is the case generator, the JSON writer and `coupled_ref` below, which
// transcribes the DEVICE-ONLY coupled kernels (`coupled_penalize_kernel`, `coupled_merge_kernel`,
// `sampled_tail_warp<true>` in sampler.cu) because the Original has no host twin for them; it is
// cross-checked against the Original's `mirror_pick` on every case.
//
// Build/run: crates/sampler-ref/oracle/build_oracle.sh (compiles with -ffp-contract=off).
#define main original_sampler_parity_main
#include "../../../engine/strata/src/kernels/sampler_parity.cpp"
#undef main
#include "strata/core/coupled_draft.hpp"
#include <cinttypes>
namespace {
using strata::kernels::SamplerParams;
// ---- deterministic case source (splitmix64; no std::random distributions, which differ per stdlib) ----
struct Rng {
uint64_t s;
uint64_t next() {
uint64_t z = (s += 0x9E3779B97F4A7C15ull);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
double uni() { return (double) (next() >> 11) * (1.0 / 9007199254740992.0); }
int below(int n) { return (int) (next() % (uint64_t) n); }
double normal() { return (uni() + uni() + uni() + uni() - 2.0) * 1.7; }
template <class T> T pick(std::initializer_list<T> v) { return *(v.begin() + below((int) v.size())); }
};
uint32_t bits_of(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; }
float float_of(uint32_t u) { float f; std::memcpy(&f, &u, 4); return f; }
constexpr uint32_t kNaN = 0x7fc00000u, kNegNaN = 0xffc00000u, kInf = 0x7f800000u, kNegInf = 0xff800000u;
FILE* out = nullptr;
bool first_item = true;
void comma() { if (!first_item) std::fputs(",", out); first_item = false; }
void put_u32s(const std::vector<float>& v) {
std::fputc('[', out);
for (size_t i = 0; i < v.size(); ++i) std::fprintf(out, i ? ",%u" : "%u", bits_of(v[i]));
std::fputc(']', out);
}
void put_ints(const std::vector<int>& v) {
std::fputc('[', out);
for (size_t i = 0; i < v.size(); ++i) std::fprintf(out, i ? ",%d" : "%d", v[i]);
std::fputc(']', out);
}
void put_i32s(const std::vector<int32_t>& v) { put_ints(std::vector<int>(v.begin(), v.end())); }
void put_params(const SamplerParams& p) {
std::fprintf(out,
"{\"top_k\":%d,\"top_p\":%u,\"min_p\":%u,\"temperature\":%u,\"min_keep\":%d,\"penalty_last_n\":%d,"
"\"penalty_repeat\":%u,\"penalty_freq\":%u,\"penalty_present\":%u,\"seed\":%" PRIu64
",\"counter\":%" PRIu64 ",\"greedy\":%s}",
p.top_k, bits_of(p.top_p), bits_of(p.min_p), bits_of(p.temperature), p.min_keep, p.penalty_last_n,
bits_of(p.penalty_repeat), bits_of(p.penalty_freq), bits_of(p.penalty_present), p.seed, p.counter,
p.greedy ? "true" : "false");
}
std::vector<int> window_of(const std::vector<int>& hist, int penalty_last_n) {
// sampler.cu: hlen = min(penalty_last_n, history_len), clamped at 0; the window is the TAIL of the row
int hlen = std::min(penalty_last_n, (int) hist.size());
if (hlen < 0) hlen = 0;
return std::vector<int>(hist.end() - hlen, hist.end());
}
bool all_finite(const std::vector<float>& l) {
for (float x : l) if (!std::isfinite(x)) return false;
return true;
}
int mismatches = 0;
int n_cases = 0;
// One chain case: either a dense logit vector or a sparse full-vocabulary description.
struct SparseLogits {
int n = 0;
float fill = 0;
std::vector<std::pair<int, float>> set;
};
void emit_chain_case(const char* name, const std::vector<float>& logits, const SparseLogits* sparse,
const SamplerParams& p, int row, const std::vector<int>& hist) {
const int nv = (int) logits.size();
const std::vector<int> window = window_of(hist, p.penalty_last_n);
const int k = sampled_k(p.top_k, nv);
const bool greedy = p.greedy || p.temperature <= 0.0f;
// the Original's own semantics for the row: greedy = the first entry of the k=1 selection
const SelList sel1 = mirror_select(logits.data(), nv, window, p, 1);
const SelList sel = greedy ? sel1 : mirror_select(logits.data(), nv, window, p, k);
const int token = greedy ? sel1.ids[0] : mirror_pick(sel, k, p, row);
// cross-check the two Original references on rows where they must agree (finite, sampled)
if (!greedy && all_finite(logits)) {
const int ref = sampled_reference(logits, window, p, row);
if (ref != token) {
++mismatches;
std::fprintf(stderr, "reference disagreement in %s: mirror %d vs sampled_reference %d\n", name, token, ref);
}
}
comma();
std::fprintf(out, "\n{\"name\":\"%s\",\"n_vocab\":%d,\"row\":%d,\"params\":", name, nv, row);
put_params(p);
if (sparse) {
std::fprintf(out, ",\"sparse\":{\"fill\":%u,\"set\":[", bits_of(sparse->fill));
for (size_t i = 0; i < sparse->set.size(); ++i)
std::fprintf(out, i ? ",[%d,%u]" : "[%d,%u]", sparse->set[i].first, bits_of(sparse->set[i].second));
std::fputs("]}", out);
} else {
std::fputs(",\"logits\":", out);
put_u32s(logits);
}
std::fputs(",\"history\":", out);
put_ints(hist);
std::fprintf(out, ",\"expect\":{\"token\":%d,\"sel_ids\":", token);
put_ints(sel.ids);
std::fputs(",\"sel_logits\":", out);
put_u32s(sel.logit);
if (!greedy) std::fprintf(out, ",\"u\":%u", bits_of(host_philox_uniform(p.seed, p.counter + (uint64_t) row)));
std::fputs("}}", out);
++n_cases;
}
std::vector<float> make_logits(Rng& g, int nv, int mode) {
std::vector<float> l((size_t) nv);
for (int v = 0; v < nv; ++v) {
double x = g.normal();
switch (mode) {
case 0: l[(size_t) v] = (float) x; break; // plain
case 1: l[(size_t) v] = (float) (std::round(x * 2.0) / 2.0); break; // many exact ties
case 2: l[(size_t) v] = 1.25f; break; // all equal
case 3: { // non-finite mix
const int r = g.below(12);
l[(size_t) v] = r == 0 ? float_of(kNegInf) : r == 1 ? float_of(kNaN) : r == 2 ? float_of(kInf)
: r == 3 ? float_of(kNegNaN) : (float) x;
break;
}
case 4: l[(size_t) v] = (float) (x * 1e30); break; // huge magnitudes
case 5: l[(size_t) v] = (float) (x * 1e-40); break; // denormals
default: l[(size_t) v] = float_of(kNegInf); break; // all -inf
}
}
return l;
}
SamplerParams make_params(Rng& g, bool allow_greedy) {
SamplerParams p;
p.top_k = g.pick<int>({0, 1, 2, 5, 20, 20, 40, 63, 64, 65, 200, -3});
p.top_p = g.pick<float>({1.0f, 1.0f, 0.95f, 0.9f, 0.5f, 0.2f, 0.0f});
p.min_p = g.pick<float>({0.0f, 0.0f, 0.01f, 0.1f, 0.5f, 1.0f});
p.temperature = g.pick<float>({0.3f, 0.7f, 1.0f, 1.0f, 1.5f, 2.0f});
if (allow_greedy && g.below(6) == 0) p.temperature = g.pick<float>({0.0f, -1.0f});
p.greedy = allow_greedy && g.below(12) == 0;
p.min_keep = g.pick<int>({1, 1, 1, 2, 3});
p.penalty_last_n = g.pick<int>({0, 0, 4, 16, 64, 5000, -2});
p.penalty_repeat = g.pick<float>({1.0f, 1.1f, 1.5f, 2.0f, 0.8f});
p.penalty_freq = g.pick<float>({0.0f, 0.25f, 0.5f});
p.penalty_present = g.pick<float>({0.0f, 0.5f, 1.5f});
p.seed = g.pick<uint64_t>({0ull, 1ull, 42ull, 123456789ull, 0xFFFFFFFFull, 0x1FFFFFFFFull, 0xDEADBEEFCAFEF00Dull,
~0ull});
p.counter = g.pick<uint64_t>({0ull, 1ull, 7ull, 1000ull, (1ull << 32) + 7ull, 0xFFFFFFFFull, ~0ull - 3ull});
return p;
}
std::vector<int> make_history(Rng& g, int nv, int pln) {
int hl = g.pick<int>({0, 8, 32, 80});
if (pln > 0 && hl == 0) hl = 8;
std::vector<int> h((size_t) hl);
for (auto& t : h) {
const int r = g.below(10);
t = r < 2 ? -1 : r == 2 ? nv + g.below(3) : g.below(std::min(nv + 1, 12));
}
return h;
}
// ---- the coupled draft, serial (TRANSCRIPTION of the device-only kernels; see the file header) ----
struct CoupledResult { int id; float prob; int sub; };
CoupledResult coupled_ref(std::vector<float> l, const std::vector<int>& sub_to_id, const std::vector<int>& id_to_sub,
int id_vocab, const SamplerParams& params, std::vector<int>& ring, int cap, int j,
int step0, int& tail_pick_check) {
const int nv = (int) l.size();
// coupled_penalize_kernel
const int h = strata::core::coupled_hist_len(params.penalty_last_n, cap);
if (h > 0) {
const int* hrow = ring.data() + strata::core::coupled_hist_start(cap, j, h);
std::vector<char> seen((size_t) nv, 0);
for (int i = 0; i < h; ++i) {
const int v = hrow[i];
if (v < 0 || v >= id_vocab) continue;
const int s = id_to_sub.empty() ? v : id_to_sub[(size_t) v];
if (s < 0 || s >= nv) continue;
if (seen[(size_t) s]) continue;
seen[(size_t) s] = 1;
int c = 0;
for (int q = 0; q < h; ++q) c += hrow[q] == v;
float x = l[(size_t) s];
if (c > 0) {
if (x <= 0.0f) x *= params.penalty_repeat; else x /= params.penalty_repeat;
x -= (float) c * params.penalty_freq + (c > 0 ? 1.0f : 0.0f) * params.penalty_present;
}
l[(size_t) s] = x;
}
}
// coupled_merge_kernel
SamplerParams p = params;
p.counter = strata::core::coupled_draft_counter((int64_t) step0);
const int k = sampled_k(p.top_k, nv);
SamplerParams none; // the split-part launch passes SamplerParams{} (no penalties)
const SelList sel = mirror_select(l.data(), nv, std::vector<int>(), none, k);
int pick_idx = 0;
float prob = 1.0f;
if (p.greedy || p.temperature <= 0.0f) {
pick_idx = 0;
tail_pick_check = sel.ids[0];
} else {
// sampled_tail_warp<true>: top_p, min_p, temperature, draw, and the pick's probability
int n_keep = k;
float mx = sel.logit[0];
for (int i = 1; i < k; ++i) mx = std::fmax(mx, sel.logit[(size_t) i]);
if (p.top_p < 1.0f) {
double sum = 0.0;
for (int i = 0; i < k; ++i) sum += std::exp((double) sel.logit[(size_t) i] - (double) mx);
double cum = 0.0;
int cut = k;
for (int i = 0; i < k; ++i) {
cum += std::exp((double) sel.logit[(size_t) 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;
n_keep = cut;
}
if (p.min_p > 0.0f) {
const float thresh = sel.logit[0] + std::log(p.min_p);
for (int i = 0; i < n_keep; ++i)
if (sel.logit[(size_t) i] < thresh) { n_keep = i; break; }
}
const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
float smx = sel.logit[0] * inv_t;
for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, sel.logit[(size_t) i] * inv_t);
std::vector<double> ex((size_t) std::max(n_keep, 1));
for (int i = 0; i < n_keep; ++i) ex[(size_t) i] = std::exp((double) (sel.logit[(size_t) i] * inv_t) - (double) smx);
double sum = 0.0;
for (int i = 0; i < n_keep; ++i) sum += ex[(size_t) i];
for (int i = 0; i < n_keep; ++i) ex[(size_t) i] = ex[(size_t) i] / sum;
const float u = host_philox_uniform(p.seed, p.counter + 0u);
double cum = 0.0;
pick_idx = n_keep > 0 ? n_keep - 1 : 0;
for (int i = 0; i < n_keep; ++i) {
cum += ex[(size_t) i];
if ((double) u < cum) { pick_idx = i; break; }
}
prob = n_keep > 0 ? (float) ex[(size_t) pick_idx] : 1.0f;
tail_pick_check = mirror_pick(sel, k, p, 0); // the Original's own tail must agree
}
const int s = sel.ids[(size_t) pick_idx];
const int id = sub_to_id.empty() ? s : sub_to_id[(size_t) s];
ring[(size_t) (cap + j)] = id;
return {id, prob, s};
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) { std::fprintf(stderr, "usage: %s out.json\n", argv[0]); return 2; }
out = std::fopen(argv[1], "w");
if (!out) { std::perror("open"); return 2; }
Rng g{0x5A17E7E5ull};
std::fputs("{\n\"meta\":{\"generator\":\"crates/sampler-ref/oracle/gen_fixtures.cpp\","
"\"oracle\":\"Original engine/strata sampler_parity.cpp host reference, included unmodified; "
"sampler.hpp + coupled_draft.hpp headers\","
"\"compile\":\"-std=c++17 -O1 -ffp-contract=off -fno-fast-math\","
"\"encoding\":\"floats are IEEE-754 binary32 bit patterns (u32)\"},\n", out);
// ---------------- philox ----------------
std::fputs("\"philox\":[", out);
first_item = true;
{
std::vector<std::pair<uint64_t, uint64_t>> pts = {
{0, 0}, {0, 1}, {1, 0}, {1, 1}, {42, 7}, {123, (1ull << 32) + 7}, {0xFFFFFFFFull, 0xFFFFFFFFull},
{0x100000000ull, 0}, {0, 0x100000000ull}, {~0ull, ~0ull}, {0xDEADBEEFCAFEF00Dull, 12345678901234ull}};
for (int i = 0; i < 80; ++i) pts.push_back({g.next(), g.next() >> (g.below(40))});
for (auto& pr : pts) {
comma();
std::fprintf(out, "\n[%" PRIu64 ",%" PRIu64 ",%u]", pr.first, pr.second,
bits_of(host_philox_uniform(pr.first, pr.second)));
}
}
std::fputs("\n],\n", out);
// ---------------- chain ----------------
std::fputs("\"chain\":[", out);
first_item = true;
{
int idx = 0;
char name[64];
// random dense rows over several vocabularies and logit shapes
for (int nv : {1, 2, 5, 16, 33, 64, 65, 100, 257})
for (int rep = 0; rep < (nv > 100 ? 2 : 14); ++rep) {
const int mode = rep % 7 == 6 ? 1 : (rep % 11 == 10 ? 2 : 0);
SamplerParams p = make_params(g, true);
const auto l = make_logits(g, nv, mode);
const auto h = make_history(g, nv, p.penalty_last_n);
std::snprintf(name, sizeof name, "rand-%d-%d", nv, rep);
emit_chain_case(name, l, nullptr, p, g.below(4), h);
++idx;
}
// edge shapes: non-finite mix, huge, denormal, all -inf, ties, k larger than the finite count
for (int mode : {3, 3, 3, 3, 4, 4, 5, 5, 6, 1, 1, 2})
for (int nv : {3, 12, 70}) {
SamplerParams p = make_params(g, true);
const auto l = make_logits(g, nv, mode);
const auto h = make_history(g, nv, p.penalty_last_n);
std::snprintf(name, sizeof name, "edge-m%d-%d-%d", mode, nv, idx++);
emit_chain_case(name, l, nullptr, p, g.below(3), h);
}
// penalties that matter: a clear head token repeatedly in the window
for (int rep = 0; rep < 16; ++rep) {
SamplerParams p = make_params(g, false);
p.penalty_last_n = 16;
p.penalty_repeat = g.pick<float>({1.5f, 2.0f, 3.0f});
p.penalty_freq = g.pick<float>({0.0f, 0.5f, 0.25f});
p.penalty_present = g.pick<float>({0.0f, 1.0f, 0.5f});
p.top_k = 8;
p.top_p = g.pick<float>({1.0f, 0.9f});
auto l = make_logits(g, 24, 0);
l[3] = 6.0f; l[9] = 5.5f; l[17] = -2.0f;
std::vector<int> h = {-1, -1, 3, 3, 3, 9, 17, 17, 40, -1, 3, 9, 17, 5, 5, 3};
std::snprintf(name, sizeof name, "penal-%d", rep);
emit_chain_case(name, l, nullptr, p, rep % 3, h);
}
// top_p lands EXACTLY on a cumulative boundary (equal logits: cum = 1/n, 2/n, ...), so `cum >= top_p` vs `>` is
// observable; 16 seeds per case so the draw reaches the entry that only the wrong comparison would keep
for (int n : {4, 8})
for (int step = 1; step < n; ++step)
for (int sd = 0; sd < 6; ++sd) {
SamplerParams p;
p.top_k = n; p.top_p = (float) step / (float) n; p.temperature = 1.0f; p.min_p = 0.0f;
p.seed = 1000 + (uint64_t) sd * 7919; p.counter = (uint64_t) sd;
std::vector<float> l((size_t) n + 2, 3.0f);
l[(size_t) n] = -20.0f; l[(size_t) n + 1] = -20.0f;
std::snprintf(name, sizeof name, "tp-boundary-%d-%d-%d", n, step, sd);
emit_chain_case(name, l, nullptr, p, 0, std::vector<int>());
}
// full-vocabulary sparse rows (the closed GPU op's geometry: 248,320 logits, up to 4,096 history slots)
for (int rep = 0; rep < 14; ++rep) {
SparseLogits sp;
sp.n = 248320;
sp.fill = g.pick<float>({-5.0f, -9.5f, 0.0f});
std::vector<float> l((size_t) sp.n, sp.fill);
const int n_set = 6 + g.below(120);
for (int i = 0; i < n_set; ++i) {
const int at = g.below(sp.n);
const float val = (float) (g.normal() * 3.0 + 2.0);
sp.set.push_back({at, val});
l[(size_t) at] = val;
}
if (rep % 4 == 1)
for (int i = 0; i < 8; ++i) { sp.set.push_back({1000 + 7 * i, 4.5f}); l[(size_t) (1000 + 7 * i)] = 4.5f; } // ties
if (rep == 13) { sp.set.push_back({5, float_of(kNegInf)}); l[5] = float_of(kNegInf); }
SamplerParams p = make_params(g, rep % 5 == 4);
if (rep % 3 == 0) { p.penalty_last_n = 64; }
std::vector<int> h(rep == 2 ? 4096 : 64, -1);
for (size_t i = h.size() > 40 ? h.size() - 40 : 0; i < h.size(); ++i)
h[i] = sp.set.empty() ? 0 : sp.set[(size_t) g.below((int) sp.set.size())].first;
if (rep == 2) p.penalty_last_n = 4096;
if (p.penalty_last_n > 0 && h.empty()) h.assign(8, -1);
std::snprintf(name, sizeof name, "full-%d", rep);
emit_chain_case(name, l, &sp, p, 0, h);
}
}
std::fputs("\n],\n", out);
// ---------------- counters (coupled_draft.hpp, verbatim header functions) ----------------
std::fputs("\"counters\":{\"cells\":[", out);
first_item = true;
for (int64_t p : {0ll, 1ll, 100ll, 4095ll, 1000000ll, (long long) 1 << 40})
for (int a : {0, 1, 7})
for (int j : {0, 1, 6}) {
comma();
const int64_t cell = strata::core::coupled_draft_cell(p, a, j);
std::fprintf(out, "\n[%" PRId64 ",%d,%d,%" PRId64 ",%" PRIu64 "]", p, a, j, cell,
strata::core::coupled_draft_counter(cell));
}
std::fputs("\n],\"hist_len\":[", out);
first_item = true;
for (int cap : {8, 64, strata::core::kCoupledHistCap})
for (int pln : {-1, 0, 1, 7, 8, 9, 64, 4095, 4096, 4097, 100000}) {
comma();
std::fprintf(out, "\n[%d,%d,%d]", pln, cap, strata::core::coupled_hist_len(pln, cap));
}
std::fputs("\n],\"hist_start\":[", out);
first_item = true;
for (int cap : {8, 64, strata::core::kCoupledHistCap})
for (int h : {1, 3, 8})
for (int j : {0, 1, 6}) {
comma();
std::fprintf(out, "\n[%d,%d,%d,%d]", cap, j, h, strata::core::coupled_hist_start(cap, j, h));
}
std::fputs("\n]},\n", out);
// ---------------- penalty_rows + coupled_hist_base (sampler.hpp / coupled_draft.hpp, verbatim) ----------------
std::fputs("\"penalty_rows\":[", out);
first_item = true;
for (int rep = 0; rep < 60; ++rep) {
const int n_tail = g.pick<int>({0, 1, 2, 5, 7, 20});
const int T = 1 + g.below(8);
const int h = g.pick<int>({1, 3, 8, 16});
std::vector<int32_t> tail((size_t) n_tail), window((size_t) T), rows((size_t) T * (size_t) h);
for (auto& t : tail) t = g.below(1000);
for (auto& t : window) t = g.below(1000);
strata::kernels::penalty_rows(tail.data(), n_tail, window.data(), T, h, rows.data());
comma();
std::fputs("\n{\"tail\":", out); put_i32s(tail);
std::fputs(",\"window\":", out); put_i32s(window);
std::fprintf(out, ",\"h\":%d,\"rows\":", h); put_i32s(rows);
const int32_t next = g.below(1000);
std::vector<int32_t> base((size_t) h, 777777);
strata::core::coupled_hist_base(tail.data(), n_tail, next, h, base.data());
std::fprintf(out, ",\"next\":%d,\"base\":", next); put_i32s(base);
std::fputs("}", out);
}
std::fputs("\n],\n", out);
// ---------------- coupled draft sampling (transcribed kernels, cross-checked against mirror_pick) ----------------
std::fputs("\"coupled\":[", out);
first_item = true;
for (int rep = 0; rep < 60; ++rep) {
const int nv = g.pick<int>({7, 24, 70, 130});
const bool subset = rep % 3 == 1;
const int id_vocab = subset ? nv * 3 : nv;
std::vector<int> sub_to_id, id_to_sub;
if (subset) {
id_to_sub.assign((size_t) id_vocab, -1);
for (int s = 0; s < nv; ++s) { // subset s -> token id 3 s + 1 (an injective map)
sub_to_id.push_back(3 * s + 1);
id_to_sub[(size_t) (3 * s + 1)] = s;
}
}
SamplerParams p = make_params(g, false);
p.penalty_last_n = g.pick<int>({0, 3, 8, 12, 20});
auto l = make_logits(g, nv, rep % 9 == 8 ? 1 : 0);
const int cap = g.pick<int>({16, 32});
const int j = g.below(4);
std::vector<int> ring((size_t) cap + 8, -1);
for (int i = 0; i < cap + j; ++i)
ring[(size_t) i] = g.below(5) == 0 ? -1 : (subset ? 3 * g.below(std::min(nv, 6)) + 1 : g.below(std::min(nv, 6)));
if (rep % 7 == 3) for (int i = 0; i < cap + j; ++i) if (g.below(4) == 0) ring[(size_t) i] = id_vocab + 1; // out of vocab
const int step0 = g.below(100000);
const std::vector<int> ring_in = ring;
int check = -1;
const CoupledResult r = coupled_ref(l, sub_to_id, id_to_sub, id_vocab, p, ring, cap, j, step0, check);
if (check != r.sub) { ++mismatches; std::fprintf(stderr, "coupled tail disagreement in case %d\n", rep); }
comma();
std::fprintf(out, "\n{\"cap\":%d,\"j\":%d,\"step0\":%d,\"id_vocab\":%d,\"logits\":", cap, j, step0, id_vocab);
put_u32s(l);
std::fputs(",\"params\":", out); put_params(p);
std::fputs(",\"sub_to_id\":", out); put_ints(sub_to_id);
std::fputs(",\"id_to_sub\":", out); put_ints(id_to_sub);
std::fputs(",\"ring\":", out); put_ints(ring_in);
std::fprintf(out, ",\"expect\":{\"id\":%d,\"sub\":%d,\"prob\":%u}}", r.id, r.sub, bits_of(r.prob));
++n_cases;
}
std::fputs("\n]\n}\n", out);
std::fclose(out);
std::fprintf(stderr, "wrote %d cases, %d oracle disagreements\n", n_cases, mismatches);
return mismatches == 0 ? 0 : 3;
}
@@ -0,0 +1,78 @@
"""Offline fixture generator (Python is allowed for experiments/fixtures, never for serving).
Runs the Original's `StrataEngine.sampling_keys` (engine/strata/serve/server.py) over a table of requests and
records the exact GEN key string it emits, plus the ranges `clean_shared_defaults` /
`sampling_defaults_from_config` enforce. Usage:
python3 -I crates/sampler-ref/oracle/gen_sampling_keys.py crates/sampler-ref/tests/fixtures/sampling_keys.json
The two pure functions are lifted verbatim from the Original's AST; nothing else of server.py is imported.
"""
import ast
import json
import os
import sys
here = os.path.dirname(os.path.abspath(__file__))
server_py = os.path.normpath(os.path.join(here, "..", "..", "..", "engine", "strata", "serve", "server.py"))
# server.py imports the whole serving stack (jinja2, sockets, ...). The two functions under test are pure, so lift
# their source verbatim out of the AST instead of importing the module.
tree = ast.parse(open(server_py).read(), server_py)
engine = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "StrataEngine")
wanted = [n for n in engine.body if isinstance(n, ast.FunctionDef) and n.name in ("sampling_keys", "projection_key")]
assert {n.name for n in wanted} == {"sampling_keys", "projection_key"}
lifted = ast.Module(body=[ast.ClassDef(name="StrataEngine", bases=[], keywords=[], body=wanted, decorator_list=[])],
type_ignores=[])
ast.fix_missing_locations(lifted)
ns = {}
exec(compile(lifted, server_py, "exec"), ns)
class server: # noqa: N801 - keeps the call below readable
StrataEngine = ns["StrataEngine"]
keys = server.StrataEngine.sampling_keys
cases = [
{},
{"temperature": 0.0},
{"temperature": 0.7},
{"temperature": 1},
{"temperature": 2.0},
{"temperature": 0.1 + 0.2},
{"temperature": 1e-7},
{"temperature": 0.7, "top_p": 0.95},
{"temperature": 0.7, "top_p": 1.0},
{"top_p": 0.0},
{"top_p": 0.5},
{"top_k": 0}, {"top_k": 1}, {"top_k": 20}, {"top_k": 64}, {"top_k": 65}, {"top_k": 100000},
{"min_p": 0.0}, {"min_p": 0.05}, {"min_p": 1.0}, {"min_p": 1e-5},
{"repetition_penalty": 1.0},
{"repetition_penalty": 1.1},
{"repetition_penalty": 1.1, "penalty_last_n": 256},
{"repetition_penalty": 1.1, "penalty_last_n": 0},
{"repetition_penalty": 1.1, "penalty_last_n": 5000},
{"frequency_penalty": 0.5},
{"frequency_penalty": -0.5},
{"presence_penalty": 0.25},
{"presence_penalty": 1.5, "frequency_penalty": 0.5, "repetition_penalty": 1.05},
{"presence_penalty": 0.0, "frequency_penalty": 0.0, "repetition_penalty": 1.0, "penalty_last_n": 33},
{"penalty_last_n": 33},
{"seed": 1}, {"seed": 42}, {"seed": 18446744073709551615},
{"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.02, "repetition_penalty": 1.1,
"presence_penalty": 0.5, "frequency_penalty": 0.25, "penalty_last_n": 128, "seed": 7},
{"temperature": 1e16}, {"temperature": 1.5e-5},
]
# the request-boundary rule (Rust) is stricter than the Original's silent skipping: those are tested in Rust only
out = {
"meta": {"generator": "crates/sampler-ref/oracle/gen_sampling_keys.py",
"oracle": "engine/strata/serve/server.py StrataEngine.sampling_keys"},
"cases": [{"request": c, "keys": keys(dict(c))} for c in cases],
}
with open(sys.argv[1], "w") as f:
f.write('{"meta":' + json.dumps(out["meta"]) + ',\n"cases":[\n')
f.write(",\n".join(json.dumps(c) for c in out["cases"]))
f.write("\n]}\n")
print(f"wrote {len(cases)} cases")
@@ -0,0 +1,38 @@
// Host-only stand-in for <cuda_runtime.h> so the Original's sampler_parity.cpp host reference
// (host_philox_uniform, sampled_reference, mirror_select, mirror_pick) can be compiled UNMODIFIED
// on a machine without CUDA. Nothing here is ever called by the fixture generator; every entry
// point aborts. The declarations only have to be enough for the file to parse.
#pragma once
#include <cstdio>
#include <cstdlib>
#include <cstddef>
typedef int cudaError_t;
typedef void* cudaStream_t;
typedef void* cudaEvent_t;
typedef void* cudaGraph_t;
typedef void* cudaGraphExec_t;
enum { cudaSuccess = 0 };
enum cudaMemcpyKind { cudaMemcpyHostToDevice = 1, cudaMemcpyDeviceToHost = 2 };
enum cudaStreamCaptureMode { cudaStreamCaptureModeThreadLocal = 1 };
[[noreturn]] inline void oracle_stub_abort() { std::fprintf(stderr, "cuda stub called\n"); std::abort(); }
inline const char* cudaGetErrorString(cudaError_t) { oracle_stub_abort(); }
template <class T> inline cudaError_t cudaMalloc(T**, size_t) { oracle_stub_abort(); }
inline cudaError_t cudaFree(void*) { oracle_stub_abort(); }
inline cudaError_t cudaMemcpy(void*, const void*, size_t, cudaMemcpyKind) { oracle_stub_abort(); }
inline cudaError_t cudaMemset(void*, int, size_t) { oracle_stub_abort(); }
inline cudaError_t cudaStreamCreate(cudaStream_t*) { oracle_stub_abort(); }
inline cudaError_t cudaStreamDestroy(cudaStream_t) { oracle_stub_abort(); }
inline cudaError_t cudaStreamSynchronize(cudaStream_t) { oracle_stub_abort(); }
inline cudaError_t cudaStreamBeginCapture(cudaStream_t, cudaStreamCaptureMode) { oracle_stub_abort(); }
inline cudaError_t cudaStreamEndCapture(cudaStream_t, cudaGraph_t*) { oracle_stub_abort(); }
inline cudaError_t cudaGraphInstantiate(cudaGraphExec_t*, cudaGraph_t, unsigned long long) { oracle_stub_abort(); }
inline cudaError_t cudaGraphLaunch(cudaGraphExec_t, cudaStream_t) { oracle_stub_abort(); }
inline cudaError_t cudaGraphDestroy(cudaGraph_t) { oracle_stub_abort(); }
inline cudaError_t cudaGraphExecDestroy(cudaGraphExec_t) { oracle_stub_abort(); }
inline cudaError_t cudaEventCreate(cudaEvent_t*) { oracle_stub_abort(); }
inline cudaError_t cudaEventDestroy(cudaEvent_t) { oracle_stub_abort(); }
inline cudaError_t cudaEventRecord(cudaEvent_t, cudaStream_t = nullptr) { oracle_stub_abort(); }
inline cudaError_t cudaEventSynchronize(cudaEvent_t) { oracle_stub_abort(); }
inline cudaError_t cudaEventElapsedTime(float*, cudaEvent_t, cudaEvent_t) { oracle_stub_abort(); }
+555
View File
@@ -0,0 +1,555 @@
//! The sampler chain, in llama.cpp's order, as the Original runs it:
//!
//! ```text
//! penalties -> top_k -> top_p -> min_p -> temperature -> inverse-CDF pick
//! ```
//!
//! Source of truth: `engine/strata/src/kernels/cuda/sampler.cu`
//! (`sampler_greedy_kernel`, `sampler_kernel`, `sampler_one_block_kernel`,
//! `sampled_tail_warp`) and the host mirrors `mirror_select` / `mirror_pick`
//! in `sampler_parity.cpp`. The three sampled kernels of the Original (old,
//! one-block, split) pick the same token bit for bit; this is that token.
//!
//! # Float-ordering assumptions (documented, not hidden)
//!
//! * Every `f32` operation is a separate IEEE operation, **no fused
//! multiply-add**: `count * freq + present_flag * present` is two multiplies
//! and one add. The oracle fixtures are built with `-ffp-contract=off`.
//! (`nvcc` fuses by default; build the sampler PTX with `--fmad=false` for
//! bit-exactness on inputs where it matters - see `original_sampler.cu`.)
//! * Sums are strictly sequential in list order (`f64`), exactly the Original's
//! ordered sums; no pairwise or vectorised summation.
//! * `exp` is `f64::exp` and the min_p threshold uses `f32::ln` (`logf`): the
//! platform libm, like the Original host reference. Cross-libm results can
//! differ by 1 ulp; that can only flip a pick when `u` lands within ~1e-16 of
//! a cumulative boundary, and can flip a cut only on a boundary tie.
//! * `fmaxf` is `f32::max` (NaN-ignoring). Selected logits are never NaN.
use crate::philox::philox_uniform;
/// The widest top_k list the Original keeps (`kSelMax` / `KMAX`).
pub const MAX_SELECT: usize = 64;
/// serve's `kPenaltyWindowCap`: history rows are capped at this many tokens.
pub const PENALTY_WINDOW_CAP: usize = 4096;
/// `strata::kernels::SamplerParams` (sampler.hpp), field for field.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SamplerParams {
/// Sampled path: 1..=63 as given; 0 (off), 64 or more keep the widest list, 64.
pub top_k: i32,
/// `>= 1.0` disables the filter.
pub top_p: f32,
/// 0 disables; keeps tokens whose logit is at least `l0 + ln(min_p)`.
pub min_p: f32,
/// `<= 0` means greedy.
pub temperature: f32,
/// top_p keeps at least this many.
pub min_keep: i32,
/// 0 disables; the window over the history rows to count occurrences in.
pub penalty_last_n: i32,
pub penalty_repeat: f32,
pub penalty_freq: f32,
pub penalty_present: f32,
/// Philox key.
pub seed: u64,
/// Absolute draw index of row 0; row `t` draws at `counter + t`.
pub counter: u64,
pub greedy: bool,
}
impl Default for SamplerParams {
/// The C++ member initialisers (`top_k = 20`, `top_p = 0.95`, `temperature = 1.0`...).
fn default() -> Self {
Self {
top_k: 20,
top_p: 0.95,
min_p: 0.0,
temperature: 1.0,
min_keep: 1,
penalty_last_n: 0,
penalty_repeat: 1.0,
penalty_freq: 0.0,
penalty_present: 0.0,
seed: 0,
counter: 0,
greedy: false,
}
}
}
impl SamplerParams {
/// `sample_tokens` takes the argmax path when `greedy || temperature <= 0`.
pub fn is_greedy(&self) -> bool {
self.greedy || self.temperature <= 0.0
}
}
/// Failures the Original reports with `exit(1)` or leaves undefined; this port fails closed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SamplerError {
/// `n_vocab == 0` with rows to sample (the Original silently returns).
EmptyVocabulary,
/// `logits.len() != n_tokens * n_vocab`.
LogitsLength { expected: usize, actual: usize },
/// `penalty_last_n > 0` without a history (the Original prints and exits).
HistoryRequired,
/// `history.len() != n_tokens * history_len`.
HistoryShape { expected: usize, actual: usize },
}
/// The top_k list in selection order: descending by penalised logit, ties to
/// the lower token id. A round that finds no finite candidate records the
/// sentinel `(id 0, -inf)`.
#[derive(Clone, Debug, PartialEq)]
pub struct Selection {
pub ids: Vec<i32>,
pub logits: Vec<f32>,
}
/// The outcome of the tail (top_p, min_p, temperature, draw).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Pick {
pub token: i32,
/// Index of `token` in the selection list.
pub index: usize,
/// Entries that survived top_p and min_p.
pub n_keep: usize,
/// Probability of `token` under the final distribution (`kProb` of the
/// coupled draft; `1.0` when nothing survived).
pub prob: f32,
/// The uniform that was drawn.
pub uniform: f32,
}
/// Top_k request -> list length: 1..=63 as given, anything else 64, never more
/// than the vocabulary (`sampled_k`).
pub fn sampled_k(top_k: i32, n_vocab: usize) -> usize {
let k = if top_k > 0 && (top_k as usize) < MAX_SELECT {
top_k as usize
} else {
MAX_SELECT
};
k.min(n_vocab)
}
/// `apply_penalties`: the repeat penalty MULTIPLIES a non-positive logit and
/// DIVIDES a positive one; the presence term is the boolean `count > 0`.
pub fn apply_penalties(mut logit: f32, count: i32, p: &SamplerParams) -> f32 {
if count <= 0 {
return logit;
}
if logit <= 0.0 {
logit *= p.penalty_repeat;
} else {
logit /= p.penalty_repeat;
}
let flag: f32 = if count > 0 { 1.0 } else { 0.0 };
let freq = (count as f32) * p.penalty_freq;
let present = flag * p.penalty_present;
logit -= freq + present;
logit
}
/// The counted window of one history row: its last `min(penalty_last_n,
/// history_len)` entries (`hrow += history_len - hlen`).
pub fn penalty_window(history_row: &[i32], penalty_last_n: i32) -> &[i32] {
let hlen = usize::try_from(penalty_last_n.max(0))
.unwrap_or(0)
.min(history_row.len());
&history_row[history_row.len() - hlen..]
}
/// Penalised logits of a row: each in-vocabulary token occurring `c > 0` times
/// in `window` goes through [`apply_penalties`] once with count `c`. Ids
/// outside `[0, n_vocab)` are ignored.
pub fn penalised_logits(logits: &[f32], window: &[i32], p: &SamplerParams) -> Vec<f32> {
let mut s = logits.to_vec();
let mut ids: Vec<usize> = window
.iter()
.filter_map(|&h| usize::try_from(h).ok())
.filter(|&h| h < logits.len())
.collect();
ids.sort_unstable();
let mut i = 0;
while i < ids.len() {
let v = ids[i];
let mut j = i;
while j < ids.len() && ids[j] == v {
j += 1;
}
s[v] = apply_penalties(logits[v], (j - i) as i32, p);
i = j;
}
s
}
/// The greedy argmax over (already penalised) logits: strict `>` from `-inf`,
/// so the LOWEST index wins ties, NaN and `-inf` are never picked, and a row
/// with no candidate answers 0.
pub fn greedy_pick(scores: &[f32]) -> i32 {
let mut bv = f32::NEG_INFINITY;
let mut best = scores.len();
for (v, &s) in scores.iter().enumerate() {
if s > bv {
bv = s;
best = v;
}
}
if best < scores.len() { best as i32 } else { 0 }
}
/// `k` rounds of "first unpicked maximum" (`mirror_select`). Sentinel rounds
/// store `(0, -inf)` and mark id 0 taken, as the Original does.
pub fn select_topk(scores: &[f32], k: usize) -> Selection {
let n = scores.len();
let mut taken = vec![false; n];
let mut ids = Vec::with_capacity(k);
let mut logits = Vec::with_capacity(k);
for _ in 0..k {
let mut best = n;
let mut bv = f32::NEG_INFINITY;
for (v, &s) in scores.iter().enumerate() {
if !taken[v] && s > bv {
bv = s;
best = v;
}
}
let id = if best < n { best } else { 0 };
taken[id] = true;
ids.push(id as i32);
logits.push(bv);
}
Selection { ids, logits }
}
/// The tail of the chain over a selection list: top_p over the whole list,
/// then min_p on its survivors, temperature, one Philox draw at `counter`.
/// `sampled_tail_warp` / `mirror_pick`, instruction for instruction.
pub fn pick_from_list(sel: &Selection, p: &SamplerParams, counter: u64) -> Pick {
let k = sel.ids.len();
let l = &sel.logits;
let inv_t: f32 = if p.temperature > 0.0 {
1.0f32 / p.temperature
} else {
0.0
};
let mut n_keep = k;
let mut mx = l[0];
for &x in &l[1..] {
mx = mx.max(x);
}
if p.top_p < 1.0 {
let mut sum = 0.0f64;
for &x in l.iter() {
sum += (f64::from(x) - f64::from(mx)).exp();
}
let mut cum = 0.0f64;
let mut cut = k;
for (i, &x) in l.iter().enumerate() {
cum += (f64::from(x) - f64::from(mx)).exp() / sum;
if cum >= f64::from(p.top_p) {
cut = i + 1;
break;
}
}
if (cut as i64) < i64::from(p.min_keep) {
cut = if i64::from(p.min_keep) < k as i64 {
p.min_keep as usize
} else {
k
};
}
n_keep = cut;
}
if p.min_p > 0.0 {
let thresh = l[0] + p.min_p.ln();
for (i, &x) in l.iter().enumerate().take(n_keep) {
if x < thresh {
n_keep = i;
break;
}
}
}
let scaled = |i: usize| l[i] * inv_t;
let mut smx = scaled(0);
for i in 1..n_keep {
smx = smx.max(scaled(i));
}
let exps: Vec<f64> = (0..n_keep)
.map(|i| (f64::from(scaled(i)) - f64::from(smx)).exp())
.collect();
let mut sum = 0.0f64;
for &e in &exps {
sum += e;
}
let u = philox_uniform(p.seed, counter);
let mut cum = 0.0f64;
let mut pi = n_keep.saturating_sub(1);
for (i, &e) in exps.iter().enumerate() {
cum += e / sum;
if f64::from(u) < cum {
pi = i;
break;
}
}
let prob = if n_keep > 0 {
(exps[pi] / sum) as f32
} else {
1.0
};
Pick {
token: sel.ids[pi],
index: pi,
n_keep,
prob,
uniform: u,
}
}
/// One row through the whole chain. `history_row` is that row's history slice
/// (`history_len` slots, unused ones `-1`, most recent last); pass `&[]` when
/// no penalties apply. `row` offsets the Philox counter.
pub fn sample_row(
logits: &[f32],
history_row: &[i32],
p: &SamplerParams,
row: u64,
) -> Result<i32, SamplerError> {
if logits.is_empty() {
return Err(SamplerError::EmptyVocabulary);
}
if p.penalty_last_n > 0 && history_row.is_empty() {
return Err(SamplerError::HistoryRequired);
}
let window = penalty_window(history_row, p.penalty_last_n);
let scores = penalised_logits(logits, window, p);
if p.is_greedy() {
return Ok(greedy_pick(&scores));
}
let k = sampled_k(p.top_k, logits.len());
let sel = select_topk(&scores, k);
Ok(pick_from_list(&sel, p, p.counter.wrapping_add(row)).token)
}
/// `sample_tokens`: `logits` is `(n_tokens, n_vocab)` row-major; `history` is
/// `(slice of n_tokens * history_len int32, history_len)` or `None`. Row `t`
/// draws at counter `p.counter + t`.
pub fn sample_tokens(
logits: &[f32],
n_tokens: usize,
n_vocab: usize,
history: Option<(&[i32], usize)>,
p: &SamplerParams,
) -> Result<Vec<i32>, SamplerError> {
if n_tokens == 0 {
return Ok(Vec::new());
}
if n_vocab == 0 {
return Err(SamplerError::EmptyVocabulary);
}
let expected = n_tokens
.checked_mul(n_vocab)
.ok_or(SamplerError::LogitsLength {
expected: usize::MAX,
actual: logits.len(),
})?;
if logits.len() != expected {
return Err(SamplerError::LogitsLength {
expected,
actual: logits.len(),
});
}
let hl = history.map_or(0, |(_, hl)| hl);
if p.penalty_last_n > 0 && (history.is_none() || hl == 0) {
return Err(SamplerError::HistoryRequired);
}
if let Some((h, hl)) = history
&& h.len() != n_tokens * hl
{
return Err(SamplerError::HistoryShape {
expected: n_tokens * hl,
actual: h.len(),
});
}
(0..n_tokens)
.map(|t| {
let row = &logits[t * n_vocab..(t + 1) * n_vocab];
let hist: &[i32] = match history {
Some((h, hl)) if hl > 0 => &h[t * hl..(t + 1) * hl],
_ => &[],
};
sample_row(row, hist, p, t as u64)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn p() -> SamplerParams {
SamplerParams {
seed: 7,
..SamplerParams::default()
}
}
#[test]
fn sampled_k_rules() {
assert_eq!(sampled_k(20, 1000), 20);
assert_eq!(sampled_k(0, 1000), 64);
assert_eq!(sampled_k(-5, 1000), 64);
assert_eq!(sampled_k(63, 1000), 63);
assert_eq!(sampled_k(64, 1000), 64);
assert_eq!(sampled_k(65, 1000), 64);
assert_eq!(sampled_k(20, 8), 8);
}
#[test]
fn repeat_penalty_multiplies_negative_and_divides_positive() {
let q = SamplerParams {
penalty_repeat: 2.0,
..p()
};
assert_eq!(apply_penalties(-3.0, 1, &q), -6.0);
assert_eq!(apply_penalties(4.0, 1, &q), 2.0);
assert_eq!(apply_penalties(4.0, 0, &q), 4.0);
let r = SamplerParams {
penalty_freq: 0.5,
penalty_present: 1.5,
..p()
};
// count 3: 3*0.5 + 1*1.5 = 3.0 off the (unchanged) logit
assert_eq!(apply_penalties(10.0, 3, &r), 7.0);
}
#[test]
fn greedy_ties_go_to_lowest_index_and_empty_rows_answer_zero() {
assert_eq!(greedy_pick(&[1.0, 3.0, 3.0, 2.0]), 1);
assert_eq!(greedy_pick(&[f32::NEG_INFINITY, f32::NAN]), 0);
assert_eq!(greedy_pick(&[f32::NAN, -1.0]), 1);
}
#[test]
fn selection_is_descending_with_lowest_id_ties() {
let s = select_topk(&[1.0, 5.0, 5.0, 2.0, 5.0], 4);
assert_eq!(s.ids, vec![1, 2, 4, 3]);
assert_eq!(s.logits, vec![5.0, 5.0, 5.0, 2.0]);
}
#[test]
fn selection_sentinel_is_id_zero_neg_inf() {
let s = select_topk(&[f32::NEG_INFINITY, 1.0, f32::NAN], 3);
assert_eq!(s.ids, vec![1, 0, 0]);
assert_eq!(s.logits[0], 1.0);
assert!(s.logits[1] == f32::NEG_INFINITY && s.logits[2] == f32::NEG_INFINITY);
}
#[test]
fn penalty_window_is_the_tail() {
let h = [-1, -1, 5, 6, 7];
assert_eq!(penalty_window(&h, 2), &[6, 7]);
assert_eq!(penalty_window(&h, 99), &h);
assert_eq!(penalty_window(&h, 0), &[] as &[i32]);
assert_eq!(penalty_window(&h, -3), &[] as &[i32]);
}
#[test]
fn history_is_required_when_penalising() {
let q = SamplerParams {
penalty_last_n: 4,
..p()
};
assert_eq!(
sample_row(&[0.0, 1.0], &[], &q, 0),
Err(SamplerError::HistoryRequired)
);
assert_eq!(
sample_tokens(&[0.0, 1.0], 1, 2, None, &q),
Err(SamplerError::HistoryRequired)
);
}
#[test]
fn shapes_are_checked() {
assert_eq!(
sample_tokens(&[0.0; 5], 2, 3, None, &p()),
Err(SamplerError::LogitsLength {
expected: 6,
actual: 5
})
);
assert_eq!(
sample_tokens(&[0.0; 6], 2, 3, Some((&[0; 5], 3)), &p()),
Err(SamplerError::HistoryShape {
expected: 6,
actual: 5
})
);
assert_eq!(sample_tokens(&[], 0, 3, None, &p()), Ok(vec![]));
assert_eq!(
sample_tokens(&[], 1, 0, None, &p()),
Err(SamplerError::EmptyVocabulary)
);
}
#[test]
fn counter_advances_per_row_and_batch_equals_singles() {
let vocab = 16;
let count = 32;
let logits = vec![0.0f32; count * vocab];
let q = SamplerParams {
top_k: 16,
top_p: 1.0,
seed: 123,
counter: (1 << 32) + 7,
..p()
};
let batch = sample_tokens(&logits, count, vocab, None, &q).unwrap();
let singles: Vec<i32> = (0..count)
.map(|i| {
let one = SamplerParams {
counter: q.counter + i as u64,
..q
};
sample_tokens(&logits[..vocab], 1, vocab, None, &one).unwrap()[0]
})
.collect();
assert_eq!(batch, singles);
assert!(
batch.iter().any(|&t| t != batch[0]),
"uniform logits must vary across draws"
);
}
#[test]
fn temperature_zero_or_greedy_flag_is_argmax() {
let l = [0.0, 2.0, 1.0];
let q = SamplerParams {
temperature: 0.0,
..p()
};
assert_eq!(sample_row(&l, &[], &q, 0), Ok(1));
let g = SamplerParams {
greedy: true,
temperature: 1.0,
..p()
};
assert_eq!(sample_row(&l, &[], &g, 0), Ok(1));
}
#[test]
fn min_p_cuts_a_prefix_of_the_list() {
let sel = Selection {
ids: vec![3, 1, 2],
logits: vec![5.0, 4.9, 0.0],
};
let q = SamplerParams {
top_p: 1.0,
min_p: 0.5,
..p()
};
let pick = pick_from_list(&sel, &q, 0);
assert_eq!(pick.n_keep, 2);
}
}
+334
View File
@@ -0,0 +1,334 @@
//! Coupled draft sampling arithmetic and the host penalty-history helpers.
//!
//! Sources: `engine/strata/include/strata/core/coupled_draft.hpp` (cell /
//! counter / ring arithmetic), `engine/strata/include/strata/kernels/sampler.hpp`
//! (`penalty_rows`) and the coupled kernels of `sampler.cu`
//! (`coupled_penalize_kernel`, `coupled_merge_kernel`).
//!
//! Counter rule (all positions are sequence indices): a verify window at
//! `pos0` draws row `t` with Philox counter `pos0 + t`; a draft made at MTP
//! cell `c` is checked by the row drawn at counter `c + 1`, whatever the
//! window size or accepted count. A draft is kept only when it EQUALS the
//! verifying row's pick, so the output is a function of the seed alone.
use crate::chain::{
MAX_SELECT, Pick, SamplerParams, apply_penalties, pick_from_list, sampled_k, select_topk,
};
/// serve's `kPenaltyWindowCap` as mirrored by the draft ring.
pub const COUPLED_HIST_CAP: i32 = 4096;
/// MTP cell of chain step `j` after a window at `p` with `a` drafts accepted.
pub fn coupled_draft_cell(p: i64, a: i32, j: i32) -> i64 {
p.wrapping_add(i64::from(a)).wrapping_add(i64::from(j))
}
/// Philox counter the verify window draws for the row that checks the draft
/// made at `cell` (`(uint64_t)(cell + 1)`).
pub fn coupled_draft_counter(cell: i64) -> u64 {
cell.wrapping_add(1) as u64
}
/// Penalty window shared by the draft layer and the target:
/// `min(penalty_last_n, cap)`, 0 when penalties are off.
pub fn coupled_hist_len(penalty_last_n: i32, cap: i32) -> i32 {
if penalty_last_n <= 0 {
0
} else if penalty_last_n < cap {
penalty_last_n
} else {
cap
}
}
/// Where draft `j`'s penalty window starts in the ring (base in
/// `[cap - h, cap)`, draft `i` written at `cap + i`).
pub fn coupled_hist_start(cap: i32, j: i32, h: i32) -> i32 {
cap + j - h
}
/// `penalty_rows`: row `t` of the returned `T x h` matrix is the last `h`
/// tokens of `tail ++ window[0..=t]`, most recent LAST, `-1` in unused front
/// slots. `tail` is what the state consumed before the window, `window[0]`
/// the fed-back token and `window[1..]` the drafts.
pub fn penalty_rows(tail: &[i32], window: &[i32], rows: usize, h: usize) -> Vec<i32> {
assert!(
rows <= window.len(),
"penalty_rows: window shorter than rows"
);
let n_tail = tail.len() as i64;
let mut out = vec![-1i32; rows * h];
for t in 0..rows {
let row = &mut out[t * h..(t + 1) * h];
let avail = n_tail + t as i64 + 1;
let take = (h as i64).min(avail);
for j in 0..take {
let i = avail - take + j;
row[(h as i64 - take + j) as usize] = if i < n_tail {
tail[i as usize]
} else {
window[(i - n_tail) as usize]
};
}
}
out
}
/// `coupled_hist_base`: the ring base on the host, the last `h` tokens of
/// `tail ++ [next]`, `-1` padded in front. Empty when `h <= 0`.
pub fn coupled_hist_base(tail: &[i32], next: i32, h: i32) -> Vec<i32> {
if h <= 0 {
return Vec::new();
}
penalty_rows(tail, &[next], 1, h as usize)
}
/// Speculative acceptance (generate.cpp): `a` is the longest prefix of the
/// drafts `window[1..]` that equals the verify picks, `window[a + 1] == picks[a]`
/// while `a < T - 1`. Returns `a`; the window yields `a + 1` tokens.
pub fn accepted_drafts(window: &[i32], picks: &[i32]) -> usize {
let t = window.len().min(picks.len());
let mut a = 0;
while a + 1 < t && window[a + 1] == picks[a] {
a += 1;
}
a
}
/// What `coupled_draft_sample` produces for one draft.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DraftSample {
/// Token id written to `*out_id` (after the optional subset -> id map).
pub id: i32,
/// Probability under the final distribution (`*out_prob`).
pub prob: f32,
/// Index in the draft head's subset (before mapping).
pub sub_index: i32,
}
/// `coupled_penalize_kernel`: penalise `logits` (the draft head's `nv` logits)
/// in place for draft `j`, over the ring window `[cap + j - h, cap + j)`. Each
/// distinct subset entry is penalised once, with the count of its token id over
/// the whole window. A history token outside the subset has no logit here.
pub fn coupled_penalize(
logits: &mut [f32],
id_to_sub: Option<&[i32]>,
id_vocab: usize,
p: &SamplerParams,
ring: &[i32],
cap: i32,
j: i32,
) {
let h = coupled_hist_len(p.penalty_last_n, cap);
if h <= 0 {
return;
}
let start = coupled_hist_start(cap, j, h) as usize;
let hrow = &ring[start..start + h as usize];
let nv = logits.len();
let mut seen = vec![false; nv];
for &v in hrow {
if v < 0 || v as usize >= id_vocab {
continue;
}
let s = id_to_sub.map_or(v, |m| m[v as usize]);
if s < 0 || s as usize >= nv {
continue;
}
let s = s as usize;
if std::mem::replace(&mut seen[s], true) {
continue;
}
let count = hrow.iter().filter(|&&x| x == v).count() as i32;
logits[s] = apply_penalties(logits[s], count, p);
}
}
/// `coupled_draft_sample`: draft `j` of the chain from one row of `nv` logits.
/// Penalises `logits` in place, selects the request's top_k, then runs the
/// target's tail with the Philox counter `coupled_draft_counter(step_rec0)`.
/// Writes the id to `ring[cap + j]` and returns it with its probability.
/// Greedy parameters take the argmax with probability 1 (the Original never
/// launches this for greedy, "defensively" it picks entry 0).
#[allow(clippy::too_many_arguments)]
pub fn coupled_draft_sample(
logits: &mut [f32],
sub_to_id: Option<&[i32]>,
id_to_sub: Option<&[i32]>,
id_vocab: usize,
params: &SamplerParams,
ring: &mut [i32],
cap: i32,
j: i32,
step_rec0: i32,
) -> DraftSample {
coupled_penalize(logits, id_to_sub, id_vocab, params, ring, cap, j);
let mut p = *params;
p.counter = coupled_draft_counter(i64::from(step_rec0));
let k = sampled_k(p.top_k, logits.len());
debug_assert!(k <= MAX_SELECT);
// The split-part kernels run with default (empty) params: the penalties are already applied.
let sel = select_topk(logits, k);
let pick: Pick = if p.greedy || p.temperature <= 0.0 {
Pick {
token: sel.ids[0],
index: 0,
n_keep: 1,
prob: 1.0,
uniform: 0.0,
}
} else {
pick_from_list(&sel, &p, p.counter)
};
let s = pick.token;
let id = sub_to_id.map_or(s, |m| m[s as usize]);
ring[(cap + j) as usize] = id;
DraftSample {
id,
prob: pick.prob,
sub_index: s,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn lcg(state: &mut u64) -> u32 {
*state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(*state >> 33) as u32
}
/// `check_chain` of coupled_draft_test.cpp: a draft's cell predicts its
/// position in the next window, and its counter is the verifying row's.
fn check_chain(p: i64, a: i32, n: i32, p_next: i64) {
for j in 0..n {
let cell = coupled_draft_cell(p, a, j);
assert_eq!(cell + 2, p_next + i64::from(j) + 1);
assert_eq!(coupled_draft_counter(cell), (p_next + i64::from(j)) as u64);
}
}
#[test]
fn serve_style_decode_counters() {
let mut s = 20260930u64;
for run in 0..200i64 {
let mut p = 100 + run * 37;
let mut t = 1u32;
for _ in 0..300 {
let a = (lcg(&mut s) % t) as i32;
let p_next = p + i64::from(a) + 1;
check_chain(p, a, 7, p_next);
p = p_next;
t = 1 + lcg(&mut s) % 8;
}
}
let mut p = 1i64;
while p < 5000 {
check_chain(p - 1, 0, 7, p);
p += 13;
}
}
#[test]
fn ring_history_equals_penalty_rows() {
let mut s = 99u64;
for cap in [8i32, 64, COUPLED_HIST_CAP] {
for h in [1i32, 3, 8, cap] {
if h > cap {
continue;
}
for n_consumed in [0usize, 1, 2, 5, 7, 20, 100, 5000] {
for n_drafts in [1usize, 3, 7] {
let consumed: Vec<i32> = (0..n_consumed)
.map(|_| (lcg(&mut s) % 1000) as i32)
.collect();
let drafts: Vec<i32> =
(0..n_drafts).map(|_| (lcg(&mut s) % 1000) as i32).collect();
let next = (lcg(&mut s) % 1000) as i32;
let mut ring = vec![888_888i32; cap as usize + n_drafts];
let base = coupled_hist_base(&consumed, next, h);
ring[(cap - h) as usize..cap as usize].copy_from_slice(&base);
let mut window = vec![next];
window.extend_from_slice(&drafts);
let rows = penalty_rows(&consumed, &window, window.len(), h as usize);
for (j, &draft) in drafts.iter().enumerate() {
let st = coupled_hist_start(cap, j as i32, h) as usize;
assert_eq!(
&ring[st..st + h as usize],
&rows[j * h as usize..(j + 1) * h as usize]
);
ring[cap as usize + j] = draft;
}
}
}
}
}
}
#[test]
fn window_length_matches_the_target() {
for pln in [-1i32, 0, 1, 64, 4095, 4096, 4097, 100_000] {
let hist_n = pln.clamp(0, 4096);
let target = if hist_n > 0 { pln.min(hist_n) } else { 0 };
assert_eq!(coupled_hist_len(pln, COUPLED_HIST_CAP), target);
}
}
#[test]
fn penalty_rows_matches_plain_definition() {
let tail = [10, 11, 12];
let window = [20, 21, 22];
let rows = penalty_rows(&tail, &window, 3, 5);
assert_eq!(&rows[0..5], &[-1, 10, 11, 12, 20]);
assert_eq!(&rows[5..10], &[10, 11, 12, 20, 21]);
assert_eq!(&rows[10..15], &[11, 12, 20, 21, 22]);
let none = penalty_rows(&[], &[7], 1, 3);
assert_eq!(none, vec![-1, -1, 7]);
}
#[test]
fn acceptance_is_exact_match_prefix() {
// window = [x, d0, d1, d2]; picks[a] must equal window[a + 1]
assert_eq!(accepted_drafts(&[5, 1, 2, 3], &[1, 2, 9, 0]), 2);
assert_eq!(accepted_drafts(&[5, 1, 2, 3], &[0, 2, 3, 0]), 0);
assert_eq!(accepted_drafts(&[5, 1, 2, 3], &[1, 2, 3, 0]), 3);
assert_eq!(accepted_drafts(&[5], &[1]), 0);
}
#[test]
fn draft_sample_appends_to_ring_and_matches_target_pick_for_same_counter() {
// Same logits, same chain, same counter => the draft equals the target's pick.
let nv = 40usize;
let logits: Vec<f32> = (0..nv)
.map(|i| ((i * 37 % 11) as f32) * 0.37 - 1.0)
.collect();
let p = SamplerParams {
top_k: 12,
top_p: 0.9,
temperature: 0.8,
seed: 31337,
penalty_last_n: 4,
penalty_repeat: 1.3,
..SamplerParams::default()
};
let cap = 16i32;
let mut ring = vec![-1i32; cap as usize + 4];
ring[(cap - 3) as usize..cap as usize].copy_from_slice(&[3, 5, 3]);
let cell = 99i64;
let mut l = logits.clone();
let d = coupled_draft_sample(&mut l, None, None, nv, &p, &mut ring, cap, 0, cell as i32);
assert_eq!(ring[cap as usize], d.id);
// the target's verify row: history row = the same window, counter = cell + 1
let hist = &ring[(cap - 4) as usize..cap as usize];
let target = SamplerParams {
counter: coupled_draft_counter(cell),
..p
};
let want = crate::chain::sample_row(&logits, hist, &target, 0).unwrap();
assert_eq!(d.id, want);
assert!(d.prob > 0.0 && d.prob <= 1.0);
}
}
+29
View File
@@ -0,0 +1,29 @@
//! CPU reference of the Original Strata sampler (`engine/strata`), in safe Rust.
//!
//! This crate is a *literal transcription* of the Original host/device sampler
//! logic, not a re-design:
//!
//! * [`philox`] - the counter-based uniform draw (`philox_uniform` in `sampler.cu`).
//! * [`chain`] - penalties -> top_k -> top_p -> min_p -> temperature -> inverse-CDF
//! pick (`sampler_kernel`, `sampled_tail_warp`, `sampler_greedy_kernel`).
//! * [`coupled`] - coupled-draft counter/ring arithmetic (`coupled_draft.hpp`),
//! `penalty_rows` (`sampler.hpp`), the draft-side sampling with its
//! probability output, and the exact-match acceptance rule.
//! * [`params`] - request-level sampling parameters: validation, the Original's
//! defaults, and the `GEN` wire keys (`serve/server.py` `sampling_keys`).
//!
//! Float-ordering assumptions are documented on the functions that depend on
//! them. Everything integer/RNG (Philox, counters, list ordering, tie-breaks,
//! window layout) is bit-exact against the Original by construction and by the
//! committed oracle fixtures; the `f64::exp` / `f32::ln` calls use the platform
//! libm exactly as the Original host reference does (see `docs/sampler-reference.md`).
//!
//! Nothing here claims a speed or model-quality result.
pub mod chain;
pub mod coupled;
pub mod params;
pub mod philox;
pub use chain::{SamplerError, SamplerParams, sample_tokens};
pub use params::{RequestSampling, SamplingError, SamplingParams};
+662
View File
@@ -0,0 +1,662 @@
//! Request-level sampling parameters: validation, normalisation and the
//! Original's defaults, in one struct.
//!
//! Sources of truth in the Original:
//!
//! * `engine/strata/src/program/generate.cpp` (`GEN` key grammar and the
//! defaults an absent key keeps): greedy, `top_p = 1.0`, `top_k = 20`,
//! `min_p = 0`, no penalties, `seed = 0` meaning "clock seed"; `min_p` is
//! clamped to `[0, 1]` and `penalty_last_n` to `>= 0`.
//! * `engine/strata/serve/server.py` `StrataEngine.sampling_keys` (which keys are
//! emitted and how floats are printed) and `sampling_defaults_from_config` /
//! `clean_shared_defaults` (the ranges the server enforces on configured
//! defaults).
//!
//! Where the Original silently ignores an invalid request field (it simply does
//! not emit the key) this module returns an error instead: the HTTP boundary
//! must fail closed rather than quietly change sampling. Valid inputs normalise
//! exactly as the Original does.
use crate::chain::{PENALTY_WINDOW_CAP, SamplerParams};
use std::num::NonZeroU64;
/// Sampling fields as they arrive from a Responses/Chat/Messages request (or
/// from configured defaults); `None` means the field was absent or null.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RequestSampling {
pub temperature: Option<f64>,
pub top_p: Option<f64>,
pub top_k: Option<i64>,
pub min_p: Option<f64>,
pub repetition_penalty: Option<f64>,
pub frequency_penalty: Option<f64>,
pub presence_penalty: Option<f64>,
pub penalty_last_n: Option<i64>,
/// Unsigned: a negative JSON seed is a deserialisation error at the boundary.
pub seed: Option<u64>,
}
/// A rejected field and the contract it broke.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SamplingError {
pub field: &'static str,
pub expected: &'static str,
}
impl std::fmt::Display for SamplingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: expected {}", self.field, self.expected)
}
}
impl std::error::Error for SamplingError {}
fn err(field: &'static str, expected: &'static str) -> SamplingError {
SamplingError { field, expected }
}
fn finite_in(
field: &'static str,
value: Option<f64>,
lo: f64,
hi: f64,
expected: &'static str,
) -> Result<(), SamplingError> {
match value {
Some(v) if !v.is_finite() || v < lo || v > hi => Err(err(field, expected)),
_ => Ok(()),
}
}
/// Window the Original's Python layer adds when a penalty is on and none given.
pub const DEFAULT_PENALTY_LAST_N: i32 = 64;
/// The engine's own `top_k` default for an absent key.
pub const DEFAULT_TOP_K: i32 = 20;
impl RequestSampling {
/// Request-boundary validation. Ranges: `temperature` in `[0, 2]` (0 is
/// greedy), `top_p` in `[0, 1]` (1 disables), `top_k >= 0`, `min_p` in
/// `[0, 1]`, `repetition_penalty > 0` (1 is off), frequency/presence
/// penalties finite and within the OpenAI `[-2, 2]`, `penalty_last_n` in
/// `[0, i32::MAX]`, `seed` any `u64` (0 means a fresh clock seed).
pub fn validate(&self) -> Result<(), SamplingError> {
finite_in(
"temperature",
self.temperature,
0.0,
2.0,
"a finite number in 0..=2",
)?;
finite_in("top_p", self.top_p, 0.0, 1.0, "a finite number in 0..=1")?;
finite_in("min_p", self.min_p, 0.0, 1.0, "a finite number in 0..=1")?;
finite_in(
"frequency_penalty",
self.frequency_penalty,
-2.0,
2.0,
"a finite number in -2..=2",
)?;
finite_in(
"presence_penalty",
self.presence_penalty,
-2.0,
2.0,
"a finite number in -2..=2",
)?;
if let Some(v) = self.repetition_penalty
&& (!v.is_finite() || v <= 0.0)
{
return Err(err("repetition_penalty", "a finite number > 0 (1 = off)"));
}
if self.top_k.is_some_and(|k| k < 0) {
return Err(err("top_k", "an integer >= 0 (0 = widest list, 64)"));
}
if self
.penalty_last_n
.is_some_and(|n| n < 0 || n > i64::from(i32::MAX))
{
return Err(err("penalty_last_n", "an integer in 0..=2147483647"));
}
Ok(())
}
/// The stricter ranges the Original enforces on *configured defaults*
/// (`sampling_defaults_from_config`): `temperature >= 0`, `0 < top_p <= 1`,
/// `0 <= min_p <= 1`, `top_k` in `1..=64`, penalties `>= 0` with
/// `repetition_penalty > 0`, `penalty_last_n >= 0`, `seed > 0`.
pub fn validate_config_defaults(&self) -> Result<(), SamplingError> {
self.validate()?;
if self.top_p.is_some_and(|v| v <= 0.0) {
return Err(err("top_p", "0 < top_p <= 1"));
}
if self.top_k.is_some_and(|k| !(1..=64).contains(&k)) {
return Err(err("top_k", "an integer 1..=64"));
}
if self.presence_penalty.is_some_and(|v| v < 0.0) {
return Err(err("presence_penalty", "a number >= 0"));
}
if self.frequency_penalty.is_some_and(|v| v < 0.0) {
return Err(err("frequency_penalty", "a number >= 0"));
}
if self.seed == Some(0) {
return Err(err("seed", "a positive integer"));
}
Ok(())
}
/// Defaults first, then the request's own non-null fields on top (an
/// explicit `temperature = 0` stays greedy). `Service.run` in server.py.
pub fn overlay(defaults: &Self, request: &Self) -> Self {
Self {
temperature: request.temperature.or(defaults.temperature),
top_p: request.top_p.or(defaults.top_p),
top_k: request.top_k.or(defaults.top_k),
min_p: request.min_p.or(defaults.min_p),
repetition_penalty: request.repetition_penalty.or(defaults.repetition_penalty),
frequency_penalty: request.frequency_penalty.or(defaults.frequency_penalty),
presence_penalty: request.presence_penalty.or(defaults.presence_penalty),
penalty_last_n: request.penalty_last_n.or(defaults.penalty_last_n),
seed: request.seed.or(defaults.seed),
}
}
fn penalties_on(&self) -> bool {
self.repetition_penalty.is_some_and(|v| v != 1.0)
|| self.frequency_penalty.is_some_and(|v| v != 0.0)
|| self.presence_penalty.is_some_and(|v| v != 0.0)
}
/// The `GEN` sampling keys exactly as `StrataEngine.sampling_keys` prints
/// them (leading space per key, `repr(float)` formatting, same order),
/// after [`validate`](Self::validate). Does not emit `strata_tune` or `cvec`.
pub fn gen_keys(&self) -> Result<String, SamplingError> {
self.validate()?;
let mut keys = String::new();
if let Some(t) = self.temperature.filter(|t| *t > 0.0) {
keys.push_str(&format!(" temperature={}", py_float_repr(t)));
}
if let Some(p) = self.top_p.filter(|p| *p < 1.0) {
keys.push_str(&format!(" top_p={}", py_float_repr(p)));
}
if let Some(k) = self.top_k {
let k = if (1..=64).contains(&k) { k } else { 64 };
keys.push_str(&format!(" top_k={k}"));
}
if let Some(m) = self.min_p.filter(|m| *m > 0.0 && *m <= 1.0) {
keys.push_str(&format!(" min_p={}", py_float_repr(m)));
}
let rp = self.repetition_penalty.filter(|v| *v != 1.0);
let pf = self.frequency_penalty.filter(|v| *v != 0.0);
let pp = self.presence_penalty.filter(|v| *v != 0.0);
if let Some(v) = rp {
keys.push_str(&format!(" penalty_repeat={}", py_float_repr(v)));
}
if let Some(v) = pf {
keys.push_str(&format!(" penalty_freq={}", py_float_repr(v)));
}
if let Some(v) = pp {
keys.push_str(&format!(" penalty_present={}", py_float_repr(v)));
}
if rp.is_some() || pf.is_some() || pp.is_some() {
match self.penalty_last_n.filter(|n| *n > 0) {
Some(n) => keys.push_str(&format!(" penalty_last_n={n}")),
None => keys.push_str(" penalty_last_n=64"),
}
}
if let Some(s) = self.seed.filter(|s| *s > 0) {
keys.push_str(&format!(" seed={s}"));
}
Ok(keys)
}
}
/// Fully normalised sampling parameters, as the engine sees them after the
/// wire: every float has been through the same decimal text the Original's
/// `strtof` parses (`repr(double)` -> nearest `f32`).
#[derive(Clone, Debug, PartialEq)]
pub struct SamplingParams {
/// `<= 0` is greedy.
pub temperature: f32,
/// `1.0` disables.
pub top_p: f32,
/// Normalised to `1..=64`.
pub top_k: i32,
pub min_p: f32,
pub penalty_repeat: f32,
pub penalty_freq: f32,
pub penalty_present: f32,
/// 0 when no penalty is active; otherwise the requested window (or 64).
/// Kernels cap it at [`PENALTY_WINDOW_CAP`] history slots.
pub penalty_last_n: i32,
/// `None`: draw a fresh clock seed per request (the Original's `seed = 0`).
pub seed: Option<NonZeroU64>,
}
/// The `f32` the Original's `strtof` makes of the text Python prints for `x`.
pub fn wire_f32(x: f64) -> f32 {
// `{:?}` is the shortest round-trip decimal, like Python's repr; parsing
// it as f32 is correctly rounded, like strtof.
format!("{x:?}").parse::<f32>().unwrap_or(f32::NAN)
}
impl SamplingParams {
/// Validate and normalise. Absent fields take the Original's `GEN`
/// defaults: greedy, `top_p = 1`, `top_k = 20`, `min_p = 0`, no penalties.
pub fn resolve(request: &RequestSampling) -> Result<Self, SamplingError> {
request.validate()?;
let temperature = wire_f32(request.temperature.unwrap_or(0.0));
let top_p = wire_f32(request.top_p.unwrap_or(1.0));
let top_k = match request.top_k {
None => DEFAULT_TOP_K,
Some(k) if (1..=64).contains(&k) => k as i32,
Some(_) => 64,
};
let min_p = wire_f32(request.min_p.unwrap_or(0.0));
let min_p = if request.min_p.is_some_and(|m| m > 0.0 && m <= 1.0) {
min_p.clamp(0.0, 1.0)
} else {
0.0
};
let rp = request.repetition_penalty.filter(|v| *v != 1.0);
let pf = request.frequency_penalty.filter(|v| *v != 0.0);
let pp = request.presence_penalty.filter(|v| *v != 0.0);
let penalty_last_n = if request.penalties_on() {
match request.penalty_last_n.filter(|n| *n > 0) {
Some(n) => n as i32,
None => DEFAULT_PENALTY_LAST_N,
}
} else {
0
};
Ok(Self {
temperature,
top_p,
top_k,
min_p,
penalty_repeat: rp.map_or(1.0, wire_f32),
penalty_freq: pf.map_or(0.0, wire_f32),
penalty_present: pp.map_or(0.0, wire_f32),
penalty_last_n,
seed: request.seed.and_then(NonZeroU64::new),
})
}
pub fn is_greedy(&self) -> bool {
self.temperature <= 0.0
}
/// The engine's `SamplerParams` for a request (generate.cpp `req_sp`):
/// `greedy = temperature <= 0`, `min_keep = 1`, `counter = 0`. `entropy` is
/// used only when the request carries no seed.
pub fn to_sampler_params(&self, entropy: u64) -> SamplerParams {
SamplerParams {
top_k: self.top_k,
top_p: self.top_p,
min_p: self.min_p,
temperature: self.temperature,
min_keep: 1,
penalty_last_n: self.penalty_last_n,
penalty_repeat: self.penalty_repeat,
penalty_freq: self.penalty_freq,
penalty_present: self.penalty_present,
seed: self.seed.map_or(entropy, NonZeroU64::get),
counter: 0,
greedy: self.temperature <= 0.0,
}
}
/// History slots a request needs per row: `min(penalty_last_n, 4096)`.
pub fn history_slots(&self) -> usize {
(self.penalty_last_n.max(0) as usize).min(PENALTY_WINDOW_CAP)
}
}
/// Python's `repr(float)` for a finite `f64` (shortest round-trip digits;
/// fixed notation for decimal exponents -4..=15, otherwise `d.ddde+XX`).
pub fn py_float_repr(x: f64) -> String {
if x == 0.0 {
return if x.is_sign_negative() {
"-0.0".into()
} else {
"0.0".into()
};
}
let sign = if x < 0.0 { "-" } else { "" };
let sci = format!("{:e}", x.abs());
let (mantissa, exponent) = sci
.split_once('e')
.expect("LowerExp always has an exponent");
let exp: i32 = exponent.parse().expect("integer exponent");
let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
let body = if (-4..16).contains(&exp) {
if exp >= 0 {
let int_len = exp as usize + 1;
if digits.len() <= int_len {
format!("{digits}{}.0", "0".repeat(int_len - digits.len()))
} else {
format!("{}.{}", &digits[..int_len], &digits[int_len..])
}
} else {
format!("0.{}{digits}", "0".repeat((-exp - 1) as usize))
}
} else {
let m = if digits.len() == 1 {
digits
} else {
format!("{}.{}", &digits[..1], &digits[1..])
};
format!("{m}e{}{:02}", if exp < 0 { '-' } else { '+' }, exp.abs())
};
format!("{sign}{body}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn python_repr_matches_known_values() {
for (x, want) in [
(0.0, "0.0"),
(1.0, "1.0"),
(0.7, "0.7"),
(0.95, "0.95"),
(100.0, "100.0"),
(1e15, "1000000000000000.0"),
(1e16, "1e+16"),
(1.5e16, "1.5e+16"),
(0.0001, "0.0001"),
(0.00001, "1e-05"),
(1.5e-7, "1.5e-07"),
(123.456, "123.456"),
(-2.5, "-2.5"),
(0.1 + 0.2, "0.30000000000000004"),
] {
assert_eq!(py_float_repr(x), want, "{x:?}");
}
}
#[test]
fn absent_fields_are_the_originals_gen_defaults() {
let p = SamplingParams::resolve(&RequestSampling::default()).unwrap();
assert!(p.is_greedy());
assert_eq!((p.top_p, p.top_k, p.min_p), (1.0, 20, 0.0));
assert_eq!(
(p.penalty_repeat, p.penalty_freq, p.penalty_present),
(1.0, 0.0, 0.0)
);
assert_eq!(p.penalty_last_n, 0);
assert_eq!(p.seed, None);
assert_eq!(RequestSampling::default().gen_keys().unwrap(), "");
}
#[test]
fn top_k_normalises_to_the_engine_range() {
for (given, want) in [(0, 64), (1, 1), (20, 20), (64, 64), (65, 64), (100_000, 64)] {
let r = RequestSampling {
top_k: Some(given),
..Default::default()
};
assert_eq!(SamplingParams::resolve(&r).unwrap().top_k, want);
assert_eq!(r.gen_keys().unwrap(), format!(" top_k={want}"));
}
}
#[test]
fn a_penalty_without_a_window_gets_64() {
let r = RequestSampling {
presence_penalty: Some(0.5),
..Default::default()
};
let p = SamplingParams::resolve(&r).unwrap();
assert_eq!(p.penalty_last_n, 64);
assert_eq!(
r.gen_keys().unwrap(),
" penalty_present=0.5 penalty_last_n=64"
);
// a window with no active penalty is not emitted and not applied
let r = RequestSampling {
penalty_last_n: Some(10),
..Default::default()
};
assert_eq!(SamplingParams::resolve(&r).unwrap().penalty_last_n, 0);
assert_eq!(r.gen_keys().unwrap(), "");
// an explicit window wins; a zero window falls back to 64 like Python
let r = RequestSampling {
repetition_penalty: Some(1.1),
penalty_last_n: Some(0),
..Default::default()
};
assert_eq!(SamplingParams::resolve(&r).unwrap().penalty_last_n, 64);
let r = RequestSampling {
repetition_penalty: Some(1.1),
penalty_last_n: Some(4097),
..Default::default()
};
let p = SamplingParams::resolve(&r).unwrap();
assert_eq!(p.penalty_last_n, 4097);
assert_eq!(p.history_slots(), 4096);
}
#[test]
fn engine_params_follow_generate_cpp() {
let r = RequestSampling {
temperature: Some(0.7),
top_p: Some(0.9),
seed: Some(42),
..Default::default()
};
let sp = SamplingParams::resolve(&r).unwrap().to_sampler_params(999);
assert!(!sp.greedy);
assert_eq!(sp.seed, 42);
assert_eq!(sp.counter, 0);
assert_eq!(sp.min_keep, 1);
assert_eq!(sp.temperature, 0.7f32);
// no seed: the caller's entropy
let r = RequestSampling {
temperature: Some(1.0),
..Default::default()
};
assert_eq!(
SamplingParams::resolve(&r)
.unwrap()
.to_sampler_params(999)
.seed,
999
);
// temperature 0 stays greedy whatever else is set
let r = RequestSampling {
temperature: Some(0.0),
top_p: Some(0.5),
..Default::default()
};
assert!(
SamplingParams::resolve(&r)
.unwrap()
.to_sampler_params(1)
.greedy
);
}
#[test]
fn invalid_fields_are_rejected() {
let bad = |r: RequestSampling| SamplingParams::resolve(&r).unwrap_err().field;
let d = RequestSampling::default;
assert_eq!(
bad(RequestSampling {
temperature: Some(-0.1),
..d()
}),
"temperature"
);
assert_eq!(
bad(RequestSampling {
temperature: Some(2.5),
..d()
}),
"temperature"
);
assert_eq!(
bad(RequestSampling {
temperature: Some(f64::NAN),
..d()
}),
"temperature"
);
assert_eq!(
bad(RequestSampling {
top_p: Some(1.5),
..d()
}),
"top_p"
);
assert_eq!(
bad(RequestSampling {
top_p: Some(f64::INFINITY),
..d()
}),
"top_p"
);
assert_eq!(
bad(RequestSampling {
top_k: Some(-1),
..d()
}),
"top_k"
);
assert_eq!(
bad(RequestSampling {
min_p: Some(1.01),
..d()
}),
"min_p"
);
assert_eq!(
bad(RequestSampling {
repetition_penalty: Some(0.0),
..d()
}),
"repetition_penalty"
);
assert_eq!(
bad(RequestSampling {
frequency_penalty: Some(3.0),
..d()
}),
"frequency_penalty"
);
assert_eq!(
bad(RequestSampling {
presence_penalty: Some(f64::NAN),
..d()
}),
"presence_penalty"
);
assert_eq!(
bad(RequestSampling {
penalty_last_n: Some(-1),
..d()
}),
"penalty_last_n"
);
// a bad request never reaches the wire either
assert!(
RequestSampling {
top_k: Some(-5),
..d()
}
.gen_keys()
.is_err()
);
}
#[test]
fn config_defaults_use_the_servers_stricter_ranges() {
let d = RequestSampling::default;
assert!(
RequestSampling {
top_p: Some(0.0),
..d()
}
.validate()
.is_ok()
);
assert!(
RequestSampling {
top_p: Some(0.0),
..d()
}
.validate_config_defaults()
.is_err()
);
assert!(
RequestSampling {
top_k: Some(0),
..d()
}
.validate_config_defaults()
.is_err()
);
assert!(
RequestSampling {
top_k: Some(65),
..d()
}
.validate_config_defaults()
.is_err()
);
assert!(
RequestSampling {
presence_penalty: Some(-0.5),
..d()
}
.validate_config_defaults()
.is_err()
);
assert!(
RequestSampling {
seed: Some(0),
..d()
}
.validate_config_defaults()
.is_err()
);
assert!(
RequestSampling {
temperature: Some(0.6),
top_k: Some(20),
seed: Some(7),
..d()
}
.validate_config_defaults()
.is_ok()
);
}
#[test]
fn overlay_lets_the_request_win_including_explicit_zero() {
let defaults = RequestSampling {
temperature: Some(0.6),
top_p: Some(0.95),
top_k: Some(20),
..Default::default()
};
let request = RequestSampling {
temperature: Some(0.0),
seed: Some(9),
..Default::default()
};
let merged = RequestSampling::overlay(&defaults, &request);
assert_eq!(merged.temperature, Some(0.0));
assert_eq!(merged.top_p, Some(0.95));
assert_eq!(merged.seed, Some(9));
assert!(SamplingParams::resolve(&merged).unwrap().is_greedy());
}
#[test]
fn wire_floats_go_through_the_decimal_text() {
assert_eq!(wire_f32(0.7), 0.7f32);
assert_eq!(wire_f32(1e-7), 1e-7f32);
assert_eq!(wire_f32(1.0), 1.0f32);
}
}
+82
View File
@@ -0,0 +1,82 @@
//! The Original's counter-based uniform generator.
//!
//! Transcribed from `philox4x32_round` / `philox_uniform` in
//! `engine/strata/src/kernels/cuda/sampler.cu` (host twin: `host_philox_uniform`
//! in `sampler_parity.cpp`). NOTE: this is "Philox-shaped", not the textbook
//! Philox4x32-10: the multipliers are the golden-ratio constants
//! `0x9E3779B9` / `0xBB67AE85` and the round key is the bare round index
//! `(i, 0)` with no Weyl key bumping. The Original's constants are kept as-is;
//! do not "fix" them to the published Philox ones.
const M0: u32 = 0x9E37_79B9;
const M1: u32 = 0xBB67_AE85;
#[inline]
fn mulhi(a: u32, b: u32) -> u32 {
((u64::from(a) * u64::from(b)) >> 32) as u32
}
/// One round: `(c0,c1,c2,c3) -> (hi1^c1^k0, lo1, hi0^c3^k1, lo0)`.
#[inline]
fn round(c: [u32; 4], k0: u32, k1: u32) -> [u32; 4] {
let hi0 = mulhi(M0, c[0]);
let hi1 = mulhi(M1, c[2]);
let lo0 = M0.wrapping_mul(c[0]);
let lo1 = M1.wrapping_mul(c[2]);
[hi1 ^ c[1] ^ k0, lo1, hi0 ^ c[3] ^ k1, lo0]
}
/// The four raw state words after the ten rounds (counter low, counter high,
/// seed low, seed high on entry).
pub fn philox_words(seed: u64, counter: u64) -> [u32; 4] {
let mut c = [
counter as u32,
(counter >> 32) as u32,
seed as u32,
(seed >> 32) as u32,
];
for i in 0..10u32 {
c = round(c, i, 0);
}
c
}
/// `philox_uniform(seed, counter)`: 24 mantissa bits of word 0, uniform in
/// `[0, 1)` and never `1.0`. The product `(c0 >> 8) as f32 * 2^-24` is exact.
pub fn philox_uniform(seed: u64, counter: u64) -> f32 {
let words = philox_words(seed, counter);
(words[0] >> 8) as f32 * (1.0f32 / 16_777_216.0f32)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uniform_is_in_unit_interval_and_deterministic() {
for counter in [
0u64,
1,
2,
u64::from(u32::MAX),
u64::MAX,
1 << 32,
(1 << 32) + 7,
] {
for seed in [0u64, 1, 123, u64::MAX, 1 << 40] {
let a = philox_uniform(seed, counter);
assert_eq!(a.to_bits(), philox_uniform(seed, counter).to_bits());
assert!((0.0..1.0).contains(&a));
}
}
}
#[test]
fn counter_and_seed_both_matter() {
assert_ne!(philox_words(1, 2), philox_words(1, 3));
assert_ne!(philox_words(1, 2), philox_words(2, 2));
// high halves participate
assert_ne!(philox_words(1, 2), philox_words(1, 2 | (1 << 32)));
assert_ne!(philox_words(1, 2), philox_words(1 | (1 << 32), 2));
}
}
File diff suppressed because one or more lines are too long
+41
View File
@@ -0,0 +1,41 @@
{"meta":{"generator": "crates/sampler-ref/oracle/gen_sampling_keys.py", "oracle": "engine/strata/serve/server.py StrataEngine.sampling_keys"},
"cases":[
{"request": {}, "keys": ""},
{"request": {"temperature": 0.0}, "keys": ""},
{"request": {"temperature": 0.7}, "keys": " temperature=0.7"},
{"request": {"temperature": 1}, "keys": " temperature=1.0"},
{"request": {"temperature": 2.0}, "keys": " temperature=2.0"},
{"request": {"temperature": 0.30000000000000004}, "keys": " temperature=0.30000000000000004"},
{"request": {"temperature": 1e-07}, "keys": " temperature=1e-07"},
{"request": {"temperature": 0.7, "top_p": 0.95}, "keys": " temperature=0.7 top_p=0.95"},
{"request": {"temperature": 0.7, "top_p": 1.0}, "keys": " temperature=0.7"},
{"request": {"top_p": 0.0}, "keys": " top_p=0.0"},
{"request": {"top_p": 0.5}, "keys": " top_p=0.5"},
{"request": {"top_k": 0}, "keys": " top_k=64"},
{"request": {"top_k": 1}, "keys": " top_k=1"},
{"request": {"top_k": 20}, "keys": " top_k=20"},
{"request": {"top_k": 64}, "keys": " top_k=64"},
{"request": {"top_k": 65}, "keys": " top_k=64"},
{"request": {"top_k": 100000}, "keys": " top_k=64"},
{"request": {"min_p": 0.0}, "keys": ""},
{"request": {"min_p": 0.05}, "keys": " min_p=0.05"},
{"request": {"min_p": 1.0}, "keys": " min_p=1.0"},
{"request": {"min_p": 1e-05}, "keys": " min_p=1e-05"},
{"request": {"repetition_penalty": 1.0}, "keys": ""},
{"request": {"repetition_penalty": 1.1}, "keys": " penalty_repeat=1.1 penalty_last_n=64"},
{"request": {"repetition_penalty": 1.1, "penalty_last_n": 256}, "keys": " penalty_repeat=1.1 penalty_last_n=256"},
{"request": {"repetition_penalty": 1.1, "penalty_last_n": 0}, "keys": " penalty_repeat=1.1 penalty_last_n=64"},
{"request": {"repetition_penalty": 1.1, "penalty_last_n": 5000}, "keys": " penalty_repeat=1.1 penalty_last_n=5000"},
{"request": {"frequency_penalty": 0.5}, "keys": " penalty_freq=0.5 penalty_last_n=64"},
{"request": {"frequency_penalty": -0.5}, "keys": " penalty_freq=-0.5 penalty_last_n=64"},
{"request": {"presence_penalty": 0.25}, "keys": " penalty_present=0.25 penalty_last_n=64"},
{"request": {"presence_penalty": 1.5, "frequency_penalty": 0.5, "repetition_penalty": 1.05}, "keys": " penalty_repeat=1.05 penalty_freq=0.5 penalty_present=1.5 penalty_last_n=64"},
{"request": {"presence_penalty": 0.0, "frequency_penalty": 0.0, "repetition_penalty": 1.0, "penalty_last_n": 33}, "keys": ""},
{"request": {"penalty_last_n": 33}, "keys": ""},
{"request": {"seed": 1}, "keys": " seed=1"},
{"request": {"seed": 42}, "keys": " seed=42"},
{"request": {"seed": 18446744073709551615}, "keys": " seed=18446744073709551615"},
{"request": {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.02, "repetition_penalty": 1.1, "presence_penalty": 0.5, "frequency_penalty": 0.25, "penalty_last_n": 128, "seed": 7}, "keys": " temperature=0.6 top_p=0.95 top_k=20 min_p=0.02 penalty_repeat=1.1 penalty_freq=0.25 penalty_present=0.5 penalty_last_n=128 seed=7"},
{"request": {"temperature": 1e+16}, "keys": " temperature=1e+16"},
{"request": {"temperature": 1.5e-05}, "keys": " temperature=1.5e-05"}
]}
+87
View File
@@ -0,0 +1,87 @@
//! `RequestSampling::gen_keys` against the strings the Original's Python
//! `StrataEngine.sampling_keys` emits (fixture produced by
//! `oracle/gen_sampling_keys.py`, which lifts that function verbatim).
use leleka_sampler_ref::params::{RequestSampling, SamplingParams};
use serde_json::Value;
fn request(v: &Value) -> RequestSampling {
let f = |k: &str| v.get(k).and_then(Value::as_f64);
let i = |k: &str| v.get(k).and_then(Value::as_i64);
RequestSampling {
temperature: f("temperature"),
top_p: f("top_p"),
top_k: i("top_k"),
min_p: f("min_p"),
repetition_penalty: f("repetition_penalty"),
frequency_penalty: f("frequency_penalty"),
presence_penalty: f("presence_penalty"),
penalty_last_n: i("penalty_last_n"),
seed: v.get("seed").and_then(Value::as_u64),
}
}
#[test]
fn gen_keys_equal_the_originals_python_output() {
let fixture: Value = serde_json::from_str(include_str!("fixtures/sampling_keys.json")).unwrap();
let cases = fixture["cases"].as_array().unwrap();
assert!(cases.len() >= 35);
let mut rejected = 0;
for case in cases {
let req = request(&case["request"]);
let want = case["keys"].as_str().unwrap();
match req.gen_keys() {
Ok(got) => assert_eq!(got, want, "request {}", case["request"]),
Err(error) => {
// The Original silently emits keys for out-of-contract values; this port refuses them.
// Only the deliberately out-of-range temperatures may be refused.
assert!(
req.temperature.is_some_and(|t| t > 2.0),
"unexpected refusal: {error}"
);
rejected += 1;
}
}
}
assert_eq!(
rejected, 1,
"exactly the temperature=1e16 case is out of the request contract"
);
}
#[test]
fn engine_floats_are_what_strtof_reads_from_the_wire_text() {
// Every float the engine would parse from the emitted text equals the f32 SamplingParams carries.
let fixture: Value = serde_json::from_str(include_str!("fixtures/sampling_keys.json")).unwrap();
for case in fixture["cases"].as_array().unwrap() {
let req = request(&case["request"]);
let Ok(keys) = req.gen_keys() else { continue };
let sp = SamplingParams::resolve(&req).unwrap();
let wire = |name: &str| -> Option<f32> {
keys.split(' ').find_map(|tok| {
tok.strip_prefix(name)?
.strip_prefix('=')?
.parse::<f32>()
.ok()
})
};
assert_eq!(wire("temperature").unwrap_or(0.0), sp.temperature, "{keys}");
assert_eq!(wire("top_p").unwrap_or(1.0), sp.top_p, "{keys}");
assert_eq!(wire("min_p").unwrap_or(0.0), sp.min_p, "{keys}");
assert_eq!(
wire("penalty_repeat").unwrap_or(1.0),
sp.penalty_repeat,
"{keys}"
);
assert_eq!(
wire("penalty_freq").unwrap_or(0.0),
sp.penalty_freq,
"{keys}"
);
assert_eq!(
wire("penalty_present").unwrap_or(0.0),
sp.penalty_present,
"{keys}"
);
}
}
+226
View File
@@ -0,0 +1,226 @@
//! The Rust reference against golden fixtures produced by the Original's host
//! sampler logic (see `oracle/gen_fixtures.cpp`). Floats travel as binary32 bit
//! patterns, so every comparison here is bitwise on the integer/RNG side and on
//! the selected list; picks follow from them.
use leleka_sampler_ref::chain::{
SamplerParams, penalised_logits, penalty_window, sample_row, sampled_k, select_topk,
};
use leleka_sampler_ref::coupled::{
coupled_draft_cell, coupled_draft_counter, coupled_draft_sample, coupled_hist_base,
coupled_hist_len, coupled_hist_start, penalty_rows,
};
use leleka_sampler_ref::philox::philox_uniform;
use serde_json::Value;
fn fixtures() -> Value {
let text = include_str!("fixtures/sampler_oracle.json");
serde_json::from_str(text).expect("fixture JSON")
}
fn u32s(v: &Value) -> Vec<u32> {
v.as_array()
.unwrap()
.iter()
.map(|x| x.as_u64().unwrap() as u32)
.collect()
}
fn floats(v: &Value) -> Vec<f32> {
u32s(v).into_iter().map(f32::from_bits).collect()
}
fn ints(v: &Value) -> Vec<i32> {
v.as_array()
.unwrap()
.iter()
.map(|x| x.as_i64().unwrap() as i32)
.collect()
}
fn params(v: &Value) -> SamplerParams {
let f = |k: &str| f32::from_bits(v[k].as_u64().unwrap() as u32);
SamplerParams {
top_k: v["top_k"].as_i64().unwrap() as i32,
top_p: f("top_p"),
min_p: f("min_p"),
temperature: f("temperature"),
min_keep: v["min_keep"].as_i64().unwrap() as i32,
penalty_last_n: v["penalty_last_n"].as_i64().unwrap() as i32,
penalty_repeat: f("penalty_repeat"),
penalty_freq: f("penalty_freq"),
penalty_present: f("penalty_present"),
seed: v["seed"].as_u64().unwrap(),
counter: v["counter"].as_u64().unwrap(),
greedy: v["greedy"].as_bool().unwrap(),
}
}
fn case_logits(case: &Value) -> Vec<f32> {
if let Some(sparse) = case.get("sparse") {
let mut l = vec![
f32::from_bits(sparse["fill"].as_u64().unwrap() as u32);
case["n_vocab"].as_u64().unwrap() as usize
];
for pair in sparse["set"].as_array().unwrap() {
l[pair[0].as_u64().unwrap() as usize] =
f32::from_bits(pair[1].as_u64().unwrap() as u32);
}
l
} else {
floats(&case["logits"])
}
}
#[test]
fn philox_matches_the_original_host_twin() {
let f = fixtures();
let rows = f["philox"].as_array().unwrap();
assert!(rows.len() >= 80);
for r in rows {
let (seed, counter, bits) = (
r[0].as_u64().unwrap(),
r[1].as_u64().unwrap(),
r[2].as_u64().unwrap() as u32,
);
assert_eq!(
philox_uniform(seed, counter).to_bits(),
bits,
"seed {seed} counter {counter}"
);
}
}
#[test]
fn chain_matches_the_original_bit_for_bit() {
let f = fixtures();
let cases = f["chain"].as_array().unwrap();
assert!(cases.len() >= 150);
let mut sampled = 0;
let mut greedy = 0;
for case in cases {
let name = case["name"].as_str().unwrap();
let p = params(&case["params"]);
let logits = case_logits(case);
let history = ints(&case["history"]);
let row = case["row"].as_u64().unwrap();
let expect = &case["expect"];
// the selection list, bitwise
let window = penalty_window(&history, p.penalty_last_n);
let scores = penalised_logits(&logits, window, &p);
let is_greedy = p.is_greedy();
let k = if is_greedy {
1
} else {
sampled_k(p.top_k, logits.len())
};
let sel = select_topk(&scores, k);
assert_eq!(sel.ids, ints(&expect["sel_ids"]), "{name}: selection ids");
let got: Vec<u32> = sel.logits.iter().map(|x| x.to_bits()).collect();
assert_eq!(got, u32s(&expect["sel_logits"]), "{name}: selection logits");
// the token
let token = sample_row(&logits, &history, &p, row).unwrap();
assert_eq!(
token,
expect["token"].as_i64().unwrap() as i32,
"{name}: token"
);
if is_greedy {
greedy += 1;
} else {
sampled += 1;
let u = philox_uniform(p.seed, p.counter.wrapping_add(row));
assert_eq!(
u.to_bits(),
expect["u"].as_u64().unwrap() as u32,
"{name}: uniform"
);
}
}
assert!(
sampled > 100 && greedy > 10,
"sampled {sampled}, greedy {greedy}"
);
}
#[test]
fn counter_arithmetic_matches_the_original_headers() {
let f = fixtures();
let c = &f["counters"];
for r in c["cells"].as_array().unwrap() {
let (p, a, j) = (
r[0].as_i64().unwrap(),
r[1].as_i64().unwrap() as i32,
r[2].as_i64().unwrap() as i32,
);
let cell = coupled_draft_cell(p, a, j);
assert_eq!(cell, r[3].as_i64().unwrap());
assert_eq!(coupled_draft_counter(cell), r[4].as_u64().unwrap());
}
for r in c["hist_len"].as_array().unwrap() {
let v = ints(r);
assert_eq!(coupled_hist_len(v[0], v[1]), v[2], "hist_len {v:?}");
}
for r in c["hist_start"].as_array().unwrap() {
let v = ints(r);
assert_eq!(
coupled_hist_start(v[0], v[1], v[2]),
v[3],
"hist_start {v:?}"
);
}
}
#[test]
fn penalty_rows_and_ring_base_match_the_original() {
let f = fixtures();
for case in f["penalty_rows"].as_array().unwrap() {
let tail = ints(&case["tail"]);
let window = ints(&case["window"]);
let h = case["h"].as_u64().unwrap() as usize;
assert_eq!(
penalty_rows(&tail, &window, window.len(), h),
ints(&case["rows"])
);
let next = case["next"].as_i64().unwrap() as i32;
assert_eq!(
coupled_hist_base(&tail, next, h as i32),
ints(&case["base"])
);
}
}
#[test]
fn coupled_draft_matches_the_transcribed_kernels() {
let f = fixtures();
let cases = f["coupled"].as_array().unwrap();
assert!(cases.len() >= 50);
let mut sampled = 0;
for case in cases {
let cap = case["cap"].as_i64().unwrap() as i32;
let j = case["j"].as_i64().unwrap() as i32;
let step0 = case["step0"].as_i64().unwrap() as i32;
let id_vocab = case["id_vocab"].as_u64().unwrap() as usize;
let p = params(&case["params"]);
let mut logits = floats(&case["logits"]);
let sub_to_id = ints(&case["sub_to_id"]);
let id_to_sub = ints(&case["id_to_sub"]);
let mut ring = ints(&case["ring"]);
let got = coupled_draft_sample(
&mut logits,
(!sub_to_id.is_empty()).then_some(&sub_to_id[..]),
(!id_to_sub.is_empty()).then_some(&id_to_sub[..]),
id_vocab,
&p,
&mut ring,
cap,
j,
step0,
);
let e = &case["expect"];
assert_eq!(got.id, e["id"].as_i64().unwrap() as i32);
assert_eq!(got.sub_index, e["sub"].as_i64().unwrap() as i32);
assert_eq!(got.prob.to_bits(), e["prob"].as_u64().unwrap() as u32);
assert_eq!(ring[(cap + j) as usize], got.id);
if !p.is_greedy() {
sampled += 1;
}
}
assert!(sampled > 40);
}