diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_6.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_6.rs index 631a104c..d5c6f0af 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_6.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_6.rs @@ -13,55 +13,29 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { count: usize, cancel: &mut dyn FnMut() -> bool, ) -> std::result::Result<(), SpecError> { - let Self { - binding, - moe, - arena, - layout, - expert_cache, - loan, - loan_tiers, - executor, - draft, - session, - kar, - dense, - embedding, - scalar_policy, - .. - } = self; let mut chunk = PromptChunk { - binding: *binding, - executor: &mut *executor, - dense: &*dense, - session: &mut *session, + binding: self.binding, + executor: &mut self.executor, + dense: &self.dense, + session: &mut self.session, source, - kar: kar.as_mut(), - moe: &mut *moe, - draft: &mut *draft, - embedding: &*embedding, - scalar_policy: &*scalar_policy, + kar: self.kar.as_mut(), + moe: &mut self.moe, + draft: &mut self.draft, + embedding: &self.embedding, + scalar_policy: &self.scalar_policy, }; let first = chunk.session.target_origin().map(|o| o.next_position()).unwrap_or(0); super::super::super::prefill_profile::begin_chunk(); - let ran = match (*loan, expert_cache.as_mut(), arena.as_mut()) { - (Some(slots), Some(cache), _) => match { - let _span = - super::super::super::prefill_profile::span(super::super::super::prefill_profile::Stage::Lend, None); - // the smallest rung of the ladder that holds the chunk - let (slots, options) = tier_for(loan_tiers, count).map_or((slots, *layout), |t| (t.slots, t.layout)); - cache.lend_prefill_tail(slots, options) - } { + let ran = match (self.loan, self.expert_cache.as_mut(), self.arena.as_mut()) { + (Some(slots), Some(cache), _) => match lend_tail(cache, &self.loan_tiers, self.layout, slots, count) { Ok(mut lent) => chunk.run(count, &mut lent, cancel), Err(e) => Err(SpecError::Forward(super::super::super::original_serve_verifier::driver_error(&e))), }, (_, _, Some(own)) => chunk.run(count, own, cancel), _ => Err(Error::IdentityMismatch.into()), }; - if ran.is_ok() { - super::super::super::prefill_profile::end_chunk(first, count); - } - ran + ran.inspect(|()| super::super::super::prefill_profile::end_chunk(first, count)) } /// The prefix cache at the end of the prefill: with `TailMode::Prompt` or `Reply` a checkpoint at `n - 1`, where the next turn of @@ -170,3 +144,16 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { self.conversation = Some(conversation); } } + +/// The chunk's loan from the expert cache: the smallest rung of the ladder that holds `count` rows, else the full loan. +fn lend_tail<'l, 'ctx>( + cache: &'l mut OriginalExpertCache<'ctx>, + tiers: &[LoanTier], + layout: PrefillLayoutOptions, + slots: usize, + count: usize, +) -> std::result::Result, leleka_cuda_driver::Error> { + let _span = super::super::super::prefill_profile::span(super::super::super::prefill_profile::Stage::Lend, None); + let (slots, options) = tier_for(tiers, count).map_or((slots, layout), |t| (t.slots, t.layout)); + cache.lend_prefill_tail(slots, options) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs index 78f6b06d..1efaff02 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs @@ -150,62 +150,11 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { (true, Some(consumed)) if self.broken.is_none() => self.prefix_after_decode(&consumed), _ => {} } - // an exit before the decode phase queued the refill still refills now; one before it waited still waits - if std::mem::take(&mut self.refill_due) { - if let Some(cache) = self.expert_cache.as_mut() { - if let Err(error) = original_serve_residency::refill_lent( - self.binding, - &self.moe, - cache, - &mut self.residency.spans, - false, - ) { - self.mark_broken(error); - } - } - } - if std::mem::take(&mut self.refill_pending) { - if let Some(cache) = self.expert_cache.as_mut() { - if let Err(error) = original_serve_residency::settle_refill(cache) { - self.mark_broken(error); - } - } - } + self.settle_lent_refills(); self.timing.1 = self.config.clock.since(started).as_secs_f64() * 1e3; profile::add("decode.phase", self.timing.1); - if profile::enabled() { - let t1 = self.residency.stats; - let (v, p, c) = ( - t1.vram_entries - tier0.vram_entries, - t1.pcie_entries - tier0.pcie_entries, - t1.cpu_entries - tier0.cpu_entries, - ); - let all = (v + p + c).max(1) as f64; - // the Original's hit rate: VRAM entries over VRAM + CPU entries (PCIe entries are in neither count) - eprintln!( - "DBG tier request: vram {v} ({:.1}%) pcie {p} ({:.1}%) cpu {c} ({:.1}%) hit_rate_original_def {:.1}% adaptations {} swaps {} pcie_num {}", - 100.0 * v as f64 / all, - 100.0 * p as f64 / all, - 100.0 * c as f64 / all, - 100.0 * v as f64 / ((v + c).max(1) as f64), - t1.adaptations - tier0.adaptations, - t1.swaps - tier0.swaps, - self.residency - .pcie_lag - .as_ref() - .map(|l| l.pcie_num()) - .or_else(|| self.residency.pcie_auto.as_ref().map(|a| a.pcie_num())) - .unwrap_or(self.config.expert_tier.pcie_num()) - ); - } - // graphs captured after the window/commit graphs: the MTP round programs of this request's drafts - let (capture_ms, instantiate_ms, _) = leleka_cuda_driver::original_capture_timing::take(); - profile::add("mtp.capture", capture_ms); - profile::add("mtp.instantiate", instantiate_ms); - profile::add("prefill.phase", self.timing.0); - profile::report("request"); - self.residency.flush_routing(); - self.seed_coverage_trace(); + self.report_tier_request(tier0); + self.report_request_profile(); result } fn finish(&mut self, ended: std::result::Result<(), ServeError>) { @@ -248,3 +197,70 @@ impl<'a, 'ctx> ServeDevice for OriginalServeStack<'a, 'ctx> { OriginalServeStack::expert_tier_stats(self) } } + +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + /// An exit before the decode phase queued the refill still refills now; one before it waited still waits. + fn settle_lent_refills(&mut self) { + if std::mem::take(&mut self.refill_due) { + if let Some(cache) = self.expert_cache.as_mut() { + if let Err(error) = original_serve_residency::refill_lent( + self.binding, + &self.moe, + cache, + &mut self.residency.spans, + false, + ) { + self.mark_broken(error); + } + } + } + if std::mem::take(&mut self.refill_pending) { + if let Some(cache) = self.expert_cache.as_mut() { + if let Err(error) = original_serve_residency::settle_refill(cache) { + self.mark_broken(error); + } + } + } + } + fn report_tier_request(&self, tier0: original_serve_residency::ResidencyStats) { + if profile::enabled() { + let t1 = self.residency.stats; + let (v, p, c) = ( + t1.vram_entries - tier0.vram_entries, + t1.pcie_entries - tier0.pcie_entries, + t1.cpu_entries - tier0.cpu_entries, + ); + let all = (v + p + c).max(1) as f64; + // the Original's hit rate: VRAM entries over VRAM + CPU entries (PCIe entries are in neither count) + eprintln!( + "DBG tier request: vram {v} ({:.1}%) pcie {p} ({:.1}%) cpu {c} ({:.1}%) \ + hit_rate_original_def {:.1}% adaptations {} swaps {} pcie_num {}", + 100.0 * v as f64 / all, + 100.0 * p as f64 / all, + 100.0 * c as f64 / all, + 100.0 * v as f64 / ((v + c).max(1) as f64), + t1.adaptations - tier0.adaptations, + t1.swaps - tier0.swaps, + self.pcie_num_for_report() + ); + } + } + fn pcie_num_for_report(&self) -> u32 { + self.residency + .pcie_lag + .as_ref() + .map(|l| l.pcie_num()) + .or_else(|| self.residency.pcie_auto.as_ref().map(|a| a.pcie_num())) + .unwrap_or(self.config.expert_tier.pcie_num()) + } + fn report_request_profile(&mut self) { + // graphs captured after the window/commit graphs: the MTP round programs of this request's drafts + let (capture_ms, instantiate_ms, _) = leleka_cuda_driver::original_capture_timing::take(); + profile::add("mtp.capture", capture_ms); + profile::add("mtp.instantiate", instantiate_ms); + profile::add("prefill.phase", self.timing.0); + profile::report("request"); + self.residency.flush_routing(); + self.seed_coverage_trace(); + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs index f88583bd..4760c748 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs @@ -24,17 +24,7 @@ impl<'ctx> PromptChunk<'_, 'ctx> { self.scalar_policy, || cancel(), ); - if let Err(e) = &pending { - crate::bringup_trace!("DBG[{:.0}s] executor.forward err {e:?}", dbg_el()); - } - let pending = match pending { - Ok(pending) => pending, - Err(error) if cancel() => { - let _ = error; - return Err(SpecError::Cancelled); - } - Err(error) => return Err(SpecError::Forward(error)), - }; + let pending = forward_outcome(pending, cancel)?; crate::bringup_trace!("DBG[{:.0}s] forward ok, publishing", dbg_el()); let _span = super::super::prefill_profile::span(super::super::prefill_profile::Stage::Publish, None); pending.publish()?; @@ -42,6 +32,20 @@ impl<'ctx> PromptChunk<'_, 'ctx> { Ok(()) } } +/// The forward's result: a failure after a cancel request is the cancel, any other is the forward's own error. +fn forward_outcome

(pending: Result

, cancel: &mut dyn FnMut() -> bool) -> std::result::Result { + if let Err(e) = &pending { + crate::bringup_trace!("DBG[{:.0}s] executor.forward err {e:?}", dbg_el()); + } + match pending { + Ok(pending) => Ok(pending), + Err(error) if cancel() => { + let _ = error; + Err(SpecError::Cancelled) + } + Err(error) => Err(SpecError::Forward(error)), + } +} /// Bring-up tracing clock (seconds since the first call); remove together with the DBG lines. /// `LELEKA_SERVE_PROFILE=1`: the card's free VRAM at a point of the stack's life (where the auto-sized cache's room goes). pub(super) fn vram_note(context: &Context<'_>, label: &str) { @@ -152,45 +156,54 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { pub(super) fn prefix_resume(&mut self, request: &ServeRequest) -> Option { let mut prefix = self.prefix.take()?; let _resume_span = profile::span("request.resume"); - let n = request.prompt.len(); let resume = if self.broken.is_some() { prefix.invalidate(); None } else { - match prefix.begin(self, &request.prompt) { - Ok(Some(start)) => { - self.reused = start.resume; - self.resume_point = start.resume; - operator_text(&format!( - "prefix request: n={n} hit=yes resume={} switched={} branch={} copied_tokens={} import_ms={:.1} (state+kv {:.1}, draft {:.1}) match_us={:.0} live_tokens={}", - start.resume, - start.switched, - start.branch, - start.copied_tokens, - start.import_ms, - prefix.last_import_split().0, - prefix.last_import_split().1, - start.match_us, - prefix.live_tokens() - )); - Some(start.resume) - } - Ok(None) => { - operator_text(&format!( - "prefix request: n={n} hit=no resume=0 match_us={:.0}", - prefix.last_match_us() - )); - None - } - Err(error) => { - // the cache is an optimisation: drop it and start from the empty prompt (`reset`) - operator_text(&format!("prefix cache: {error:?}; reading the whole prompt")); - prefix.invalidate(); - None - } - } + self.prefix_begin(&mut prefix, request) }; self.prefix = Some(prefix); resume } + fn prefix_begin( + &mut self, + prefix: &mut PrefixServe, + request: &ServeRequest, + ) -> Option { + let n = request.prompt.len(); + match prefix.begin(self, &request.prompt) { + Ok(Some(start)) => { + self.reused = start.resume; + self.resume_point = start.resume; + operator_text(&prefix_hit_text(n, &start, prefix)); + Some(start.resume) + } + Ok(None) => { + operator_text(&format!("prefix request: n={n} hit=no resume=0 match_us={:.0}", prefix.last_match_us())); + None + } + Err(error) => { + // the cache is an optimisation: drop it and start from the empty prompt (`reset`) + operator_text(&format!("prefix cache: {error:?}; reading the whole prompt")); + prefix.invalidate(); + None + } + } + } +} + +fn prefix_hit_text(n: usize, start: &prefix::Start, prefix: &PrefixServe) -> String { + format!( + "prefix request: n={n} hit=yes resume={} switched={} branch={} copied_tokens={} import_ms={:.1} \ + (state+kv {:.1}, draft {:.1}) match_us={:.0} live_tokens={}", + start.resume, + start.switched, + start.branch, + start.copied_tokens, + start.import_ms, + prefix.last_import_split().0, + prefix.last_import_split().1, + start.match_us, + prefix.live_tokens() + ) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_adaptive_env.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_adaptive_env.rs index 63d8a013..a8e8b8a8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_adaptive_env.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_adaptive_env.rs @@ -6,33 +6,21 @@ use leleka_engine_core::spec::adaptive::AdaptiveConfig; /// `LELEKA_SPEC_EXPLORE` (period), `_MARGIN`, `_MIN_P_LO`, `_DRAFT_STEP_MS`, `_COST_ALPHA`, `_DECAY`, `_BIAS_RATE`, `_FLOOR_CEILING`; `LELEKA_SPEC_POLICY=legacy` /// first restores the constants the policy shipped with before the draft-round change (see `AdaptiveConfig::with_policy`). pub(crate) fn from_environment(mut config: AdaptiveConfig, env: &impl crate::settings::EnvSource) -> AdaptiveConfig { - fn num(env: &impl crate::settings::EnvSource, name: &str) -> Option { - env.get(name).and_then(|v| v.trim().parse().ok()) - } config = config.with_policy(env.get("LELEKA_SPEC_POLICY").as_deref()); - if let Some(v) = num(env, "LELEKA_SPEC_FLOOR_CEILING") { - config.min_p_hi = v; - } - if let Some(v) = num(env, "LELEKA_SPEC_EXPLORE") { - config.explore_period = v; - } - if let Some(v) = num(env, "LELEKA_SPEC_MARGIN") { - config.margin = v; - } - if let Some(v) = num(env, "LELEKA_SPEC_MIN_P_LO") { - config.min_p_lo = v; - } - if let Some(v) = num(env, "LELEKA_SPEC_DRAFT_STEP_MS") { - config.draft_step_ms = v; - } - if let Some(v) = num(env, "LELEKA_SPEC_COST_ALPHA") { - config.cost_alpha = v; - } - if let Some(v) = num(env, "LELEKA_SPEC_DECAY") { - config.decay = v; - } - if let Some(v) = num(env, "LELEKA_SPEC_BIAS_RATE") { - config.bias_rate = v; - } + override_with(env, "LELEKA_SPEC_FLOOR_CEILING", &mut config.min_p_hi); + override_with(env, "LELEKA_SPEC_EXPLORE", &mut config.explore_period); + override_with(env, "LELEKA_SPEC_MARGIN", &mut config.margin); + override_with(env, "LELEKA_SPEC_MIN_P_LO", &mut config.min_p_lo); + override_with(env, "LELEKA_SPEC_DRAFT_STEP_MS", &mut config.draft_step_ms); + override_with(env, "LELEKA_SPEC_COST_ALPHA", &mut config.cost_alpha); + override_with(env, "LELEKA_SPEC_DECAY", &mut config.decay); + override_with(env, "LELEKA_SPEC_BIAS_RATE", &mut config.bias_rate); config } + +/// Replaces `slot` with the variable's value when it is set and parses. +fn override_with(env: &impl crate::settings::EnvSource, name: &str, slot: &mut T) { + if let Some(v) = env.get(name).and_then(|v| v.trim().parse().ok()) { + *slot = v; + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2.rs index de4d296b..20e7a07d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2.rs @@ -59,44 +59,9 @@ impl OriginalSpecController { /// Prompt suffix/history is reset for each request, including resumed ones. /// Root reads the prompt only through n-2; row n-1 is first verify input. pub(crate) fn begin_request(&mut self, prompt: &[i32], max_new: usize, min_p: f32, eos_ids: &[i32]) -> Result<()> { - if self.failed { - return Err(Error::IdentityMismatch); - } - if self.request.as_ref().is_some_and(|r| !r.finished || r.pending_draft) { - return Err(Error::IdentityMismatch); - } - if prompt.is_empty() || prompt.len() > self.config.max_context as usize || !min_p.is_finite() { - return Err(Error::InvalidDimension); - } - let valid = |v: i32| v >= 0 && (v as u32) < self.config.vocabulary; - if prompt.iter().chain(eos_ids).any(|&v| !valid(v)) { - return Err(Error::InvalidToken); - } - // Precharge all append capacity BEFORE actual inference. Original - // reserves n+max_new+S; max-context+S also bounds accepted overshoot. - let cap = prompt - .len() - .checked_add(max_new) - .and_then(|n| n.checked_add(self.config.max_t)) - .ok_or(Error::Overflow)? - .min((self.config.max_context as usize).checked_add(MAX_T).ok_or(Error::Overflow)?); - let mut consumed = Vec::new(); - consumed.try_reserve_exact(cap).map_err(|_| Error::InputAllocation)?; - consumed.extend_from_slice(&prompt[..prompt.len() - 1]); - let mut eos = Vec::new(); - eos.try_reserve_exact(eos_ids.len()).map_err(|_| Error::InputAllocation)?; - eos.extend_from_slice(eos_ids); - // Reserve/admit before resetting the previous suffix state. - self.suffix.reserve_reset(prompt.len())?; - self.suffix.reset(); - if self.config.suffix_min_match > 0 { - self.suffix.append(prompt)?; - } - self.plan = None; - if let Some(pol) = self.adaptive.as_mut() { - pol.begin_request(min_p); - self.plan = Some(pol.draft_plan()); - } + self.check_begin(prompt, min_p, eos_ids)?; + let (consumed, eos) = self.precharge(prompt, max_new, eos_ids)?; + self.reset_for_request(prompt, min_p)?; self.request = Some(Request { consumed, input: prompt[prompt.len() - 1], @@ -113,6 +78,53 @@ impl OriginalSpecController { }); Ok(()) } + fn check_begin(&self, prompt: &[i32], min_p: f32, eos_ids: &[i32]) -> Result<()> { + if self.failed { + return Err(Error::IdentityMismatch); + } + if self.request.as_ref().is_some_and(|r| !r.finished || r.pending_draft) { + return Err(Error::IdentityMismatch); + } + if prompt.is_empty() || prompt.len() > self.config.max_context as usize || !min_p.is_finite() { + return Err(Error::InvalidDimension); + } + let valid = |v: i32| v >= 0 && (v as u32) < self.config.vocabulary; + if prompt.iter().chain(eos_ids).any(|&v| !valid(v)) { + return Err(Error::InvalidToken); + } + Ok(()) + } + /// Precharge all append capacity BEFORE actual inference. Original + /// reserves n+max_new+S; max-context+S also bounds accepted overshoot. + fn precharge(&self, prompt: &[i32], max_new: usize, eos_ids: &[i32]) -> Result<(Vec, Vec)> { + let cap = prompt + .len() + .checked_add(max_new) + .and_then(|n| n.checked_add(self.config.max_t)) + .ok_or(Error::Overflow)? + .min((self.config.max_context as usize).checked_add(MAX_T).ok_or(Error::Overflow)?); + let mut consumed = Vec::new(); + consumed.try_reserve_exact(cap).map_err(|_| Error::InputAllocation)?; + consumed.extend_from_slice(&prompt[..prompt.len() - 1]); + let mut eos = Vec::new(); + eos.try_reserve_exact(eos_ids.len()).map_err(|_| Error::InputAllocation)?; + eos.extend_from_slice(eos_ids); + Ok((consumed, eos)) + } + /// Reserve/admit before resetting the previous suffix state. + fn reset_for_request(&mut self, prompt: &[i32], min_p: f32) -> Result<()> { + self.suffix.reserve_reset(prompt.len())?; + self.suffix.reset(); + if self.config.suffix_min_match > 0 { + self.suffix.append(prompt)?; + } + self.plan = None; + if let Some(pol) = self.adaptive.as_mut() { + pol.begin_request(min_p); + self.plan = Some(pol.draft_plan()); + } + Ok(()) + } pub(crate) fn host_bytes(&self) -> Result { let mut bytes = self.suffix.metadata_bytes()?.checked_add(std::mem::size_of::() + 64).ok_or(Error::Overflow)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs index 5f414dfe..3f01b933 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs @@ -32,37 +32,46 @@ impl NanGuard { self.inject_times = times; self } - /// From the three values; a malformed one is refused with its name (a guard that silently differs from what the operator wrote is worse than none). - pub(crate) fn parse( - switch: Option<&str>, - retries: Option<&str>, - inject: Option<&str>, - ) -> std::result::Result { - let on = match switch.map(|v| v.trim().to_ascii_lowercase()).as_deref() { + fn parse_switch(switch: Option<&str>) -> std::result::Result { + Ok(match switch.map(|v| v.trim().to_ascii_lowercase()).as_deref() { None | Some("") => Self::DEFAULT_ON, Some("on" | "1" | "yes" | "true") => true, Some("off" | "0" | "no" | "false") => false, Some(other) => return Err(format!("LELEKA_ORIGINAL_SERVE_NAN_GUARD={other}: expected on or off")), - }; - let retries = match retries.map(str::trim).filter(|v| !v.is_empty()) { + }) + } + fn parse_retries(retries: Option<&str>) -> std::result::Result { + Ok(match retries.map(str::trim).filter(|v| !v.is_empty()) { None => Self::DEFAULT_RETRIES, Some(v) => v .parse::() .ok() .filter(|&n| n <= 8) .ok_or_else(|| format!("LELEKA_ORIGINAL_SERVE_NAN_GUARD_RETRIES={v}: expected 0..=8"))?, + }) + } + fn parse_injection(v: &str) -> std::result::Result<(u64, u32), String> { + let (at, times) = match v.split_once('x') { + Some((a, k)) => (a, k), + None => (v, "1"), }; + let bad = || format!("LELEKA_ORIGINAL_SERVE_NAN_INJECT={v}: expected n or nxK"); + Ok(( + at.parse::().ok().filter(|&n| n > 0).ok_or_else(bad)?, + times.parse::().ok().filter(|&n| n > 0).ok_or_else(bad)?, + )) + } + /// From the three values; a malformed one is refused with its name (a guard that silently differs from what the operator wrote is worse than none). + pub(crate) fn parse( + switch: Option<&str>, + retries: Option<&str>, + inject: Option<&str>, + ) -> std::result::Result { + let on = Self::parse_switch(switch)?; + let retries = Self::parse_retries(retries)?; let mut guard = if on { Self::with_retries(retries) } else { Self::off() }; if let Some(v) = inject.map(str::trim).filter(|v| !v.is_empty()) { - let (at, times) = match v.split_once('x') { - Some((a, k)) => (a, k), - None => (v, "1"), - }; - let bad = || format!("LELEKA_ORIGINAL_SERVE_NAN_INJECT={v}: expected n or nxK"); - let (at, times) = ( - at.parse::().ok().filter(|&n| n > 0).ok_or_else(bad)?, - times.parse::().ok().filter(|&n| n > 0).ok_or_else(bad)?, - ); + let (at, times) = Self::parse_injection(v)?; guard = guard.with_injection(at, times); } Ok(guard) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs index 3d4c4fdb..e3e2fef2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs @@ -105,6 +105,22 @@ impl DraftPreparation { min_p: f32, coupled: bool, ) -> Result { + self.check_verified(p, a, outputs, consumed, vetted, min_p)?; + let result = self.seed_and_chain(engine, verified, p, a, outputs, consumed, min_p, coupled); + let drain = engine.drain_draft(); + // Preserves stage primary; adapter must retain/poison uncertainty even + // when an earlier finite/admission error is returned to the caller. + drain_after(result, drain) + } + fn check_verified( + &self, + p: i64, + a: usize, + outputs: &[i32], + consumed: &[i32], + vetted: &mut PrefixMemo, + min_p: f32, + ) -> Result<()> { if outputs.is_empty() || outputs.len() > self.max_t || a >= outputs.len() @@ -121,31 +137,56 @@ impl DraftPreparation { { return Err(Error::InvalidToken); } - let result = (|| { - if coupled { - engine.stage_coupled_history(consumed, outputs[a])?; - } - engine.replay_target_kv(verified, p, outputs)?; - let cell = p.checked_add(a as i64).ok_or(Error::Overflow)?; - let mut batch = DraftBatch::empty(); - batch.push(engine.full_target_seed(verified, a, cell, outputs[a], coupled)?, self.vocabulary)?; - let mut j = 1; - while j < (self.max_t - 1).min(self.max_drafts) && batch.probabilities[j - 1] >= min_p { - let next_cell = cell.checked_add(j as i64).ok_or(Error::Overflow)?; - batch.push(engine.full_chain_step(next_cell, j, batch.ids[j - 1], coupled)?, self.vocabulary)?; - j += 1; - } - Ok(batch) - })(); - let drain = engine.drain_draft(); - // Preserves stage primary; adapter must retain/poison uncertainty even - // when an earlier finite/admission error is returned to the caller. - match result { - Err(e) => Err(e), - Ok(b) => { - drain?; - Ok(b) - } + Ok(()) + } + fn seed_and_chain>( + &self, + engine: &mut E, + verified: &V, + p: i64, + a: usize, + outputs: &[i32], + consumed: &[i32], + min_p: f32, + coupled: bool, + ) -> Result { + if coupled { + engine.stage_coupled_history(consumed, outputs[a])?; + } + engine.replay_target_kv(verified, p, outputs)?; + let cell = p.checked_add(a as i64).ok_or(Error::Overflow)?; + let mut batch = DraftBatch::empty(); + batch.push(engine.full_target_seed(verified, a, cell, outputs[a], coupled)?, self.vocabulary)?; + self.chain(&mut batch, cell, min_p, |next_cell, j, previous| { + engine.full_chain_step(next_cell, j, previous, coupled) + })?; + Ok(batch) + } + /// The confidence-gated chain after the seed: step j runs at cell + j while the previous probability holds `min_p`. + fn chain( + &self, + batch: &mut DraftBatch, + cell: i64, + min_p: f32, + mut step: impl FnMut(i64, usize, i32) -> Result, + ) -> Result<()> { + let mut j = 1; + while j < (self.max_t - 1).min(self.max_drafts) && batch.probabilities[j - 1] >= min_p { + let next_cell = cell.checked_add(j as i64).ok_or(Error::Overflow)?; + batch.push(step(next_cell, j, batch.ids[j - 1])?, self.vocabulary)?; + j += 1; + } + Ok(()) + } +} + +/// The drain outcome only surfaces when the draft itself succeeded. +fn drain_after(result: Result, drain: Result<()>) -> Result { + match result { + Err(e) => Err(e), + Ok(b) => { + drain?; + Ok(b) } } } @@ -266,26 +307,24 @@ impl DraftPreparation { { return Err(Error::InvalidDimension); } - let result = (|| { - engine.replay_first_seed_kv(seed, self.max_t, cell, token)?; - let mut batch = DraftBatch::empty(); - batch.push(engine.full_first_seed(seed, cell, token, coupled)?, self.vocabulary)?; - let mut j = 1; - while j < (self.max_t - 1).min(self.max_drafts) && batch.probabilities[j - 1] >= min_p { - let next = cell.checked_add(j as i64).ok_or(Error::Overflow)?; - batch.push(engine.first_chain_step(next, j, batch.ids[j - 1], coupled)?, self.vocabulary)?; - j += 1; - } - Ok(batch) - })(); + let result = self.first_seed_and_chain(engine, seed, cell, token, min_p, coupled); let drain = engine.drain_first_seed(); - match result { - Err(e) => Err(e), - Ok(batch) => { - drain?; - Ok(batch) - } - } + drain_after(result, drain) + } + fn first_seed_and_chain>( + &self, + engine: &mut E, + seed: &S, + cell: i64, + token: i32, + min_p: f32, + coupled: bool, + ) -> Result { + engine.replay_first_seed_kv(seed, self.max_t, cell, token)?; + let mut batch = DraftBatch::empty(); + batch.push(engine.full_first_seed(seed, cell, token, coupled)?, self.vocabulary)?; + self.chain(&mut batch, cell, min_p, |next, j, previous| engine.first_chain_step(next, j, previous, coupled))?; + Ok(batch) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_suffix.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_suffix.rs index 1a045654..0b1bd66f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_suffix.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_suffix.rs @@ -139,7 +139,23 @@ impl SuffixDrafter { let Some(i) = self.find_slot(key, false) else { return 0; }; - let slot = self.table[i]; + let (best_end, best_len) = self.longest_match(self.table[i], cur); + if best_len < self.min_match { + return 0; + } + self.last_match = best_len; + let mut k = 0; + for q in best_end + 1..=cur { + if k == out.len() { + break; + } + out[k] = self.history[q]; + k += 1; + } + k + } + /// The earlier occurrence in `slot` that shares the longest suffix with the history ending at `cur`: (end, length). + fn longest_match(&self, slot: Slot, cur: usize) -> (usize, usize) { let (mut best_end, mut best_len) = (0, 0); for w in 0..slot.n as usize { let p = slot.pos[w] as usize; @@ -155,19 +171,7 @@ impl SuffixDrafter { best_end = p; } } - if best_len < self.min_match { - return 0; - } - self.last_match = best_len; - let mut k = 0; - for q in best_end + 1..=cur { - if k == out.len() { - break; - } - out[k] = self.history[q]; - k += 1; - } - k + (best_end, best_len) } pub(crate) fn last_match(&self) -> usize { self.last_match diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs index 0da466ed..5c041db3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs @@ -69,19 +69,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { // before the existing head load and before the caller's profile preload. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) fn load_compact(binding: &ModelBinding, context: &'context Context<'driver>) -> Result { - let required = context - .allocated_bytes() - .checked_add(OUTPUT_STAGE_BUDGET) - .and_then(|bytes| bytes.checked_add(HEAD_GREEDY_WORKSPACE_BYTES)) - .ok_or(Error::Overflow)?; - let physical = HEAD_GREEDY_WORKSPACE_BYTES.checked_add(128 * 1024 * 1024).ok_or(Error::Overflow)?; - if required > context.budget_bytes() { - return Err(Error::InputAllocation); - } - let (free, _) = context.memory_info().map_err(driver_error)?; - if free < physical { - return Err(Error::InputAllocation); - } + Self::check_compact_budget(context)?; let workspace = context.head_greedy_workspace().map_err(driver_error)?; if workspace.allocated_bytes() != HEAD_GREEDY_WORKSPACE_BYTES { let primary = Error::InvalidDimension; @@ -102,6 +90,24 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { } } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + fn check_compact_budget(context: &Context<'driver>) -> Result<()> { + let required = context + .allocated_bytes() + .checked_add(OUTPUT_STAGE_BUDGET) + .and_then(|bytes| bytes.checked_add(HEAD_GREEDY_WORKSPACE_BYTES)) + .ok_or(Error::Overflow)?; + let physical = HEAD_GREEDY_WORKSPACE_BYTES.checked_add(128 * 1024 * 1024).ok_or(Error::Overflow)?; + if required > context.budget_bytes() { + return Err(Error::InputAllocation); + } + let (free, _) = context.memory_info().map_err(driver_error)?; + if free < physical { + return Err(Error::InputAllocation); + } + Ok(()) + } + pub(in super::super::super) fn logits( &self, binding: &ModelBinding, @@ -119,33 +125,8 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { cache: Option<&super::super::super::dense_weight_cache::DenseWeightCache<'_>>, ) -> Result { let identity = binding.identity(); - txn.validate_binding(&identity)?; - if !self.binding.matches(&identity) { - return Err(Error::IdentityMismatch); - } - { - let context = txn.cuda_context()?; - if !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - } - - let token = txn.token(); - let position = txn.position(); - let final_layer = binding.layer_count().checked_sub(1).ok_or(Error::InvalidLayer)?; - let layer = LayerId::new(u64::from(final_layer), Dimension::new(u64::from(binding.layer_count()))?)?; - residual.identity().validate(token, position, layer)?; - txn.validate_input(token, position)?; - - // STRA-162 owns this complete final output_hc computation. This is the - // sole call; output.rs never duplicates or reorders its GR arithmetic. - let mixed = GrStage::final_mix(binding, residual, txn, cache)?; - if mixed.len() != EMBEDDING { - return Err(Error::InvalidDimension); - } - if mixed.iter().any(|value| !value.is_finite()) { - return Err(Error::NonFinite); - } + let (token, position, layer) = self.check_step(binding, residual, txn)?; + let mixed = Self::checked_final_mix(binding, residual, txn, cache)?; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if super::super::super::oracle_capture::enabled() { @@ -158,23 +139,82 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { logits = self.sample_complete(logits)?; } if matches!(&logits.values, LogitValues::Compact(_)) { - let current = binding.identity(); - txn.validate_binding(¤t)?; - txn.validate_input(token, position)?; - residual.identity().validate(token, position, layer)?; - let context = txn.cuda_context()?; - if !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - if context.is_poisoned() { - return Err(Error::CudaExecution); - } - logits.validate_for(¤t, token, position)?; - self.record_compact_completion()?; + self.finish_compact_step(binding, residual, txn, layer, &logits)?; } Ok(logits) } + /// The step transaction, stage and residual all describe the same final-layer step: (token, position, layer). + fn check_step( + &self, + binding: &ModelBinding, + residual: &InjectedResidual, + txn: &mut QwenStepTxn, + ) -> Result<(TokenId, Position, LayerId)> { + let identity = binding.identity(); + txn.validate_binding(&identity)?; + if !self.binding.matches(&identity) { + return Err(Error::IdentityMismatch); + } + self.require_context(txn.cuda_context()?)?; + + let token = txn.token(); + let position = txn.position(); + let final_layer = binding.layer_count().checked_sub(1).ok_or(Error::InvalidLayer)?; + let layer = LayerId::new(u64::from(final_layer), Dimension::new(u64::from(binding.layer_count()))?)?; + residual.identity().validate(token, position, layer)?; + txn.validate_input(token, position)?; + Ok((token, position, layer)) + } + + fn checked_final_mix( + binding: &ModelBinding, + residual: &InjectedResidual, + txn: &mut QwenStepTxn, + cache: Option<&super::super::super::dense_weight_cache::DenseWeightCache<'_>>, + ) -> Result> { + // STRA-162 owns this complete final output_hc computation. This is the + // sole call; output.rs never duplicates or reorders its GR arithmetic. + let mixed = GrStage::final_mix(binding, residual, txn, cache)?; + if mixed.len() != EMBEDDING { + return Err(Error::InvalidDimension); + } + if mixed.iter().any(|value| !value.is_finite()) { + return Err(Error::NonFinite); + } + Ok(mixed) + } + + /// The compact argmax is only accepted when the step is still the one it was computed for. + fn finish_compact_step( + &self, + binding: &ModelBinding, + residual: &InjectedResidual, + txn: &mut QwenStepTxn, + layer: LayerId, + logits: &FiniteLogits, + ) -> Result<()> { + let (token, position) = (txn.token(), txn.position()); + let current = binding.identity(); + txn.validate_binding(¤t)?; + txn.validate_input(token, position)?; + residual.identity().validate(token, position, layer)?; + let context = txn.cuda_context()?; + self.require_context(context)?; + if context.is_poisoned() { + return Err(Error::CudaExecution); + } + logits.validate_for(¤t, token, position)?; + self.record_compact_completion() + } + + fn require_context(&self, context: &Context<'_>) -> Result<()> { + if !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(in super::super::super) fn mtp_greedy( &self, binding: &ModelBinding, @@ -200,20 +240,28 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { false, )?; if matches!(&logits.values, LogitValues::Compact(_)) { - mixed.frame().validate(binding, session)?; - let current = session.mtp_context()?; - if !std::ptr::eq(self.context, current) { - return Err(Error::IdentityMismatch); - } - if current.is_poisoned() { - return Err(Error::CudaExecution); - } - logits.validate_for(&binding.identity(), mixed.frame().token(), mixed.frame().position())?; - self.record_compact_completion()?; + self.finish_compact_mtp(binding, mixed, session, &logits)?; } greedy(logits) } + fn finish_compact_mtp( + &self, + binding: &ModelBinding, + mixed: &super::super::super::mtp::MtpFinalMixed, + session: &super::super::super::session::QwenSession<'_>, + logits: &FiniteLogits, + ) -> Result<()> { + mixed.frame().validate(binding, session)?; + let current = session.mtp_context()?; + self.require_context(current)?; + if current.is_poisoned() { + return Err(Error::CudaExecution); + } + logits.validate_for(&binding.identity(), mixed.frame().token(), mixed.frame().position())?; + self.record_compact_completion() + } + /// Arm the per-request sampler for the plain decode path. One request at a time. pub(crate) fn arm_sampler(&self, sampler: super::super::super::step_sampler::StepSampler) -> Result<()> { let mut slot = self.sampler.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs index 45b5da4a..b7d1b8a7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs @@ -30,25 +30,8 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { Ok(FiniteLogits { values: LogitValues::Selected(token), ..logits }) } - pub(in super::super) fn project_mixed( - &self, - identity: BindingIdentity, - token: TokenId, - position: Position, - mixed: &[f32], - context: &Context<'_>, - force_full: bool, - ) -> Result { - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = - crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Head); - if self.compact.try_borrow().map_err(|_| Error::IdentityMismatch)?.is_some() - && !force_full - && !self.full_head_observer_active() - { - return self.project_mixed_compact(identity, token, position, mixed, context); - } - if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) { + fn check_projection(&self, identity: &BindingIdentity, mixed: &[f32], context: &Context<'_>) -> Result<()> { + if !self.binding.matches(identity) || !std::ptr::eq(self.context, context) { return Err(Error::IdentityMismatch); } if mixed.len() != EMBEDDING { @@ -62,6 +45,43 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { if required > context.budget_bytes() { return Err(Error::InputAllocation); } + Ok(()) + } + + /// Upload the activation, project it through the Q6_K head into a candidate logit buffer and hand that to `consume`. + /// Both short-lived buffers are explicitly accounted for before the result is published; any teardown failure is a + /// refusal, and the first error stays primary. + fn with_projected( + &self, + context: &Context<'_>, + mixed: &[f32], + consume: impl FnOnce(&DeviceBuffer<'_>) -> Result<()>, + ) -> Result<()> { + let activation = Self::upload_activation(context, mixed)?; + let mut candidate = match context.allocate(LOGIT_BYTES) { + Ok(buffer) => buffer, + Err(error) => { + let primary = driver_error(error); + return combine(Err(primary), activation.release().map_err(driver_error)); + } + }; + let projection = context.q6_k_q8_1( + &self.weights, + &activation, + &mut candidate, + Q6KProjectionShape { rows: VOCABULARY, columns: EMBEDDING }, + ); + let mut result = projection.map_err(driver_error); + if result.is_ok() { + result = consume(&candidate); + } + let candidate_release = candidate.release().map_err(driver_error); + let activation_release = activation.release().map_err(driver_error); + let result = combine(result, candidate_release); + combine(result, activation_release) + } + + fn upload_activation<'c>(context: &'c Context<'_>, mixed: &[f32]) -> Result> { // This limit was preflighted at load() as the persistent head plus all // transient buffers and the Q6 driver's fixed scratch/status bytes. let activation_bytes = encode_activation(mixed)?; @@ -70,47 +90,55 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { let primary = driver_error(error); return combine(Err(primary), activation.release().map_err(driver_error)); } + Ok(activation) + } - let mut candidate = match context.allocate(LOGIT_BYTES) { - Ok(buffer) => buffer, - Err(error) => { - let primary = driver_error(error); - return combine(Err(primary), activation.release().map_err(driver_error)); - } - }; + fn read_logits(candidate: &DeviceBuffer<'_>) -> Result> { + let mut bytes = Vec::new(); + bytes.try_reserve_exact(LOGIT_BYTES).map_err(|_| Error::InputAllocation)?; + bytes.resize(LOGIT_BYTES, 0); + candidate.copy_to(&mut bytes).map_err(driver_error)?; + decode_logits(&bytes) + } - let projection = context.q6_k_q8_1( - &self.weights, - &activation, - &mut candidate, - Q6KProjectionShape { rows: VOCABULARY, columns: EMBEDDING }, - ); - let mut result = projection.map_err(driver_error); - let mut decoded_logits = None; - if result.is_ok() { - let mut bytes = Vec::new(); - if bytes.try_reserve_exact(LOGIT_BYTES).is_err() { - result = Err(Error::InputAllocation); - } else { - bytes.resize(LOGIT_BYTES, 0); - if let Err(error) = candidate.copy_to(&mut bytes) { - result = Err(driver_error(error)); - } else { - match decode_logits(&bytes) { - Ok(values) => decoded_logits = Some(values), - Err(error) => result = Err(error), - } - } - } + fn select_compact(&self, candidate: &DeviceBuffer<'_>) -> Result { + // The exclusive loan ends before either source buffer is + // released. No immutable weight/cache callback is reentered. + let mut owner = self.compact.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + let workspace = owner.as_mut().ok_or(Error::IdentityMismatch)?; + if workspace.allocated_bytes() != HEAD_GREEDY_WORKSPACE_BYTES { + return Err(Error::InvalidDimension); } + workspace.select(candidate).map_err(driver_error)?.ok_or(Error::NonFinite) + } - // Explicitly account for both short-lived buffers before publishing - // the stage-owned candidate. Any teardown failure is a refusal. - let candidate_release = candidate.release().map_err(driver_error); - let activation_release = activation.release().map_err(driver_error); - let result = combine(result, candidate_release); - let result = combine(result, activation_release); - result?; + fn wants_compact(&self, force_full: bool) -> Result { + Ok(self.compact.try_borrow().map_err(|_| Error::IdentityMismatch)?.is_some() + && !force_full + && !self.full_head_observer_active()) + } + + pub(in super::super) fn project_mixed( + &self, + identity: BindingIdentity, + token: TokenId, + position: Position, + mixed: &[f32], + context: &Context<'_>, + force_full: bool, + ) -> Result { + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Head); + if self.wants_compact(force_full)? { + return self.project_mixed_compact(identity, token, position, mixed, context); + } + self.check_projection(&identity, mixed, context)?; + let mut decoded_logits = None; + self.with_projected(context, mixed, |candidate| { + decoded_logits = Some(Self::read_logits(candidate)?); + Ok(()) + })?; let raw_logits = decoded_logits.ok_or(Error::InvalidDimension)?; Ok(FiniteLogits { @@ -150,66 +178,12 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { mixed: &[f32], context: &Context<'_>, ) -> Result { - if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - if mixed.len() != EMBEDDING { - return Err(Error::InvalidDimension); - } - if mixed.iter().any(|v| !v.is_finite()) { - return Err(Error::NonFinite); - } - let required = - context.allocated_bytes().checked_add(OUTPUT_STAGE_BUDGET - OUTPUT_WEIGHT_BYTES).ok_or(Error::Overflow)?; - if required > context.budget_bytes() { - return Err(Error::InputAllocation); - } - // This limit was preflighted at load() as the persistent head plus all - // transient buffers and the Q6 driver's fixed scratch/status bytes. - let activation_bytes = encode_activation(mixed)?; - let mut activation = context.allocate(ACTIVATION_BYTES).map_err(driver_error)?; - if let Err(error) = activation.copy_from(&activation_bytes) { - let primary = driver_error(error); - return combine(Err(primary), activation.release().map_err(driver_error)); - } - - let mut candidate = match context.allocate(LOGIT_BYTES) { - Ok(buffer) => buffer, - Err(error) => { - let primary = driver_error(error); - return combine(Err(primary), activation.release().map_err(driver_error)); - } - }; - - let projection = context.q6_k_q8_1( - &self.weights, - &activation, - &mut candidate, - Q6KProjectionShape { rows: VOCABULARY, columns: EMBEDDING }, - ); + self.check_projection(&identity, mixed, context)?; let mut selection = None; - let mut result = projection.map_err(driver_error); - if result.is_ok() { - result = (|| { - // The exclusive loan ends before either source buffer is - // released. No immutable weight/cache callback is reentered. - let mut owner = self.compact.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - let workspace = owner.as_mut().ok_or(Error::IdentityMismatch)?; - if workspace.allocated_bytes() != HEAD_GREEDY_WORKSPACE_BYTES { - return Err(Error::InvalidDimension); - } - selection = workspace.select(&candidate).map_err(driver_error)?; - if selection.is_none() { - return Err(Error::NonFinite); - } - Ok(()) - })(); - } - let candidate_release = candidate.release().map_err(driver_error); - let activation_release = activation.release().map_err(driver_error); - let result = combine(result, candidate_release); - let result = combine(result, activation_release); - result?; + self.with_projected(context, mixed, |candidate| { + selection = Some(self.select_compact(candidate)?); + Ok(()) + })?; if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs index 52c8033f..54087382 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs @@ -65,6 +65,24 @@ impl<'ctx> OriginalNativeOutput<'ctx> { dispatch: NativeHeadDispatch, with_embedding: bool, ) -> Result { + let head = Self::load_head(binding, context, dispatch)?; + let mut owner = Self { binding: binding.identity(), context, head: Some(head), embed: None }; + if with_embedding { + match Self::load_embedding(binding, context) { + Ok(embed) => owner.embed = Some(embed), + Err(primary) => { + let _ = owner.close(); + return Err(primary); + } + } + } + Ok(owner) + } + fn load_head( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + dispatch: NativeHeadDispatch, + ) -> Result> { // A refusal here is reported with its cause on stderr: the class alone (InvalidDimension) hides which of the // binding, the weight block or the driver refused. let weights = binding.native_output_block(NativeOutputRole::Head).map_err(|e| { @@ -74,43 +92,27 @@ impl<'ctx> OriginalNativeOutput<'ctx> { if !weights.matches(&binding.identity()) { return Err(Error::IdentityMismatch); } - let head = context + context .original_native_head(weights.kind(), weights.columns(), weights.vocabulary(), weights.bytes(), dispatch) .map_err(|e| { eprintln!("OriginalNativeOutput::load: native head refused: {e:?}"); driver(e) - })?; - let mut owner = Self { binding: binding.identity(), context, head: Some(head), embed: None }; - let operation = (|| { - if with_embedding { - let embedding = binding.native_output_block(NativeOutputRole::Embedding).map_err(|e| { - eprintln!("OriginalNativeOutput::load: embedding block refused: {e:?}"); - Error::InvalidDimension - })?; - if !embedding.matches(&binding.identity()) { - return Err(Error::IdentityMismatch); - } - owner.embed = Some( - context - .original_native_embed( - embedding.kind(), - embedding.columns(), - embedding.vocabulary(), - embedding.bytes(), - ) - .map_err(|e| { - eprintln!("OriginalNativeOutput::load: native embedding refused: {e:?}"); - driver(e) - })?, - ); - } - Ok(()) - })(); - if let Err(primary) = operation { - let _ = owner.close(); - return Err(primary); + }) + } + fn load_embedding(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result> { + let embedding = binding.native_output_block(NativeOutputRole::Embedding).map_err(|e| { + eprintln!("OriginalNativeOutput::load: embedding block refused: {e:?}"); + Error::InvalidDimension + })?; + if !embedding.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); } - Ok(owner) + context + .original_native_embed(embedding.kind(), embedding.columns(), embedding.vocabulary(), embedding.bytes()) + .map_err(|e| { + eprintln!("OriginalNativeOutput::load: native embedding refused: {e:?}"); + driver(e) + }) } fn validate(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> { if !self.binding.matches(&binding.identity()) || !std::ptr::eq(context, self.context) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output_native_history.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output_native_history.rs index d7055845..ef1f056a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output_native_history.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output_native_history.rs @@ -60,67 +60,26 @@ impl<'ctx> OriginalNativePenaltyHistory<'ctx> { ) -> Result { origin.validate(session)?; authenticate()?; - if self.failed || self.context.is_poisoned() { - return Err(Error::CudaExecution); - } - if !self.binding.matches(&binding.identity()) - || !std::ptr::eq(self.context, session.mtp_context()?) - || !(1..=ROWS).contains(&window.len()) - || tail.len() as u64 != origin.next_position() - { - return Err(Error::IdentityMismatch); - } - params.validate().map_err(driver)?; - let vocabulary = 248320; - if window.iter().any(|&id| id < 0 || id >= vocabulary) || !self.tail_checked.in_range(tail, vocabulary) { - return Err(Error::InvalidToken); - } - origin.next_position().checked_add(window.len() as u64).ok_or(Error::Overflow)?; + self.admit_window(binding, session, origin, tail, window, ¶ms)?; let h = if params.penalty_last_n <= 0 { 0 } else { (params.penalty_last_n as usize).min(HISTORY) }; - if h > 0 { - // Literal penalty_rows: row t sees tail plus window[0..=t], most - // recent token last and the unavailable prefix padded with -1. - for t in 0..window.len() { - let available = tail.len().checked_add(t + 1).ok_or(Error::Overflow)?; - let take = h.min(available); - for j in 0..h { - let value = if j < h - take { - -1 - } else { - let i = available - take + j - (h - take); - if i < tail.len() { tail[i] } else { window[i - tail.len()] } - }; - let offset = (t * h + j) * 4; - self.staging[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); - } - } - let used = window.len() * h * 4; - let upload = self - .device - .as_mut() - .ok_or(Error::IdentityMismatch)? - .copy_from_range(0, &self.staging[..used]) - .map_err(driver); - if upload.is_err() || self.context.is_poisoned() { - self.failed = true; - } - upload?; - } + self.upload_penalty_rows(tail, window, h)?; let history = if h == 0 { None } else { Some(self.device.as_ref().ok_or(Error::IdentityMismatch)?) }; - let operation = consume(NativeHeadSampling { - position: origin.next_position(), - params, - history, - history_len: h, - path, - enabled, - }); + let position = origin.next_position(); + let operation = consume(NativeHeadSampling { position, params, history, history_len: h, path, enabled }); // Actual canonical target stays pending throughout verification; a // reset/rewind or failed source check refuses the selection unchanged. - let checked = (|| { - origin.validate(session)?; - authenticate() - })(); + let checked = Self::recheck(origin, session, &mut authenticate); + self.settle(operation, checked) + } + fn recheck( + origin: &TargetStepOrigin, + session: &QwenSession<'ctx>, + authenticate: &mut impl FnMut() -> Result<()>, + ) -> Result<()> { + origin.validate(session)?; + authenticate() + } + fn settle(&mut self, operation: Result, checked: Result<()>) -> Result { if operation.is_err() || checked.is_err() || self.context.is_poisoned() { self.failed = true; } @@ -132,6 +91,80 @@ impl<'ctx> OriginalNativePenaltyHistory<'ctx> { } } } + fn admit_window( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + origin: &TargetStepOrigin, + tail: &[i32], + window: &[i32], + params: &SamplerParams, + ) -> Result<()> { + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + self.check_identity(binding, session, origin, tail, window)?; + params.validate().map_err(driver)?; + let vocabulary = 248320; + if window.iter().any(|&id| id < 0 || id >= vocabulary) || !self.tail_checked.in_range(tail, vocabulary) { + return Err(Error::InvalidToken); + } + origin.next_position().checked_add(window.len() as u64).ok_or(Error::Overflow)?; + Ok(()) + } + fn check_identity( + &self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + origin: &TargetStepOrigin, + tail: &[i32], + window: &[i32], + ) -> Result<()> { + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(self.context, session.mtp_context()?) + || !(1..=ROWS).contains(&window.len()) + || tail.len() as u64 != origin.next_position() + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + fn upload_penalty_rows(&mut self, tail: &[i32], window: &[i32], h: usize) -> Result<()> { + if h == 0 { + return Ok(()); + } + // Literal penalty_rows: row t sees tail plus window[0..=t], most + // recent token last and the unavailable prefix padded with -1. + for t in 0..window.len() { + self.fill_penalty_row(tail, window, h, t)?; + } + let used = window.len() * h * 4; + let upload = self + .device + .as_mut() + .ok_or(Error::IdentityMismatch)? + .copy_from_range(0, &self.staging[..used]) + .map_err(driver); + if upload.is_err() || self.context.is_poisoned() { + self.failed = true; + } + upload + } + fn fill_penalty_row(&mut self, tail: &[i32], window: &[i32], h: usize, t: usize) -> Result<()> { + let available = tail.len().checked_add(t + 1).ok_or(Error::Overflow)?; + let take = h.min(available); + for j in 0..h { + let value = if j < h - take { + -1 + } else { + let i = available - take + j - (h - take); + if i < tail.len() { tail[i] } else { window[i - tail.len()] } + }; + let offset = (t * h + j) * 4; + self.staging[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + } + Ok(()) + } pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { self.close_inner() } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/owner_wall_profile.rs b/crates/engine-qwen35-cuda/src/qwen_forward/owner_wall_profile.rs index 5969cd71..b2eb5f4c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/owner_wall_profile.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/owner_wall_profile.rs @@ -126,32 +126,40 @@ impl Drop for Scope { return; }; let elapsed = u64::try_from(started.elapsed().as_nanos()); - let recorded = STATE.try_with(|cell| { - let Ok(mut state) = cell.try_borrow_mut() else { - recording_fault(); - return; - }; - if !state.active || state.generation != generation || state.in_flight == 0 { - state.invalid = true; - return; - } - state.in_flight -= 1; - let Ok(elapsed) = elapsed else { - state.invalid = true; - return; - }; - let totals = &mut state.totals[self.stage as usize]; - let update = totals.count.checked_add(1).zip(totals.total_ns.checked_add(elapsed)); - if let Some((count, total_ns)) = update { - totals.count = count; - totals.total_ns = total_ns; - totals.max_ns = totals.max_ns.max(elapsed); - } else { - state.invalid = true; - } - }); + let recorded = STATE.try_with(|cell| leave(cell, self.stage, generation, elapsed)); if recorded.is_err() { recording_fault(); } } } + +fn leave(cell: &RefCell, stage: Stage, generation: u64, elapsed: Result) { + let Ok(mut state) = cell.try_borrow_mut() else { + recording_fault(); + return; + }; + if !state.active || state.generation != generation || state.in_flight == 0 { + state.invalid = true; + return; + } + state.in_flight -= 1; + let Ok(elapsed) = elapsed else { + state.invalid = true; + return; + }; + state.add(stage, elapsed); +} + +impl State { + fn add(&mut self, stage: Stage, elapsed: u64) { + let totals = &mut self.totals[stage as usize]; + let update = totals.count.checked_add(1).zip(totals.total_ns.checked_add(elapsed)); + if let Some((count, total_ns)) = update { + totals.count = count; + totals.total_ns = total_ns; + totals.max_ns = totals.max_ns.max(elapsed); + } else { + self.invalid = true; + } + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs index 09ab04e8..13e30ba2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs @@ -184,6 +184,24 @@ pub(crate) fn begin_chunk() { CHUNK.with(|c| *c.borrow_mut() = Some(Instant::now())); } +/// The top-level spans of a chunk (the nested moe.* and inject spans are excluded). +const TOP_LEVEL: [Stage; 14] = [ + Stage::Input, + Stage::Initialize, + Stage::Ple, + Stage::Validate, + Stage::AttnRead, + Stage::Gdn, + Stage::Qsa, + Stage::FfnRead, + Stage::Moe, + Stage::Final, + Stage::DraftKv, + Stage::FinishPreview, + Stage::Publish, + Stage::Lend, +]; + /// Print the chunk's breakdown (`tokens` rows, starting at `first`) and reset. pub(crate) fn end_chunk(first: u64, tokens: usize) { if !enabled() { @@ -205,24 +223,8 @@ pub(crate) fn end_chunk(first: u64, tokens: usize) { line.push_str(&format!(" {}={:.1}", stage.name(), ms(value))); } } - // Time of the chunk outside every top-level span (the nested moe.* and inject spans are excluded). - let top = [ - Stage::Input, - Stage::Initialize, - Stage::Ple, - Stage::Validate, - Stage::AttnRead, - Stage::Gdn, - Stage::Qsa, - Stage::FfnRead, - Stage::Moe, - Stage::Final, - Stage::DraftKv, - Stage::FinishPreview, - Stage::Publish, - Stage::Lend, - ]; - let covered: Duration = top.iter().map(|s| acc[s.index()]).sum(); + let covered: Duration = TOP_LEVEL.iter().map(|s| acc[s.index()]).sum(); + // Time of the chunk outside every top-level span. line.push_str(&format!(" other={:.1}", ms(total.saturating_sub(covered)))); eprintln!("{line}"); let commands = leleka_cuda_driver::command_profile::take_report(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs index 8e6625b1..35cfab48 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs @@ -84,4 +84,4 @@ use impl_promptdeviceread::produce_original_gdn; use impl_promptdeviceread::produce_original_qsa; mod impl_promptplehistory; #[allow(unused_imports)] -use impl_promptplehistory::micro_driver_error; +use impl_promptplehistory::{micro_driver_error, run_transfer}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs index 7565a110..03796fa6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs @@ -1,5 +1,6 @@ //! Moved out of the parent module by STRA-338: impl PromptDeviceRead. +use super::produce_original_gdn_fn::{GdnLayer, Lap, QsaLayerDevices, inject_span, produce_block}; #[allow(unused_imports)] use super::*; @@ -29,6 +30,22 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx pub(in crate::qwen_forward) fn device(&self) -> &OriginalDeviceGrRead<'arena, 'loan, 'ctx> { &self.device } + /// The attention layer these rows are at (the producer's layer id) and the context, in the phase `same_phase` accepts. + fn attention_layer( + &self, + same_phase: impl FnOnce(&OriginalPromptPhase) -> bool, + ) -> Result<(LayerId, &'ctx Context<'ctx>)> { + let layer = match self.sources.role { + GrRole::Attention(layer) => layer, + _ => return Err(Error::IdentityMismatch), + }; + let layer = LayerId::new(layer as u64, Dimension::new(48)?)?; + let context = self.sources.context; + if self.sources.original_phase()?.is_none_or(|phase| !same_phase(&phase)) { + return Err(Error::IdentityMismatch); + } + Ok((layer, context)) + } /// Full prompt GDN projections/conv/recurrence/Out consume the real Read. /// Only its genuine completed end recurrence/history enters the journal. pub(in crate::qwen_forward) fn complete_original_gdn( @@ -39,37 +56,12 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx producer: &mut OriginalPromptDevice<'ctx>, gdn: &mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, ) -> Result> { - let layer = match self.sources.role { - GrRole::Attention(layer) => layer, - _ => return Err(Error::IdentityMismatch), - }; - let layer = LayerId::new(layer as u64, Dimension::new(48)?)?; - let context = self.sources.context; - if self.sources.original_phase()?.is_none_or(|phase| !phase.same(&txn.phase())) { - return Err(Error::IdentityMismatch); - } + let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?; self.complete_with(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { - let prior = txn.gdn_prior(layer)?; - let (start, rows) = - super::super::super::session::chunk::GdnChunkStart::from_original_prompt(txn, layer, &prior)?; - let mut owner = - super::super::super::gdn::chunk_device::GdnChunkDevice::new(binding, context, dense, start.clone())?; - let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - let (block, edges) = super::super::super::gdn::GdnStage::produce_prompt_device( - binding, - layer, - dense, - context, - &mut owner, - rows, - read, - gdn, - &mut workspace, - )?; - drop(workspace); - let seal = super::super::super::session::chunk::GdnChunkSeal::from_original_prompt(txn, &start, edges)?; - let next = owner.finish(seal, binding, dense)?; - txn.stage_gdn(&prior, next)?; + let mut lap = Lap::off(); + let (mut state, rows) = GdnLayer::enter(binding, dense, txn, context, layer, &mut lap)?; + let (block, edges) = state.compute(binding, dense, rows, read, gdn)?; + state.leave(binding, dense, txn, edges, &mut lap)?; Ok(block) }) } @@ -81,15 +73,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx producer: &mut OriginalPromptDevice<'ctx>, gdn: &mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, ) -> Result> { - let layer = match self.sources.role { - GrRole::Attention(layer) => layer, - _ => return Err(Error::IdentityMismatch), - }; - let layer = LayerId::new(layer as u64, Dimension::new(48)?)?; - let context = self.sources.context; - if self.sources.original_phase()?.is_none_or(|phase| !phase.same(&txn.phase())) { - return Err(Error::IdentityMismatch); - } + let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?; self.complete_with_normed(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { produce_original_gdn(binding, dense, txn, context, layer, read, gdn) }) @@ -105,17 +89,10 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx transport: &mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, attention: &mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, ) -> Result> { - let layer = match self.sources.role { - GrRole::Attention(layer) => layer, - _ => return Err(Error::IdentityMismatch), - }; - let layer = LayerId::new(layer as u64, Dimension::new(48)?)?; - let context = self.sources.context; - if self.sources.original_phase()?.is_none_or(|phase| !phase.same(&txn.phase())) { - return Err(Error::IdentityMismatch); - } + let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?; self.complete_with(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { - produce_original_qsa(binding, dense, txn, context, layer, read, layer_owner, qsa, transport, attention) + let devices = QsaLayerDevices { layer_owner, qsa, transport, attention }; + produce_original_qsa(binding, dense, txn, context, layer, read, devices) }) } pub(in crate::qwen_forward) fn complete_original_qsa_normed<'weight>( @@ -129,17 +106,10 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx transport: &mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, attention: &mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, ) -> Result> { - let layer = match self.sources.role { - GrRole::Attention(layer) => layer, - _ => return Err(Error::IdentityMismatch), - }; - let layer = LayerId::new(layer as u64, Dimension::new(48)?)?; - let context = self.sources.context; - if self.sources.original_phase()?.is_none_or(|phase| !phase.same(&txn.phase())) { - return Err(Error::IdentityMismatch); - } + let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?; self.complete_with_normed(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { - produce_original_qsa(binding, dense, txn, context, layer, read, layer_owner, qsa, transport, attention) + let devices = QsaLayerDevices { layer_owner, qsa, transport, attention }; + produce_original_qsa(binding, dense, txn, context, layer, read, devices) }) } /// Complete actual FFN arithmetic on the same physical arena, then the @@ -198,6 +168,24 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx next_role: GrRole, produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> Result>, ) -> Result> { + self.check_next_role(binding, cache, next_role)?; + let block = produce_block(self.device, produce)?; + self.sources.validate(binding, cache)?; + let context = self.sources.context; + let span = inject_span(context); + let device = run_transfer(binding, cache, context, producer, span, |producer, workspace| { + producer.inject_gr(block, workspace).map_err(micro_driver_error) + })?; + self.sources.validate(binding, cache)?; + if let Some(phase) = self.sources.original_phase()? { + phase.inject(self.sources.role, next_role)?; + } + let mut sources = self.sources; + sources.role = next_role; + sources.validated = 0; + Ok(PromptDeviceRows { sources, device }) + } + fn check_next_role(&self, binding: &ModelBinding, cache: &DenseWeightCache<'ctx>, next_role: GrRole) -> Result<()> { self.sources.validate(binding, cache)?; if self.sources.validated != self.sources.rows.len() { return Err(Error::IdentityMismatch); @@ -213,33 +201,6 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx if next_role != expected { return Err(Error::IdentityMismatch); } - let identity = self.device.lease_identity(); - let block = produce(self.device)?; - if !identity.same_lease(&block.lease_identity()) { - return Err(Error::IdentityMismatch); - } - self.sources.validate(binding, cache)?; - let context = self.sources.context; - let inject_span = super::super::super::prefill_profile::span( - super::super::super::prefill_profile::Stage::Inject, - Some(context as &dyn super::super::super::prefill_profile::Drain), - ); - let result = (|| { - let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - producer.inject_gr(block, &mut workspace).map_err(micro_driver_error) - })(); - drop(inject_span); - if producer.is_failed() { - cache.transport_failure_flag(binding, context)?.set(true) - } - let device = result?; - self.sources.validate(binding, cache)?; - if let Some(phase) = self.sources.original_phase()? { - phase.inject(self.sources.role, next_role)?; - } - let mut sources = self.sources; - sources.role = next_role; - sources.validated = 0; - Ok(PromptDeviceRows { sources, device }) + Ok(()) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs index fb8a9e9c..99823665 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs @@ -3,6 +3,101 @@ #[allow(unused_imports)] use super::*; +use super::super::super::gdn::GdnPrior; +use super::super::super::gdn::chunk_device::{ChunkEdge, GdnChunkDevice}; +use super::super::super::qsa_index::prompt_device::resident_device::{ + ResidentQsaCompleted, ResidentQsaLayer, ResidentQsaPrior, ResidentQsaSelection, +}; +use super::super::super::session::chunk::{GdnChunkRow, GdnChunkSeal, GdnChunkStart}; +use std::cell::RefMut; + +/// Host timing laps of one prompt layer producer (`command_profile`): recorded only when that is enabled. +pub(super) struct Lap { + timed: bool, + mark: std::time::Instant, + tag: &'static str, +} +impl Lap { + pub(super) fn new(tag: &'static str) -> Self { + Self { timed: leleka_cuda_driver::command_profile::enabled(), mark: std::time::Instant::now(), tag } + } + /// A lap that never records. + pub(super) fn off() -> Self { + Self { timed: false, mark: std::time::Instant::now(), tag: "" } + } + pub(super) fn at(&mut self, index: usize, label: &'static str) { + if self.timed { + leleka_cuda_driver::command_profile::record(self.tag, index, label, self.mark.elapsed()); + self.mark = std::time::Instant::now(); + } + } +} + +/// One prompt GDN layer between its state-in and its state-out: the prior, the chunk start and the device owner. +pub(super) struct GdnLayer<'ctx> { + context: &'ctx Context<'ctx>, + layer: LayerId, + prior: GdnPrior, + start: GdnChunkStart, + owner: GdnChunkDevice<'ctx>, +} +impl<'ctx> GdnLayer<'ctx> { + pub(super) fn enter( + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + context: &'ctx Context<'ctx>, + layer: LayerId, + lap: &mut Lap, + ) -> Result<(Self, Vec)> { + let prior = txn.gdn_prior(layer)?; + lap.at(1, "in: gdn_prior"); + let (start, rows) = GdnChunkStart::from_original_prompt(txn, layer, &prior)?; + lap.at(2, "in: chunk start + row keys"); + let owner = GdnChunkDevice::new(binding, context, dense, start.clone())?; + lap.at(3, "in: chunk device (state upload, alloc)"); + Ok((Self { context, layer, prior, start, owner }, rows)) + } + pub(super) fn compute<'arena, 'loan>( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + rows: Vec, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + gdn: &mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, + ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, Vec)> { + let context = self.context; + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + super::super::super::gdn::GdnStage::produce_prompt_device( + binding, + self.layer, + dense, + context, + &mut self.owner, + rows, + read, + gdn, + &mut workspace, + ) + } + pub(super) fn leave( + self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + edges: Vec, + lap: &mut Lap, + ) -> Result<()> { + let seal = GdnChunkSeal::from_original_prompt(txn, &self.start, edges)?; + lap.at(5, "out: seal (row edges)"); + let next = self.owner.finish(seal, binding, dense)?; + lap.at(6, "out: owner.finish (download, mirror)"); + txn.stage_gdn(&self.prior, next)?; + lap.at(7, "out: stage_gdn"); + Ok(()) + } +} + /// End-state is staged only from the same completed whole-layer producer. pub(in super::super) fn produce_original_gdn<'arena, 'loan, 'ctx>( binding: &ModelBinding, @@ -15,49 +110,113 @@ pub(in super::super) fn produce_original_gdn<'arena, 'loan, 'ctx>( ) -> Result> { use super::super::super::prefill_profile::{Drain, Stage as P, span}; let drain = Some(context as &dyn Drain); - let timed = leleka_cuda_driver::command_profile::enabled(); - let mut mark = std::time::Instant::now(); - let mut lap = |index: usize, label: &'static str| { - if timed { - leleka_cuda_driver::command_profile::record("gdn-host", index, label, mark.elapsed()); - mark = std::time::Instant::now(); - } - }; + let mut lap = Lap::new("gdn-host"); let state_in = span(P::GdnStateIn, drain); - let prior = txn.gdn_prior(layer)?; - lap(1, "in: gdn_prior"); - let (start, rows) = super::super::super::session::chunk::GdnChunkStart::from_original_prompt(txn, layer, &prior)?; - lap(2, "in: chunk start + row keys"); - let mut owner = - super::super::super::gdn::chunk_device::GdnChunkDevice::new(binding, context, dense, start.clone())?; - lap(3, "in: chunk device (state upload, alloc)"); + let (mut state, rows) = GdnLayer::enter(binding, dense, txn, context, layer, &mut lap)?; drop(state_in); let compute = span(P::GdnCompute, drain); - let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - let (block, edges) = super::super::super::gdn::GdnStage::produce_prompt_device( - binding, - layer, - dense, - context, - &mut owner, - rows, - read, - gdn, - &mut workspace, - )?; - drop(workspace); + let (block, edges) = state.compute(binding, dense, rows, read, gdn)?; drop(compute); - lap(4, "compute: produce_prompt_device"); + lap.at(4, "compute: produce_prompt_device"); let _state_out = span(P::GdnStateOut, drain); - let seal = super::super::super::session::chunk::GdnChunkSeal::from_original_prompt(txn, &start, edges)?; - lap(5, "out: seal (row edges)"); - let next = owner.finish(seal, binding, dense)?; - lap(6, "out: owner.finish (download, mirror)"); - txn.stage_gdn(&prior, next)?; - lap(7, "out: stage_gdn"); + state.leave(binding, dense, txn, edges, &mut lap)?; Ok(block) } -#[allow(clippy::too_many_arguments)] + +/// The devices of one resident QSA layer: its index/KV owner, the prompt producer, the transport and the attention. +pub(in super::super) struct QsaLayerDevices<'a, 'ctx> { + pub(in super::super) layer_owner: &'a mut ResidentQsaLayer<'ctx>, + pub(in super::super) qsa: &'a mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, + pub(in super::super) transport: &'a mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, + pub(in super::super) attention: &'a mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, +} + +/// One prompt QSA layer between its host setup and its stage: inputs, prior and the batch workspace. +struct QsaLayerRun<'a, 's, 'ctx> { + binding: &'a ModelBinding, + dense: &'a DenseWeightCache<'ctx>, + txn: &'a OriginalPromptTxn<'s, 'ctx>, + inputs: Vec<&'a InputReady>, + prior: ResidentQsaPrior<'ctx>, + workspace: RefMut<'a, leleka_cuda_driver::NativeBatchWorkspace<'ctx>>, + lap: Lap, +} +impl<'a, 's, 'ctx> QsaLayerRun<'a, 's, 'ctx> { + fn new( + binding: &'a ModelBinding, + dense: &'a DenseWeightCache<'ctx>, + txn: &'a OriginalPromptTxn<'s, 'ctx>, + context: &'ctx Context<'ctx>, + layer: LayerId, + ) -> Result { + let mut lap = Lap::new("qsa-host"); + txn.validate_phase(GrRole::Attention(layer.get()), true)?; + let inputs = txn.input_references()?; + let prior = txn.qsa_prior(binding, layer)?; + let workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + lap.at(1, "host setup"); + Ok(Self { binding, dense, txn, inputs, prior, workspace, lap }) + } + /// The layer's prior-KV prefix copy starts on a side stream now and overlaps the projections and the indexer + /// (a no-op unless LELEKA_PREFILL_QSA_PREFETCH). + fn prepare<'lease, 'index, 'arena, 'loan>( + &mut self, + layer_owner: &'index mut ResidentQsaLayer<'ctx>, + qsa: &'lease mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, + transport: &mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + ) -> Result> { + layer_owner.begin_prefix(&mut self.workspace, transport, &self.prior, &read)?; + let session = self.txn.original_session(); + let prepared = layer_owner.prepare( + self.binding, + self.dense, + session, + &self.inputs, + &self.prior, + qsa, + read, + &mut self.workspace, + ); + let selected = match prepared { + Ok(selected) => selected, + Err(error) => { + let _ = transport.cancel_prefix(); + return Err(error); + } + }; + self.lap.at(2, "prepare (index, projections)"); + Ok(selected) + } + fn complete<'lease, 'index, 'arena, 'loan>( + &mut self, + selected: ResidentQsaSelection<'lease, 'index, 'a, 'arena, 'loan, 'ctx>, + transport: &mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, + attention: &mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, + ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, ResidentQsaCompleted<'index, 'a, 'ctx>)> { + let session = self.txn.original_session(); + let done = selected.complete(self.binding, self.dense, session, &mut self.workspace, transport, attention)?; + self.lap.at(3, "complete (kv, attention, out)"); + Ok(done) + } + fn seal( + mut self, + completed: ResidentQsaCompleted<'_, '_, 'ctx>, + qsa: &mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, + ) -> Result<()> { + let session = self.txn.original_session(); + completed.validate_rows(self.binding, self.dense, session, &self.inputs)?; + self.lap.at(4, "validate_rows"); + let accepted = self.txn.len(); + let ws = &mut self.workspace; + let seal = completed.seal_prefix(self.binding, self.dense, session, &self.inputs, qsa, ws, accepted)?; + self.lap.at(5, "seal_prefix"); + drop(self.workspace); + self.txn.stage_qsa(self.binding, self.dense, seal)?; + self.lap.at(6, "stage_qsa"); + Ok(()) + } +} pub(in super::super) fn produce_original_qsa<'arena, 'loan, 'ctx>( binding: &ModelBinding, dense: &DenseWeightCache<'ctx>, @@ -65,46 +224,13 @@ pub(in super::super) fn produce_original_qsa<'arena, 'loan, 'ctx>( context: &'ctx Context<'ctx>, layer: LayerId, read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, - layer_owner: &mut super::super::super::qsa_index::prompt_device::resident_device::ResidentQsaLayer<'ctx>, - qsa: &mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, - transport: &mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, - attention: &mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, + devices: QsaLayerDevices<'_, 'ctx>, ) -> Result> { - let timed = leleka_cuda_driver::command_profile::enabled(); - let mut mark = std::time::Instant::now(); - let mut lap = |index: usize, label: &'static str| { - if timed { - leleka_cuda_driver::command_profile::record("qsa-host", index, label, mark.elapsed()); - mark = std::time::Instant::now(); - } - }; - txn.validate_phase(GrRole::Attention(layer.get()), true)?; - let inputs = txn.input_references()?; - let prior = txn.qsa_prior(binding, layer)?; - let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - lap(1, "host setup"); - // the layer's prior-KV prefix copy starts on a side stream now and overlaps the projections and the indexer (a no-op unless LELEKA_PREFILL_QSA_PREFETCH) - layer_owner.begin_prefix(&mut workspace, transport, &prior, &read)?; - let selected = - match layer_owner.prepare(binding, dense, txn.original_session(), &inputs, &prior, qsa, read, &mut workspace) { - Ok(selected) => selected, - Err(error) => { - let _ = transport.cancel_prefix(); - return Err(error); - } - }; - lap(2, "prepare (index, projections)"); - let (block, completed) = - selected.complete(binding, dense, txn.original_session(), &mut workspace, transport, attention)?; - lap(3, "complete (kv, attention, out)"); - completed.validate_rows(binding, dense, txn.original_session(), &inputs)?; - lap(4, "validate_rows"); - let seal = - completed.seal_prefix(binding, dense, txn.original_session(), &inputs, qsa, &mut workspace, txn.len())?; - lap(5, "seal_prefix"); - drop(workspace); - txn.stage_qsa(binding, dense, seal)?; - lap(6, "stage_qsa"); + let QsaLayerDevices { layer_owner, qsa, transport, attention } = devices; + let mut run = QsaLayerRun::new(binding, dense, txn, context, layer)?; + let selected = run.prepare(layer_owner, qsa, transport, read)?; + let (block, completed) = run.complete(selected, transport, attention)?; + run.seal(completed, qsa)?; Ok(block) } impl<'weight, 'source, 'arena, 'loan, 'ctx> PromptDeviceNormedRows<'weight, 'source, 'arena, 'loan, 'ctx> { @@ -136,29 +262,9 @@ impl<'weight, 'source, 'arena, 'loan, 'ctx> PromptDeviceNormedRows<'weight, 'sou cache: &DenseWeightCache<'ctx>, producer: &mut OriginalPromptDevice<'ctx>, ) -> Result> { - self.sources.validate(binding, cache)?; - if self.sources.validated != self.sources.rows.len() { - return Err(Error::IdentityMismatch); - } - if let Some(phase) = self.sources.original_phase()? { - phase.prepare_read(self.sources.role)?; - } + self.sources.begin_read(binding, cache, self.sources.role)?; let context = self.sources.context; - let resident = cache.gr(binding, self.sources.role)?; - if !resident.weights.matches(&binding.identity(), self.sources.role) { - return Err(Error::IdentityMismatch); - } - let [gamma, down, up, inject] = cache.gr_buffers(resident)?.map(|w| w.ok_or(Error::IdentityMismatch)); - let result = (|| { - let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - producer - .read_gr_normed(self.device, &mut workspace, [gamma?, down?, up?, inject?], resident.weights.epsilon()) - .map_err(micro_driver_error) - })(); - if producer.is_failed() { - cache.transport_failure_flag(binding, context)?.set(true) - } - let device = result?; + let device = Self::read_device(self.device, binding, cache, context, producer, self.sources.role)?; self.sources.validate(binding, cache)?; if let Some(phase) = self.sources.original_phase()? { phase.read(self.sources.role)?; @@ -167,6 +273,25 @@ impl<'weight, 'source, 'arena, 'loan, 'ctx> PromptDeviceNormedRows<'weight, 'sou sources.validated = 0; Ok(PromptDeviceRead { sources, device }) } + fn read_device( + device: OriginalDeviceNormedResidual<'weight, 'arena, 'loan, 'ctx>, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + context: &Context<'_>, + producer: &mut OriginalPromptDevice<'ctx>, + role: GrRole, + ) -> Result> { + let resident = cache.gr(binding, role)?; + if !resident.weights.matches(&binding.identity(), role) { + return Err(Error::IdentityMismatch); + } + let [gamma, down, up, inject] = cache.gr_buffers(resident)?.map(|w| w.ok_or(Error::IdentityMismatch)); + run_transfer(binding, cache, context, producer, (), |producer, workspace| { + producer + .read_gr_normed(device, workspace, [gamma?, down?, up?, inject?], resident.weights.epsilon()) + .map_err(micro_driver_error) + }) + } } impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx> { /// Original caller eligibility additionally excludes cvec/unfused modes. @@ -180,6 +305,30 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx next_role: GrRole, produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> Result>, ) -> Result> { + self.check_normed_step(binding, cache, next_role)?; + let (gamma, epsilon) = normed_gamma(binding, cache, next_role)?; + let block = produce_block(self.device, produce)?; + self.sources.validate(binding, cache)?; + let context = self.sources.context; + let span = inject_span(context); + let device = run_transfer(binding, cache, context, producer, span, |producer, workspace| { + producer.inject_gr_fused(block, workspace, gamma, epsilon).map_err(micro_driver_error) + })?; + self.sources.validate(binding, cache)?; + if let Some(phase) = self.sources.original_phase()? { + phase.inject(self.sources.role, next_role)?; + } + let mut sources = self.sources; + sources.role = next_role; + sources.validated = 0; + Ok(PromptDeviceNormedRows { sources, device }) + } + fn check_normed_step( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + next_role: GrRole, + ) -> Result<()> { self.sources.validate(binding, cache)?; if self.sources.validated != self.sources.rows.len() { return Err(Error::IdentityMismatch); @@ -196,40 +345,39 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx if next_role != expected || next_role == GrRole::Attention(1) || layer >= binding.layer_count() { return Err(Error::IdentityMismatch); } - let resident = cache.gr(binding, next_role)?; - if !resident.weights.matches(&binding.identity(), next_role) { - return Err(Error::IdentityMismatch); - } - let gamma = cache.gr_buffers(resident)?[0].ok_or(Error::IdentityMismatch)?; - let identity = self.device.lease_identity(); - let block = produce(self.device)?; - if !identity.same_lease(&block.lease_identity()) { - return Err(Error::IdentityMismatch); - } - self.sources.validate(binding, cache)?; - let context = self.sources.context; - let inject_span = super::super::super::prefill_profile::span( - super::super::super::prefill_profile::Stage::Inject, - Some(context as &dyn super::super::super::prefill_profile::Drain), - ); - let result = (|| { - let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - producer - .inject_gr_fused(block, &mut workspace, gamma, resident.weights.epsilon()) - .map_err(micro_driver_error) - })(); - drop(inject_span); - if producer.is_failed() { - cache.transport_failure_flag(binding, context)?.set(true) - } - let device = result?; - self.sources.validate(binding, cache)?; - if let Some(phase) = self.sources.original_phase()? { - phase.inject(self.sources.role, next_role)?; - } - let mut sources = self.sources; - sources.role = next_role; - sources.validated = 0; - Ok(PromptDeviceNormedRows { sources, device }) + Ok(()) } } + +/// The next layer's gamma (the norm the fused injection carries) and its epsilon. +fn normed_gamma<'w, 'ctx>( + binding: &ModelBinding, + cache: &'w DenseWeightCache<'ctx>, + role: GrRole, +) -> Result<(&'w leleka_cuda_driver::DeviceBuffer<'ctx>, f32)> { + let resident = cache.gr(binding, role)?; + if !resident.weights.matches(&binding.identity(), role) { + return Err(Error::IdentityMismatch); + } + let gamma = cache.gr_buffers(resident)?[0].ok_or(Error::IdentityMismatch)?; + Ok((gamma, resident.weights.epsilon())) +} + +/// The producer consumes the device read and must return a block of the very same lease. +pub(super) fn produce_block<'arena, 'loan, 'ctx>( + device: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> Result>, +) -> Result> { + let identity = device.lease_identity(); + let block = produce(device)?; + if !identity.same_lease(&block.lease_identity()) { + return Err(Error::IdentityMismatch); + } + Ok(block) +} + +/// The profiling span of the GR injection, synchronized with the context when `LELEKA_PREFILL_PROFILE_SYNC` is set. +pub(super) fn inject_span<'a>(context: &'a Context<'_>) -> super::super::super::prefill_profile::Span<'a> { + use super::super::super::prefill_profile::{Drain, Stage, span}; + span(Stage::Inject, Some(context as &dyn Drain)) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs index 9b82d22b..18fa447a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs @@ -53,3 +53,25 @@ pub(super) fn micro_driver_error(error: leleka_cuda_driver::Error) -> Error { _ => Error::CudaExecution, } } + +/// One producer transfer under the cache's native batch workspace. `span` (a profiling guard, or `()`) ends as soon as +/// the transfer has returned; a producer that failed then marks the transport failed, before the transfer's own result +/// is handed back. +pub(super) fn run_transfer<'ctx, T>( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + context: &Context<'_>, + producer: &mut OriginalPromptDevice<'ctx>, + span: impl Sized, + transfer: impl FnOnce(&mut OriginalPromptDevice<'ctx>, &mut leleka_cuda_driver::NativeBatchWorkspace<'ctx>) -> Result, +) -> Result { + let result = (|| { + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + transfer(&mut *producer, &mut workspace) + })(); + drop(span); + if producer.is_failed() { + cache.transport_failure_flag(binding, context)?.set(true) + } + result +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs index 72f2e445..74530906 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs @@ -4,15 +4,13 @@ use super::*; impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> { - /// Original Prefill consumes only the known-next conditioning prefix. - /// Keep the genuine all-row residual on device for the shifted MTP input; - /// the final seed is handled by Verifier, not by this prefill producer. - pub(in crate::qwen_forward) fn preview_conditioning( - &mut self, + /// The final phase of `txn` is the one these rows hold: its phase, and the last row's token and position. + fn final_point( + &self, binding: &ModelBinding, cache: &DenseWeightCache<'ctx>, txn: &OriginalPromptTxn<'_, '_>, - ) -> Result { + ) -> Result<(Rc, TokenId, Position)> { self.sources.validate(binding, cache)?; txn.validate_phase(GrRole::Final, false)?; if self.sources.role != GrRole::Final || self.sources.rows.len() != txn.len() { @@ -26,6 +24,18 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx if last.input.position().get().checked_add(1) != Some(txn.end_position()) { return Err(Error::IdentityMismatch); } + Ok((phase, last.input.token(), last.input.position())) + } + /// Original Prefill consumes only the known-next conditioning prefix. + /// Keep the genuine all-row residual on device for the shifted MTP input; + /// the final seed is handled by Verifier, not by this prefill producer. + pub(in crate::qwen_forward) fn preview_conditioning( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + ) -> Result { + let (phase, token, position) = self.final_point(binding, cache, txn)?; let known_next = txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; let lease_identity = self.device.lease_identity(); self.device.resolve_guards().map_err(micro_driver_error)?; @@ -33,8 +43,8 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx Ok(PromptDeviceFinal { binding: binding.identity(), phase, - token: last.input.token(), - position: last.input.position(), + token, + position, product: FinalProduct::DeviceConditioning { known_next }, lease_identity, }) @@ -47,19 +57,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx cache: &DenseWeightCache<'ctx>, txn: &OriginalPromptTxn<'_, '_>, ) -> Result { - self.sources.validate(binding, cache)?; - txn.validate_phase(GrRole::Final, false)?; - if self.sources.role != GrRole::Final || self.sources.rows.len() != txn.len() { - return Err(Error::IdentityMismatch); - } - let phase = self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; - if !phase.same(&txn.phase()) { - return Err(Error::IdentityMismatch); - } - let last = self.sources.rows.last().ok_or(Error::IdentityMismatch)?; - if last.input.position().get().checked_add(1) != Some(txn.end_position()) { - return Err(Error::IdentityMismatch); - } + let (phase, token, position) = self.final_point(binding, cache, txn)?; let lease_identity = self.device.lease_identity(); let streams = self.device.read_prompt_row(txn.len() - 1).map_err(micro_driver_error)?; self.sources.validate(binding, cache)?; @@ -70,8 +68,8 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx Ok(PromptDeviceFinal { binding: binding.identity(), phase, - token: last.input.token(), - position: last.input.position(), + token, + position, product: FinalProduct::Host(streams), lease_identity, }) @@ -138,19 +136,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx cache: &DenseWeightCache<'ctx>, txn: &OriginalPromptTxn<'_, '_>, ) -> Result { - self.sources.validate(binding, cache)?; - txn.validate_phase(GrRole::Final, false)?; - if self.sources.role != GrRole::Final || self.sources.rows.len() != txn.len() { - return Err(Error::IdentityMismatch); - } - let phase = self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; - if !phase.same(&txn.phase()) { - return Err(Error::IdentityMismatch); - } - let last = self.sources.rows.last().ok_or(Error::IdentityMismatch)?; - if last.input.position().get().checked_add(1) != Some(txn.end_position()) { - return Err(Error::IdentityMismatch); - } + let (phase, token, position) = self.final_point(binding, cache, txn)?; let lease_identity = self.device.lease_identity(); let streams = self.device.finish_prompt_row(txn.len() - 1).map_err(micro_driver_error)?; self.sources.validate(binding, cache)?; @@ -158,8 +144,8 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx Ok(PromptDeviceFinal { binding: binding.identity(), phase, - token: last.input.token(), - position: last.input.position(), + token, + position, product: FinalProduct::Host(streams), lease_identity, }) @@ -182,36 +168,34 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx // Only initial real source staging: Original also uploads initial R // and PLE embeddings. Later layer phases retain this same device R. // The driver stages every row's streams and PLE embedding in place (one pass, same bytes and refusals). - let deferred = sources.rows.iter().filter(|s| s.input.is_deferred()).count(); - if deferred != 0 && (deferred != sources.rows.len() || stage.is_none()) || deferred == 0 && stage.is_some() { - return Err(Error::IdentityMismatch); - } - let result = if let Some(stage) = stage { - (|| { - let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - producer.initialize_staged(lease, &mut workspace, stage).map_err(micro_driver_error) - })() - } else { - let mut slices = Vec::new(); - slices.try_reserve_exact(sources.rows.len()).map_err(|_| Error::InputAllocation)?; - for s in &sources.rows { - slices.push((s.input.streams().values(), s.input.ple_embedding())); - } - (|| { - let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - producer.initialize_rows(lease, &mut workspace, &slices).map_err(micro_driver_error) - })() - }; - if producer.is_failed() { - cache.transport_failure_flag(binding, context)?.set(true) - } - let device = result?; - sources.validate(binding, cache)?; - if let Some(phase) = sources.original_phase()? { - phase.initialize(sources.rows.len())?; - } + sources.check_staging(stage.is_some())?; + let device = Self::stage_rows(binding, cache, context, producer, lease, &sources, stage)?; + sources.finish_initialize(binding, cache)?; Ok(Self { sources, device }) } + fn stage_rows( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + context: &Context<'_>, + producer: &mut OriginalPromptDevice<'ctx>, + lease: OriginalPromptRows<'arena, 'loan, 'ctx>, + sources: &Sources<'source, 'ctx>, + stage: Option>, + ) -> Result> { + if let Some(stage) = stage { + return run_transfer(binding, cache, context, producer, (), |producer, workspace| { + producer.initialize_staged(lease, workspace, stage).map_err(micro_driver_error) + }); + } + let mut slices = Vec::new(); + slices.try_reserve_exact(sources.rows.len()).map_err(|_| Error::InputAllocation)?; + for s in &sources.rows { + slices.push((s.input.streams().values(), s.input.ple_embedding())); + } + run_transfer(binding, cache, context, producer, (), |producer, workspace| { + producer.initialize_rows(lease, workspace, &slices).map_err(micro_driver_error) + }) + } pub(in crate::qwen_forward) fn validate_original_rows( &mut self, binding: &ModelBinding, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs index 289b2dfa..8853dee1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs @@ -11,6 +11,26 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx producer: &mut OriginalPromptDevice<'ctx>, history: &mut PromptPleHistory<'ctx>, ) -> Result { + self.check_ple(binding, cache, history)?; + let context = self.sources.context; + let weights = Self::ple_weights(binding, cache, context)?; + self.device = run_transfer(binding, cache, context, producer, (), |producer, workspace| { + producer.apply_ple(self.device, workspace, weights, &mut history.device).map_err(micro_driver_error) + })?; + self.sources.validate(binding, cache)?; + history.completed_rows = Some(self.sources.rows.len()); + if let Some(phase) = self.sources.original_phase()? { + phase.ple_complete()?; + } + self.sources.validated = 0; + Ok(self) + } + fn check_ple( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + history: &PromptPleHistory<'ctx>, + ) -> Result<()> { self.sources.validate(binding, cache)?; if self.sources.validated != self.sources.rows.len() || self.sources.role != GrRole::Attention(1) @@ -20,31 +40,22 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx { return Err(Error::IdentityMismatch); } - let context = self.sources.context; + Ok(()) + } + fn ple_weights<'w>( + binding: &ModelBinding, + cache: &'w DenseWeightCache<'ctx>, + context: &Context<'_>, + ) -> Result> { let entry = cache.ple(binding, context)?; if !entry.weights.matches(&binding.identity()) { return Err(Error::IdentityMismatch); } - let weights = leleka_cuda_driver::PleClosedWeights { + Ok(leleka_cuda_driver::PleClosedWeights { key: cache.ple_key(entry)?, value: cache.ple_value(entry)?, aux: cache.ple_aux(entry)?, - }; - let result = (|| { - let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - producer.apply_ple(self.device, &mut workspace, weights, &mut history.device).map_err(micro_driver_error) - })(); - if producer.is_failed() { - cache.transport_failure_flag(binding, context)?.set(true) - } - self.device = result?; - self.sources.validate(binding, cache)?; - history.completed_rows = Some(self.sources.rows.len()); - if let Some(phase) = self.sources.original_phase()? { - phase.ple_complete()?; - } - self.sources.validated = 0; - Ok(self) + }) } pub(in crate::qwen_forward) fn read( self, @@ -53,29 +64,9 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx producer: &mut OriginalPromptDevice<'ctx>, role: GrRole, ) -> Result> { - self.sources.validate(binding, cache)?; - if self.sources.validated != self.sources.rows.len() || self.sources.role != role { - return Err(Error::IdentityMismatch); - } - if let Some(phase) = self.sources.original_phase()? { - phase.prepare_read(role)?; - } + self.sources.begin_read(binding, cache, role)?; let context = self.sources.context; - let resident = cache.gr(binding, role)?; - if !resident.weights.matches(&binding.identity(), role) { - return Err(Error::IdentityMismatch); - } - let [gamma, down, up, inject] = cache.gr_buffers(resident)?.map(|w| w.ok_or(Error::IdentityMismatch)); - let result = (|| { - let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - producer - .read_gr(self.device, &mut workspace, [gamma?, down?, up?, inject?], resident.weights.epsilon()) - .map_err(micro_driver_error) - })(); - if producer.is_failed() { - cache.transport_failure_flag(binding, context)?.set(true) - } - let device = result?; + let device = Self::read_device(self.device, binding, cache, context, producer, role)?; self.sources.validate(binding, cache)?; if let Some(phase) = self.sources.original_phase()? { phase.read(role)?; @@ -84,4 +75,23 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx sources.validated = 0; Ok(PromptDeviceRead { sources, device }) } + fn read_device( + device: OriginalDeviceResidual<'arena, 'loan, 'ctx>, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + context: &Context<'_>, + producer: &mut OriginalPromptDevice<'ctx>, + role: GrRole, + ) -> Result> { + let resident = cache.gr(binding, role)?; + if !resident.weights.matches(&binding.identity(), role) { + return Err(Error::IdentityMismatch); + } + let [gamma, down, up, inject] = cache.gr_buffers(resident)?.map(|w| w.ok_or(Error::IdentityMismatch)); + run_transfer(binding, cache, context, producer, (), |producer, workspace| { + producer + .read_gr(device, workspace, [gamma?, down?, up?, inject?], resident.weights.epsilon()) + .map_err(micro_driver_error) + }) + } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs index 419d5ad7..2b5e2504 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs @@ -98,6 +98,39 @@ impl PromptDeviceFinal { } } impl Sources<'_, '_> { + /// After the initial staging: the sources are still the ones validated, and the phase records the rows. + pub(super) fn finish_initialize(&self, binding: &ModelBinding, cache: &DenseWeightCache<'_>) -> Result<()> { + self.validate(binding, cache)?; + if let Some(phase) = self.original_phase()? { + phase.initialize(self.rows.len())?; + } + Ok(()) + } + /// Before a GR read: the rows are validated and fully consumed (at `role`), and the phase + /// agrees that the read is next. + pub(in super::super) fn begin_read( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + role: GrRole, + ) -> Result<()> { + self.validate(binding, cache)?; + if self.validated != self.rows.len() || self.role != role { + return Err(Error::IdentityMismatch); + } + if let Some(phase) = self.original_phase()? { + phase.prepare_read(role)?; + } + Ok(()) + } + /// Deferred inputs (staged by the driver in one pass) are all or none of the rows, and need the stage. + pub(super) fn check_staging(&self, staged: bool) -> Result<()> { + let deferred = self.rows.iter().filter(|s| s.input.is_deferred()).count(); + if deferred != 0 && (deferred != self.rows.len() || !staged) || deferred == 0 && staged { + return Err(Error::IdentityMismatch); + } + Ok(()) + } pub(in super::super) fn original_phase(&self) -> Result>> { let first = self.rows.first().ok_or(Error::IdentityMismatch)?.original.as_ref().map(OriginalPromptRowKey::phase);