Files
lotherk c8c3ca492c Sampler: DRY anti-repetition penalty, exposed end to end
The sampler chain gains llama.cpp's dry stage (penalties -> DRY -> top_k -> ...): a token that would extend a
repeat longer than dry_allowed_length over the last dry_penalty_last_n history tokens loses
dry_multiplier * dry_base^(repeat - allowed_length), with tokenized restart sequences capping the scan.

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

121 lines
7.7 KiB
C++

// include/strata/kernels/sampler.hpp - the sampler chain, host-callable (P2.S2).
//
// penalties -> top_k -> top_p -> min_p -> temperature -> pick
//
// llama.cpp's default chain (issue #53): ONE penalties stage, first, and temperature AFTER the truncation filters;
// top_p cuts before min_p. `src/kernels/cuda/sampler.cu` has the details and `sampler_parity` pins them.
#pragma once
#include <algorithm>
#include <cstddef>
#include <cstdint>
namespace strata::kernels {
struct SamplerParams {
int top_k = 20; // sampled path: 1..64 as given; 0 (off) or more than 64 keep the widest list, 64
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
float penalty_repeat = 1.0f;
float penalty_freq = 0.0f;
float penalty_present = 0.0f;
uint64_t seed = 0; // drives Philox, which is counter-based on (seed, token index)
uint64_t counter = 0; // absolute draw index of row 0; advance across decode calls
bool greedy = false;
// DRY (llama.cpp's `dry` sampler, applied straight after the penalties above): a token that would EXTEND a
// repeat longer than `dry_allowed_length` loses `dry_multiplier * dry_base^(repeat - allowed_length)`, over
// the last `dry_penalty_last_n` history tokens. Restart sequences cap the repeat length. `dry_multiplier`
// 0, `dry_base` < 1, or `dry_penalty_last_n` 0 disables it (llama.cpp's `dry_enabled`). Only the last
// `kDryWindowCap` window tokens are examined; a longer `dry_penalty_last_n` is clamped there.
float dry_multiplier = 0.0f;
float dry_base = 1.75f;
int dry_allowed_length = 2;
int dry_penalty_last_n = 0; // 0 disables; the window over `history`, the same row the penalties count
};
// The DRY Z-algorithm runs in DEVICE SHARED memory, one window per row: the cap bounds that window (and the
// sequence-breaker scan). llama.cpp's default is 256; the engine's penalty window may be wider (up to 4096).
constexpr int kDryWindowCap = 512;
// DRY sequence breakers, tokenized (llama.cpp's `dry_processed_breakers`): `n` restart sequences, sequence k is
// `flat[off[k] .. off[k+1])`, its head `flat[off[k]]` and its tail the rest. A head with an empty tail is a
// single-token sequence and is never penalised. DEVICE pointers; `n == 0` means no breakers.
struct DryBreakers {
const int* flat = nullptr;
const int* off = nullptr;
int n = 0;
};
// `dry_enabled` (llama.cpp's condition): the multiplier, the base and a non-zero window must all agree. Both the
// host launch path and the device kernels call it, so it is host-and-device (the header is not CUDA-only).
#if defined(__CUDACC__)
__host__ __device__
#endif
inline bool dry_enabled(const SamplerParams& p) {
return p.dry_multiplier != 0.0f && p.dry_base >= 1.0f && p.dry_penalty_last_n != 0;
}
// logits (n_tokens, n_vocab) -> one sampled token id per row in `out`.
//
// **`logits` AND `out` ARE DEVICE POINTERS.** This is a CUDA kernel launch, not a host function, and nothing
// in the parameter names or the types says so - `const float* logits` reads exactly like a host buffer.
// Measured: passing host memory for `logits` faults inside the kernel with an ILLEGAL MEMORY ACCESS that is
// reported by whatever synchronising call happens NEXT, which will be somewhere else entirely and will name a
// buffer that has nothing to do with it. A sticky async fault does not know where it came from.
//
// `history` is (n_tokens, history_len) int32 - ONE ROW PER TOKEN ROW, at a stride of `history_len` - the most
// recent tokens that row's pick follows, with any unused slots set to -1; only the last `p.penalty_last_n` of
// each row are counted, and ids outside [0, n_vocab) are ignored. DRY counts over the last `p.dry_penalty_last_n`
// of the SAME row; `breakers` are its tokenized restart sequences (a head with an empty tail is a single-token
// sequence and is never penalised), `n == 0` for none. Pass history nullptr and 0 when no penalties apply.
// A verify window's rows need DIFFERENT histories: row t follows the window's drafts 1..t (`penalty_rows`).
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
const SamplerParams& p, int* out, void* stream, const DryBreakers& breakers = DryBreakers{});
// The greedy pick (no penalties) on a thread-block cluster of 8 CTAs per row (sm_90+, CUDA; S19): the same token as
// sample_tokens' one-block argmax, which takes it unless STRATA_ARGMAX_MULTI=0. False (nothing launched) where it
// cannot run: HIP, a card or a build below sm_90. Device pointers; capturable.
bool sample_greedy_cluster(const float* logits, int n_tokens, int n_vocab, int* out, void* stream);
// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp, STRATA_SPEC_COUPLED=1). Device pointers
// throughout; every per-request / per-round value comes from device memory, so the calls can be captured.
//
// The scratch `coupled_draft_sample` needs for `nv` logits (0: too wide for the split merge, coupled cannot run).
size_t coupled_draft_scratch_bytes(int nv);
// A round's inputs: `*params` <- `*mapped_params`, ring[cap - h, cap) <- mapped_hist[cap - h, cap) with h =
// coupled_hist_len(penalty_last_n, cap). `mapped_*` are mapped host memory.
void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params,
int32_t* ring, int cap, void* stream);
// Draft j of the chain from ONE row of `nv` logits (modified in place: the penalties): the target's chain with
// `*params`, the penalty window ring[cap + j - h, cap + j), Philox counter coupled_draft_counter(step_rec[0]).
// `sub_to_id` / `id_to_sub` map the draft head's subset to token ids and back (null: the whole vocabulary,
// `id_vocab` ids). Writes the token id to *out_id, its probability under the final distribution to *out_prob, and
// the id to ring[cap + j].
void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
void* scratch, int32_t* out_id, float* out_prob, void* stream,
const DryBreakers& breakers = DryBreakers{});
// The penalty-history rows of a verify window, on the host: row t of `out` (T rows of `h` slots) is the last `h`
// tokens of `tail[0..n_tail)` followed by `window[0..t]`, most recent LAST, -1 in the unused front slots.
// `tail` is what the state consumed before the window, `window[0]` the fed-back token and `window[1..]` the
// drafts: row t is exactly the history plain decode counts when it picks the token after `window[t]`, so drafting
// cannot change which tokens are penalised. Row 0 alone is the single row the engine staged before 0.1.19.
inline void penalty_rows(const int32_t* tail, int64_t n_tail, const int32_t* window, int T, int h, int32_t* out) {
for (int t = 0; t < T; ++t) {
int32_t* row = out + (size_t) t * (size_t) h;
const int64_t avail = n_tail + t + 1; // tail + window[0..t]
const int take = (int) std::min<int64_t>(h, avail);
std::fill(row, row + (h - take), -1);
for (int j = 0; j < take; ++j) {
const int64_t i = avail - take + j; // index into (tail, window)
row[h - take + j] = i < n_tail ? tail[i] : window[i - n_tail];
}
}
}
} // namespace strata::kernels