diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs index 7bb4eb0c..ebf2320a 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs @@ -1,601 +1,627 @@ -//! The real owners behind `NativeServePort`: the serving host of the Original verified-window decode. -//! -//! One `OriginalServeHost` lives for one decode phase (one request). It borrows the target session, the -//! MTP draft session, the prompt executor (which owns the MTP actor), the penalty-history stage, the PLE -//! operator source and the routed-expert pool, and it implements every callback the serve port demands: -//! -//! * `validate_current` / `checkpoint_target` / `restore_target` over the committed-lineage ledger; -//! * `run_window`: window PLE rows, the literal penalty-history tail plus request sampling, and the -//! expert pool callback around `Verifier::run`; -//! * `publish_committed`: after the commit event, the twelve resident QSA witnesses are read from the -//! verifier's own journal and the accepted rows are published to the session (position, predecessors, -//! witnesses; the recurrent GDN/PLE state follows at `settle_state`); -//! * `draft_committed`: the literal `MtpDrafter::draft_from_verifier` over the published branch; -//! * `stage_draft_history` / `restore_draft` / `drain_draft` over the MTP actor and the draft session. -//! -//! Nothing here computes a model number or certifies one: it moves the owners' own receipts between each -//! other in the order generate.cpp does, and refuses every receipt that does not match the session. -use super::{ - contract::{Error, Result, Stage}, - dense_weight_cache::DenseWeightCache, - executor::original_prompt::OriginalPromptExecutor, - gdn::GdnPrior, - input::{InputStage, PlePrior}, - kar_ple_cache::KarPleCache, - original_mtp_verified_adapter::{OriginalCommittedMtpReceipt, OriginalLaunchedMtpDraft}, - original_serve_engine::DraftCompletion, - original_serve_ledger::{LedgerCheckpoint, ServeLedger}, - original_serve_native::NativeServeHost, - original_serve_pool::OriginalServePool, - original_serve_profile as profile, - original_serve_verifier::{driver_error, read_ple_history, ServeFailure}, - output_native::OriginalNativePenaltyHistory, - session::{ - original_prompt::draft::{OriginalDraftCheckpoint, OriginalDraftSession}, - QwenSession, TargetStepOrigin, - }, -}; -use crate::model_binding::qwen4exp_input::{BoundLayerKind, ModelBinding}; -use leleka_cuda_driver::{ - Context, DeviceBuffer, NativeHeadSelection, OriginalGpuEvent, OriginalNativeHeadGraphResources, OriginalMtpFullPolicy, - OriginalVerifier, OriginalVerifyGraphResources, OriginalVerifyQsaJournal, OriginalVerifyWindow, - OriginalVerifyWindowResult, SamplerParams, SamplerPath, -}; -use std::rc::Rc; - -/// What the request asked of the sampler: the CPU-reference parameters mapped field for field, the kernel -/// path chosen once from the environment. -#[derive(Clone, Copy, Debug)] -pub(in crate::qwen_forward) struct RequestSampling { - pub(in crate::qwen_forward) params: SamplerParams, - pub(in crate::qwen_forward) path: SamplerPath, -} -impl RequestSampling { - pub(in crate::qwen_forward) fn new(params: SamplerParams, path: SamplerPath) -> Result { - params.validate().map_err(|e| driver_error(&e))?; - Ok(Self { params, path }) - } - /// `req_sampling`: the head samples only when the request is stochastic or penalized; a greedy request - /// without history takes the plain argmax even if the flag is set, so setting it is always safe. - pub(in crate::qwen_forward) fn enabled(&self) -> bool { - !self.params.greedy || self.params.penalty_last_n > 0 - } -} - -/// The ending state of a host: what the stack needs to decide whether the physical owners need a repair -/// and whether the session can serve another request without a reset. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub(in crate::qwen_forward) struct HostOutcome { - /// The ledger saw an inconsistency (a failed publication, an unrecoverable restore). - pub(in crate::qwen_forward) failed: bool, - /// A window ran whose physical effects were never published: the QSA owners need their rollback. - pub(in crate::qwen_forward) dirty: bool, - /// The session's recurrent GDN/PLE priors lag its position (see `settle_state`). - pub(in crate::qwen_forward) state_lag: bool, - pub(in crate::qwen_forward) position: u64, -} - -pub(in crate::qwen_forward) struct OriginalServeHost<'a, 'ctx> { - binding: &'a ModelBinding, - dense: &'a DenseWeightCache<'ctx>, - context: &'ctx Context<'ctx>, - session: &'a mut QwenSession<'ctx>, - draft: &'a mut OriginalDraftSession<'ctx>, - executor: &'a mut OriginalPromptExecutor<'ctx>, - kar: Option<&'a mut KarPleCache<'ctx>>, - history: &'a mut OriginalNativePenaltyHistory<'ctx>, - pool: &'a mut dyn OriginalServePool<'ctx>, - /// A second reference to the verifier's QSA journal, only to read the committed mapped prefixes. - qsa: Rc>, - /// Model layer index of journal layer `i`. - slots: [usize; 12], - ple_history: &'a DeviceBuffer<'ctx>, - policy: &'a OriginalMtpFullPolicy, - sampling: RequestSampling, - ledger: ServeLedger, - /// The session origin the last window started from (the draft receipt names it). - window_origin: Option, - /// A draft launched behind the enqueued commit, completed after the publication (`launch_draft`). - launched: Option, -} - -/// Everything a host borrows, in one place so the stack can build it in one expression. -pub(in crate::qwen_forward) struct HostOwners<'a, 'ctx> { - pub(in crate::qwen_forward) binding: &'a ModelBinding, - pub(in crate::qwen_forward) dense: &'a DenseWeightCache<'ctx>, - pub(in crate::qwen_forward) context: &'ctx Context<'ctx>, - pub(in crate::qwen_forward) session: &'a mut QwenSession<'ctx>, - pub(in crate::qwen_forward) draft: &'a mut OriginalDraftSession<'ctx>, - pub(in crate::qwen_forward) executor: &'a mut OriginalPromptExecutor<'ctx>, - pub(in crate::qwen_forward) kar: Option<&'a mut KarPleCache<'ctx>>, - pub(in crate::qwen_forward) history: &'a mut OriginalNativePenaltyHistory<'ctx>, - pub(in crate::qwen_forward) pool: &'a mut dyn OriginalServePool<'ctx>, - pub(in crate::qwen_forward) qsa: Rc>, - pub(in crate::qwen_forward) slots: [usize; 12], - pub(in crate::qwen_forward) ple_history: &'a DeviceBuffer<'ctx>, - pub(in crate::qwen_forward) policy: &'a OriginalMtpFullPolicy, -} - -/// `LELEKA_SERVE_PUBLISH=serial`: the per-layer checkpoint publication (A/B control of the batched one). -fn serial_publish() -> bool { - static SERIAL: std::sync::OnceLock = std::sync::OnceLock::new(); - *SERIAL.get_or_init(|| std::env::var("LELEKA_SERVE_PUBLISH").is_ok_and(|v| v == "serial")) -} - -fn operator_line(what: &str, failure: &ServeFailure) { - use std::io::Write; - // Fixed driver strings and error classes only; never request data. - let _ = writeln!(std::io::stderr().lock(), "leleka-serve {what}: {}", failure.describe()); -} - -impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { - /// `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( - owners: HostOwners<'a, 'ctx>, - committed: Vec, - limit: u64, - sampling: RequestSampling, - ) -> Result { - let HostOwners { binding, dense, context, session, draft, executor, kar, history, pool, qsa, slots, ple_history, policy } = - owners; - let position = session.target_origin()?.next_position(); - if session.original_state_lag().is_some() - || committed.len() as u64 != position - || !std::ptr::eq(context, session.mtp_context()?) - || binding.kar_ple_binding().is_some() != kar.is_some() - { - return Err(Error::IdentityMismatch); - } - let ledger = ServeLedger::new(committed, limit)?; - Ok(Self { - binding, - dense, - context, - session, - draft, - executor, - kar, - history, - pool, - qsa, - slots, - ple_history, - policy, - sampling, - ledger, - window_origin: None, - launched: None, - }) - } - - fn position(&self) -> Result { - Ok(self.session.target_origin()?.next_position()) - } - - /// The session's recurrent GDN and PLE priors, brought to its position from the verifier's canonical - /// image (one device-to-host transfer per request). Not needed for a request that is followed by a - /// reset; required before the session is checkpointed or reused as a resume source. - pub(in crate::qwen_forward) fn settle_state(&mut self, verifier: &mut OriginalVerifier<'ctx, R>) -> Result<()> - where - R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, - { - let Some(from) = self.session.original_state_lag() else { return Ok(()) }; - let position = self.position()?; - let rows = usize::try_from(position.checked_sub(from).ok_or(Error::InvalidPosition)?).map_err(|_| Error::Overflow)?; - let base = self.session.original_verified_base()?; - let mut gdn: [Option; 48] = std::array::from_fn(|_| None); - let mut ordinal = 0usize; - for layer in self.binding.ordered_layers() { - if layer.kind() != BoundLayerKind::Gdn { - continue; - } - let slot = layer.index() as usize; - let prior = base.gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?; - let (values, history) = verifier - .with_committed_gdn(ordinal, |values, history| { - let mut v = Vec::new(); - v.try_reserve_exact(values.len()).map_err(|_| leleka_cuda_driver::Error::HostAllocation)?; - v.extend_from_slice(values); - let mut h = Vec::new(); - h.try_reserve_exact(history.len()).map_err(|_| leleka_cuda_driver::Error::HostAllocation)?; - h.extend_from_slice(history); - Ok((v.into_boxed_slice(), h.into_boxed_slice())) - }) - .map_err(|e| driver_error(&e))?; - gdn[slot] = Some(GdnPrior::from_original_verified(prior, rows, values, history)?); - ordinal += 1; - } - if ordinal != 36 { - return Err(Error::IdentityMismatch); - } - let ple = match base.ple.as_ref() { - Some(prior) => Some(PlePrior::from_original_verified(prior, rows, read_ple_history(self.ple_history)?)?), - None => None, - }; - self.session.publish_original_resident_state(gdn, ple) - } - - /// The tokens the session holds (the prompt without its last token, then every committed window input): - /// generate.cpp's `consumed`, what a continuing request must start with. - pub(in crate::qwen_forward) fn committed(&self) -> &[i32] { - self.ledger.committed() - } - - /// Whether the MTP draft ring stands at the session's position, so the next request could continue from - /// the session as is. False after a request that stopped on EOS/length: generate.cpp skips the draft of - /// the last window, so the ring never received that window's cells. - pub(in crate::qwen_forward) fn draft_in_step(&self) -> bool { - !self.ledger.is_failed() && !self.ledger.is_dirty() && self.draft.in_step(self.binding, self.session) - } - - /// The end of the decode phase: nothing is borrowed from the owners any more except through the - /// returned outcome. The caller drops the host (releasing its journal reference) before it closes the - /// verifier and takes the QSA owners back. - pub(in crate::qwen_forward) fn finish(self) -> HostOutcome { - let position = self.session.target_origin().map(|o| o.next_position()).unwrap_or(0); - HostOutcome { - failed: self.ledger.is_failed(), - dirty: self.ledger.is_dirty(), - state_lag: self.session.original_state_lag().is_some(), - position, - } - } -} - -impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { - /// 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. - fn apply_draft_cap(&mut self, max_drafts: usize) -> Result<()> { - let want = i32::try_from(max_drafts).map_err(|_| Error::Overflow)?; - let actor = self.executor.mtp_actor(self.binding)?; - if actor.settings().max_drafts() != want { - actor.set_max_drafts(want); - } - Ok(()) - } -} - -impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { - type TargetCheckpoint = LedgerCheckpoint; - type DraftCheckpoint = OriginalDraftCheckpoint; - type Adaptive = (); - type Seed = (); - - fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> { - self.ledger.validate_current(consumed, input, position, self.position()?) - } - fn checkpoint_target(&self) -> Result { - self.ledger.checkpoint(self.position()?) - } - fn checkpoint_draft(&self) -> Result { - self.draft.checkpoint(self.binding, self.session) - } - fn restore_target(&mut self, checkpoint: &LedgerCheckpoint) -> Result<()> { - // An unpublished window never touched the session; its physical effects are rolled back when the - // phase ends. A commit that was enqueued cannot be undone and poisons the ledger. - self.window_origin = None; - let position = self.position()?; - self.ledger.restore(checkpoint, position) - } - fn restore_draft(&mut self, checkpoint: &OriginalDraftCheckpoint) -> Result<()> { - self.draft.restore_current(self.binding, self.dense, self.session, checkpoint) - } - fn apply_pending(&mut self) -> Result<()> { - // generate.cpp `apply_pending(false)`: completed adaptive swaps become resident (no work for the - // all-CPU tier). - self.pool.apply_pending() - } - - fn run_window( - &mut self, - verifier: &mut OriginalVerifier<'ctx, R>, - position: i64, - inputs: &[i32], - consumed: &[i32], - ) -> Result - where - R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, - { - let window_clock = super::original_serve_pool::window_trace::now(); - let _ = super::original_serve_pool::window_trace::take(); - let session_position = self.position()?; - self.ledger.begin_window(position, inputs, consumed, session_position)?; - let first = usize::try_from(position).map_err(|_| Error::InvalidPosition)?; - let origin = self.session.target_origin()?; - let ple_span = profile::span("window.ple"); - let ple = if self.session.original_ple_required() { - let predecessors = self.session.original_predecessors()?; - Some(InputStage::original_window_ple(self.binding, self.kar.as_deref_mut(), self.context, predecessors, inputs)?) - } else { - None - }; - let ple_ms = window_clock.map(|c| c.elapsed().as_secs_f64() * 1e3); - let mut verifier_ms = 0.0f64; - drop(ple_span); - let mut history_span = profile::span("window.history"); - let (params, path, enabled) = (self.sampling.params, self.sampling.path, self.sampling.enabled()); - let mut pool_error: Option = None; - let mut driver_failure: Option = None; - let Self { binding, session, history, pool, ledger, .. } = &mut *self; - let committed = ledger.committed(); - let result = history.with_sampling( - binding, - &**session, - &origin, - consumed, - inputs, - params, - path, - enabled, - || if committed == consumed { Ok(()) } else { Err(Error::IdentityMismatch) }, - |sampling| { - history_span.stop(); - let _p = profile::span("window.verifier"); - let verifier_clock = super::original_serve_pool::window_trace::now(); - let ran = verifier - .run(inputs, first, ple.as_deref(), sampling, |rows, sink, copy| { - let group_clock = super::original_serve_pool::window_trace::now(); - let ran = pool.run_group(rows, sink, copy).map_err(|error| { - pool_error = Some(error); - leleka_cuda_driver::Error::InvalidDriverValue("Original serve expert pool refused a layer group") - }); - if let Some(c) = group_clock { - super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::POOL, c.elapsed().as_secs_f64() * 1e3); - } - ran - }); - if let Some(c) = verifier_clock { - verifier_ms = c.elapsed().as_secs_f64() * 1e3; - } - ran - .map_err(|error| { - let failure = ServeFailure::from(error); - let class = failure.error; - driver_failure = Some(failure); - class - }) - }, - ); - if let (Some(c), Some(ple_ms)) = (window_clock, ple_ms) { - let total = c.elapsed().as_secs_f64() * 1e3; - let sums = super::original_serve_pool::window_trace::take(); - let parts: Vec = super::original_serve_pool::window_trace::NAMES - .iter() - .zip(sums) - .map(|(name, v)| format!("{name}={v:.2}")) - .collect(); - eprintln!( - "DBG window rows={} total={total:.2} ple={ple_ms:.2} sampling_setup={:.2} verifier={verifier_ms:.2} gpu_wait_and_head={:.2} {}", - inputs.len(), - total - ple_ms - verifier_ms, - verifier_ms - sums[super::original_serve_pool::window_trace::POOL], - parts.join(" ") - ); - } - match result { - Ok(window) => { - self.window_origin = Some(origin); - Ok(window) - } - Err(error) => { - if let Some(failure) = driver_failure.as_ref() { - operator_line("window", failure); - } - // A pool refusal is the cause; the driver error it provoked is its echo. - Err(pool_error.unwrap_or(error)) - } - } - } - - fn commit_enqueued(&mut self, keep: usize) -> Result<()> { - self.ledger.commit_enqueued(keep) - } - - fn publish_committed(&mut self, verifier: &mut OriginalVerifier<'ctx, R>, position: i64, committed: &[i32]) -> Result<()> - where - R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, - { - let p = profile::span("publish.witnesses"); - let origin_after = self.session.original_origin_after(committed.len())?; - let witnesses = self.session.original_qsa_witnesses()?; - drop(p); - let mut next: [Option<_>; 48] = std::array::from_fn(|_| None); - { - let p = profile::span("publish.workspace"); - let mut workspace = self.dense.native_batch_workspace(self.binding, self.context)?.ok_or(Error::IdentityMismatch)?; - drop(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() { - None - } else { - Some(verifier.checkpoint_committed_qsa_all(&mut workspace).map_err(|e| driver_error(&e))?.map(Some)) - }; - drop(p); - for (journal_layer, &slot) in self.slots.iter().enumerate() { - let prior = witnesses[slot].as_ref().ok_or(Error::IdentityMismatch)?; - let p = profile::span("publish.index_checkpoint"); - let index = match batched.as_mut() { - Some(all) => all[journal_layer].take().ok_or(Error::IdentityMismatch)?, - None => verifier - .with_committed_qsa(journal_layer, |index| index.checkpoint(&mut workspace)) - .map_err(|e| driver_error(&e))?, - }; - drop(p); - let p = profile::span("publish.kv_prefix"); - let kv = self.qsa.committed_mapped_prefix(journal_layer).map_err(|e| driver_error(&e))?; - drop(p); - next[slot] = Some(prior.advanced(origin_after.clone(), index, kv)?); - } - } - let p = profile::span("publish.session"); - if serial_publish() { - 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 - self.session.publish_original_verified_rows_fenced(committed, self.ledger.limit(), next)?; - } - drop(p); - self.ledger.published(position, committed) - } - - fn begin_adaptation(&mut self, next_round: u64) -> Result<()> { - // generate.cpp `adapt()` when `(rounds + 1) % adapt_every == 0`, issued before the commit; its copies - // run on the tier's own stream beside the commit and the draft (no work for the all-CPU tier). - self.pool.begin_adaptation(next_round) - } - fn join_adaptation(&mut self, _work: ()) -> Result<()> { - Ok(()) - } - fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { - self.executor.set_mtp_draft_history(self.binding, consumed, next) - } - - fn draft_committed( - &mut self, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - position: i64, - accepted_row: usize, - max_drafts: usize, - min_p: f32, - _coupled: bool, - ) -> Result { - let before = self.window_origin.take().ok_or(Error::IdentityMismatch)?; - let first = u64::try_from(position).map_err(|_| Error::InvalidPosition)?; - if before.next_position() != first { - return Err(Error::IdentityMismatch); - } - // The actor drafts the chain length it is configured with: the request's cap, or the adaptive window's plan for this round. - self.apply_draft_cap(max_drafts)?; - let p = profile::span("draft.receipt"); - let receipt = OriginalCommittedMtpReceipt::for_published_window( - self.binding, - self.session, - self.context, - window, - selection, - before, - accepted_row, - )?; - drop(p); - let _p = profile::span("draft.drafter"); - let drafted = self.executor.draft_committed_mtp(self.binding, self.session, self.draft, receipt, min_p, self.policy)?; - let first_cell = i64::try_from(drafted.first_position()).map_err(|_| Error::Overflow)? - + i64::try_from(drafted.accepted_row()).map_err(|_| Error::Overflow)?; - Ok(DraftCompletion { - ids: drafted.ids().to_vec(), - probabilities: drafted.probabilities().to_vec(), - first_cell, - accepted_row: drafted.accepted_row(), - }) - } - fn launch_draft( - &mut self, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - position: i64, - accepted_row: usize, - max_drafts: usize, - min_p: f32, - after: Option<&mut OriginalGpuEvent<'ctx>>, - ) -> Result<()> { - if self.launched.is_some() { - return Err(Error::IdentityMismatch); - } - let before = self.window_origin.take().ok_or(Error::IdentityMismatch)?; - let first = u64::try_from(position).map_err(|_| Error::InvalidPosition)?; - if before.next_position() != first { - return Err(Error::IdentityMismatch); - } - // The actor drafts the chain length it is configured with: the request's cap, or the adaptive window's plan for this round. - self.apply_draft_cap(max_drafts)?; - let launched = self.executor.launch_committing_mtp( - self.binding, - self.session, - self.draft, - window, - selection, - before, - accepted_row, - min_p, - self.policy, - after, - )?; - self.launched = Some(launched); - Ok(()) - } - fn finish_draft(&mut self) -> Result { - let launched = self.launched.take().ok_or(Error::IdentityMismatch)?; - let drafted = self.executor.finish_committing_mtp(self.binding, self.session, self.draft, launched, self.policy)?; - let first_cell = i64::try_from(drafted.first_position()).map_err(|_| Error::Overflow)? - + i64::try_from(drafted.accepted_row()).map_err(|_| Error::Overflow)?; - Ok(DraftCompletion { - ids: drafted.ids().to_vec(), - probabilities: drafted.probabilities().to_vec(), - first_cell, - accepted_row: drafted.accepted_row(), - }) - } - fn drain_draft(&mut self) -> Result<()> { - self.executor.mtp_idle(self.binding) - } - fn draft_first( - &mut self, - _seed: &(), - _t: usize, - _cell: i64, - _token: i32, - _max_drafts: usize, - _min_p: f32, - _coupled: bool, - ) -> Result { - // generate.cpp calls `draft_first` only on the CLI's first window; the serve loop drafts from the - // verifier window of the first decode round. There is no seed receipt to draft from here. - Err(Error::Unsupported(Stage::Session)) - } - fn drain_first(&mut self) -> Result<()> { - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn greedy() -> SamplerParams { - crate::qwen_forward::original_serve_config::greedy_params(1) - } - - #[test] - fn a_greedy_request_without_penalties_does_not_enable_the_sampling_head() { - let sampling = RequestSampling::new(greedy(), SamplerPath::Split).unwrap(); - assert!(!sampling.enabled()); - let mut penalized = greedy(); - penalized.penalty_last_n = 64; - assert!(RequestSampling::new(penalized, SamplerPath::Split).unwrap().enabled()); - let mut stochastic = SamplerParams::default(); - stochastic.temperature = 0.7; - stochastic.greedy = false; - assert!(RequestSampling::new(stochastic, SamplerPath::OneBlock).unwrap().enabled()); - } - - #[test] - fn invalid_sampler_parameters_are_refused_before_any_window() { - let mut bad = greedy(); - bad.top_p = 1.5; - assert!(RequestSampling::new(bad, SamplerPath::Split).is_err()); - let mut nan = greedy(); - nan.temperature = f32::NAN; - assert!(RequestSampling::new(nan, SamplerPath::Split).is_err()); - } - - #[test] - fn the_host_outcome_names_the_four_things_the_stack_decides_on() { - let outcome = HostOutcome { failed: false, dirty: true, state_lag: true, position: 9 }; - assert!(outcome.dirty && outcome.state_lag && !outcome.failed); - assert_eq!(outcome.position, 9); - } -} +//! The real owners behind `NativeServePort`: the serving host of the Original verified-window decode. +//! +//! One `OriginalServeHost` lives for one decode phase (one request). It borrows the target session, the +//! MTP draft session, the prompt executor (which owns the MTP actor), the penalty-history stage, the PLE +//! operator source and the routed-expert pool, and it implements every callback the serve port demands: +//! +//! * `validate_current` / `checkpoint_target` / `restore_target` over the committed-lineage ledger; +//! * `run_window`: window PLE rows, the literal penalty-history tail plus request sampling, and the +//! expert pool callback around `Verifier::run`; +//! * `publish_committed`: after the commit event, the twelve resident QSA witnesses are read from the +//! verifier's own journal and the accepted rows are published to the session (position, predecessors, +//! witnesses; the recurrent GDN/PLE state follows at `settle_state`); +//! * `draft_committed`: the literal `MtpDrafter::draft_from_verifier` over the published branch; +//! * `stage_draft_history` / `restore_draft` / `drain_draft` over the MTP actor and the draft session. +//! +//! Nothing here computes a model number or certifies one: it moves the owners' own receipts between each +//! other in the order generate.cpp does, and refuses every receipt that does not match the session. +use super::{ + contract::{Error, Result, Stage}, + dense_weight_cache::DenseWeightCache, + executor::original_prompt::OriginalPromptExecutor, + gdn::GdnPrior, + input::{InputStage, PlePrior}, + kar_ple_cache::KarPleCache, + original_mtp_verified_adapter::{OriginalCommittedMtpReceipt, OriginalLaunchedMtpDraft}, + original_serve_engine::DraftCompletion, + original_serve_ledger::{LedgerCheckpoint, ServeLedger}, + original_serve_native::NativeServeHost, + original_serve_pool::OriginalServePool, + original_serve_profile as profile, + original_serve_verifier::{driver_error, read_ple_history, ServeFailure}, + output_native::OriginalNativePenaltyHistory, + session::{ + original_prompt::draft::{OriginalDraftCheckpoint, OriginalDraftSession}, + QwenSession, TargetStepOrigin, + }, +}; +use crate::model_binding::qwen4exp_input::{BoundLayerKind, ModelBinding}; +use leleka_cuda_driver::{ + Context, DeviceBuffer, NativeHeadSelection, OriginalGpuEvent, OriginalNativeHeadGraphResources, OriginalMtpFullPolicy, + OriginalVerifier, OriginalVerifyGraphResources, OriginalVerifyQsaJournal, OriginalVerifyWindow, + OriginalVerifyWindowResult, SamplerParams, SamplerPath, +}; +use std::rc::Rc; + +/// What the request asked of the sampler: the CPU-reference parameters mapped field for field, the kernel +/// path chosen once from the environment. +#[derive(Clone, Copy, Debug)] +pub(in crate::qwen_forward) struct RequestSampling { + pub(in crate::qwen_forward) params: SamplerParams, + pub(in crate::qwen_forward) path: SamplerPath, +} +impl RequestSampling { + pub(in crate::qwen_forward) fn new(params: SamplerParams, path: SamplerPath) -> Result { + params.validate().map_err(|e| driver_error(&e))?; + Ok(Self { params, path }) + } + /// `req_sampling`: the head samples only when the request is stochastic or penalized; a greedy request + /// without history takes the plain argmax even if the flag is set, so setting it is always safe. + pub(in crate::qwen_forward) fn enabled(&self) -> bool { + !self.params.greedy || self.params.penalty_last_n > 0 + } +} + +/// The ending state of a host: what the stack needs to decide whether the physical owners need a repair +/// and whether the session can serve another request without a reset. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(in crate::qwen_forward) struct HostOutcome { + /// The ledger saw an inconsistency (a failed publication, an unrecoverable restore). + pub(in crate::qwen_forward) failed: bool, + /// A window ran whose physical effects were never published: the QSA owners need their rollback. + pub(in crate::qwen_forward) dirty: bool, + /// The session's recurrent GDN/PLE priors lag its position (see `settle_state`). + pub(in crate::qwen_forward) state_lag: bool, + pub(in crate::qwen_forward) position: u64, +} + +pub(in crate::qwen_forward) struct OriginalServeHost<'a, 'ctx> { + binding: &'a ModelBinding, + dense: &'a DenseWeightCache<'ctx>, + context: &'ctx Context<'ctx>, + session: &'a mut QwenSession<'ctx>, + draft: &'a mut OriginalDraftSession<'ctx>, + executor: &'a mut OriginalPromptExecutor<'ctx>, + kar: Option<&'a mut KarPleCache<'ctx>>, + history: &'a mut OriginalNativePenaltyHistory<'ctx>, + pool: &'a mut dyn OriginalServePool<'ctx>, + /// A second reference to the verifier's QSA journal, only to read the committed mapped prefixes. + qsa: Rc>, + /// Model layer index of journal layer `i`. + slots: [usize; 12], + ple_history: &'a DeviceBuffer<'ctx>, + policy: &'a OriginalMtpFullPolicy, + sampling: RequestSampling, + ledger: ServeLedger, + /// The session origin the last window started from (the draft receipt names it). + window_origin: Option, + /// A draft launched behind the enqueued commit, completed after the publication (`launch_draft`). + launched: Option, + /// The round whose adaptive swaps are still to be planned and queued (`LELEKA_SERVE_ADAPT_DEFER`, default on): the host does that + /// work while the GPU runs the draft instead of before the commit and the draft are enqueued. + deferred_adaptation: Option, +} + +/// Everything a host borrows, in one place so the stack can build it in one expression. +pub(in crate::qwen_forward) struct HostOwners<'a, 'ctx> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) dense: &'a DenseWeightCache<'ctx>, + pub(in crate::qwen_forward) context: &'ctx Context<'ctx>, + pub(in crate::qwen_forward) session: &'a mut QwenSession<'ctx>, + pub(in crate::qwen_forward) draft: &'a mut OriginalDraftSession<'ctx>, + pub(in crate::qwen_forward) executor: &'a mut OriginalPromptExecutor<'ctx>, + pub(in crate::qwen_forward) kar: Option<&'a mut KarPleCache<'ctx>>, + pub(in crate::qwen_forward) history: &'a mut OriginalNativePenaltyHistory<'ctx>, + pub(in crate::qwen_forward) pool: &'a mut dyn OriginalServePool<'ctx>, + pub(in crate::qwen_forward) qsa: Rc>, + pub(in crate::qwen_forward) slots: [usize; 12], + pub(in crate::qwen_forward) ple_history: &'a DeviceBuffer<'ctx>, + pub(in crate::qwen_forward) policy: &'a OriginalMtpFullPolicy, +} + +/// `LELEKA_SERVE_PUBLISH=serial`: the per-layer checkpoint publication (A/B control of the batched one). +fn serial_publish() -> bool { + static SERIAL: std::sync::OnceLock = std::sync::OnceLock::new(); + *SERIAL.get_or_init(|| std::env::var("LELEKA_SERVE_PUBLISH").is_ok_and(|v| v == "serial")) +} + +fn operator_line(what: &str, failure: &ServeFailure) { + use std::io::Write; + // Fixed driver strings and error classes only; never request data. + let _ = writeln!(std::io::stderr().lock(), "leleka-serve {what}: {}", failure.describe()); +} + +impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { + /// `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( + owners: HostOwners<'a, 'ctx>, + committed: Vec, + limit: u64, + sampling: RequestSampling, + ) -> Result { + let HostOwners { binding, dense, context, session, draft, executor, kar, history, pool, qsa, slots, ple_history, policy } = + owners; + let position = session.target_origin()?.next_position(); + if session.original_state_lag().is_some() + || committed.len() as u64 != position + || !std::ptr::eq(context, session.mtp_context()?) + || binding.kar_ple_binding().is_some() != kar.is_some() + { + return Err(Error::IdentityMismatch); + } + let ledger = ServeLedger::new(committed, limit)?; + Ok(Self { + binding, + dense, + context, + session, + draft, + executor, + kar, + history, + pool, + qsa, + slots, + ple_history, + policy, + sampling, + ledger, + window_origin: None, + launched: None, + deferred_adaptation: None, + }) + } + + fn position(&self) -> Result { + Ok(self.session.target_origin()?.next_position()) + } + + /// The session's recurrent GDN and PLE priors, brought to its position from the verifier's canonical + /// image (one device-to-host transfer per request). Not needed for a request that is followed by a + /// reset; required before the session is checkpointed or reused as a resume source. + pub(in crate::qwen_forward) fn settle_state(&mut self, verifier: &mut OriginalVerifier<'ctx, R>) -> Result<()> + where + R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, + { + let Some(from) = self.session.original_state_lag() else { return Ok(()) }; + let position = self.position()?; + let rows = usize::try_from(position.checked_sub(from).ok_or(Error::InvalidPosition)?).map_err(|_| Error::Overflow)?; + let base = self.session.original_verified_base()?; + let mut gdn: [Option; 48] = std::array::from_fn(|_| None); + let mut ordinal = 0usize; + for layer in self.binding.ordered_layers() { + if layer.kind() != BoundLayerKind::Gdn { + continue; + } + let slot = layer.index() as usize; + let prior = base.gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?; + let (values, history) = verifier + .with_committed_gdn(ordinal, |values, history| { + let mut v = Vec::new(); + v.try_reserve_exact(values.len()).map_err(|_| leleka_cuda_driver::Error::HostAllocation)?; + v.extend_from_slice(values); + let mut h = Vec::new(); + h.try_reserve_exact(history.len()).map_err(|_| leleka_cuda_driver::Error::HostAllocation)?; + h.extend_from_slice(history); + Ok((v.into_boxed_slice(), h.into_boxed_slice())) + }) + .map_err(|e| driver_error(&e))?; + gdn[slot] = Some(GdnPrior::from_original_verified(prior, rows, values, history)?); + ordinal += 1; + } + if ordinal != 36 { + return Err(Error::IdentityMismatch); + } + let ple = match base.ple.as_ref() { + Some(prior) => Some(PlePrior::from_original_verified(prior, rows, read_ple_history(self.ple_history)?)?), + None => None, + }; + self.session.publish_original_resident_state(gdn, ple) + } + + /// The tokens the session holds (the prompt without its last token, then every committed window input): + /// generate.cpp's `consumed`, what a continuing request must start with. + pub(in crate::qwen_forward) fn committed(&self) -> &[i32] { + self.ledger.committed() + } + + /// Whether the MTP draft ring stands at the session's position, so the next request could continue from + /// the session as is. False after a request that stopped on EOS/length: generate.cpp skips the draft of + /// the last window, so the ring never received that window's cells. + pub(in crate::qwen_forward) fn draft_in_step(&self) -> bool { + !self.ledger.is_failed() && !self.ledger.is_dirty() && self.draft.in_step(self.binding, self.session) + } + + /// The end of the decode phase: nothing is borrowed from the owners any more except through the + /// returned outcome. The caller drops the host (releasing its journal reference) before it closes the + /// verifier and takes the QSA owners back. + pub(in crate::qwen_forward) fn finish(self) -> HostOutcome { + let position = self.session.target_origin().map(|o| o.next_position()).unwrap_or(0); + HostOutcome { + failed: self.ledger.is_failed(), + dirty: self.ledger.is_dirty(), + state_lag: self.session.original_state_lag().is_some(), + position, + } + } +} + +/// `LELEKA_SERVE_ADAPT_DEFER=off`: plan and queue the adaptive swaps before the commit (the earlier order; the A/B control). +fn adapt_defer() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("LELEKA_SERVE_ADAPT_DEFER").is_ok_and(|v| v == "off" || v == "0")) +} + +impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { + /// 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. + fn apply_draft_cap(&mut self, max_drafts: usize) -> Result<()> { + let want = i32::try_from(max_drafts).map_err(|_| Error::Overflow)?; + let actor = self.executor.mtp_actor(self.binding)?; + if actor.settings().max_drafts() != want { + actor.set_max_drafts(want); + } + Ok(()) + } +} + +impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { + type TargetCheckpoint = LedgerCheckpoint; + type DraftCheckpoint = OriginalDraftCheckpoint; + type Adaptive = (); + type Seed = (); + + fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> { + self.ledger.validate_current(consumed, input, position, self.position()?) + } + fn checkpoint_target(&self) -> Result { + self.ledger.checkpoint(self.position()?) + } + fn checkpoint_draft(&self) -> Result { + self.draft.checkpoint(self.binding, self.session) + } + fn restore_target(&mut self, checkpoint: &LedgerCheckpoint) -> Result<()> { + // An unpublished window never touched the session; its physical effects are rolled back when the + // phase ends. A commit that was enqueued cannot be undone and poisons the ledger. + self.window_origin = None; + let position = self.position()?; + self.ledger.restore(checkpoint, position) + } + fn restore_draft(&mut self, checkpoint: &OriginalDraftCheckpoint) -> Result<()> { + self.draft.restore_current(self.binding, self.dense, self.session, checkpoint) + } + fn apply_pending(&mut self) -> Result<()> { + // generate.cpp `apply_pending(false)`: completed adaptive swaps become resident (no work for the + // all-CPU tier). + self.pool.apply_pending() + } + + fn run_window( + &mut self, + verifier: &mut OriginalVerifier<'ctx, R>, + position: i64, + inputs: &[i32], + consumed: &[i32], + ) -> Result + where + R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, + { + let window_clock = super::original_serve_pool::window_trace::now(); + let _ = super::original_serve_pool::window_trace::take(); + let session_position = self.position()?; + self.ledger.begin_window(position, inputs, consumed, session_position)?; + let first = usize::try_from(position).map_err(|_| Error::InvalidPosition)?; + let origin = self.session.target_origin()?; + let ple_span = profile::span("window.ple"); + let ple = if self.session.original_ple_required() { + let predecessors = self.session.original_predecessors()?; + Some(InputStage::original_window_ple(self.binding, self.kar.as_deref_mut(), self.context, predecessors, inputs)?) + } else { + None + }; + let ple_ms = window_clock.map(|c| c.elapsed().as_secs_f64() * 1e3); + let mut verifier_ms = 0.0f64; + drop(ple_span); + let mut history_span = profile::span("window.history"); + let (params, path, enabled) = (self.sampling.params, self.sampling.path, self.sampling.enabled()); + let mut pool_error: Option = None; + let mut driver_failure: Option = None; + let Self { binding, session, history, pool, ledger, .. } = &mut *self; + let committed = ledger.committed(); + let result = history.with_sampling( + binding, + &**session, + &origin, + consumed, + inputs, + params, + path, + enabled, + || if committed == consumed { Ok(()) } else { Err(Error::IdentityMismatch) }, + |sampling| { + history_span.stop(); + let _p = profile::span("window.verifier"); + let verifier_clock = super::original_serve_pool::window_trace::now(); + let ran = verifier + .run(inputs, first, ple.as_deref(), sampling, |rows, sink, copy| { + let group_clock = super::original_serve_pool::window_trace::now(); + let ran = pool.run_group(rows, sink, copy).map_err(|error| { + pool_error = Some(error); + leleka_cuda_driver::Error::InvalidDriverValue("Original serve expert pool refused a layer group") + }); + if let Some(c) = group_clock { + super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::POOL, c.elapsed().as_secs_f64() * 1e3); + } + ran + }); + if let Some(c) = verifier_clock { + verifier_ms = c.elapsed().as_secs_f64() * 1e3; + } + ran + .map_err(|error| { + let failure = ServeFailure::from(error); + let class = failure.error; + driver_failure = Some(failure); + class + }) + }, + ); + if let (Some(c), Some(ple_ms)) = (window_clock, ple_ms) { + let total = c.elapsed().as_secs_f64() * 1e3; + let sums = super::original_serve_pool::window_trace::take(); + let parts: Vec = super::original_serve_pool::window_trace::NAMES + .iter() + .zip(sums) + .map(|(name, v)| format!("{name}={v:.2}")) + .collect(); + eprintln!( + "DBG window rows={} total={total:.2} ple={ple_ms:.2} sampling_setup={:.2} verifier={verifier_ms:.2} gpu_wait_and_head={:.2} {}", + inputs.len(), + total - ple_ms - verifier_ms, + verifier_ms - sums[super::original_serve_pool::window_trace::POOL], + parts.join(" ") + ); + } + match result { + Ok(window) => { + self.window_origin = Some(origin); + Ok(window) + } + Err(error) => { + if let Some(failure) = driver_failure.as_ref() { + operator_line("window", failure); + } + // A pool refusal is the cause; the driver error it provoked is its echo. + Err(pool_error.unwrap_or(error)) + } + } + } + + fn commit_enqueued(&mut self, keep: usize) -> Result<()> { + self.ledger.commit_enqueued(keep) + } + + fn publish_committed(&mut self, verifier: &mut OriginalVerifier<'ctx, R>, position: i64, committed: &[i32]) -> Result<()> + where + R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, + { + let p = profile::span("publish.witnesses"); + let origin_after = self.session.original_origin_after(committed.len())?; + let witnesses = self.session.original_qsa_witnesses()?; + drop(p); + let mut next: [Option<_>; 48] = std::array::from_fn(|_| None); + { + let p = profile::span("publish.workspace"); + let mut workspace = self.dense.native_batch_workspace(self.binding, self.context)?.ok_or(Error::IdentityMismatch)?; + drop(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() { + None + } else { + Some(verifier.checkpoint_committed_qsa_all(&mut workspace).map_err(|e| driver_error(&e))?.map(Some)) + }; + drop(p); + for (journal_layer, &slot) in self.slots.iter().enumerate() { + let prior = witnesses[slot].as_ref().ok_or(Error::IdentityMismatch)?; + let p = profile::span("publish.index_checkpoint"); + let index = match batched.as_mut() { + Some(all) => all[journal_layer].take().ok_or(Error::IdentityMismatch)?, + None => verifier + .with_committed_qsa(journal_layer, |index| index.checkpoint(&mut workspace)) + .map_err(|e| driver_error(&e))?, + }; + drop(p); + let p = profile::span("publish.kv_prefix"); + let kv = self.qsa.committed_mapped_prefix(journal_layer).map_err(|e| driver_error(&e))?; + drop(p); + next[slot] = Some(prior.advanced(origin_after.clone(), index, kv)?); + } + } + let p = profile::span("publish.session"); + if serial_publish() { + 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 + self.session.publish_original_verified_rows_fenced(committed, self.ledger.limit(), next)?; + } + drop(p); + self.ledger.published(position, committed) + } + + fn begin_adaptation(&mut self, next_round: u64) -> Result<()> { + // generate.cpp `adapt()` when `(rounds + 1) % adapt_every == 0`, issued before the commit; its copies + // run on the tier's own stream beside the commit and the draft (no work for the all-CPU tier). + // The planning and the queueing are host work (0.6 ms on an adaptation round) that sat between the window 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.deferred_adaptation.is_some() { + return Err(Error::IdentityMismatch); + } + self.deferred_adaptation = Some(next_round); + return Ok(()); + } + self.pool.begin_adaptation(next_round) + } + fn run_deferred_adaptation(&mut self) -> Result<()> { + match self.deferred_adaptation.take() { + Some(round) => self.pool.begin_adaptation(round), + None => Ok(()), + } + } + fn join_adaptation(&mut self, _work: ()) -> Result<()> { + self.run_deferred_adaptation() + } + fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { + self.executor.set_mtp_draft_history(self.binding, consumed, next) + } + + fn draft_committed( + &mut self, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + position: i64, + accepted_row: usize, + max_drafts: usize, + min_p: f32, + _coupled: bool, + ) -> Result { + let before = self.window_origin.take().ok_or(Error::IdentityMismatch)?; + let first = u64::try_from(position).map_err(|_| Error::InvalidPosition)?; + if before.next_position() != first { + return Err(Error::IdentityMismatch); + } + // The actor drafts the chain length it is configured with: the request's cap, or the adaptive window's plan for this round. + self.apply_draft_cap(max_drafts)?; + let p = profile::span("draft.receipt"); + let receipt = OriginalCommittedMtpReceipt::for_published_window( + self.binding, + self.session, + self.context, + window, + selection, + before, + accepted_row, + )?; + drop(p); + let _p = profile::span("draft.drafter"); + let drafted = self.executor.draft_committed_mtp(self.binding, self.session, self.draft, receipt, min_p, self.policy)?; + let first_cell = i64::try_from(drafted.first_position()).map_err(|_| Error::Overflow)? + + i64::try_from(drafted.accepted_row()).map_err(|_| Error::Overflow)?; + Ok(DraftCompletion { + ids: drafted.ids().to_vec(), + probabilities: drafted.probabilities().to_vec(), + first_cell, + accepted_row: drafted.accepted_row(), + }) + } + fn launch_draft( + &mut self, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + position: i64, + accepted_row: usize, + max_drafts: usize, + min_p: f32, + after: Option<&mut OriginalGpuEvent<'ctx>>, + ) -> Result<()> { + if self.launched.is_some() { + return Err(Error::IdentityMismatch); + } + let before = self.window_origin.take().ok_or(Error::IdentityMismatch)?; + let first = u64::try_from(position).map_err(|_| Error::InvalidPosition)?; + if before.next_position() != first { + return Err(Error::IdentityMismatch); + } + // The actor drafts the chain length it is configured with: the request's cap, or the adaptive window's plan for this round. + self.apply_draft_cap(max_drafts)?; + let launched = self.executor.launch_committing_mtp( + self.binding, + self.session, + self.draft, + window, + selection, + before, + accepted_row, + min_p, + self.policy, + after, + )?; + self.launched = Some(launched); + Ok(()) + } + fn finish_draft(&mut self) -> Result { + let launched = self.launched.take().ok_or(Error::IdentityMismatch)?; + let drafted = self.executor.finish_committing_mtp(self.binding, self.session, self.draft, launched, self.policy)?; + let first_cell = i64::try_from(drafted.first_position()).map_err(|_| Error::Overflow)? + + i64::try_from(drafted.accepted_row()).map_err(|_| Error::Overflow)?; + Ok(DraftCompletion { + ids: drafted.ids().to_vec(), + probabilities: drafted.probabilities().to_vec(), + first_cell, + accepted_row: drafted.accepted_row(), + }) + } + fn drain_draft(&mut self) -> Result<()> { + self.executor.mtp_idle(self.binding) + } + fn draft_first( + &mut self, + _seed: &(), + _t: usize, + _cell: i64, + _token: i32, + _max_drafts: usize, + _min_p: f32, + _coupled: bool, + ) -> Result { + // generate.cpp calls `draft_first` only on the CLI's first window; the serve loop drafts from the + // verifier window of the first decode round. There is no seed receipt to draft from here. + Err(Error::Unsupported(Stage::Session)) + } + fn drain_first(&mut self) -> Result<()> { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn greedy() -> SamplerParams { + crate::qwen_forward::original_serve_config::greedy_params(1) + } + + #[test] + fn a_greedy_request_without_penalties_does_not_enable_the_sampling_head() { + let sampling = RequestSampling::new(greedy(), SamplerPath::Split).unwrap(); + assert!(!sampling.enabled()); + let mut penalized = greedy(); + penalized.penalty_last_n = 64; + assert!(RequestSampling::new(penalized, SamplerPath::Split).unwrap().enabled()); + let mut stochastic = SamplerParams::default(); + stochastic.temperature = 0.7; + stochastic.greedy = false; + assert!(RequestSampling::new(stochastic, SamplerPath::OneBlock).unwrap().enabled()); + } + + #[test] + fn invalid_sampler_parameters_are_refused_before_any_window() { + let mut bad = greedy(); + bad.top_p = 1.5; + assert!(RequestSampling::new(bad, SamplerPath::Split).is_err()); + let mut nan = greedy(); + nan.temperature = f32::NAN; + assert!(RequestSampling::new(nan, SamplerPath::Split).is_err()); + } + + #[test] + fn the_host_outcome_names_the_four_things_the_stack_decides_on() { + let outcome = HostOutcome { failed: false, dirty: true, state_lag: true, position: 9 }; + assert!(outcome.dirty && outcome.state_lag && !outcome.failed); + assert_eq!(outcome.position, 9); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_native.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_native.rs index 6b4c8cea..98bd95b3 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_native.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_native.rs @@ -1,278 +1,283 @@ -//! Native binding of `OriginalServePort` to the genuine driver Verifier. -//! -//! The Verifier itself (`OriginalVerifier::run/commit/wait_commit/completed_window`) -//! is bound here directly: windows are only the receipts of a genuinely completed -//! `run`, the commit is the driver's asynchronous event commit, and the accepted -//! prefix is cross-checked against the driver's own staged commit tokens before the -//! session lineage is published. Everything that needs owners that do not exist as -//! typed runtime objects yet is demanded from a `NativeServeHost` implementation -//! (PLE rows, request penalty history/sampler, the CPU expert pool and PCIe plan -//! callbacks, target/draft lineage checkpoints, the MTP ring and drafter, and the -//! verified-window session publication; see `original_serve_host.rs`). Nothing here fabricates one of them. -use super::contract::{Error,Result}; -use super::original_serve_profile as profile; -use super::original_serve_engine::{DraftCompletion,OriginalServePort}; -use leleka_cuda_driver::{NativeHeadSelection,OriginalGpuEvent,OriginalNativeHeadGraphResources,OriginalVerifier, - OriginalVerifyGraphResources,OriginalVerifyWindow,OriginalVerifyWindowResult}; -use std::cell::RefCell; - -/// What the serving owner must supply for the verified-window serve path. -pub(in crate::qwen_forward) trait NativeServeHost<'ctx> { - type TargetCheckpoint; - type DraftCheckpoint; - type Adaptive; - type Seed; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>; - fn checkpoint_target(&self)->Result; - fn checkpoint_draft(&self)->Result; - fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()>; - fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()>; - fn apply_pending(&mut self)->Result<()>; - /// Stage literal per-row penalty histories (counter = cell), the PLE rows and the CPU - /// pool/PCIe callbacks, and call `verifier.run` on the authenticated window. - fn run_window+OriginalNativeHeadGraphResources<'ctx>>( - &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,inputs:&[i32],consumed:&[i32], - )->Result; - /// The driver commit for `keep` rows is about to be enqueued (called BEFORE `verifier.commit`, so - /// that an uncertain enqueue is already on the books as a commit that may have changed the verifier). - fn commit_enqueued(&mut self,keep:usize)->Result<()>; - /// Publish the accepted prefix (target position, predecessors and QSA witnesses; the recurrent - /// GDN/PLE state follows lazily) AFTER the driver commit event completed. `committed` are the - /// accepted input tokens exactly as the driver staged them. - fn publish_committed+OriginalNativeHeadGraphResources<'ctx>>( - &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,committed:&[i32], - )->Result<()>; - fn begin_adaptation(&mut self,next_round:u64)->Result; - fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>; - fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>; - /// Literal `OriginalMtpDrafter::draft_from_verifier` over the same ring/snapshot lineage. - #[allow(clippy::too_many_arguments)] - fn draft_committed(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, - accepted_row:usize,max_drafts:usize,min_p:f32,coupled:bool)->Result; - /// `draft_committed` in generate.cpp's order: launched while the commit is enqueued and NOT yet published (the - /// draft stream waits `after`, the commit event, on the device), BEFORE `publish_committed`... - #[allow(clippy::too_many_arguments)] - fn launch_draft(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, - accepted_row:usize,max_drafts:usize,min_p:f32,after:Option<&mut OriginalGpuEvent<'ctx>>)->Result<()>; - /// ...and completed AFTER it, over the published branch. - fn finish_draft(&mut self)->Result; - fn drain_draft(&mut self)->Result<()>; - #[allow(clippy::too_many_arguments)] - fn draft_first(&mut self,seed:&Self::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result; - fn drain_first(&mut self)->Result<()>; -} - -/// Receipt of one completed driver window. The head selection is single-use: the -/// draft consumes it exactly once, mirroring `draft_from_verifier`'s by-value argument. -pub(in crate::qwen_forward) struct NativeWindow { - generation:u64,position:i64,rows:usize,ids:Vec,inputs:Vec, - selection:RefCell>,keep:Option, -} -impl NativeWindow { - pub(in crate::qwen_forward) fn generation(&self)->u64 {self.generation} -} - -pub(in crate::qwen_forward) struct NativeServePort<'ctx,R,H> -where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { - verifier:OriginalVerifier<'ctx,R>,host:H,pending_publish:Option<(i64,Vec)>,failed:bool, -} -impl<'ctx,R,H> NativeServePort<'ctx,R,H> -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 verifier(&self)->&OriginalVerifier<'ctx,R> {&self.verifier} - pub(in crate::qwen_forward) fn verifier_mut(&mut self)->&mut OriginalVerifier<'ctx,R> {&mut self.verifier} - pub(in crate::qwen_forward) fn host(&self)->&H {&self.host} - pub(in crate::qwen_forward) fn into_parts(self)->(OriginalVerifier<'ctx,R>,H) {(self.verifier,self.host)} - fn live(&self)->Result<()> {if self.failed {Err(Error::IdentityMismatch)} else {Ok(())}} - /// Wait the driver commit event and publish the accepted prefix to the session. Idempotent: with - /// nothing outstanding on our side the driver event must agree. The draft needs the PUBLISHED target - /// branch, so `draft_committed` settles through here too (the engine's later settle is then a no-op). - fn settle_commit(&mut self)->Result<()> { - let Some((position,expected))=self.pending_publish.take() else { - return match self.verifier.wait_commit() {Ok(())=>Ok(()),Err(_)=>{self.failed=true;Err(Error::CudaExecution)}}; - }; - let waited={let _p=profile::span("commit.wait");self.verifier.wait_commit()}; - if waited.is_err() {self.failed=true;return Err(Error::CudaExecution);} - // The driver staged the commit tokens itself; they must be exactly the accepted prefix. - let staged=match self.verifier.accepted_tokens() {Ok(t)=>t.to_vec(),Err(_)=>{self.failed=true;return Err(Error::CudaExecution);}}; - if staged!=expected {self.failed=true;return Err(Error::IdentityMismatch);} - let _p=profile::span("commit.publish"); - let published=self.host.publish_committed(&mut self.verifier,position,&expected); - if published.is_err() {self.failed=true;}published - } -} - -/// The two bring-up window traces, read once (they sat on the per-window path). -fn trace_logprobs()->Option { - static TOPK:std::sync::OnceLock>=std::sync::OnceLock::new(); - *TOPK.get_or_init(||std::env::var("LELEKA_TRACE_LOGPROBS").ok().and_then(|v|v.parse::().ok()).filter(|k|*k>0)) -} -fn trace_residual()->Option<&'static std::ffi::OsString> { - static DIR:std::sync::OnceLock>=std::sync::OnceLock::new(); - DIR.get_or_init(||std::env::var_os("LELEKA_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: generate.cpp's order, the draft enqueued behind the commit event. -fn overlap()->bool { - static ON:std::sync::OnceLock=std::sync::OnceLock::new(); - *ON.get_or_init(||!std::env::var("LELEKA_SERVE_OVERLAP").is_ok_and(|v|v=="off"||v=="0")) -} - -impl<'ctx,R,H> OriginalServePort for NativeServePort<'ctx,R,H> -where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { - type Window=NativeWindow; - type Seed=H::Seed; - type TargetCheckpoint=H::TargetCheckpoint; - type DraftCheckpoint=H::DraftCheckpoint; - type Adaptive=H::Adaptive; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { - self.live()?;self.host.validate_current(consumed,input,position) - } - fn checkpoint_target(&self)->Result {self.live()?;self.host.checkpoint_target()} - fn checkpoint_draft(&self)->Result {self.live()?;self.host.checkpoint_draft()} - fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> { - // Whatever was in flight is dead: the window state is discarded by the driver (the - // uncommitted window never touched GDN state, and a committed one is fenced first). - self.pending_publish=None; - let restored=self.host.restore_target(checkpoint); - if restored.is_err() {self.failed=true;}restored - } - fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> { - let restored=self.host.restore_draft(checkpoint); - if restored.is_err() {self.failed=true;}restored - } - fn apply_pending(&mut self)->Result<()> {self.live()?;let _p=profile::span("round.apply_pending");self.host.apply_pending()} - fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { - self.live()?; - let first=usize::try_from(position).map_err(|_|Error::InvalidPosition)?; - let result={let _p=profile::span("round.run_window");self.host.run_window(&mut self.verifier,position,inputs,consumed)?}; - // The driver's own receipt is authoritative: it must describe exactly this window. - let t=inputs.len(); - let ok=result.rows==t&&result.first_position==first&&result.selection.ids().len()==t - &&result.selection.position()==position as u64; - if !ok {self.failed=true;return Err(Error::IdentityMismatch);} - let mut ids=result.selection.ids().to_vec(); - // Quality gate only (an installed `quality_force` sequence; nothing installs one in production): the picks - // the controller verifies drafts against and commits next are the forced text's tokens. - let forced_differ=super::quality_force::apply(position,&mut ids); - if forced_differ>0 {crate::bringup_trace!("DBG forced window position={position} picks_replaced={forced_differ}");} - // Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=): top-k head logprobs of every row of the completed window. - if let Some(k)=trace_logprobs() { - let mut line:Vec=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) { - Ok(())=>eprintln!("{}",String::from_utf8_lossy(&line).trim_end()), - Err(e)=>crate::bringup_trace!("DBG logprobs err {e:?}"), - } - } - // Bring-up diagnostic (LELEKA_TRACE_RESIDUAL=): the final residual R of every row of the completed window, - // raw little-endian f32 (rows, hc*n_embd), file `r_win_pos.f32`. - if let Some(dir)=trace_residual() { - match self.verifier.window_residual_rows() { - Ok((rows,start,values))=>{ - let bytes:Vec=values.iter().flat_map(|v|v.to_le_bytes()).collect(); - static WINDOW_SEQ:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0); - let seq=WINDOW_SEQ.fetch_add(1,std::sync::atomic::Ordering::Relaxed); - let path=std::path::Path::new(&dir).join(format!("r_win{seq:05}_pos{start}.f32")); - eprintln!("DBG residual window seq={seq} first={start} rows={rows} inputs={inputs:?} floats={} -> {}",values.len(),path.display()); - if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG residual write err {e:?}"); } - if let Ok(Some(ladder))=self.verifier.window_ladder_rows() { - let bytes:Vec=ladder.iter().flat_map(|v|v.to_le_bytes()).collect(); - let path=std::path::Path::new(&dir).join(format!("l_win{seq:05}_pos{start}.f32")); - if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG ladder write err {e:?}"); } - } - } - Err(e)=>eprintln!("DBG residual err {e:?}"), - } - } - Ok(NativeWindow{generation:result.generation,position,rows:t,ids,inputs:inputs.to_vec(), - selection:RefCell::new(Some(result.selection)),keep:None}) - } - fn validate_window(&self,window:&NativeWindow,position:i64,inputs:&[i32])->Result<()> { - self.live()?; - if window.position!=position||window.inputs!=inputs {return Err(Error::IdentityMismatch);} - // A capture-only or already-superseded window cannot pass: the driver mints - // `completed_window` only for the genuinely completed current generation. - let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch)?; - if completed.generation()!=window.generation||completed.rows()!=window.rows - ||completed.first_position()!=usize::try_from(position).map_err(|_|Error::InvalidPosition)? { - return Err(Error::IdentityMismatch); - } - if let Some(selection)=window.selection.borrow().as_ref() { - completed.validate_selection(selection).map_err(|_|Error::IdentityMismatch)?; - } - Ok(()) - } - fn window_outputs<'a>(&self,window:&'a NativeWindow)->&'a[i32] {&window.ids} - fn commit_window(&mut self,window:&mut NativeWindow,keep:usize)->Result<()> { - self.live()?; - if keep==0||keep>window.rows||window.keep.is_some()||self.pending_publish.is_some() {return Err(Error::IdentityMismatch);} - let _p=profile::span("round.commit"); - if let Err(e)=self.host.commit_enqueued(keep) {self.failed=true;return Err(e);} - if let Err(_e)=self.verifier.commit(keep,true) {self.failed=true;return Err(Error::CudaExecution);} - window.keep=Some(keep); - self.pending_publish=Some((window.position,window.inputs[..keep].to_vec()));Ok(()) - } - fn wait_commit(&mut self)->Result<()> {self.settle_commit()} - fn drain_window(&mut self,_window:NativeWindow)->Result<()> { - // The retained residuals belong to the driver bank; they stay alive until the next - // window (the bank, not this receipt, owns them), so draining releases only the receipt. - Ok(()) - } - fn discard_window(&mut self)->Result<()> { - // an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears `pending_publish`) - if self.pending_publish.is_some() {self.failed=true;return Err(Error::IdentityMismatch);} - let _p=profile::span("round.discard_window"); - if let Err(e)=self.verifier.discard_window() { - eprintln!("leleka-serve nan-guard: the verifier could not take the refused window back ({e:?})"); - self.failed=true;return Err(super::original_serve_verifier::driver_error(&e)); - } - Ok(()) - } - fn begin_adaptation(&mut self,next_round:u64)->Result {self.live()?;let _p=profile::span("round.adapt");self.host.begin_adaptation(next_round)} - fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()> {self.host.join_adaptation(work)} - fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.live()?;self.host.stage_draft_history(consumed,next)} - fn draft_committed(&mut self,window:&NativeWindow,position:i64,accepted_row:usize,outputs:&[i32], - max_drafts:usize,min_p:f32,coupled:bool)->Result { - self.live()?; - let _p=profile::span("round.draft_committed"); - // Literal order: commit enqueued first, draft depends on its event on the same stream. - 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() { - // generate.cpp: commit -> draft on one stream, the host waits only for the draft's tokens. The draft is - // enqueued behind the commit event; the session is published (commit wait, witnesses) while it runs, and - // the draft completes only over that published branch. - let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); - let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); - let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; - let launched={let _p=profile::span("draft.launch"); - self.host.launch_draft(completed,selection,position,accepted_row,max_drafts,min_p,self.verifier.pending_commit_event())}; - if let Err(e)=launched {self.failed=true;return Err(e);} - self.settle_commit()?; - let finished={let _p=profile::span("draft.finish");self.host.finish_draft()}; - if finished.is_err() {self.failed=true;} - return finished; - } - // Serialized: the MTP receipt names the PUBLISHED branch, the commit event completes and the session is - // published before the draft launches. - self.settle_commit()?; - let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); - let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); - let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; - let draft={let _p=profile::span("draft.mtp");self.host.draft_committed(completed,selection,position,accepted_row,max_drafts,min_p,coupled)}; - if draft.is_err() {self.failed=true;}draft - } - fn drain_draft(&mut self)->Result<()> { - let drained=self.host.drain_draft(); - if drained.is_err() {self.failed=true;}drained - } - fn draft_first(&mut self,seed:&H::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result { - self.live()?;self.host.draft_first(seed,t,cell,token,max_drafts,min_p,coupled) - } - fn drain_first(&mut self)->Result<()> {self.host.drain_first()} -} +//! Native binding of `OriginalServePort` to the genuine driver Verifier. +//! +//! The Verifier itself (`OriginalVerifier::run/commit/wait_commit/completed_window`) +//! is bound here directly: windows are only the receipts of a genuinely completed +//! `run`, the commit is the driver's asynchronous event commit, and the accepted +//! prefix is cross-checked against the driver's own staged commit tokens before the +//! session lineage is published. Everything that needs owners that do not exist as +//! typed runtime objects yet is demanded from a `NativeServeHost` implementation +//! (PLE rows, request penalty history/sampler, the CPU expert pool and PCIe plan +//! callbacks, target/draft lineage checkpoints, the MTP ring and drafter, and the +//! verified-window session publication; see `original_serve_host.rs`). Nothing here fabricates one of them. +use super::contract::{Error,Result}; +use super::original_serve_profile as profile; +use super::original_serve_engine::{DraftCompletion,OriginalServePort}; +use leleka_cuda_driver::{NativeHeadSelection,OriginalGpuEvent,OriginalNativeHeadGraphResources,OriginalVerifier, + OriginalVerifyGraphResources,OriginalVerifyWindow,OriginalVerifyWindowResult}; +use std::cell::RefCell; + +/// What the serving owner must supply for the verified-window serve path. +pub(in crate::qwen_forward) trait NativeServeHost<'ctx> { + type TargetCheckpoint; + type DraftCheckpoint; + type Adaptive; + type Seed; + fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>; + fn checkpoint_target(&self)->Result; + fn checkpoint_draft(&self)->Result; + fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()>; + fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()>; + fn apply_pending(&mut self)->Result<()>; + /// Stage literal per-row penalty histories (counter = cell), the PLE rows and the CPU + /// pool/PCIe callbacks, and call `verifier.run` on the authenticated window. + fn run_window+OriginalNativeHeadGraphResources<'ctx>>( + &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,inputs:&[i32],consumed:&[i32], + )->Result; + /// The driver commit for `keep` rows is about to be enqueued (called BEFORE `verifier.commit`, so + /// that an uncertain enqueue is already on the books as a commit that may have changed the verifier). + fn commit_enqueued(&mut self,keep:usize)->Result<()>; + /// Publish the accepted prefix (target position, predecessors and QSA witnesses; the recurrent + /// GDN/PLE state follows lazily) AFTER the driver commit event completed. `committed` are the + /// accepted input tokens exactly as the driver staged them. + fn publish_committed+OriginalNativeHeadGraphResources<'ctx>>( + &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,committed:&[i32], + )->Result<()>; + fn begin_adaptation(&mut self,next_round:u64)->Result; + /// Adaptive work a host deferred at `begin_adaptation`: run it now (the draft is launched, the GPU is busy). A host that does its work + /// at `begin_adaptation` has nothing to run. `join_adaptation` must run whatever is still deferred. + fn run_deferred_adaptation(&mut self)->Result<()> {Ok(())} + fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>; + fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>; + /// Literal `OriginalMtpDrafter::draft_from_verifier` over the same ring/snapshot lineage. + #[allow(clippy::too_many_arguments)] + fn draft_committed(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, + accepted_row:usize,max_drafts:usize,min_p:f32,coupled:bool)->Result; + /// `draft_committed` in generate.cpp's order: launched while the commit is enqueued and NOT yet published (the + /// draft stream waits `after`, the commit event, on the device), BEFORE `publish_committed`... + #[allow(clippy::too_many_arguments)] + fn launch_draft(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, + accepted_row:usize,max_drafts:usize,min_p:f32,after:Option<&mut OriginalGpuEvent<'ctx>>)->Result<()>; + /// ...and completed AFTER it, over the published branch. + fn finish_draft(&mut self)->Result; + fn drain_draft(&mut self)->Result<()>; + #[allow(clippy::too_many_arguments)] + fn draft_first(&mut self,seed:&Self::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result; + fn drain_first(&mut self)->Result<()>; +} + +/// Receipt of one completed driver window. The head selection is single-use: the +/// draft consumes it exactly once, mirroring `draft_from_verifier`'s by-value argument. +pub(in crate::qwen_forward) struct NativeWindow { + generation:u64,position:i64,rows:usize,ids:Vec,inputs:Vec, + selection:RefCell>,keep:Option, +} +impl NativeWindow { + pub(in crate::qwen_forward) fn generation(&self)->u64 {self.generation} +} + +pub(in crate::qwen_forward) struct NativeServePort<'ctx,R,H> +where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { + verifier:OriginalVerifier<'ctx,R>,host:H,pending_publish:Option<(i64,Vec)>,failed:bool, +} +impl<'ctx,R,H> NativeServePort<'ctx,R,H> +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 verifier(&self)->&OriginalVerifier<'ctx,R> {&self.verifier} + pub(in crate::qwen_forward) fn verifier_mut(&mut self)->&mut OriginalVerifier<'ctx,R> {&mut self.verifier} + pub(in crate::qwen_forward) fn host(&self)->&H {&self.host} + pub(in crate::qwen_forward) fn into_parts(self)->(OriginalVerifier<'ctx,R>,H) {(self.verifier,self.host)} + fn live(&self)->Result<()> {if self.failed {Err(Error::IdentityMismatch)} else {Ok(())}} + /// Wait the driver commit event and publish the accepted prefix to the session. Idempotent: with + /// nothing outstanding on our side the driver event must agree. The draft needs the PUBLISHED target + /// branch, so `draft_committed` settles through here too (the engine's later settle is then a no-op). + fn settle_commit(&mut self)->Result<()> { + let Some((position,expected))=self.pending_publish.take() else { + return match self.verifier.wait_commit() {Ok(())=>Ok(()),Err(_)=>{self.failed=true;Err(Error::CudaExecution)}}; + }; + let waited={let _p=profile::span("commit.wait");self.verifier.wait_commit()}; + if waited.is_err() {self.failed=true;return Err(Error::CudaExecution);} + // The driver staged the commit tokens itself; they must be exactly the accepted prefix. + let staged=match self.verifier.accepted_tokens() {Ok(t)=>t.to_vec(),Err(_)=>{self.failed=true;return Err(Error::CudaExecution);}}; + if staged!=expected {self.failed=true;return Err(Error::IdentityMismatch);} + let _p=profile::span("commit.publish"); + let published=self.host.publish_committed(&mut self.verifier,position,&expected); + if published.is_err() {self.failed=true;}published + } +} + +/// The two bring-up window traces, read once (they sat on the per-window path). +fn trace_logprobs()->Option { + static TOPK:std::sync::OnceLock>=std::sync::OnceLock::new(); + *TOPK.get_or_init(||std::env::var("LELEKA_TRACE_LOGPROBS").ok().and_then(|v|v.parse::().ok()).filter(|k|*k>0)) +} +fn trace_residual()->Option<&'static std::ffi::OsString> { + static DIR:std::sync::OnceLock>=std::sync::OnceLock::new(); + DIR.get_or_init(||std::env::var_os("LELEKA_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: generate.cpp's order, the draft enqueued behind the commit event. +fn overlap()->bool { + static ON:std::sync::OnceLock=std::sync::OnceLock::new(); + *ON.get_or_init(||!std::env::var("LELEKA_SERVE_OVERLAP").is_ok_and(|v|v=="off"||v=="0")) +} + +impl<'ctx,R,H> OriginalServePort for NativeServePort<'ctx,R,H> +where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { + type Window=NativeWindow; + type Seed=H::Seed; + type TargetCheckpoint=H::TargetCheckpoint; + type DraftCheckpoint=H::DraftCheckpoint; + type Adaptive=H::Adaptive; + fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { + self.live()?;self.host.validate_current(consumed,input,position) + } + fn checkpoint_target(&self)->Result {self.live()?;self.host.checkpoint_target()} + fn checkpoint_draft(&self)->Result {self.live()?;self.host.checkpoint_draft()} + fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> { + // Whatever was in flight is dead: the window state is discarded by the driver (the + // uncommitted window never touched GDN state, and a committed one is fenced first). + self.pending_publish=None; + let restored=self.host.restore_target(checkpoint); + if restored.is_err() {self.failed=true;}restored + } + fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> { + let restored=self.host.restore_draft(checkpoint); + if restored.is_err() {self.failed=true;}restored + } + fn apply_pending(&mut self)->Result<()> {self.live()?;let _p=profile::span("round.apply_pending");self.host.apply_pending()} + fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { + self.live()?; + let first=usize::try_from(position).map_err(|_|Error::InvalidPosition)?; + let result={let _p=profile::span("round.run_window");self.host.run_window(&mut self.verifier,position,inputs,consumed)?}; + // The driver's own receipt is authoritative: it must describe exactly this window. + let t=inputs.len(); + let ok=result.rows==t&&result.first_position==first&&result.selection.ids().len()==t + &&result.selection.position()==position as u64; + if !ok {self.failed=true;return Err(Error::IdentityMismatch);} + let mut ids=result.selection.ids().to_vec(); + // Quality gate only (an installed `quality_force` sequence; nothing installs one in production): the picks + // the controller verifies drafts against and commits next are the forced text's tokens. + let forced_differ=super::quality_force::apply(position,&mut ids); + if forced_differ>0 {crate::bringup_trace!("DBG forced window position={position} picks_replaced={forced_differ}");} + // Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=): top-k head logprobs of every row of the completed window. + if let Some(k)=trace_logprobs() { + let mut line:Vec=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) { + Ok(())=>eprintln!("{}",String::from_utf8_lossy(&line).trim_end()), + Err(e)=>crate::bringup_trace!("DBG logprobs err {e:?}"), + } + } + // Bring-up diagnostic (LELEKA_TRACE_RESIDUAL=): the final residual R of every row of the completed window, + // raw little-endian f32 (rows, hc*n_embd), file `r_win_pos.f32`. + if let Some(dir)=trace_residual() { + match self.verifier.window_residual_rows() { + Ok((rows,start,values))=>{ + let bytes:Vec=values.iter().flat_map(|v|v.to_le_bytes()).collect(); + static WINDOW_SEQ:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0); + let seq=WINDOW_SEQ.fetch_add(1,std::sync::atomic::Ordering::Relaxed); + let path=std::path::Path::new(&dir).join(format!("r_win{seq:05}_pos{start}.f32")); + eprintln!("DBG residual window seq={seq} first={start} rows={rows} inputs={inputs:?} floats={} -> {}",values.len(),path.display()); + if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG residual write err {e:?}"); } + if let Ok(Some(ladder))=self.verifier.window_ladder_rows() { + let bytes:Vec=ladder.iter().flat_map(|v|v.to_le_bytes()).collect(); + let path=std::path::Path::new(&dir).join(format!("l_win{seq:05}_pos{start}.f32")); + if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG ladder write err {e:?}"); } + } + } + Err(e)=>eprintln!("DBG residual err {e:?}"), + } + } + Ok(NativeWindow{generation:result.generation,position,rows:t,ids,inputs:inputs.to_vec(), + selection:RefCell::new(Some(result.selection)),keep:None}) + } + fn validate_window(&self,window:&NativeWindow,position:i64,inputs:&[i32])->Result<()> { + self.live()?; + if window.position!=position||window.inputs!=inputs {return Err(Error::IdentityMismatch);} + // A capture-only or already-superseded window cannot pass: the driver mints + // `completed_window` only for the genuinely completed current generation. + let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch)?; + if completed.generation()!=window.generation||completed.rows()!=window.rows + ||completed.first_position()!=usize::try_from(position).map_err(|_|Error::InvalidPosition)? { + return Err(Error::IdentityMismatch); + } + if let Some(selection)=window.selection.borrow().as_ref() { + completed.validate_selection(selection).map_err(|_|Error::IdentityMismatch)?; + } + Ok(()) + } + fn window_outputs<'a>(&self,window:&'a NativeWindow)->&'a[i32] {&window.ids} + fn commit_window(&mut self,window:&mut NativeWindow,keep:usize)->Result<()> { + self.live()?; + if keep==0||keep>window.rows||window.keep.is_some()||self.pending_publish.is_some() {return Err(Error::IdentityMismatch);} + let _p=profile::span("round.commit"); + if let Err(e)=self.host.commit_enqueued(keep) {self.failed=true;return Err(e);} + if let Err(_e)=self.verifier.commit(keep,true) {self.failed=true;return Err(Error::CudaExecution);} + window.keep=Some(keep); + self.pending_publish=Some((window.position,window.inputs[..keep].to_vec()));Ok(()) + } + fn wait_commit(&mut self)->Result<()> {self.settle_commit()} + fn drain_window(&mut self,_window:NativeWindow)->Result<()> { + // The retained residuals belong to the driver bank; they stay alive until the next + // window (the bank, not this receipt, owns them), so draining releases only the receipt. + Ok(()) + } + fn discard_window(&mut self)->Result<()> { + // an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears `pending_publish`) + if self.pending_publish.is_some() {self.failed=true;return Err(Error::IdentityMismatch);} + let _p=profile::span("round.discard_window"); + if let Err(e)=self.verifier.discard_window() { + eprintln!("leleka-serve nan-guard: the verifier could not take the refused window back ({e:?})"); + self.failed=true;return Err(super::original_serve_verifier::driver_error(&e)); + } + Ok(()) + } + fn begin_adaptation(&mut self,next_round:u64)->Result {self.live()?;let _p=profile::span("round.adapt");self.host.begin_adaptation(next_round)} + fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()> {self.host.join_adaptation(work)} + fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.live()?;self.host.stage_draft_history(consumed,next)} + fn draft_committed(&mut self,window:&NativeWindow,position:i64,accepted_row:usize,outputs:&[i32], + max_drafts:usize,min_p:f32,coupled:bool)->Result { + self.live()?; + let _p=profile::span("round.draft_committed"); + // Literal order: commit enqueued first, draft depends on its event on the same stream. + 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() { + // generate.cpp: commit -> draft on one stream, the host waits only for the draft's tokens. The draft is + // enqueued behind the commit event; the session is published (commit wait, witnesses) while it runs, and + // the draft completes only over that published branch. + let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); + let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); + let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; + let launched={let _p=profile::span("draft.launch"); + self.host.launch_draft(completed,selection,position,accepted_row,max_drafts,min_p,self.verifier.pending_commit_event())}; + if let Err(e)=launched {self.failed=true;return Err(e);} + // the GPU is on the draft now: the adaptive planning/queueing the host deferred runs in its shadow + if let Err(e)={let _p=profile::span("round.adapt_deferred");self.host.run_deferred_adaptation()} {self.failed=true;return Err(e);} + self.settle_commit()?; + let finished={let _p=profile::span("draft.finish");self.host.finish_draft()}; + if finished.is_err() {self.failed=true;} + return finished; + } + // Serialized: the MTP receipt names the PUBLISHED branch, the commit event completes and the session is + // published before the draft launches. + self.settle_commit()?; + let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); + let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); + let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; + let draft={let _p=profile::span("draft.mtp");self.host.draft_committed(completed,selection,position,accepted_row,max_drafts,min_p,coupled)}; + if draft.is_err() {self.failed=true;}draft + } + fn drain_draft(&mut self)->Result<()> { + let drained=self.host.drain_draft(); + if drained.is_err() {self.failed=true;}drained + } + fn draft_first(&mut self,seed:&H::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result { + self.live()?;self.host.draft_first(seed,t,cell,token,max_drafts,min_p,coupled) + } + fn drain_first(&mut self)->Result<()> {self.host.drain_first()} +}