engine: the window loop, the host and the controller read the decode settings of their binding (STRA-338)

NativeServePort holds the DecodeSettings of its host's binding (overlap, draft after commit, the logprob, draft and
residual traces); the serve host reads publish serial, adapt defer and PLE on chain from its binding; the prompt-lookup
drafter's sparse reset is a field the controller configuration sets (SpecConfig::with_sparse_suffix_reset).
This commit is contained in:
Pavlo Ratushnyi
2026-11-28 10:26:44 +01:00
parent 1b065ddb9a
commit f846a10fa4
15 changed files with 56 additions and 59 deletions
@@ -176,6 +176,8 @@ pub(crate) struct OriginalServeSettings {
/// `LELEKA_SPEC_TRACE` and `LELEKA_SPEC_STATS`: the operator lines of the controller (round trace, request stats).
pub(crate) trace_rounds: bool,
pub(crate) trace_stats: bool,
/// `LELEKA_SUFFIX_RESET` (default sparse): how the prompt-lookup table is cleared between requests.
pub(crate) suffix_sparse_reset: bool,
/// An arm's own `spec_min_p` for the requests it serves (`fixed4@0`), overriding the harness default; `None` = the
/// harness's.
pub(crate) request_min_p: Option<f32>,
@@ -24,6 +24,7 @@ impl OriginalServeSettings {
nan_guard: NanGuard::off(),
trace_rounds: false,
trace_stats: false,
suffix_sparse_reset: true,
request_min_p: None,
}
}
@@ -39,6 +40,7 @@ impl OriginalServeSettings {
s.nan_guard = NanGuard::from_environment(env);
let decode = crate::settings::DecodeSettings::from_source(env);
(s.trace_rounds, s.trace_stats) = (decode.spec_trace, decode.spec_stats);
s.suffix_sparse_reset = decode.suffix_reset_sparse;
if let Some(spec) = num("LELEKA_SPEC") {
let spec = spec.clamp(2, MAX_T);
s.max_t = (spec + 2).min(MAX_T);
@@ -179,7 +181,8 @@ impl OriginalServeSettings {
)?
.with_adaptive(self.adaptive)
.with_nan_guard(self.nan_guard)
.with_trace(self.trace_rounds, self.trace_stats),
.with_trace(self.trace_rounds, self.trace_stats)
.with_sparse_suffix_reset(self.suffix_sparse_reset),
)
}
}
@@ -342,6 +342,7 @@ fn serve_settings(max_context: i64) -> OriginalServeSettings {
nan_guard: NanGuard::off(),
trace_rounds: false,
trace_stats: false,
suffix_sparse_reset: true,
request_min_p: None,
}
}
@@ -119,7 +119,6 @@ pub(in crate::qwen_forward) struct HostOwners<'a, 'ctx, P> {
mod tests;
mod request_sampling;
use request_sampling::adapt_defer;
use request_sampling::operator_line;
mod ple_on_chain;
mod run_window_steps;
@@ -5,7 +5,7 @@ use super::{
AcceptedWindow, DraftCompletion, DraftLaunch, Error, LedgerCheckpoint, MtpDraftOwners, NativeServeHost,
OriginalCommittedMtpReceipt, OriginalDraftCheckpoint, OriginalGpuEvent, OriginalNativeHeadGraphResources,
OriginalServeHost, OriginalServePool, OriginalVerifier, OriginalVerifyGraphResources, OriginalVerifyWindowResult,
Result, Stage, adapt_defer, ple_on_chain, profile, report_window,
Result, Stage, ple_on_chain, profile, report_window,
};
use crate::qwen_forward::original_mtp_verified_adapter::VerifiedWindow;
use crate::qwen_forward::original_serve_engine::{DraftLimits, FirstDraftSeed};
@@ -97,7 +97,7 @@ impl<'a, 'ctx, P: OriginalServePool<'ctx>> NativeServeHost<'ctx> for OriginalSer
// and the commit/draft launch; with the deferral they run once the draft is launched
// (`run_deferred_adaptation`) or, at the latest, at the join, always before the next round's
// `apply_pending`. LELEKA_SERVE_ADAPT_DEFER=off runs them here as before.
if adapt_defer() {
if self.binding.settings().decode.adapt_defer {
if self.deferred_adaptation.is_some() {
return Err(Error::IdentityMismatch);
}
@@ -87,7 +87,7 @@ fn window_before(start: WindowStart, k: usize, drafted: &[i32]) -> [i32; 2] {
impl<'ctx, P: OriginalServePool<'ctx>> OriginalServeHost<'_, 'ctx, P> {
/// Where the next window starts when its PLE rows may be gathered during the draft, else `None`.
pub(super) fn ple_window_start(&mut self) -> Option<WindowStart> {
let mode = crate::settings::process().decode.ple_on_chain;
let mode = self.binding.settings().decode.ple_on_chain;
note_mode(mode);
let first = self.next_input.take()?;
if self.kar.is_none() || !enabled(mode, self.session.original_ple_required()) {
@@ -37,11 +37,6 @@ impl RequestSampling {
}
}
/// `LELEKA_SERVE_PUBLISH=serial`: the per-layer checkpoint publication (A/B control of the batched one).
pub(super) fn serial_publish() -> bool {
crate::settings::process().decode.publish_serial
}
pub(super) fn operator_line(what: &str, failure: &ServeFailure) {
use std::io::Write;
// Fixed driver strings and error classes only; never request data.
@@ -49,6 +44,10 @@ pub(super) fn operator_line(what: &str, failure: &ServeFailure) {
}
impl<'a, 'ctx, P: OriginalServePool<'ctx>> OriginalServeHost<'a, 'ctx, P> {
/// The decode switches of the binding this host serves over, for the native port wrapped around it.
pub(in crate::qwen_forward) fn decode_settings(&self) -> crate::settings::DecodeSettings {
self.binding.settings().decode.clone()
}
/// `committed` is the token sequence the session holds (the prompt without its last token); `limit` is
/// the last position a state may end at. The session must stand exactly there, in step.
pub(in crate::qwen_forward) fn new(
@@ -172,12 +171,6 @@ impl<'a, 'ctx, P: OriginalServePool<'ctx>> OriginalServeHost<'a, 'ctx, P> {
}
}
/// `LELEKA_SERVE_ADAPT_DEFER=off`: plan and queue the adaptive swaps before the commit (the earlier order; the A/B
/// control).
pub(super) fn adapt_defer() -> bool {
crate::settings::process().decode.adapt_defer
}
impl<'a, 'ctx, P: OriginalServePool<'ctx>> OriginalServeHost<'a, 'ctx, P> {
/// The MTP actor drafts as many chain steps as it is configured for (`set_max_drafts`); an adaptive round's plan is
/// applied here (the engine has already bounded it by the request's cap). Equal values cost one comparison.
@@ -230,7 +223,7 @@ impl<'a, 'ctx, P: OriginalServePool<'ctx>> OriginalServeHost<'a, 'ctx, P> {
// The twelve index checkpoints in one batch after the commit event (one stream drain, pooled buffers),
// or one by one with a context synchronize each (LELEKA_SERVE_PUBLISH=serial, the earlier path).
let p = profile::span("publish.index_checkpoint");
let mut batched = if serial_publish() {
let mut batched = if self.binding.settings().decode.publish_serial {
None
} else {
Some(verifier.checkpoint_committed_qsa_all(&mut workspace).map_err(|e| driver_error(&e))?.map(Some))
@@ -268,7 +261,7 @@ impl<'a, 'ctx, P: OriginalServePool<'ctx>> OriginalServeHost<'a, 'ctx, P> {
}
pub(super) fn publish_to_session(&mut self, committed: &[i32], next: QsaPriors<'ctx>) -> Result<()> {
let p = profile::span("publish.session");
if serial_publish() {
if self.binding.settings().decode.publish_serial {
self.session.publish_original_verified_rows(committed, self.ledger.limit(), next)?;
} else {
// fenced: the commit event was waited and the batched witness checkpoints drained above
@@ -114,6 +114,8 @@ where
{
verifier: OriginalVerifier<'ctx, R>,
host: H,
/// The operator switches of the window loop (overlap, draft order, bring-up traces), from the binding's settings.
decode: crate::settings::DecodeSettings,
pending_publish: Option<(i64, Vec<i32>)>,
failed: bool,
}
@@ -139,6 +141,5 @@ mod tests {
mod native_window;
#[cfg(test)]
use native_window::draft_waits_for_commit_from;
use native_window::overlap;
use native_window::trace_draft_line;
mod native_serve_port_original_serve_port;
@@ -4,7 +4,7 @@
use super::{
CommittedWindow, DraftCompletion, DraftLimits, Error, FirstDraftSeed, NativeServeHost, NativeServePort,
NativeWindow, OriginalNativeHeadGraphResources, OriginalServePort, OriginalVerifyGraphResources,
OriginalVerifyWindow, RefCell, Result, overlap, profile, trace_draft_line,
OriginalVerifyWindow, RefCell, Result, profile, trace_draft_line,
};
impl<'ctx, R, H> OriginalServePort for NativeServePort<'ctx, R, H>
@@ -160,7 +160,7 @@ where
if window.keep != Some(accepted_row + 1) || window.position != position || outputs != window.ids.as_slice() {
return Err(Error::IdentityMismatch);
}
if overlap() && self.pending_publish.is_some() {
if self.decode.overlap && self.pending_publish.is_some() {
return self.draft_overlapped(window, (position, accepted_row), (max_drafts, min_p));
}
self.draft_serialized(window, (position, accepted_row), (max_drafts, min_p, coupled))
@@ -17,8 +17,12 @@ where
R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>,
H: NativeServeHost<'ctx>,
{
pub(in crate::qwen_forward) fn new(verifier: OriginalVerifier<'ctx, R>, host: H) -> Self {
Self { verifier, host, pending_publish: None, failed: false }
pub(in crate::qwen_forward) fn new(
verifier: OriginalVerifier<'ctx, R>,
host: H,
decode: crate::settings::DecodeSettings,
) -> Self {
Self { verifier, host, decode, pending_publish: None, failed: false }
}
pub(in crate::qwen_forward) fn verifier(&self) -> &OriginalVerifier<'ctx, R> {
&self.verifier
@@ -100,7 +104,7 @@ where
}
/// Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=<topk>): top-k head logprobs of every row of the completed window.
pub(super) fn trace_window_logprobs(&mut self, position: i64, inputs: &[i32], ids: &[i32]) {
if let Some(k) = trace_logprobs() {
if let Some(k) = self.decode.trace_logprobs {
let mut line: Vec<u8> = Vec::new();
crate::bringup_trace!("DBG logprobs window position={position} inputs={inputs:?} argmax_ids={ids:?}");
match self.verifier.window_logprobs_topk(ids, -1, k, &mut line) {
@@ -112,7 +116,7 @@ where
/// Bring-up diagnostic (LELEKA_TRACE_RESIDUAL=<dir>): the final residual R of every row of the completed
/// window, raw little-endian f32 (rows, hc*n_embd), file `r_win<seq>_pos<first position>.f32`.
pub(super) fn trace_window_residual(&mut self, inputs: &[i32]) {
let Some(dir) = trace_residual() else { return };
let Some(dir) = self.decode.trace_residual.clone() else { return };
match self.verifier.window_residual_rows() {
Ok((rows, start, values)) => {
let bytes: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
@@ -127,7 +131,7 @@ where
if let Err(e) = std::fs::write(&path, bytes) {
eprintln!("DBG residual write err {e:?}");
}
self.trace_window_ladder(dir, seq, start);
self.trace_window_ladder(&dir, seq, start);
}
Err(e) => eprintln!("DBG residual err {e:?}"),
}
@@ -184,7 +188,7 @@ where
let (completed, selection) = self.take_window_parts(window)?;
let launched = {
let _p = profile::span("draft.launch");
let after = if draft_waits_for_commit() { self.verifier.pending_commit_event() } else { None };
let after = if self.decode.draft_after_commit { self.verifier.pending_commit_event() } else { None };
let committed = NativeCommittedWindow { window: completed, selection, position, accepted_row };
self.host.launch_draft(committed, DraftLimits { max_drafts, min_p }, after)
};
@@ -220,28 +224,18 @@ where
if draft.is_err() {
self.failed = true;
}
if let Ok(c) = &draft {
if let (Ok(c), true) = (&draft, self.decode.trace_draft) {
trace_draft_line(position, accepted_row, c);
}
draft
}
}
/// The two bring-up window traces, read once (they sat on the per-window path).
pub(super) fn trace_logprobs() -> Option<usize> {
crate::settings::process().decode.trace_logprobs
}
/// `LELEKA_TRACE_DRAFT=1`: one line per completed draft (position, accepted row, the draft ids and the IEEE bits of
/// their probabilities). The draft's numerics
/// are bit-compared across builds and settings by diffing these lines (draft-round identity gate); nothing reads them
/// in production.
pub(super) fn trace_draft() -> bool {
crate::settings::process().decode.trace_draft
}
pub(super) fn trace_draft_line(position: i64, accepted_row: usize, c: &DraftCompletion) {
if !trace_draft() {
return;
}
let bits: Vec<String> = c.probabilities.iter().map(|p| format!("{:08x}", p.to_bits())).collect();
eprintln!(
"DRAFT position={position} accepted_row={accepted_row} cell={} ids={:?} pbits=[{}]",
@@ -250,17 +244,10 @@ pub(super) fn trace_draft_line(position: i64, accepted_row: usize, c: &DraftComp
bits.join(",")
);
}
pub(super) fn trace_residual() -> Option<&'static std::ffi::OsString> {
crate::settings::process().decode.trace_residual.as_ref()
}
/// `LELEKA_SERVE_OVERLAP=off`: settle the commit (wait + publish) before the draft launches (the earlier, serialized
/// order; A/B control). Default: the draft is enqueued while the commit runs (`draft_waits_for_commit` says whether it
/// also waits for
/// the commit event on the device), and the host publishes the session while the draft's first graph runs.
pub(super) fn overlap() -> bool {
crate::settings::process().decode.overlap
}
// `LELEKA_SERVE_OVERLAP=off` (`decode.overlap`): settle the commit (wait + publish) before the draft launches (the
// earlier, serialized order; A/B control). Default: the draft is enqueued while the commit runs
// (`LELEKA_SERVE_DRAFT_AFTER_COMMIT` says whether it also waits for the commit event on the device), and the host
// publishes the session while the draft's first graph runs.
/// Whether the draft stream waits for the verifier's commit event on the device before its first command.
/// Upstream's serve loop does not: `Verifier::commit` (core/verify.cpp, `set_commit_async`) enqueues the commit graph
@@ -272,9 +259,6 @@ pub(super) fn overlap() -> bool {
/// the draft behind the commit event, which put the commit graph (~0.36 ms: 36 GDN layers, 12 QSA appends, the PLE
/// history) in front of
/// every draft on the critical path. `LELEKA_SERVE_DRAFT_AFTER_COMMIT=on` restores that order (A/B control).
pub(super) fn draft_waits_for_commit() -> bool {
crate::settings::process().decode.draft_after_commit
}
#[cfg(test)]
pub(super) fn draft_waits_for_commit_from(value: Option<&str>) -> bool {
crate::settings::text_is_one_of(value, &crate::settings::DRAFT_AFTER_COMMIT_ON)
@@ -42,7 +42,8 @@ pub(super) fn serve_over_host<'a, 'ctx, P: OriginalServePool<'ctx>>(
Err(error) => return Ok((Err(SpecError::Forward(error)), verifier, None)),
Ok(host) => host,
};
let port = super::super::super::original_serve_engine::TracePort(NativeServePort::new(verifier, host));
let decode = host.decode_settings();
let port = super::super::super::original_serve_engine::TracePort(NativeServePort::new(verifier, host, decode));
let engine = OriginalServeEngine::new(port, VOCABULARY, env.settings.max_t, env.settings.max_drafts());
let mut engine = match engine {
Err(_) => {
@@ -111,6 +111,8 @@ pub(crate) struct SpecConfig {
/// `LELEKA_SPEC_TRACE`: the round trace lines; `LELEKA_SPEC_STATS`: the request stats line.
trace_rounds: bool,
trace_stats: bool,
/// `LELEKA_SUFFIX_RESET`: the prompt-lookup table is cleared sparsely (default) or in full.
suffix_sparse_reset: bool,
}
struct Request {
consumed: Vec<i32>,
@@ -36,7 +36,8 @@ impl OriginalSpecController {
}
pub(crate) fn new(config: SpecConfig) -> Result<Self> {
let cap = (config.max_context as usize).checked_add(4096).ok_or(Error::Overflow)?;
let suffix = SuffixDrafter::new(config.suffix_min_match.max(1), 64, cap)?;
let suffix =
SuffixDrafter::new(config.suffix_min_match.max(1), 64, cap)?.with_sparse_reset(config.suffix_sparse_reset);
let policy = DraftPolicy::new(config.max_t, 0.03)?;
let adaptive = config.adaptive.map(AdaptivePolicy::new);
Ok(Self {
@@ -117,6 +117,7 @@ impl SpecConfig {
nan_guard: NanGuard::off(),
trace_rounds: false,
trace_stats: false,
suffix_sparse_reset: true,
})
}
/// `new` for the context of an unconfigured process (262144 serving cells).
@@ -138,6 +139,11 @@ impl SpecConfig {
self.trace_stats = stats;
self
}
/// `LELEKA_SUFFIX_RESET` (default sparse; `full` clears the whole prompt-lookup table on every reset).
pub(crate) fn with_sparse_suffix_reset(mut self, sparse: bool) -> Self {
self.suffix_sparse_reset = sparse;
self
}
pub(crate) fn with_nan_guard(mut self, guard: NanGuard) -> Self {
self.nan_guard = guard;
self
@@ -16,10 +16,9 @@ pub(crate) struct SuffixDrafter {
/// Table slots claimed since the last reset, so a reset clears those instead of the whole table (the table is
/// sized for the whole context: 32 MB at 262144 cells, a request touches a few thousand slots).
touched: Vec<u32>,
}
/// `LELEKA_SUFFIX_RESET=full`: clear the whole table on every reset (the earlier behaviour; A/B control).
fn sparse_reset() -> bool {
crate::settings::process().decode.suffix_reset_sparse
/// `LELEKA_SUFFIX_RESET=full` turns this off: clear the whole table on every reset (the earlier behaviour; A/B
/// control).
sparse_reset: bool,
}
fn mix(mut x: u64) -> u64 {
x ^= x >> 33;
@@ -47,8 +46,13 @@ impl SuffixDrafter {
mask: cap - 1,
last_match: 0,
touched: Vec::new(),
sparse_reset: true,
})
}
pub(crate) fn with_sparse_reset(mut self, sparse: bool) -> Self {
self.sparse_reset = sparse;
self
}
pub(crate) fn metadata_bytes(&self) -> Result<usize> {
self.history
.capacity()
@@ -61,7 +65,7 @@ impl SuffixDrafter {
self.history.clear();
self.last_match = 0;
// Only a slot `find_slot(.., true)` claimed holds anything: clearing those is the same table as a full fill.
if sparse_reset() && self.touched.len() <= self.table.len() / 4 {
if self.sparse_reset && self.touched.len() <= self.table.len() / 4 {
for &i in &self.touched {
self.table[i as usize] = Slot::default();
}