diff --git a/crates/leleka-runtime/src/qwen_forward/input.rs b/crates/leleka-runtime/src/qwen_forward/input.rs index 3b1f6359..deb8bfd7 100644 --- a/crates/leleka-runtime/src/qwen_forward/input.rs +++ b/crates/leleka-runtime/src/qwen_forward/input.rs @@ -127,6 +127,48 @@ impl InputStage { ple_rows: rows, }) } + /// The PLE input rows of one verifier window: for each input token, the sixteen PLE rows its + /// two committed predecessors select (`hash::rows`) gathered from the model's own PLE provider + /// (the KAR archive when the model is bound to one, else the native table). Row `i`'s + /// predecessors are the last two tokens of `predecessors ++ tokens[..i]`, exactly what a + /// per-token step would see; the result is `tokens.len() * 2560` floats, row-major. + pub(in crate::qwen_forward) fn original_window_ple( + binding: &ModelBinding, + mut kar: Option<&mut kar_cache::KarPleCache<'_>>, + context: &Context<'_>, + predecessors: [i32; 2], + tokens: &[i32], + ) -> Result> { + if tokens.is_empty() || tokens.len() > 8 { + return Err(Error::InvalidDimension); + } + let mut out = Vec::new(); + out.try_reserve_exact(tokens.len() * EMBEDDING_VALUES) + .map_err(|_| Error::InputAllocation)?; + let mut before = predecessors; + for &token in tokens { + if !(0..VOCABULARY as i32).contains(&token) { + return Err(Error::InvalidToken); + } + let rows = hash::rows(token as u32, before, binding.input_constants())?; + let gathered = match (binding.kar_ple_binding(), kar.as_deref_mut()) { + (Some(provider), Some(cache)) => { + if !provider.matches(&binding.identity()) || !cache.context_matches(context) { + return Err(Error::IdentityMismatch); + } + cache.gather(provider, &rows)? + } + (None, None) => gather_ple(binding, &rows).map_err(Error::from)?, + _ => return Err(Error::IdentityMismatch), + }; + if gathered.len() != EMBEDDING_VALUES { + return Err(Error::InvalidDimension); + } + out.extend_from_slice(&gathered); + before = [before[1], token]; + } + Ok(out) + } fn prepare( binding: &ModelBinding, token: TokenId, diff --git a/crates/leleka-runtime/src/qwen_forward/mod.rs b/crates/leleka-runtime/src/qwen_forward/mod.rs index bde6ded6..1591e28a 100644 --- a/crates/leleka-runtime/src/qwen_forward/mod.rs +++ b/crates/leleka-runtime/src/qwen_forward/mod.rs @@ -86,3 +86,11 @@ mod original_mtp_full_owner; mod original_mtp_verified_adapter; #[cfg(all(target_os="linux",target_arch="x86_64"))] mod original_serve_native; + +// The routed-expert tier of the Original verifier window (all-CPU pool over the pinned mapped weights). +#[cfg(all(target_os="linux",target_arch="x86_64"))] +pub(crate) mod original_serve_pool; +#[cfg(all(target_os="linux",target_arch="x86_64"))] +pub(crate) mod original_serve_ledger; +#[cfg(all(target_os="linux",target_arch="x86_64"))] +pub(crate) mod original_serve_config; diff --git a/crates/leleka-runtime/src/qwen_forward/original_mtp_verified_adapter.rs b/crates/leleka-runtime/src/qwen_forward/original_mtp_verified_adapter.rs index 16c54d93..62848f57 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_mtp_verified_adapter.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_mtp_verified_adapter.rs @@ -84,6 +84,28 @@ impl<'ctx> OriginalVerifiedMtpReceipt<'ctx>{ } impl<'ctx> OriginalCommittedMtpReceipt<'ctx>{ + /// The receipt of a completed verifier window whose accepted prefix the session ALREADY holds. + /// The serve path publishes the session when the commit event completes (the accepted state is read + /// back from the verifier then), so the draft is requested with the pre-window origin captured at + /// `run` time and the session's current (committed) origin; nothing here advances either. Exactly the + /// same acceptance rules as `after_target_commit`, without a `TargetStepProduct` (the native verifier + /// has none): same session and branch, the window started where the session stood, and the session now + /// stands exactly `accepted_row + 1` rows later. + pub(in crate::qwen_forward) fn for_published_window(binding:&ModelBinding,session:&QwenSession<'ctx>, + context:&'ctx Context<'ctx>,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection, + before:TargetStepOrigin,accepted_row:usize)->Result{ + let committed=session.target_origin()?; + window.validate_context(context).map_err(driver_error)?; + window.validate_selection(&selection).map_err(driver_error)?; + let first=u64::try_from(window.first_position()).map_err(|_|Error::Overflow)?; + let expected=first.checked_add(accepted_row as u64).and_then(|n|n.checked_add(1)).ok_or(Error::Overflow)?; + if !std::ptr::eq(context,session.mtp_context()?)||accepted_row>=window.rows() + ||!before.same_session(&committed)||before.next_position()!=first||committed.next_position()!=expected{ + return Err(Error::IdentityMismatch); + } + before.validate_projection_branch(session)?; + Ok(Self{binding:binding.identity(),context,window,selection,before,committed,accepted_row}) + } fn validate(&self,binding:&ModelBinding,session:&QwenSession<'ctx>,context:&Context<'ctx>)->Result<()> { self.window.validate_context(context).map_err(driver_error)?; self.window.validate_selection(&self.selection).map_err(driver_error)?; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_config.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_config.rs new file mode 100644 index 00000000..7210d01b --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_config.rs @@ -0,0 +1,386 @@ +//! Mode17 values of the Original serve path, derived once from the model binding and the process serving +//! context. Everything here is configuration, never a certificate: each value names the line of the +//! Original it mirrors, so a hardware run can diff them against the CLI it is compared with. +use super::contract::{Error, Result}; +use crate::model_binding::qwen4exp_input::{ModelBinding, MoeMatrixRole}; +use leleka_cuda_driver::{ + DraftKvPolicy, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpScalarPolicy, OriginalVerifyExpertLayout, + OriginalVerifyGeometry, OriginalVerifyRope, PrefillKvStage, PrefillLayoutOptions, SamplerParams, SamplerPath, +}; + +/// `n_rot` of the QSA layers (`QsaShapes::n_rot`). +const N_ROT: f32 = 64.0; +/// `kVerifyMaxT`. +pub(in crate::qwen_forward) const VERIFY_MAX_T: usize = 8; +const VOCABULARY: usize = 248_320; + +/// Per-layer routed-expert byte sizes (one expert's gate, up and down matrices), the quantities the +/// Original sizes its expert blobs, staging ring and grouped MMQ buffers from +/// (`expert_layout().blob_bytes(l)`, `mmq::matrix_bytes(gt, 1280, N)`, `matrix_bytes(dt, N, 640)`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(in crate::qwen_forward) struct ExpertBlobSizes { + blob: [usize; 48], + gate_up_max: usize, + down_max: usize, + max_blob: usize, +} +impl ExpertBlobSizes { + pub(in crate::qwen_forward) fn from_layer_bytes(gate: [usize; 48], up: [usize; 48], down: [usize; 48]) -> Result { + let mut blob = [0usize; 48]; + let (mut gate_up_max, mut down_max) = (0usize, 0usize); + for layer in 0..48 { + let gate_up = gate[layer].checked_add(up[layer]).ok_or(Error::Overflow)?; + let total = gate_up.checked_add(down[layer]).ok_or(Error::Overflow)?; + if gate[layer] == 0 || up[layer] == 0 || down[layer] == 0 { + return Err(Error::InvalidDimension); + } + // the verifier stages whole 16-byte blobs + blob[layer] = total.checked_add(15).ok_or(Error::Overflow)? & !15; + gate_up_max = gate_up_max.max(gate_up); + down_max = down_max.max(down[layer]); + } + let max_blob = *blob.iter().max().ok_or(Error::InvalidDimension)?; + Ok(Self { blob, gate_up_max, down_max, max_blob }) + } + /// From the binding's own expert descriptors (expert 0 of each layer; every expert of a layer has the + /// same shape and type). + pub(in crate::qwen_forward) fn from_binding(binding: &ModelBinding) -> Result { + if binding.layer_count() != 48 { + return Err(Error::InvalidDimension); + } + let mut sizes = [[0usize; 48]; 3]; + for layer in 0..48u32 { + for (slot, role) in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down].into_iter().enumerate() { + let d = binding.moe_preload_descriptor(layer, 0, role).map_err(|_| Error::IdentityMismatch)?; + if d.layer != layer || d.expert != Some(0) { + return Err(Error::IdentityMismatch); + } + sizes[slot][layer as usize] = d.bytes; + } + } + Self::from_layer_bytes(sizes[0], sizes[1], sizes[2]) + } + pub(in crate::qwen_forward) fn blob_bytes(&self, layer: usize) -> Option { + self.blob.get(layer).copied() + } + pub(in crate::qwen_forward) fn max_blob(&self) -> usize { + self.max_blob + } + pub(in crate::qwen_forward) fn gate_up_max(&self) -> usize { + self.gate_up_max + } + pub(in crate::qwen_forward) fn down_max(&self) -> usize { + self.down_max + } + pub(in crate::qwen_forward) fn layout(&self) -> Result { + OriginalVerifyExpertLayout::new(self.blob, self.max_blob).map_err(|_| Error::InvalidDimension) + } +} + +/// The RoPE constants of the draft K/V append and the verifier's QSA indexer append: the analytic form +/// the Original uses unless `STRATA_ROPE_TABLE=1` registers a table (not supported here, so the table +/// pointers stay absent). `theta_scale = powf(freq_base, -2 / n_rot)` in f32 as in `native_qsa_indexer.cu`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::qwen_forward) struct RopeConstants { + pub(in crate::qwen_forward) theta_scale: f32, + pub(in crate::qwen_forward) freq_scale: f32, + pub(in crate::qwen_forward) corr_low: f32, + pub(in crate::qwen_forward) corr_high: f32, + pub(in crate::qwen_forward) ext_factor: f32, + /// `RopeKernelArgs::attn_factor` (the Original passes it as `mscale`/`magnitude`). + pub(in crate::qwen_forward) magnitude: f32, +} +impl RopeConstants { + /// From the process-wide serving context (`configure_serving_context`, fixed before any CUDA user). + pub(in crate::qwen_forward) fn from_serving_context() -> Self { + let serving = leleka_cuda_driver::serving_context(); + Self::from_parts(serving.rope.freq_base, serving.rope_args) + } + pub(in crate::qwen_forward) fn from_parts(freq_base: f64, args: leleka_context::rope_scaling::RopeKernelArgs) -> Self { + Self { + theta_scale: (freq_base as f32).powf(-2.0f32 / N_ROT), + freq_scale: args.freq_scale, + corr_low: args.corr_low, + corr_high: args.corr_high, + ext_factor: args.ext_factor, + magnitude: args.attn_factor, + } + } + pub(in crate::qwen_forward) fn verify_rope<'a, 'ctx>(&self) -> OriginalVerifyRope<'a, 'ctx> { + OriginalVerifyRope { + theta_scale: self.theta_scale, + freq_scale: self.freq_scale, + corr_low: self.corr_low, + corr_high: self.corr_high, + ext_factor: self.ext_factor, + magnitude: self.magnitude, + positions: None, + angles: None, + } + } + /// The draft K/V policy: INT8, no hybrid/Q4/rotation/table/multimodal positions (the closed profile + /// the retained owners refuse to leave), with these RoPE constants. + pub(in crate::qwen_forward) fn draft_kv(&self) -> DraftKvPolicy { + let mut kv = DraftKvPolicy::original_int8(self.theta_scale); + kv.freq_scale = self.freq_scale; + kv.corr_low = self.corr_low; + kv.corr_high = self.corr_high; + kv.ext_factor = self.ext_factor; + kv.mscale = self.magnitude; + kv + } +} + +/// The `--native` preset of generate.cpp (native router, combine, shared scalar, final GR) with the +/// default (plain) GR variant and FP16 final GR; INT8 draft K/V. +pub(in crate::qwen_forward) fn mtp_full_policy(rope: &RopeConstants) -> OriginalMtpFullPolicy { + OriginalMtpFullPolicy { + native_router: true, + legacy_router_mode: 0, + native_shared_scalar: true, + native_combine: true, + old_grouped_s2: false, + native_final_gr: true, + fp32_final_gr: false, + gr: OriginalMtpGrVariant::Plain, + kv: rope.draft_kv(), + coupled_j: None, + } +} +pub(in crate::qwen_forward) fn mtp_scalar_policy(rope: &RopeConstants) -> OriginalMtpScalarPolicy { + OriginalMtpScalarPolicy { + gr: OriginalMtpGrVariant::Plain, + // `STRATA_MTP_PREFILL_SYNC` unset + per_group_sync: false, + kv: rope.draft_kv(), + } +} + +/// `sampled_path()` of sampler.cu, read once: `STRATA_OLD_SAMPLER` selects the old kernel, +/// `STRATA_SAMPLER_ONE_BLOCK` the one-block kernel, otherwise the split top-k. A flag is set when it is +/// non-empty and not "0". `lookup` is injected so the choice is testable. +pub(in crate::qwen_forward) fn sampler_path(lookup: impl Fn(&str) -> Option) -> SamplerPath { + let flag = |name: &str| lookup(name).is_some_and(|v| !v.is_empty() && v != "0"); + if flag("STRATA_OLD_SAMPLER") { + SamplerPath::Old + } else if flag("STRATA_SAMPLER_ONE_BLOCK") { + SamplerPath::OneBlock + } else { + SamplerPath::Split + } +} +pub(in crate::qwen_forward) fn sampler_path_from_environment() -> SamplerPath { + sampler_path(|name| std::env::var(name).ok()) +} + +/// The CPU reference `SamplerParams` of a request as the driver sampler takes them (field for field; +/// the driver record keeps private padding, so it starts from its default). +pub(in crate::qwen_forward) fn driver_sampler_params(p: &leleka_sampler_ref::chain::SamplerParams) -> SamplerParams { + let mut out = SamplerParams::default(); + out.top_k = p.top_k; + out.top_p = p.top_p; + out.min_p = p.min_p; + out.temperature = p.temperature; + out.min_keep = p.min_keep; + out.penalty_last_n = p.penalty_last_n; + out.penalty_repeat = p.penalty_repeat; + out.penalty_freq = p.penalty_freq; + out.penalty_present = p.penalty_present; + out.seed = p.seed; + out.counter = p.counter; + out.greedy = p.greedy; + out +} +/// A greedy request: the Original's `req_sp` for `temperature <= 0` (`greedy = true`, seed 0 -> clock). +pub(in crate::qwen_forward) fn greedy_params(seed: u64) -> SamplerParams { + let mut out = SamplerParams::default(); + out.greedy = true; + out.temperature = 0.0; + out.seed = seed; + out +} + +/// Verifier bank geometry (`Verifier::init`): the model-fixed shape constants of `OriginalVerifyLayout`, +/// the window width, the serving cell count and the staging blob bound of the expert layout. +pub(in crate::qwen_forward) fn verify_geometry(max_t: usize, max_cells: usize, blobs: &ExpertBlobSizes) -> Result { + let geometry = OriginalVerifyGeometry { + max_t, + n: 2560, + hc: 4, + lr: 320, + ff: 640, + experts: 512, + k: 10, + channels: 10240, + value_heads: 48, + key_heads: 16, + heads: 24, + kv_heads: 2, + head_dim: 256, + index_heads: 4, + index_dim: 128, + index_block: 4, + selection: 2051, + max_cells, + vocabulary: VOCABULARY, + max_expert_blob: blobs.max_blob(), + }; + geometry.validate().map_err(|_| Error::InvalidDimension)?; + Ok(geometry) +} + +/// Prefill arena carve (`Prefill::init`): `pinned_share` 1.0 (the mapped bank is the pinned source), +/// streaming from `STRATA_PREFILL_STREAM_MIN` 1024, the literal high-only BF16 policy (no `bf16x2`), +/// fused GR (no separate `xn`), MMQ on without the dequantized fallback, and the INT8 KV staging pool of +/// the mapped positional K/V (`take_stage`: every cell of both kv heads). +pub(in crate::qwen_forward) fn prefill_layout_options( + capacity: usize, + max_cells: usize, + blobs: &ExpertBlobSizes, +) -> PrefillLayoutOptions { + PrefillLayoutOptions { + capacity, + n_expert: 512, + qsa_heads: 24, + qsa_selection: 2051, + // `max_cells / idx_block + 2` + qsa_max_blocks: max_cells / 4 + 2, + mmq_any: true, + mmq_fallback: false, + mmq_gu_max: blobs.gate_up_max(), + mmq_down_max: blobs.down_max(), + max_expert_blob: blobs.max_blob(), + pinned_share: 1.0, + stream_all_min: 1024, + ring_override: None, + gr_unfused: false, + bf16x2: false, + bf16x2_hc: false, + kv_stage: PrefillKvStage::Int8 { rows: max_cells * 2, head_dim: 256, without_key: false }, + kv_stage_own: false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use leleka_context::rope_scaling::RopeKernelArgs; + + fn blobs() -> ExpertBlobSizes { + ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]).unwrap() + } + + #[test] + fn blob_sizes_are_whole_sixteen_byte_units_and_track_the_maxima() { + let sizes = blobs(); + assert_eq!(sizes.blob_bytes(0), Some(2_300_000)); + assert_eq!(sizes.blob_bytes(47), Some((700_000 + 4096 * 47 + 700_000 + 900_000 + 15) & !15)); + assert_eq!(sizes.blob_bytes(48), None); + assert_eq!(sizes.max_blob(), sizes.blob_bytes(47).unwrap()); + assert_eq!(sizes.gate_up_max(), 700_000 + 4096 * 47 + 700_000); + assert_eq!(sizes.down_max(), 900_000); + assert!((0..48).all(|l| sizes.blob_bytes(l).unwrap() % 16 == 0)); + assert!(sizes.layout().is_ok()); + let mut zero = [1usize; 48]; + zero[3] = 0; + assert_eq!(ExpertBlobSizes::from_layer_bytes(zero, [1; 48], [1; 48]).err(), Some(Error::InvalidDimension)); + assert_eq!(ExpertBlobSizes::from_layer_bytes([usize::MAX; 48], [1; 48], [1; 48]).err(), Some(Error::Overflow)); + } + + #[test] + fn theta_scale_is_powf_of_the_frequency_base_over_the_rotation_width() { + let identity = RopeConstants::from_parts(1e7, RopeKernelArgs::default()); + assert_eq!(identity.theta_scale, 1e7f32.powf(-2.0 / 64.0)); + assert_eq!((identity.freq_scale, identity.corr_low, identity.corr_high), (1.0, 0.0, 0.0)); + assert_eq!((identity.ext_factor, identity.magnitude), (0.0, 1.0)); + let scaled = RopeConstants::from_parts( + 1e7, + RopeKernelArgs { freq_scale: 0.5, corr_low: 3.0, corr_high: 40.0, ext_factor: 1.0, attn_factor: 1.07 }, + ); + let kv = scaled.draft_kv(); + assert_eq!(kv.theta_scale, scaled.theta_scale); + assert_eq!((kv.freq_scale, kv.corr_low, kv.corr_high, kv.ext_factor, kv.mscale), (0.5, 3.0, 40.0, 1.0, 1.07)); + assert!(!kv.disabled && !kv.hybrid && !kv.q4 && !kv.rotated && !kv.alternate_f16); + assert!(!kv.rope_table_enabled && !kv.multimodal_positions && kv.mode == 0); + let rope = scaled.verify_rope(); + assert_eq!((rope.theta_scale, rope.magnitude), (scaled.theta_scale, 1.07)); + assert!(rope.positions.is_none() && rope.angles.is_none()); + } + + #[test] + fn mtp_policies_stay_inside_the_closed_profile_and_share_one_kv_policy() { + let rope = RopeConstants::from_parts(1e7, RopeKernelArgs::default()); + let full = mtp_full_policy(&rope); + let scalar = mtp_scalar_policy(&rope); + assert!(full.native_router && full.native_combine && full.native_shared_scalar && full.native_final_gr); + assert!(!full.old_grouped_s2 && !full.fp32_final_gr && full.coupled_j.is_none() && full.legacy_router_mode == 0); + assert!(full.gr == OriginalMtpGrVariant::Plain && scalar.gr == OriginalMtpGrVariant::Plain); + assert!(!scalar.per_group_sync); + assert_eq!(full.kv.theta_scale, scalar.kv.theta_scale); + } + + #[test] + fn sampler_path_follows_the_two_environment_flags_with_old_taking_precedence() { + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| (*v).to_owned()) + }; + assert_eq!(sampler_path(env(&[])), SamplerPath::Split); + assert_eq!(sampler_path(env(&[("STRATA_SAMPLER_ONE_BLOCK", "1")])), SamplerPath::OneBlock); + assert_eq!(sampler_path(env(&[("STRATA_OLD_SAMPLER", "1"), ("STRATA_SAMPLER_ONE_BLOCK", "1")])), SamplerPath::Old); + assert_eq!(sampler_path(env(&[("STRATA_OLD_SAMPLER", "0")])), SamplerPath::Split); + assert_eq!(sampler_path(env(&[("STRATA_OLD_SAMPLER", "")])), SamplerPath::Split); + } + + #[test] + fn request_params_map_field_for_field() { + let reference = leleka_sampler_ref::chain::SamplerParams { + top_k: 33, + top_p: 0.8, + min_p: 0.05, + temperature: 0.7, + min_keep: 2, + penalty_last_n: 64, + penalty_repeat: 1.1, + penalty_freq: 0.2, + penalty_present: -0.3, + seed: 99, + counter: 7, + greedy: false, + }; + let driver = driver_sampler_params(&reference); + assert_eq!((driver.top_k, driver.top_p, driver.min_p, driver.temperature), (33, 0.8, 0.05, 0.7)); + assert_eq!((driver.min_keep, driver.penalty_last_n, driver.penalty_repeat), (2, 64, 1.1)); + assert_eq!((driver.penalty_freq, driver.penalty_present, driver.seed, driver.counter), (0.2, -0.3, 99, 7)); + assert!(!driver.greedy); + assert!(driver.validate().is_ok()); + let greedy = greedy_params(5); + assert!(greedy.greedy && greedy.temperature == 0.0 && greedy.seed == 5); + assert!(greedy.validate().is_ok()); + } + + #[test] + fn geometry_and_prefill_carve_close_for_the_selected_capacities_and_contexts() { + for max_t in [2usize, 6, 8] { + for cells in [262_144usize, 524_288] { + let g = verify_geometry(max_t, cells, &blobs()).unwrap(); + assert_eq!((g.max_t, g.max_cells, g.vocabulary), (max_t, cells, 248_320)); + assert!(g.max_expert_blob >= 2_000_000); + } + } + assert!(verify_geometry(1, 262_144, &blobs()).is_err(), "Verifier::init refuses a one-row window"); + assert!(verify_geometry(9, 262_144, &blobs()).is_err()); + for capacity in [256usize, 1024, 8192] { + let options = prefill_layout_options(capacity, 262_144, &blobs()); + let layout = options.carve().expect("carve"); + assert_eq!(layout.capacity, capacity); + // the four INT8 staging runs the resident QSA transport requires, byte for byte + let runs = leleka_cuda_driver::serving_context().geometry.stage_runs().unwrap(); + let want = [("kv_k_q", runs[0]), ("kv_v_q", runs[1]), ("kv_k_scale", runs[2]), ("kv_v_scale", runs[3])]; + for (name, bytes) in want { + let span = layout.span(leleka_cuda_driver::PrefillPhase::Common, name).expect(name); + assert_eq!(span.bytes, bytes, "{name}"); + } + assert!(layout.separately_owned_bytes == 0); + } + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_ledger.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_ledger.rs new file mode 100644 index 00000000..2d809001 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_ledger.rs @@ -0,0 +1,298 @@ +//! The host's own bookkeeping of one request's committed lineage, free of every device owner. +//! +//! The serve controller reasons about `consumed` (the tokens the session holds), the current input and +//! the position. The session, the verifier and the draft ring are the authorities, but the host also +//! keeps the committed token sequence: it is the penalty-history tail of the next window, the +//! coupled-draft history, and the evidence that the controller and the session agree. This ledger is that +//! sequence plus the window state machine (`Idle -> Open -> Idle`) that decides when a restore must repair +//! a physical owner. It mints nothing and certifies no numerics. +use super::contract::{Error, Result}; + +const VOCABULARY: i32 = 248_320; + +/// What the controller may ask a host to undo after `checkpoint`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(in crate::qwen_forward) struct LedgerCheckpoint { + pub(in crate::qwen_forward) committed_len: usize, + pub(in crate::qwen_forward) position: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Window { + Idle, + /// `run` started at `position` with `rows` inputs; nothing is published yet. + Open { position: u64, rows: usize }, + /// `commit` was enqueued for `keep` rows; the session is published when the event completes. + Committing { position: u64, rows: usize, keep: usize }, +} + +pub(in crate::qwen_forward) struct ServeLedger { + committed: Vec, + limit: u64, + window: Window, + /// A window ran and its physical effects (provisional QSA appends, an armed journal) were never + /// published; the owners must be rolled back to the session's lineage before they are reused. + dirty: bool, + failed: bool, +} + +impl ServeLedger { + /// `limit` is the last position a state may end at (the context bound). + pub(in crate::qwen_forward) fn new(committed: Vec, limit: u64) -> Result { + if committed.iter().any(|&t| !(0..VOCABULARY).contains(&t)) { + return Err(Error::InvalidToken); + } + if committed.len() as u64 > limit { + return Err(Error::InvalidPosition); + } + Ok(Self { committed, limit, window: Window::Idle, dirty: false, failed: false }) + } + pub(in crate::qwen_forward) fn committed(&self) -> &[i32] { + &self.committed + } + pub(in crate::qwen_forward) fn limit(&self) -> u64 { + self.limit + } + pub(in crate::qwen_forward) fn is_dirty(&self) -> bool { + self.dirty + } + pub(in crate::qwen_forward) fn is_failed(&self) -> bool { + self.failed + } + pub(in crate::qwen_forward) fn poison(&mut self) { + self.failed = true; + } + fn live(&self) -> Result<()> { + if self.failed { + Err(Error::IdentityMismatch) + } else { + Ok(()) + } + } + + /// The controller's view must be the session's: `consumed` is exactly the committed sequence, the + /// position is its length and the session's next position. + pub(in crate::qwen_forward) fn validate_current( + &self, + consumed: &[i32], + input: i32, + position: i64, + session_position: u64, + ) -> Result<()> { + self.live()?; + if !(0..VOCABULARY).contains(&input) { + return Err(Error::InvalidToken); + } + let position = u64::try_from(position).map_err(|_| Error::InvalidPosition)?; + if position != session_position + || consumed.len() as u64 != position + || self.committed.as_slice() != consumed + || !matches!(self.window, Window::Idle) + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + + pub(in crate::qwen_forward) fn checkpoint(&self, session_position: u64) -> Result { + self.live()?; + if !matches!(self.window, Window::Idle) || self.committed.len() as u64 != session_position { + return Err(Error::IdentityMismatch); + } + Ok(LedgerCheckpoint { committed_len: self.committed.len(), position: session_position }) + } + + /// A verification window is about to run. The penalty tail is `consumed`; the window starts at the + /// session's position and ends inside the context. + pub(in crate::qwen_forward) fn begin_window( + &mut self, + position: i64, + inputs: &[i32], + consumed: &[i32], + session_position: u64, + ) -> Result<()> { + self.validate_current(consumed, *inputs.first().ok_or(Error::InvalidDimension)?, position, session_position)?; + if inputs.len() > 8 { + return Err(Error::InvalidDimension); + } + if inputs.iter().any(|&t| !(0..VOCABULARY).contains(&t)) { + return Err(Error::InvalidToken); + } + let end = session_position.checked_add(inputs.len() as u64).ok_or(Error::Overflow)?; + if end > self.limit { + return Err(Error::InvalidPosition); + } + self.window = Window::Open { position: session_position, rows: inputs.len() }; + // From the first launch on, the journal and the provisional appends are live. + self.dirty = true; + Ok(()) + } + + /// `commit(keep)` was enqueued for the open window. + pub(in crate::qwen_forward) fn commit_enqueued(&mut self, keep: usize) -> Result<()> { + self.live()?; + match self.window { + Window::Open { position, rows } if (1..=rows).contains(&keep) => { + self.window = Window::Committing { position, rows, keep }; + Ok(()) + } + _ => Err(Error::IdentityMismatch), + } + } + + /// The commit event completed and the session published `accepted` (the committed INPUT tokens). + /// Only the exact prefix the enqueue named may be appended. + pub(in crate::qwen_forward) fn published(&mut self, position: i64, accepted: &[i32]) -> Result<()> { + self.live()?; + match self.window { + Window::Committing { position: at, keep, .. } + if u64::try_from(position).ok() == Some(at) && accepted.len() == keep => + { + if accepted.iter().any(|&t| !(0..VOCABULARY).contains(&t)) { + return Err(Error::InvalidToken); + } + if self.committed.len() as u64 != at { + return Err(Error::IdentityMismatch); + } + self.committed.try_reserve(accepted.len()).map_err(|_| Error::InputAllocation)?; + self.committed.extend_from_slice(accepted); + self.window = Window::Idle; + self.dirty = false; + Ok(()) + } + _ => Err(Error::IdentityMismatch), + } + } + + /// The controller asked to undo back to `checkpoint`. Possible only while the session never advanced + /// past it (a window that did not publish); the owners are then repaired by the host at the end of + /// the decode. A publication in between cannot be undone and poisons the ledger. + pub(in crate::qwen_forward) fn restore(&mut self, checkpoint: &LedgerCheckpoint, session_position: u64) -> Result<()> { + if session_position != checkpoint.position + || self.committed.len() != checkpoint.committed_len + || matches!(self.window, Window::Committing { .. }) + { + // An enqueued commit may already have changed the verifier's canonical state. + self.failed = true; + return Err(Error::IdentityMismatch); + } + self.window = Window::Idle; + // `dirty` is left as is: an opened window still needs its physical rollback. + Ok(()) + } + + /// After the decode phase ended and the owners were rolled back to the session's lineage. + pub(in crate::qwen_forward) fn repaired(&mut self) { + self.window = Window::Idle; + self.dirty = false; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ledger(prompt: &[i32]) -> ServeLedger { + ServeLedger::new(prompt.to_vec(), 100).unwrap() + } + + #[test] + fn committed_prefix_is_validated_against_the_controller_view() { + let l = ledger(&[5, 6, 7]); + assert!(l.validate_current(&[5, 6, 7], 8, 3, 3).is_ok()); + assert_eq!(l.validate_current(&[5, 6], 8, 3, 3), Err(Error::IdentityMismatch)); + assert_eq!(l.validate_current(&[5, 6, 9], 8, 3, 3), Err(Error::IdentityMismatch)); + assert_eq!(l.validate_current(&[5, 6, 7], 8, 4, 4), Err(Error::IdentityMismatch)); + assert_eq!(l.validate_current(&[5, 6, 7], 8, 3, 2), Err(Error::IdentityMismatch)); + assert_eq!(l.validate_current(&[5, 6, 7], 8, -1, 3), Err(Error::InvalidPosition)); + assert_eq!(l.validate_current(&[5, 6, 7], 248_320, 3, 3), Err(Error::InvalidToken)); + assert_eq!(ServeLedger::new(vec![-1], 10).err(), Some(Error::InvalidToken)); + assert_eq!(ServeLedger::new(vec![1; 11], 10).err(), Some(Error::InvalidPosition)); + } + + #[test] + fn a_published_window_appends_exactly_the_accepted_inputs_and_cleans_the_ledger() { + let mut l = ledger(&[1, 2]); + l.begin_window(2, &[3, 4, 5], &[1, 2], 2).unwrap(); + assert!(l.is_dirty()); + l.commit_enqueued(2).unwrap(); + l.published(2, &[3, 4]).unwrap(); + assert_eq!(l.committed(), &[1, 2, 3, 4]); + assert!(!l.is_dirty()); + // the next window continues at the new position + assert!(l.validate_current(&[1, 2, 3, 4], 9, 4, 4).is_ok()); + assert_eq!(l.checkpoint(4), Ok(LedgerCheckpoint { committed_len: 4, position: 4 })); + } + + #[test] + fn window_state_machine_refuses_out_of_order_calls() { + let mut l = ledger(&[1, 2]); + assert_eq!(l.commit_enqueued(1), Err(Error::IdentityMismatch)); + assert_eq!(l.published(2, &[3]), Err(Error::IdentityMismatch)); + l.begin_window(2, &[3, 4], &[1, 2], 2).unwrap(); + // a second window while one is open + assert_eq!(l.begin_window(2, &[3, 4], &[1, 2], 2), Err(Error::IdentityMismatch)); + assert_eq!(l.commit_enqueued(0), Err(Error::IdentityMismatch)); + assert_eq!(l.commit_enqueued(3), Err(Error::IdentityMismatch)); + l.commit_enqueued(1).unwrap(); + // the published prefix must be the one that was enqueued, at the enqueued position + assert_eq!(l.published(2, &[3, 4]), Err(Error::IdentityMismatch)); + assert_eq!(l.published(3, &[3]), Err(Error::IdentityMismatch)); + l.published(2, &[3]).unwrap(); + assert_eq!(l.committed(), &[1, 2, 3]); + } + + #[test] + fn window_must_stay_inside_the_context() { + let mut l = ServeLedger::new(vec![1, 2], 4).unwrap(); + assert_eq!(l.begin_window(2, &[3, 4, 5], &[1, 2], 2), Err(Error::InvalidPosition)); + assert!(!l.is_dirty()); + assert_eq!(l.begin_window(2, &[3; 9], &[1, 2], 2), Err(Error::InvalidDimension)); + assert_eq!(l.begin_window(2, &[3, 248_320], &[1, 2], 2), Err(Error::InvalidToken)); + assert_eq!(l.begin_window(2, &[], &[1, 2], 2), Err(Error::InvalidDimension)); + l.begin_window(2, &[3, 4], &[1, 2], 2).unwrap(); + } + + #[test] + fn restore_before_publication_keeps_the_prefix_and_marks_the_owners_for_repair() { + let mut l = ledger(&[1, 2]); + let cp = l.checkpoint(2).unwrap(); + l.begin_window(2, &[3, 4], &[1, 2], 2).unwrap(); + l.restore(&cp, 2).unwrap(); + assert_eq!(l.committed(), &[1, 2]); + assert!(l.is_dirty(), "the window's provisional effects still need the physical rollback"); + assert!(!l.is_failed()); + l.repaired(); + assert!(!l.is_dirty()); + l.begin_window(2, &[3], &[1, 2], 2).unwrap(); + } + + #[test] + fn restore_after_an_enqueued_or_published_commit_poisons_the_ledger() { + let mut l = ledger(&[1, 2]); + let cp = l.checkpoint(2).unwrap(); + l.begin_window(2, &[3, 4], &[1, 2], 2).unwrap(); + l.commit_enqueued(2).unwrap(); + assert_eq!(l.restore(&cp, 2), Err(Error::IdentityMismatch)); + assert!(l.is_failed()); + assert_eq!(l.validate_current(&[1, 2], 3, 2, 2), Err(Error::IdentityMismatch)); + // published, then a stale restore + let mut l = ledger(&[1, 2]); + let cp = l.checkpoint(2).unwrap(); + l.begin_window(2, &[3, 4], &[1, 2], 2).unwrap(); + l.commit_enqueued(2).unwrap(); + l.published(2, &[3, 4]).unwrap(); + assert_eq!(l.restore(&cp, 4), Err(Error::IdentityMismatch)); + assert!(l.is_failed()); + } + + #[test] + fn checkpoint_requires_an_idle_ledger_that_matches_the_session() { + let mut l = ledger(&[1, 2]); + assert_eq!(l.checkpoint(3), Err(Error::IdentityMismatch)); + l.begin_window(2, &[3], &[1, 2], 2).unwrap(); + assert_eq!(l.checkpoint(2), Err(Error::IdentityMismatch)); + l.poison(); + assert_eq!(l.checkpoint(2), Err(Error::IdentityMismatch)); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs new file mode 100644 index 00000000..1552b39d --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs @@ -0,0 +1,289 @@ +//! The routed-expert pool of the Original verifier window. +//! +//! Per layer group the native verifier hands the pool the group's normed activations and the router's +//! top-10 expert ids and weights (`OriginalVerifyCpuRows`) and expects the unweighted expert outputs back +//! in the mapped destination (`OriginalVerifyCpuSink`, `rows * 10 * 2560` floats, slot `(row, j)` at +//! `(row * 10 + j) * 2560`); the window's combine applies the route weights on the device. +//! +//! `OriginalServePool` is the seam. `CpuExpertPool` is the real owner for the all-CPU tier: every routed +//! expert of the group runs on the native CPU expert kernels over the pinned model's own mapped weights +//! (the exact `PreparedJob`s the CPU-miss tier of the Rust-native decoder uses). With no GPU expert +//! residency this is the literal result of an EMPTY pool plan: the driver publishes the empty plan itself, +//! so no expert is a GPU hit or a PCIe copy and the copy-from-mapped kernel takes every slot from here. +//! A GPU slot cache with a non-empty plan is a different pool implementation behind the same trait. +use super::{ + contract::{Error, Result}, + cpu_expert_miss::{runtime_error, CpuMissWorkspace}, + input::binding_error, +}; +use crate::model_binding::qwen4exp_input::{ModelBinding, MoeMatrixRole}; +use leleka_cuda_driver::{OriginalGpuStream, OriginalVerifyCpuRows, OriginalVerifyCpuSink}; + +const HIDDEN: usize = 2560; +const TOP_K: usize = 10; +const EXPERTS: i32 = 512; +/// Distinct experts prepared, run and scattered per native batch (`MAX_JOBS` is 96; the Original admits +/// at most 16 jobs / 48 MiB of owned bytes per batch, this keeps a margin below that). +const JOBS_PER_BATCH: usize = 12; +const BATCH_ALLOWANCE: usize = 48 << 20; + +/// The expert tier of a window group. +pub(in crate::qwen_forward) trait OriginalServePool<'ctx> { + /// Complete every routed `(row, slot)` of this group into `sink` before returning; an error leaves + /// the window to be released by the verifier (it never publishes a half-written group). + fn run_group( + &mut self, + rows: OriginalVerifyCpuRows<'_>, + sink: &mut OriginalVerifyCpuSink<'_, 'ctx>, + copy: &mut OriginalGpuStream<'ctx>, + ) -> Result<()>; +} + +/// One expert's work in a group: every `(row, slot)` that selected it, rows ascending. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(in crate::qwen_forward) struct ExpertJob { + pub(in crate::qwen_forward) expert: i32, + pub(in crate::qwen_forward) pairs: Vec<(usize, usize)>, +} + +/// Group the router's ids by expert. Experts are visited in first-use order (row-major), pairs keep +/// ascending `(row, slot)`; a pair is never listed twice and every pair is listed once. +pub(in crate::qwen_forward) fn plan_experts(ids: &[i32], rows: usize) -> Result> { + if rows == 0 || rows > 8 || ids.len() != rows * TOP_K { + return Err(Error::InvalidDimension); + } + let mut jobs: Vec = Vec::new(); + jobs.try_reserve_exact(ids.len()).map_err(|_| Error::InputAllocation)?; + let mut index = [usize::MAX; EXPERTS as usize]; + for row in 0..rows { + let mut seen = [false; EXPERTS as usize]; + for slot in 0..TOP_K { + let expert = ids[row * TOP_K + slot]; + if !(0..EXPERTS).contains(&expert) { + return Err(Error::InvalidExpert); + } + // top-k ids of one row are distinct; a repeat is a corrupt plan, never silently merged + if std::mem::replace(&mut seen[expert as usize], true) { + return Err(Error::InvalidExpert); + } + let at = &mut index[expert as usize]; + if *at == usize::MAX { + *at = jobs.len(); + jobs.push(ExpertJob { expert, pairs: Vec::new() }); + } + jobs[*at].pairs.push((row, slot)); + } + } + Ok(jobs) +} + +/// Offset of slot `(row, slot)` in the group's output, in floats. +pub(in crate::qwen_forward) const fn output_offset(row: usize, slot: usize) -> usize { + (row * TOP_K + slot) * HIDDEN +} + +/// Scatter one expert's output rows (one per pair, pair order) into the group output. +pub(in crate::qwen_forward) fn scatter(out: &mut [f32], job: &ExpertJob, values: &[f32]) -> Result<()> { + if values.len() != job.pairs.len() * HIDDEN { + return Err(Error::InvalidDimension); + } + for (i, &(row, slot)) in job.pairs.iter().enumerate() { + let at = output_offset(row, slot); + out.get_mut(at..at + HIDDEN) + .ok_or(Error::InvalidDimension)? + .copy_from_slice(&values[i * HIDDEN..(i + 1) * HIDDEN]); + } + Ok(()) +} + +/// The all-CPU expert tier over the pinned model's mapped routed weights. +pub(in crate::qwen_forward) struct CpuExpertPool<'a> { + binding: &'a ModelBinding, + cpu: CpuMissWorkspace, +} +impl<'a> CpuExpertPool<'a> { + pub(in crate::qwen_forward) fn new(binding: &'a ModelBinding, workers: i32) -> Result { + if binding.expert_count() != EXPERTS as u32 || binding.expert_used_count() != TOP_K as u32 { + return Err(Error::IdentityMismatch); + } + Ok(Self { binding, cpu: CpuMissWorkspace::new(binding, workers).map_err(runtime_error)? }) + } +} +impl<'ctx> OriginalServePool<'ctx> for CpuExpertPool<'_> { + fn run_group( + &mut self, + rows: OriginalVerifyCpuRows<'_>, + sink: &mut OriginalVerifyCpuSink<'_, 'ctx>, + _copy: &mut OriginalGpuStream<'ctx>, + ) -> Result<()> { + let count = rows.ids.len() / TOP_K; + if rows.layer >= 48 + || rows.activation.len() != count * HIDDEN + || rows.ids.len() != count * TOP_K + || rows.route_weights.len() != count * TOP_K + { + return Err(Error::InvalidDimension); + } + let binding = self.binding; + let layer = rows.layer as u32; + let plan = plan_experts(rows.ids, count)?; + // Every batch is prepared, run and joined before the next; results are held until the whole + // group is complete so the mapped destination is written in one bounded pass. + let mut results: Vec<(usize, Box<[f32]>)> = Vec::new(); + results.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?; + for (batch_index, batch) in plan.chunks(JOBS_PER_BATCH).enumerate() { + let mut jobs = Vec::new(); + jobs.try_reserve_exact(batch.len()).map_err(|_| Error::InputAllocation)?; + for job in batch { + let (first_row, first_slot) = job.pairs[0]; + let selected = selection(rows.ids, first_row)?; + let weights = binding.moe_expert_weights(layer, selected).map_err(binding_error)?; + let members = [(&weights, first_slot)]; + let mut inputs: Vec<&[f32]> = Vec::new(); + inputs.try_reserve_exact(job.pairs.len()).map_err(|_| Error::InputAllocation)?; + for &(row, _) in &job.pairs { + inputs.push(&rows.activation[row * HIDDEN..(row + 1) * HIDDEN]); + } + let prepared = binding.with_moe_routed_source(&members, binding_error, |source| { + let prepared = self.cpu.prepare_scoped(binding, source, 0, &inputs).map_err(runtime_error)?; + source.finish().map_err(binding_error)?; + Ok(prepared) + })?; + jobs.push(prepared); + } + let pending = self.cpu.start(jobs, BATCH_ALLOWANCE).map_err(runtime_error)?; + let completed = pending.join().map_err(runtime_error)?; + if completed.len() != batch.len() { + return Err(Error::IdentityMismatch); + } + for (k, (done, job)) in completed.into_iter().zip(batch).enumerate() { + // Re-open the source and require the finished rows to belong to exactly this expert's + // gate/up/down descriptors before they may reach the window. + let (first_row, first_slot) = job.pairs[0]; + let weights = binding.moe_expert_weights(layer, selection(rows.ids, first_row)?).map_err(binding_error)?; + let members = [(&weights, first_slot)]; + binding.with_moe_routed_source(&members, binding_error, |source| { + let keys = [ + source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?, + source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?, + source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + if !done.matches(binding, &keys) || done.values().len() != job.pairs.len() * HIDDEN { + return Err(Error::IdentityMismatch); + } + source.finish().map_err(binding_error)?; + Ok(()) + })?; + results.push((batch_index * JOBS_PER_BATCH + k, done.into_values())); + } + } + let mut failure = None; + let written = sink.with_output(|out| { + if out.len() != count * TOP_K * HIDDEN { + failure = Some(Error::InvalidDimension); + return Err(leleka_cuda_driver::Error::InvalidQwenShape); + } + for (job_index, values) in &results { + if let Err(error) = scatter(out, &plan[*job_index], values) { + failure = Some(error); + return Err(leleka_cuda_driver::Error::InvalidQwenShape); + } + } + Ok(()) + }); + match (written, failure) { + (Ok(()), None) => Ok(()), + (_, Some(error)) => Err(error), + (Err(_), None) => Err(Error::CudaExecution), + } + } +} + +fn selection(ids: &[i32], row: usize) -> Result<[u32; TOP_K]> { + let slice = ids.get(row * TOP_K..(row + 1) * TOP_K).ok_or(Error::InvalidDimension)?; + let mut selected = [0u32; TOP_K]; + for (out, &id) in selected.iter_mut().zip(slice) { + *out = u32::try_from(id).map_err(|_| Error::InvalidExpert)?; + } + Ok(selected) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ids(rows: &[[i32; TOP_K]]) -> Vec { + rows.iter().flatten().copied().collect() + } + + #[test] + fn every_pair_is_planned_exactly_once_and_experts_keep_first_use_order() { + let a = [5, 1, 9, 2, 3, 4, 6, 7, 8, 0]; + let b = [9, 5, 11, 12, 13, 14, 15, 16, 17, 18]; + let plan = plan_experts(&ids(&[a, b]), 2).unwrap(); + assert_eq!(plan[0], ExpertJob { expert: 5, pairs: vec![(0, 0), (1, 1)] }); + assert_eq!(plan[1], ExpertJob { expert: 1, pairs: vec![(0, 1)] }); + assert_eq!(plan[2], ExpertJob { expert: 9, pairs: vec![(0, 2), (1, 0)] }); + let total: usize = plan.iter().map(|j| j.pairs.len()).sum(); + assert_eq!(total, 20); + let mut all: Vec<_> = plan.iter().flat_map(|j| j.pairs.iter().copied()).collect(); + all.sort_unstable(); + all.dedup(); + assert_eq!(all.len(), 20); + // distinct experts: 10 + 8 new in row 1 (9 and 5 shared) + assert_eq!(plan.len(), 18); + } + + #[test] + fn invalid_router_output_is_refused_not_repaired() { + let good = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + assert_eq!(plan_experts(&ids(&[good]), 0), Err(Error::InvalidDimension)); + assert_eq!(plan_experts(&good, 2), Err(Error::InvalidDimension)); + assert_eq!(plan_experts(&vec![0; 90], 9), Err(Error::InvalidDimension)); + let mut out_of_range = good; + out_of_range[3] = 512; + assert_eq!(plan_experts(&ids(&[out_of_range]), 1), Err(Error::InvalidExpert)); + out_of_range[3] = -1; + assert_eq!(plan_experts(&ids(&[out_of_range]), 1), Err(Error::InvalidExpert)); + let mut repeated = good; + repeated[9] = 0; + assert_eq!(plan_experts(&ids(&[repeated]), 1), Err(Error::InvalidExpert)); + } + + #[test] + fn scatter_writes_each_slot_at_the_documented_offset_and_nothing_else() { + let rows = 3; + let mut out = vec![-1.0f32; rows * TOP_K * HIDDEN]; + let job = ExpertJob { expert: 7, pairs: vec![(0, 4), (2, 9)] }; + let mut values = vec![0.0f32; 2 * HIDDEN]; + values[..HIDDEN].fill(1.0); + values[HIDDEN..].fill(2.0); + scatter(&mut out, &job, &values).unwrap(); + for row in 0..rows { + for slot in 0..TOP_K { + let at = output_offset(row, slot); + let want = match (row, slot) { + (0, 4) => 1.0, + (2, 9) => 2.0, + _ => -1.0, + }; + assert!(out[at..at + HIDDEN].iter().all(|&v| v == want), "slot ({row},{slot})"); + } + } + assert_eq!(output_offset(1, 3), (TOP_K + 3) * HIDDEN); + // wrong value count / out-of-window pair + assert_eq!(scatter(&mut out, &job, &values[..HIDDEN]), Err(Error::InvalidDimension)); + let far = ExpertJob { expert: 1, pairs: vec![(rows, 0)] }; + assert_eq!(scatter(&mut out, &far, &values[..HIDDEN]), Err(Error::InvalidDimension)); + } + + #[test] + fn selection_rejects_negative_ids_and_short_rows() { + let good = ids(&[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]); + assert_eq!(selection(&good, 0), Ok([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])); + assert_eq!(selection(&good, 1), Err(Error::InvalidDimension)); + let mut bad = good.clone(); + bad[2] = -3; + assert_eq!(selection(&bad, 0), Err(Error::InvalidExpert)); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_original_draft.rs b/crates/leleka-runtime/src/qwen_forward/session_original_draft.rs index 58606a0b..0264add4 100644 --- a/crates/leleka-runtime/src/qwen_forward/session_original_draft.rs +++ b/crates/leleka-runtime/src/qwen_forward/session_original_draft.rs @@ -173,6 +173,15 @@ impl<'ctx> OriginalDraftSession<'ctx>{ if result.is_err(){self.failed=true;} result } + /// Roll the MTP ring back to `prior` and rebind it to the (already restored) target branch. The + /// serve host calls this for a failed round after the target side was repaired: both physical + /// restores are attempted by the caller's order (target first, then this). + pub(in crate::qwen_forward) fn restore_current(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, + session:&QwenSession<'ctx>,prior:&OriginalDraftCheckpoint)->Result<()> { + self.restore_physical(binding,dense,prior)?; + let actual=session.target_origin()?; + self.rebind_restored(prior,&actual) + } pub(super) fn rebind_restored(&mut self,prior:&OriginalDraftCheckpoint,actual:&TargetStepOrigin)->Result<()> { if self.failed||!self.origin.same_prefix(&prior.origin)||!actual.same_session(&prior.origin) ||actual.next_position()!=prior.origin.next_position() diff --git a/crates/leleka-runtime/src/qwen_forward/session_original_verified.rs b/crates/leleka-runtime/src/qwen_forward/session_original_verified.rs index 0983950e..7580413d 100644 --- a/crates/leleka-runtime/src/qwen_forward/session_original_verified.rs +++ b/crates/leleka-runtime/src/qwen_forward/session_original_verified.rs @@ -83,6 +83,13 @@ impl<'driver> QwenSession<'driver> { Ok(OriginalVerifiedBase { position: self.next_position, ple, gdn, qsa }) } + /// The two committed tokens before the next input, oldest first (-1 = absent): the hash context of the + /// next window's first PLE row. + pub(in crate::qwen_forward) fn original_predecessors(&self) -> Result<[i32; 2]> { + self.target_origin()?; + Ok(self.predecessors) + } + /// The origin the target will have once `rows` more positions are committed on this branch. pub(in crate::qwen_forward) fn original_origin_after(&self, rows: usize) -> Result { self.target_origin()?;