diff --git a/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs b/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs index 855823fb..5d501c91 100644 --- a/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs +++ b/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs @@ -96,23 +96,34 @@ fn prefill_tiles( } let end = tile_end(run, (position, prompt.len()), adaptive_prefill); let next = prompt.get(end).copied(); - let product = if end - position == 1 && next.is_none() && !adaptive_prefill { + let lone = end - position == 1 && next.is_none() && !adaptive_prefill; + let product = if lone { // Other policies keep the original lone-row actual-head producer. Some(run.target_step(prompt[position], position)?) } else { run.prefill_chunk(&prompt[position..end], position, next, decoder, start)? }; - if next.is_none() { - *latest = Some(product.ok_or_else(|| invalid("missing final prefill source"))?); - } else if product.is_some() { - return Err(invalid("unexpected intermediate prefill head").into()); - } + keep_final_product(latest, product, next.is_none())?; committed.extend_from_slice(&prompt[position..end]); position = end; } Ok(()) } +/// Only the final tile yields a head product; an intermediate one must not. +fn keep_final_product( + latest: &mut Option, + product: Option, + is_final: bool, +) -> Result<(), GenerationFailure> { + if is_final { + *latest = Some(product.ok_or_else(|| invalid("missing final prefill source"))?); + } else if product.is_some() { + return Err(invalid("unexpected intermediate prefill head").into()); + } + Ok(()) +} + /// The verified window from `product`: the cancel probe also watches the shutdown flag, the sink and the deadline. fn verified_window( run: &mut Generation<'_, '_, '_, C>, @@ -168,7 +179,8 @@ fn observe_window(run: &Generation<'_, '_, '_, C>, draft_steps: usize, }); } -/// Commit and emit the tokens of a verified window; returns the product to continue from and whether the window stopped. +/// Commit and emit the tokens of a verified window; returns the product to continue from and whether the window +/// stopped. fn commit_window( run: &Generation<'_, '_, '_, C>, window: MtpVerifiedWindow, diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs index 53e27d37..39366f9a 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs @@ -119,9 +119,12 @@ mod run_parts; use run_parts::drop_model_page_cache; #[allow(unused_imports)] use run_parts::{ - GenerateEnv, Live, ReopenEnv, abandon_stack, close_context, close_stack, emit_cache_line, open_run_stack, - reconfigure, serve_generate, sweep_idle, + GenerateEnv, abandon_stack, close_context, close_stack, emit_cache_line, open_run_stack, serve_generate, sweep_idle, }; +#[path = "runner/reconfigure_parts.rs"] +mod reconfigure_parts; +#[allow(unused_imports)] +use reconfigure_parts::{Live, ReopenEnv, reconfigure}; #[path = "runner/run_fn.rs"] mod run_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs index bb7ed100..cd865988 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs @@ -103,7 +103,8 @@ pub(in super::super::super) fn generate( Ok((reason, usage)) } -/// The serve call's result as the request's outcome: a failure captured while delivering, the deadline, or the stack's own refusal. +/// The serve call's result as the request's outcome: a failure captured while delivering, the deadline, or the stack's +/// own refusal. fn served_outcome( captured: Option, timed_out: bool, @@ -117,27 +118,23 @@ fn served_outcome( leleka_memory::telemetry::request_aborted(); return Err(unavailable("generation deadline exceeded").into()); } - match result { - Ok(outcome) => Ok(outcome), - Err(ServeError::Cancelled) => { - leleka_memory::telemetry::request_aborted(); - Err(GenerationFailure::Cancelled) - } - Err(ServeError::Refused(admission)) => { - leleka_memory::telemetry::request_aborted(); - Err(admission_error(admission).into()) - } - Err(ServeError::Failed(error)) => { - leleka_memory::telemetry::request_aborted(); + let error = match result { + Ok(outcome) => return Ok(outcome), + Err(error) => error, + }; + leleka_memory::telemetry::request_aborted(); + Err(match error { + ServeError::Cancelled => GenerationFailure::Cancelled, + ServeError::Refused(admission) => admission_error(admission).into(), + ServeError::Failed(error) => { operator_class("leleka-serve request failed", error); - Err(unavailable("Original serve request failed").into()) + unavailable("Original serve request failed").into() } - Err(ServeError::Broken(error)) => { - leleka_memory::telemetry::request_aborted(); + ServeError::Broken(error) => { operator_class("leleka-serve stack lost an owner", error); - Err(unavailable("Original serve stack lost a physical owner").into()) + unavailable("Original serve stack lost a physical owner").into() } - } + }) } fn operator_class(what: &str, class: impl std::fmt::Debug) { diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/reconfigure_parts.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/reconfigure_parts.rs new file mode 100644 index 00000000..ff02ec5c --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/reconfigure_parts.rs @@ -0,0 +1,174 @@ +//! `Command::Reconfigure` of the Original owner loop, moved out of `run_parts` by STRA-338 (size): close the old stack, open +//! one with the new settings, or reopen the previous ones. + +#[allow(unused_imports)] +use super::*; +use leleka_cuda_driver::Context; +use std::time::Instant; + +type Stack<'a, 'ctx> = OriginalServeStack<'a, 'ctx>; + +/// The run-time state of the owner loop that `Command::Reconfigure` may replace. +pub(super) struct Live<'r, 'a, 'ctx> { + pub(super) options: &'r mut OriginalServeOptions, + pub(super) context_tokens: &'r mut u32, + pub(super) workers: &'r mut i32, + pub(super) stack: &'r mut Option>, +} + +/// What a reconfigure reads: the owners the new stack is built over, the shared flags and the clock. +pub(super) struct ReopenEnv<'a, 'ctx, 'r> { + pub(super) binding: &'a ModelBinding, + pub(super) context: &'ctx Rc>, + pub(super) shared: &'r Shared, + pub(super) clock: &'r SystemClock, +} + +/// The old stack is closed before the new one opens, so the new one's pinned host memory (K/V, rings, pools) must fit +/// in +/// what is free now. Refuse up front on a starved host instead of leaving the engine without a stack (live native run +/// 2026-10-25). +fn refuse_starved_host() -> Result<(), BackendError> { + if let Some(governor) = leleka_memory::Governor::global() { + let need = governor.policy().soft_floor.saturating_add(RECONFIGURE_HEADROOM_BYTES); + if let Some(available) = governor.probe().effective_available().filter(|available| *available < need) { + return Err(BackendError { + code: ErrorCode::ResourceExhausted, + message: format!( + "reconfigure refused: only {} MiB of host memory are available and reopening the serve stack needs {} MiB (the soft floor plus {} MiB); free memory first or restart with `leleka up`; nothing was changed", + available >> 20, + need >> 20, + RECONFIGURE_HEADROOM_BYTES >> 20 + ), + retryable: false, + }); + } + } + Ok(()) +} + +fn open_stack<'a, 'ctx>( + env: &ReopenEnv<'a, 'ctx, '_>, + options: &OriginalServeOptions, + tokens: u32, +) -> Result<(Stack<'a, 'ctx>, i32), BackendError> { + let config = stack_config(options, tokens)?; + let workers = config.cpu_workers; + let opened = OriginalServeStack::open(env.binding, env.context.as_ref(), Rc::clone(env.context), config) + .map_err(|failure| open_error(&failure))?; + Ok((opened, workers)) +} + +/// The previous settings are reopened after the new ones failed; with no stack left the process ends a moment after +/// the reply. +fn roll_back<'a, 'ctx>( + env: &ReopenEnv<'a, 'ctx, '_>, + live: &mut Live<'_, 'a, 'ctx>, + failure: &BackendError, +) -> Result<(), BackendError> { + use std::io::Write; + let _ = writeln!( + std::io::stderr().lock(), + "leleka-serve reconfigure failed: {}; reopening with the previous settings", + failure.message + ); + match open_stack(env, live.options, *live.context_tokens) { + Ok((again, w)) => { + publish_prefix_summary(&again, env.shared); + *live.stack = Some(again); + *live.workers = w; + env.shared.ready.store(true, Ordering::Release); + } + Err(_) => { + env.shared.shutdown.store(true, Ordering::Release); + return Err(exit_for_restart()); + } + } + Ok(()) +} + +/// No stack is left and none can be built here: end the process a moment after the reply goes out so that the +/// supervisor starts a fresh engine instead of keeping a half-dead one. +fn exit_for_restart() -> BackendError { + use std::io::Write; + let _ = writeln!( + std::io::stderr().lock(), + "leleka-serve: reconfigure and rollback both failed; exiting so that the supervisor restarts the engine" + ); + thread::spawn(|| { + thread::sleep(Duration::from_secs(2)); + std::process::exit(70); + }); + unavailable("reconfigure failed and the previous settings could not be restored") +} + +/// Close the old stack and open one with the new settings; on failure the previous settings come back and the reply is +/// the refusal. +fn swap_stack<'a, 'ctx>( + env: &ReopenEnv<'a, 'ctx, '_>, + live: &mut Live<'_, 'a, 'ctx>, + next: (OriginalServeOptions, u32), +) -> Result<(), BackendError> { + let (next_options, next_context) = next; + match open_stack(env, &next_options, next_context) { + Ok((opened, w)) => { + publish_prefix_summary(&opened, env.shared); + *live.stack = Some(opened); + *live.options = next_options; + *live.context_tokens = next_context; + *live.workers = w; + Ok(()) + } + Err(failure) => { + roll_back(env, live, &failure)?; + Err(BackendError { + code: ErrorCode::InvalidRequest, + message: format!("reconfigure refused: {}; the previous settings are back", failure.message), + retryable: false, + }) + } + } +} + +/// `Command::Reconfigure`: new inference settings as a JSON document; the reply is the effective settings. +pub(super) fn reconfigure<'a, 'ctx>( + env: &ReopenEnv<'a, 'ctx, '_>, + live: &mut Live<'_, 'a, 'ctx>, + text: &str, +) -> Result { + let tuning = crate::serve_tuning::Tuning::parse(text).map_err(super::super::super::invalid_dynamic)?; + let mut next_options = live.options.clone(); + let mut next_context = *live.context_tokens; + let changed = tuning.apply(&mut next_options, &mut next_context).map_err(super::super::super::invalid_dynamic)?; + if changed.is_empty() || live.stack.is_none() { + return Ok(crate::serve_tuning::describe(live.options, *live.context_tokens, *live.workers, None).to_string()); + } + use std::io::Write; + refuse_starved_host()?; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure: {changed:?}; reopening the serve stack"); + let started = env.clock.now(); + env.shared.ready.store(false, Ordering::Release); + if let Some(old) = live.stack.take() { + if old.close().is_err() { + env.shared.shutdown.store(true, Ordering::Release); + return Err(unavailable("Original serve stack cleanup failed during reconfigure")); + } + } + swap_stack(env, live, (next_options, next_context))?; + Ok(publish_effective(env, live, started)) +} + +/// The new stack serves: ready again, the telemetry carries the effective settings, which are also the reply. +fn publish_effective(env: &ReopenEnv<'_, '_, '_>, live: &Live<'_, '_, '_>, started: Instant) -> String { + use std::io::Write; + env.shared.ready.store(true, Ordering::Release); + leleka_memory::telemetry::set_context_max(u64::from(*live.context_tokens)); + let effective = crate::serve_tuning::describe(live.options, *live.context_tokens, *live.workers, None); + leleka_memory::telemetry::set_settings(effective.clone()); + let _ = writeln!( + std::io::stderr().lock(), + "leleka-serve reconfigure done in {:.1} s", + env.clock.since(started).as_secs_f64() + ); + effective.to_string() +} diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_parts.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_parts.rs index 5f96b138..3516f126 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_parts.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_parts.rs @@ -1,4 +1,5 @@ -//! Steps of the Original owner loop `run`, moved out of it by STRA-338 (size): each helper does one step of the loop in the +//! Steps of the Original owner loop `run`, moved out of it by STRA-338 (size): each helper does one step of the loop +//! in the //! order `run` did it; early exits of `run` stay in `run`. #[allow(unused_imports)] @@ -21,7 +22,8 @@ pub(super) fn open_run_stack<'a, 'ctx>( ) -> Result<(Stack<'a, 'ctx>, i32), BackendError> { let config = stack_config(options, context_tokens)?; let workers = config.cpu_workers; - // STRA-325: build id, recorded model digest and effective tuning, once, before the stack opens (operator log only; reads nothing the stack uses) + // STRA-325: build id, recorded model digest and effective tuning, once, before the stack opens (operator log only; + // reads nothing the stack uses) crate::serve_meta::emit(&crate::serve_meta::startup_lines( &crate::serve_meta::BuildInfo::current(), &crate::serve_meta::ProfileInfo::from_settings(crate::settings::process()), @@ -57,9 +59,12 @@ pub(super) fn emit_cache_line(stack: &Stack<'_, '_>) { crate::serve_meta::emit(&[crate::serve_meta::cache_line(&facts)]); } -/// The first release (right after the expert bank was copied) cannot see what the stack open reads next: the dense tensors of shard 0 and the -/// MTP pack go through the page cache (4-5 GiB measured at idle on the 5090), and the resident copies are in the engine's own memory. Give -/// those pages back too, so that no model byte is held twice (clean pages only, POSIX_FADV_DONTNEED, never drop_caches; best effort). +/// The first release (right after the expert bank was copied) cannot see what the stack open reads next: the dense +/// tensors of shard 0 and the +/// MTP pack go through the page cache (4-5 GiB measured at idle on the 5090), and the resident copies are in the +/// engine's own memory. Give +/// those pages back too, so that no model byte is held twice (clean pages only, POSIX_FADV_DONTNEED, never +/// drop_caches; best effort). #[cfg(target_os = "linux")] pub(super) fn drop_model_page_cache(options: &OriginalServeOptions, model_files: &[PathBuf]) { if options.expert_source == crate::backend::ExpertSource::Resident { @@ -102,167 +107,6 @@ pub(super) fn sweep_idle( } } -/// The run-time state of the owner loop that `Command::Reconfigure` may replace. -pub(super) struct Live<'r, 'a, 'ctx> { - pub(super) options: &'r mut OriginalServeOptions, - pub(super) context_tokens: &'r mut u32, - pub(super) workers: &'r mut i32, - pub(super) stack: &'r mut Option>, -} - -/// What a reconfigure reads: the owners the new stack is built over, the shared flags and the clock. -pub(super) struct ReopenEnv<'a, 'ctx, 'r> { - pub(super) binding: &'a ModelBinding, - pub(super) context: &'ctx Rc>, - pub(super) shared: &'r Shared, - pub(super) clock: &'r SystemClock, -} - -/// The old stack is closed before the new one opens, so the new one's pinned host memory (K/V, rings, pools) must fit in -/// what is free now. Refuse up front on a starved host instead of leaving the engine without a stack (live native run 2026-10-25). -fn refuse_starved_host() -> Result<(), BackendError> { - if let Some(governor) = leleka_memory::Governor::global() { - let need = governor.policy().soft_floor.saturating_add(RECONFIGURE_HEADROOM_BYTES); - if let Some(available) = governor.probe().effective_available().filter(|available| *available < need) { - return Err(BackendError { - code: ErrorCode::ResourceExhausted, - message: format!( - "reconfigure refused: only {} MiB of host memory are available and reopening the serve stack needs {} MiB (the soft floor plus {} MiB); free memory first or restart with `leleka up`; nothing was changed", - available >> 20, - need >> 20, - RECONFIGURE_HEADROOM_BYTES >> 20 - ), - retryable: false, - }); - } - } - Ok(()) -} - -fn open_stack<'a, 'ctx>( - env: &ReopenEnv<'a, 'ctx, '_>, - options: &OriginalServeOptions, - tokens: u32, -) -> Result<(Stack<'a, 'ctx>, i32), BackendError> { - let config = stack_config(options, tokens)?; - let workers = config.cpu_workers; - let opened = OriginalServeStack::open(env.binding, env.context.as_ref(), Rc::clone(env.context), config) - .map_err(|failure| open_error(&failure))?; - Ok((opened, workers)) -} - -/// The previous settings are reopened after the new ones failed; with no stack left the process ends a moment after the reply. -fn roll_back<'a, 'ctx>( - env: &ReopenEnv<'a, 'ctx, '_>, - live: &mut Live<'_, 'a, 'ctx>, - failure: &BackendError, -) -> Result<(), BackendError> { - use std::io::Write; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-serve reconfigure failed: {}; reopening with the previous settings", - failure.message - ); - match open_stack(env, live.options, *live.context_tokens) { - Ok((again, w)) => { - publish_prefix_summary(&again, env.shared); - *live.stack = Some(again); - *live.workers = w; - env.shared.ready.store(true, Ordering::Release); - } - Err(_) => { - env.shared.shutdown.store(true, Ordering::Release); - return Err(exit_for_restart()); - } - } - Ok(()) -} - -/// No stack is left and none can be built here: end the process a moment after the reply goes out so that the -/// supervisor starts a fresh engine instead of keeping a half-dead one. -fn exit_for_restart() -> BackendError { - use std::io::Write; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-serve: reconfigure and rollback both failed; exiting so that the supervisor restarts the engine" - ); - thread::spawn(|| { - thread::sleep(Duration::from_secs(2)); - std::process::exit(70); - }); - unavailable("reconfigure failed and the previous settings could not be restored") -} - -/// Close the old stack and open one with the new settings; on failure the previous settings come back and the reply is the refusal. -fn swap_stack<'a, 'ctx>( - env: &ReopenEnv<'a, 'ctx, '_>, - live: &mut Live<'_, 'a, 'ctx>, - next: (OriginalServeOptions, u32), -) -> Result<(), BackendError> { - let (next_options, next_context) = next; - match open_stack(env, &next_options, next_context) { - Ok((opened, w)) => { - publish_prefix_summary(&opened, env.shared); - *live.stack = Some(opened); - *live.options = next_options; - *live.context_tokens = next_context; - *live.workers = w; - Ok(()) - } - Err(failure) => { - roll_back(env, live, &failure)?; - Err(BackendError { - code: ErrorCode::InvalidRequest, - message: format!("reconfigure refused: {}; the previous settings are back", failure.message), - retryable: false, - }) - } - } -} - -/// `Command::Reconfigure`: new inference settings as a JSON document; the reply is the effective settings. -pub(super) fn reconfigure<'a, 'ctx>( - env: &ReopenEnv<'a, 'ctx, '_>, - live: &mut Live<'_, 'a, 'ctx>, - text: &str, -) -> Result { - let tuning = crate::serve_tuning::Tuning::parse(text).map_err(super::super::super::invalid_dynamic)?; - let mut next_options = live.options.clone(); - let mut next_context = *live.context_tokens; - let changed = tuning.apply(&mut next_options, &mut next_context).map_err(super::super::super::invalid_dynamic)?; - if changed.is_empty() || live.stack.is_none() { - return Ok(crate::serve_tuning::describe(live.options, *live.context_tokens, *live.workers, None).to_string()); - } - use std::io::Write; - refuse_starved_host()?; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure: {changed:?}; reopening the serve stack"); - let started = env.clock.now(); - env.shared.ready.store(false, Ordering::Release); - if let Some(old) = live.stack.take() { - if old.close().is_err() { - env.shared.shutdown.store(true, Ordering::Release); - return Err(unavailable("Original serve stack cleanup failed during reconfigure")); - } - } - swap_stack(env, live, (next_options, next_context))?; - Ok(publish_effective(env, live, started)) -} - -/// The new stack serves: ready again, the telemetry carries the effective settings, which are also the reply. -fn publish_effective(env: &ReopenEnv<'_, '_, '_>, live: &Live<'_, '_, '_>, started: Instant) -> String { - use std::io::Write; - env.shared.ready.store(true, Ordering::Release); - leleka_memory::telemetry::set_context_max(u64::from(*live.context_tokens)); - let effective = crate::serve_tuning::describe(live.options, *live.context_tokens, *live.workers, None); - leleka_memory::telemetry::set_settings(effective.clone()); - let _ = writeln!( - std::io::stderr().lock(), - "leleka-serve reconfigure done in {:.1} s", - env.clock.since(started).as_secs_f64() - ); - effective.to_string() -} - /// What a generate command reads besides the stack: the loaded model, the tokenizer and the shared flags. pub(super) struct GenerateEnv<'r> { pub(super) shared: &'r Shared, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs index 1ab6f258..fecaca61 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs @@ -85,6 +85,15 @@ pub(in crate::qwen_forward) enum OriginalPromptDraftOutcome { Cancelled, Completed(OriginalDraftKvPending), } +/// `last_next` must be a token of the 248,320-token vocabulary. +fn check_vocabulary(last_next: TokenId) -> Result<()> { + let vocab = Dimension::new(248320)?; + if last_next != TokenId::new(u64::from(last_next.get()), vocab)? { + return Err(Error::InvalidToken); + } + Ok(()) +} + impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> { /// The pending prompt, the Final phase and the lease the draft conditioning reads must be one and the same. fn check_final_sources( @@ -107,10 +116,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx { return Err(Error::IdentityMismatch); } - let vocab = Dimension::new(248320)?; - if last_next != TokenId::new(u64::from(last_next.get()), vocab)? { - return Err(Error::InvalidToken); - } + check_vocabulary(last_next)?; Ok(phase) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs index 2ca5567a..294d03b9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs @@ -48,7 +48,8 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx } } -/// The retained scalar weights come from the same owner the drafter was built with: each of the eleven roles must have the +/// The retained scalar weights come from the same owner the drafter was built with: each of the eleven roles must have +/// the /// pack's shape and be the very buffer the loans hold. fn check_retained_matrices<'ctx>( binding: &ModelBinding, @@ -79,7 +80,8 @@ fn check_retained_matrices<'ctx>( .map_err(micro_driver_error) } -/// The retained scalar weights come from the same owner the drafter was built with: the pinned pack's cache, or with an RT +/// The retained scalar weights come from the same owner the drafter was built with: the pinned pack's cache, or with +/// an RT /// directory (--mtp-rt-dir) its own bank, whose buffers are not the MoE cache's. Check against that owner. fn pack_matrix<'ctx>( mtp: &RetainedOriginalMtpWeights<'ctx>, @@ -120,6 +122,20 @@ fn check_role( } impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> { + fn sources_agree( + &self, + txn: &OriginalPromptTxn<'_, '_>, + preview: &PromptDeviceFinal, + phase: &OriginalPromptPhase, + ) -> Result { + Ok(self.sources.role == GrRole::Final + && self.sources.rows.len() == txn.len() + && phase.same(&txn.phase()) + && preview.lease_identity.same_lease(&self.device.lease_identity()) + && self.device.context_matches(self.sources.context) + && std::ptr::eq(txn.context()?, self.sources.context)) + } + /// The scalar producer also pins the lease and the prompt's known next token. fn check_scalar_sources( &self, @@ -133,22 +149,13 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx txn.validate_final(preview)?; preview.validate_conditioning(last_next)?; let phase = self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; - if self.sources.role != GrRole::Final - || self.sources.rows.len() != txn.len() - || !phase.same(&txn.phase()) - || !preview.lease_identity.same_lease(&self.device.lease_identity()) - || !self.device.context_matches(self.sources.context) - || !std::ptr::eq(txn.context()?, self.sources.context) - { + if !self.sources_agree(txn, preview, &phase)? { return Err(Error::IdentityMismatch); } if txn.known_prompt_next()?.is_some_and(|known| known != last_next) { return Err(Error::IdentityMismatch); } - let vocab = Dimension::new(248320)?; - if last_next != TokenId::new(u64::from(last_next.get()), vocab)? { - return Err(Error::InvalidToken); - } + check_vocabulary(last_next)?; Ok(phase) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/window_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/window_parts.rs index 558c7655..6bc6d7b0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/window_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/window_parts.rs @@ -1,4 +1,5 @@ -//! Steps of `NativeServeHost::run_window` for the Original host, moved out of it by STRA-338 (size): each helper does one step +//! Steps of `NativeServeHost::run_window` for the Original host, moved out of it by STRA-338 (size): each helper does +//! one step //! of the window in the order `run_window` ran it. use super::super::original_serve_pool::window_trace; @@ -34,7 +35,7 @@ pub(super) fn report_window(window_clock: Option, ple_ms: Option, let parts: Vec = window_trace::NAMES.iter().zip(sums).map(|(name, v)| format!("{name}={v:.2}")).collect(); eprintln!( - "DBG window rows={rows} total={total:.2} ple={ple_ms:.2} sampling_setup={:.2} verifier={verifier_ms:.2} gpu_wait_and_head={:.2} {}", + "DBG window rows={rows} total={total:.2} ple={ple_ms:.2} sampling_setup={:.2} \n verifier={verifier_ms:.2} gpu_wait_and_head={:.2} {}", total - ple_ms - verifier_ms, verifier_ms - sums[window_trace::POOL], parts.join(" ") diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs index 3f5515e1..deeb9bdb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs @@ -1,4 +1,5 @@ -//! Steps of `CpuExpertPool::run_direct`, moved out of it by STRA-338 (size): each helper does one step of the group in the +//! Steps of `CpuExpertPool::run_direct`, moved out of it by STRA-338 (size): each helper does one step of the group in +//! the //! order `run_direct` ran it. #[allow(unused_imports)] @@ -61,7 +62,8 @@ pub(super) fn borrow_experts<'p>(plan: &'p [ExpertJob], opened: &'p [Opened]) -> Ok(experts) } -/// Zero the entries the GPU tier owns and compute the rest of the group in place; the sink's result and the failure it saw. +/// Zero the entries the GPU tier owns and compute the rest of the group in place; the sink's result and the failure it +/// saw. pub(super) fn compute_into_sink( pool: &mut DirectCpuPool, sink: &mut OriginalVerifyCpuSink<'_, '_>, @@ -137,7 +139,8 @@ impl DirectTier { } } - /// The pool's stage timings of the group, and the prefetch policy's measurement when the group ran over a mapped source. + /// The pool's stage timings of the group, and the prefetch policy's measurement when the group ran over a mapped + /// source. pub(super) fn finish_group(&mut self, record: Option, group: (std::time::Instant, usize)) { if let Some(stages) = self.pool.take_timing() { for (name, ms) in leleka_native_cpu_expert::POOL_TIMING_NAMES.iter().copied().zip(stages) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/decode_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/decode_parts.rs index 45812b85..6a63c67e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/decode_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/decode_parts.rs @@ -1,4 +1,5 @@ -//! Phases of `OriginalServeStack::decode_phase`, moved out of it by STRA-338 (size): each helper takes the stack fields it +//! Phases of `OriginalServeStack::decode_phase`, moved out of it by STRA-338 (size): each helper takes the stack +//! fields it //! touches, so the destructured borrows of `decode_phase` stay as they were and the order of operations is unchanged. #[allow(unused_imports)] @@ -69,7 +70,8 @@ fn note_window_retry(failed: usize, next: usize) { )) } -/// Assemble the verifier over the QSA owners, repeating with the windows that fit when a graph runs out of device memory. +/// Assemble the verifier over the QSA owners, repeating with the windows that fit when a graph runs out of device +/// memory. pub(super) fn assemble_decode<'a, 'ctx>( inputs: &AssembleInputs<'_, 'a, 'ctx>, executor: &mut OriginalPromptExecutor<'ctx>, @@ -81,7 +83,8 @@ pub(super) fn assemble_decode<'a, 'ctx>( let p = profile::span("decode.assemble"); let mut refill = refill; let mut queue_refill = || refill.queue(inputs.binding, moe); - // A window or commit graph that does not fit in device memory costs the widest windows, not the request or the engine + // A window or commit graph that does not fit in device memory costs the widest windows, not the request or the + // engine // (upstream a8c1d4b7): the assembly is repeated with the windows that fit. The owners come back from each failure. let mut owners_slot = Some(owners); let assembled = assemble_with_window_fallback( @@ -121,7 +124,8 @@ impl<'a, 'ctx> AssembleInputs<'_, 'a, 'ctx> { } } -/// One assembly attempt at `max_t`; the owners come back from a failure into `owners_slot` when a narrower window may fit. +/// One assembly attempt at `max_t`; the owners come back from a failure into `owners_slot` when a narrower window may +/// fit. fn assemble_attempt<'a, 'ctx>( inputs: &AssembleInputs<'_, 'a, 'ctx>, owners_slot: &mut Option>, @@ -191,7 +195,8 @@ pub(super) fn resolve_assembled<'a, 'ctx>( Err(SpecError::Forward(lost.failure.error)) } -/// The card holds windows only up to `used_max_t`: every policy of the stack follows, for this and the later requests (the +/// The card holds windows only up to `used_max_t`: every policy of the stack follows, for this and the later requests +/// (the /// controllers restart; what they learned about the wider windows no longer applies). pub(super) fn narrow_window_policy( stack: (&mut OriginalServeSettings, &mut OriginalSpecController, &mut usize), @@ -244,7 +249,8 @@ pub(super) fn gpu_expert_pool<'p, 'a, 'ctx>( }) } -/// The end of the decode phase: release the MTP drafter's bindings to this verifier's bank, close the verifier and take the +/// The end of the decode phase: release the MTP drafter's bindings to this verifier's bank, close the verifier and +/// take the /// physical QSA owners back at the session's lineage (an abandoned window is rolled back there). #[allow(clippy::too_many_arguments)] pub(super) fn teardown_decode<'a, 'ctx>( @@ -258,7 +264,8 @@ pub(super) fn teardown_decode<'a, 'ctx>( broken: &mut Option, ) { release_mtp(executor, binding, broken); - // the card at the end of the decode phase, graph pools and all windows captured: the real low-water mark of a request + // the card at the end of the decode phase, graph pools and all windows captured: the real low-water mark of a + // request vram_note(context, "decode end before disassemble"); let p = profile::span("decode.disassemble"); let disassembled = disassemble(resources); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs index 8f6baebc..4012bba5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs @@ -1,4 +1,5 @@ -//! Phases of `OriginalServeStack::open`, moved out of it by STRA-338 (size): each helper runs one step of the startup in the +//! Phases of `OriginalServeStack::open`, moved out of it by STRA-338 (size): each helper runs one step of the startup +//! in the //! order `open` called it, with the same stage marks, notes and error context. #[allow(unused_imports)] @@ -15,7 +16,8 @@ pub(super) struct Policies { pub(super) controller: OriginalSpecController, } -/// The weights the stack owns besides the session: native head, embedding table, KAR PLE cache, dense weights, MoE arena. +/// The weights the stack owns besides the session: native head, embedding table, KAR PLE cache, dense weights, MoE +/// arena. pub(super) struct Weights<'ctx> { pub(super) output: OriginalNativeOutput<'ctx>, pub(super) embedding: OriginalPromptEmbedding<'ctx>, @@ -24,7 +26,8 @@ pub(super) struct Weights<'ctx> { pub(super) moe: MoeWeightCache<'ctx>, } -/// The refusals that precede any allocation: the config, the process-wide KV window, the context identity, the model shape. +/// The refusals that precede any allocation: the config, the process-wide KV window, the context identity, the model +/// shape. pub(super) fn check_open<'ctx>( binding: &ModelBinding, context: &'ctx Context<'ctx>, @@ -93,7 +96,8 @@ pub(super) fn serve_policies(config: &StackConfig) -> std::result::Result( binding: &ModelBinding, @@ -226,7 +230,8 @@ fn open_full_mtp_executor<'a, 'ctx>( Ok((executor, draft)) } -/// RT-directory draft: the MTP dense roles sit twice in VRAM (this cache's pinned-pack upload and the RT bank's); merge them when proven byte-equal +/// RT-directory draft: the MTP dense roles sit twice in VRAM (this cache's pinned-pack upload and the RT bank's); +/// merge them when proven byte-equal pub(super) fn share_rt_dense_roles<'ctx>( config: &StackConfig, executor: &OriginalPromptExecutor<'ctx>, @@ -247,7 +252,8 @@ pub(super) fn share_rt_dense_roles<'ctx>( Ok(()) } -/// The cross-session prefix cache of the config, sized from the memory governor's budget; `None` when it is off or has no budget. +/// The cross-session prefix cache of the config, sized from the memory governor's budget; `None` when it is off or has +/// no budget. pub(super) fn open_prefix(config: &StackConfig) -> Option> { let prefix_config = config.prefix.as_ref()?; let available = crate::conversation::memory::available_memory(); @@ -257,7 +263,8 @@ pub(super) fn open_prefix(config: &StackConfig) -> Option, bytes: u64, avail )); } -/// The VRAM expert tier and the number of its last slots the prompt path borrows (`None`: it allocates its own buffers). +/// The VRAM expert tier and the number of its last slots the prompt path borrows (`None`: it allocates its own +/// buffers). pub(super) fn open_expert_cache<'ctx>( binding: &ModelBinding, context: &'ctx Context<'ctx>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs index e9647877..3e410580 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs @@ -122,7 +122,8 @@ fn settle_served<'a, 'ctx>( settle_state_into(verifier, host, env, (live, tail)); } -/// Whether the session can be continued as is (`live`: conversation cache) and whether the prefix tail checkpoints (`tail`). +/// Whether the session can be continued as is (`live`: conversation cache) and whether the prefix tail checkpoints +/// (`tail`). fn settle_wanted( host: &OriginalServeHost<'_, '_>, result: &std::result::Result, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/assemble_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/assemble_parts.rs index c50bfa3a..c21ea25c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/assemble_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/assemble_parts.rs @@ -3,7 +3,7 @@ #[allow(unused_imports)] use super::*; -use leleka_cuda_driver::{OriginalVerifyCanonicalGdn, OriginalVerifyGeometry}; +use leleka_cuda_driver::{OriginalNativeEmbedRows, OriginalVerifyCanonicalGdn, OriginalVerifyGeometry}; type Window<'a, 'ctx> = OriginalVerifyWindowResources<'a, 'ctx>; type Qsa<'a, 'ctx> = Rc>; @@ -90,6 +90,18 @@ fn aggregate<'a, 'ctx>( let head = env.output.rows(binding, t)?; let resources = OriginalVerifyResources::new(context, journal, Rc::clone(env.qsa), head)?; let embed = env.output.embedding(binding)?.rows(t)?; + window_over(env, resources, embed, t) +} + +/// The window's resources: the embedding rows, the projections, the GR, the QSA and the MoE of the verify path. +fn window_over<'a, 'ctx>( + env: &RecordEnv<'_, 'a, 'ctx>, + resources: OriginalVerifyResources<'a, 'ctx>, + embed: OriginalNativeEmbedRows<'ctx>, + t: usize, +) -> std::result::Result, ServeFailure> { + let (binding, context, weights, geometry) = (env.binding, env.context, env.weights, &env.geometry); + let dense = weights.dense; let window = OriginalVerifyWindowResources::new(context, resources, embed, env.blobs.layout()?, t)? .with_projections(dense.original_verify_projections(binding, geometry)?)? .with_gr(dense.original_verify_gr(binding, weights.ple_scratch, env.ple_history)?)? @@ -120,7 +132,8 @@ fn build_aggregates<'a, 'ctx>( Ok((windows, commit)) } -/// Record every window graph and the commit graph. A refusal closes the verifier and names the narrower window worth retrying. +/// Record every window graph and the commit graph. A refusal closes the verifier and names the narrower window worth +/// retrying. fn record_windows<'a, 'ctx>( mut verifier: OriginalVerifier<'ctx, Window<'a, 'ctx>>, aggregates: Aggregates<'a, 'ctx>, @@ -131,21 +144,13 @@ fn record_windows<'a, 'ctx>( let (mut windows, commit) = aggregates; let _ = leleka_cuda_driver::original_capture_timing::take(); let _p = super::super::original_serve_profile::span("assemble.record_all"); - // `Verifier::set_pcie_mode`: the copy kernel stages the PCIe share inside the graph (2), or DMA (0). - let mut policy = OriginalVerifyWindowPolicy::mode17(); - policy.pcie_mode = pcie_mode; - // docs/upstream-port-plan.md row 2.5: the decode top-k as a thread-block cluster (same ids as qsa_topk_ref; sm_90+, the driver - // turns it off again on an older card). `LELEKA_QSA_CLUSTER=1` / `0`; unset: QSA_CLUSTER_DEFAULT. - policy.qsa.cluster_topk = leleka_cuda_driver::qsa_cluster_requested(QSA_CLUSTER_DEFAULT); + let policy = window_policy(pcie_mode); let recorded = verifier.record_all( policy, |t| windows.get_mut(t - 1).and_then(Option::take).ok_or(leleka_cuda_driver::Error::InvalidQwenShape), commit, ); - let (capture_ms, instantiate_ms, modules_ms) = leleka_cuda_driver::original_capture_timing::take(); - super::super::original_serve_profile::add("record.capture", capture_ms); - super::super::original_serve_profile::add("record.instantiate", instantiate_ms); - super::super::original_serve_profile::add("record.modules", modules_ms); + add_capture_timing(); if let Err(error) = recorded { // dropping the unused aggregates and closing the verifier releases every journal reference drop(windows); @@ -156,6 +161,24 @@ fn record_windows<'a, 'ctx>( Ok(verifier) } +/// `Verifier::set_pcie_mode`: the copy kernel stages the PCIe share inside the graph (2), or DMA (0). +/// docs/upstream-port-plan.md row 2.5: the decode top-k as a thread-block cluster (same ids as qsa_topk_ref; sm_90+, +/// the driver +/// turns it off again on an older card). `LELEKA_QSA_CLUSTER=1` / `0`; unset: QSA_CLUSTER_DEFAULT. +fn window_policy(pcie_mode: u8) -> OriginalVerifyWindowPolicy { + let mut policy = OriginalVerifyWindowPolicy::mode17(); + policy.pcie_mode = pcie_mode; + policy.qsa.cluster_topk = leleka_cuda_driver::qsa_cluster_requested(QSA_CLUSTER_DEFAULT); + policy +} + +fn add_capture_timing() { + let (capture_ms, instantiate_ms, modules_ms) = leleka_cuda_driver::original_capture_timing::take(); + super::super::original_serve_profile::add("record.capture", capture_ms); + super::super::original_serve_profile::add("record.instantiate", instantiate_ms); + super::super::original_serve_profile::add("record.modules", modules_ms); +} + /// A verifier over the QSA journal with every window graph and the commit graph recorded. pub(super) fn capture_verifier<'a, 'ctx>( env: &RecordEnv<'_, 'a, 'ctx>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs index eb13146f..99e886e7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs @@ -1,10 +1,12 @@ -//! Phases of `OriginalSpecController::finish_round`, moved out of it by STRA-338 (size): each helper does one step of the +//! Phases of `OriginalSpecController::finish_round`, moved out of it by STRA-338 (size): each helper does one step of +//! the //! round's end in the order `finish_round` did it. #[allow(unused_imports)] use super::*; -/// The round's final result from the draft stage, the adaptive join and the drain, in the order of precedence of the Original. +/// The round's final result from the draft stage, the adaptive join and the drain, in the order of precedence of the +/// Original. pub(super) fn combine_round( result: SpecResult>, join: Result<()>, @@ -50,7 +52,8 @@ impl RoundFacts { } } -/// The chain of this round: the request's (`mtp_t - 1` drafts down to `min_p`) or the adaptive plan, clamped to the cells +/// The chain of this round: the request's (`mtp_t - 1` drafts down to `min_p`) or the adaptive plan, clamped to the +/// cells /// that exist. Draft j writes its K/V at the cell p+a+j, and cells end at `max_context`: near the context's end the /// round drafts only the cells that exist (upstream `max_steps = min(.., max_cells - (p + a))`, mtp.cpp). /// Draft 0 always fits: the window's rows did, and a < t. Returns the chain, the floor and whether it was clamped. @@ -98,6 +101,30 @@ fn trace_fixed(round: &RoundFacts, ms: f64, drafts_after: usize) { ); } +/// The draft rows conditioned on the verified window of the round. +fn draft_batch( + engine: &mut E, + round: &CommittedRound, + r: &mut Request, + prepared: (DraftPreparation, f32, bool), +) -> SpecResult> { + let (preparation, floor, coupled) = prepared; + preparation + .after_verified( + engine, + &round.verified, + round.position, + round.accepted, + &round.outputs[..round.t], + &r.consumed, + &mut r.vetted, + floor, + coupled, + ) + .map(Some) + .map_err(Into::into) +} + impl OriginalSpecController { /// The receipt belongs to this controller's pending round. pub(super) fn round_admission(&self, round: &CommittedRound) -> Result<()> { @@ -137,24 +164,12 @@ impl OriginalSpecController { let preparation = DraftPreparation::new(self.config.max_t, chain, self.config.vocabulary); match (planned, preparation) { (Err(e), _) | (_, Err(e)) => Err(e.into()), - (Ok(()), Ok(preparation)) => preparation - .after_verified( - engine, - &round.verified, - round.position, - round.accepted, - &round.outputs[..round.t], - &r.consumed, - &mut r.vetted, - floor, - self.config.coupled, - ) - .map(Some) - .map_err(Into::into), + (Ok(()), Ok(preparation)) => draft_batch(engine, round, r, (preparation, floor, self.config.coupled)), } } - /// Commit remains real, but this failed request cannot continue with stale draft logits or an unknown completed source. + /// Commit remains real, but this failed request cannot continue with stale draft logits or an unknown completed + /// source. pub(super) fn fail_request(&mut self) { self.failed = true; if let Some(r) = self.request.as_mut() { @@ -163,7 +178,8 @@ impl OriginalSpecController { } } - /// The round succeeded: adopt the next draft, feed the window policy with the round's measured cost, check the cancel. + /// The round succeeded: adopt the next draft, feed the window policy with the round's measured cost, check the + /// cancel. pub(super) fn adopt_draft( &mut self, round: &RoundFacts, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs index 6a93dc7a..7f7cc578 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs @@ -1,4 +1,5 @@ -//! Phases of `OriginalSpecController::verify_commit`, moved out of it by STRA-338 (size): each helper does one step of the +//! Phases of `OriginalSpecController::verify_commit`, moved out of it by STRA-338 (size): each helper does one step of +//! the //! round in the order `verify_commit` did it, with the same checks, restores and log lines. #[allow(unused_imports)] @@ -128,7 +129,8 @@ fn run_window( }; match admit_outputs(engine, round, &v, vocabulary) { Err(e) => Err((e, Some(v))), - // the debug injection of upstream's STRATA_NAN_INJECT: the n-th checked window (first `times` attempts) reads as non-finite + // the debug injection of upstream's STRATA_NAN_INJECT: the n-th checked window (first `times` attempts) reads + // as non-finite Ok(()) => { if guard.injects(windows_checked, attempt) { Err((Error::NonFinite, Some(v))) @@ -163,8 +165,10 @@ impl OriginalSpecController { } /// Rows p .. p+t-1 each need a cell: past `max_context` there is none. Upstream 41cf05a0 (`e85567b6`, generate.cpp - /// `room`): near the context's end the window takes only the rows that fit (the admission checked the prompt, `max_new` - /// and 8 cells of margin, which a full window of up to 8 rows can overrun). No room at all ends the request as length + /// `room`): near the context's end the window takes only the rows that fit (the admission checked the prompt, + /// `max_new` + /// and 8 cells of margin, which a full window of up to 8 rows can overrun). No room at all ends the request as + /// length /// (`false`). pub(super) fn fit_window(&mut self, plan: &mut WindowPlan) -> SpecResult { let r = self.request.as_ref().ok_or(Error::IdentityMismatch)?; @@ -191,8 +195,10 @@ impl OriginalSpecController { Ok(true) } - /// NaN guard (upstream STRATA_NAN_GUARD, f332a855 / 894f133b): a window whose logits or stage outputs are not finite is run again from - /// this round's checkpoints instead of failing the request. Nothing of the window is committed or emitted before it passed, and the + /// NaN guard (upstream STRATA_NAN_GUARD, f332a855 / 894f133b): a window whose logits or stage outputs are not + /// finite is run again from + /// this round's checkpoints instead of failing the request. Nothing of the window is committed or emitted before + /// it passed, and the /// restore is the one `abort` does. Off: the first failure aborts, exactly as before. pub(super) fn verify_window( &mut self, @@ -231,7 +237,8 @@ impl OriginalSpecController { eprintln!("leleka-serve nan-guard: healed the window at position {p} ({t} rows) after {attempt} restart(s)"); } - /// A window failed: `None` restarts it from the round's checkpoints (the attempt counter advanced), `Some` ends the round. + /// A window failed: `None` restarts it from the round's checkpoints (the attempt counter advanced), `Some` ends + /// the round. fn window_failed( &mut self, engine: &mut E, @@ -244,22 +251,7 @@ impl OriginalSpecController { let guard = self.config.nan_guard; let what = format!("position {p}, {t} rows, attempt {} of {}: {e:?}", *attempt + 1, guard.retries); if guard.retries > *attempt && matches!(e, Error::NonFinite) && !cancel() { - // The window ran on the device and nothing was committed: restoring the checkpoints puts the lineage back, taking the - // window back lets the verifier stage the same rows again (a completed, uncommitted window refuses the next one). - let restored = (engine.restore_target(round.target), engine.restore_draft(round.draft)); - let taken_back = if restored.0.is_ok() && restored.1.is_ok() { engine.discard_window() } else { Ok(()) }; - if restored.0.is_ok() && restored.1.is_ok() && taken_back.is_ok() { - *attempt += 1; - eprintln!( - "leleka-serve nan-guard: a non-finite window ({what}); the round restarts from its checkpoint" - ); - return None; - } - self.fail_undone( - &what, - format!("{:?}, restore draft {:?}, take back {:?}", restored.0, restored.1, taken_back), - ); - return Some(e.into()); + return self.retry_window(engine, round, (e, &what), attempt); } if guard.retries > 0 && matches!(e, Error::NonFinite) { leleka_memory::telemetry::nan_guard_unhealed(&what); @@ -268,6 +260,29 @@ impl OriginalSpecController { Some(self.abort(engine, round.target, round.draft, e.into())) } + /// The window ran on the device and nothing was committed: restoring the checkpoints puts the lineage back, taking the + /// window back lets the verifier stage the same rows again (a completed, uncommitted window refuses the next one). + /// `None`: restarted; `Some`: the state is unknown and the round ends. + fn retry_window( + &mut self, + engine: &mut E, + round: &Round<'_, E>, + failed: (Error, &str), + attempt: &mut u32, + ) -> Option { + let (e, what) = failed; + let restored = (engine.restore_target(round.target), engine.restore_draft(round.draft)); + let taken_back = if restored.0.is_ok() && restored.1.is_ok() { engine.discard_window() } else { Ok(()) }; + if restored.0.is_ok() && restored.1.is_ok() && taken_back.is_ok() { + *attempt += 1; + eprintln!("leleka-serve nan-guard: a non-finite window ({what}); the round restarts from its checkpoint"); + return None; + } + let outcomes = format!("{:?}, restore draft {:?}, take back {:?}", restored.0, restored.1, taken_back); + self.fail_undone(what, outcomes); + Some(e.into()) + } + /// The checkpoint could not be restored or the window not taken back: the state is unknown, nothing to retry on. fn fail_undone(&mut self, what: &str, outcomes: String) { self.failed = true; @@ -276,7 +291,7 @@ impl OriginalSpecController { } leleka_memory::telemetry::nan_guard_unhealed(&format!("{what}; the round could not be undone")); eprintln!( - "leleka-serve nan-guard: a non-finite window ({what}) and the round could not be undone (restore target {outcomes})" + "leleka-serve nan-guard: a non-finite window ({what}) and the round could not be undone \n (restore target {outcomes})" ); }