From 730d05d4e09739098eb805fa4e1cdc0b837b000a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 14:43:22 +0100 Subject: [PATCH] STRA-338 size: engine more helper splits (verify_parts, finish_parts, serve_tuning, direct_parts, mtp prefill) --- .../runner/generate_fn.rs | 11 ++- .../src/qwen_forward/original_mtp_prefill.rs | 26 ++++-- .../original_mtp_scalar_prefill.rs | 69 ++++++++------ .../original_serve_pool/direct_parts.rs | 43 ++++++--- .../impl_default_for_ttftmarks.rs | 6 ++ .../impl_originalservestack/open_parts.rs | 36 ++++---- .../impl_originalservestack/serve_parts.rs | 4 +- .../original_spec_controller/finish_parts.rs | 89 +++++++++++-------- .../verify_parts.rs | 55 +++++++----- crates/engine-qwen35-cuda/src/serve_tuning.rs | 37 +++++--- 10 files changed, 231 insertions(+), 145 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs index 45d7622c..bb7ed100 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs @@ -129,19 +129,22 @@ fn served_outcome( } Err(ServeError::Failed(error)) => { leleka_memory::telemetry::request_aborted(); - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve request failed: class={error:?}"); + operator_class("leleka-serve request failed", error); Err(unavailable("Original serve request failed").into()) } Err(ServeError::Broken(error)) => { leleka_memory::telemetry::request_aborted(); - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve stack lost an owner: class={error:?}"); + operator_class("leleka-serve stack lost an owner", error); Err(unavailable("Original serve stack lost a physical owner").into()) } } } +fn operator_class(what: &str, class: impl std::fmt::Debug) { + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "{what}: class={class:?}"); +} + /// The telemetry, the usage event and the operator lines of a request that completed. fn report_completed( stack: &impl ServeDevice, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs index 7f33ade6..1ab6f258 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs @@ -21,6 +21,23 @@ pub(in crate::qwen_forward) struct OriginalDraftKvPending { completed: CompletedDraftKv, } impl OriginalDraftKvPending { + fn new( + binding: &ModelBinding, + txn: &OriginalPromptTxn<'_, '_>, + phase: Rc, + last_next: TokenId, + completed: CompletedDraftKv, + ) -> Self { + Self { + binding: binding.identity(), + phase, + first: txn.start_position(), + end: txn.end_position(), + last_next, + completed, + } + } + pub(in crate::qwen_forward) fn validate( &self, binding: &ModelBinding, @@ -139,14 +156,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx DraftKvOutcome::Skipped => OriginalPromptDraftOutcome::Skipped, DraftKvOutcome::Cancelled => OriginalPromptDraftOutcome::Cancelled, DraftKvOutcome::Completed(completed) => { - let pending = OriginalDraftKvPending { - binding: binding.identity(), - phase, - first: txn.start_position(), - end: txn.end_position(), - last_next, - completed, - }; + let pending = OriginalDraftKvPending::new(binding, txn, phase, last_next, completed); pending.validate_current(binding, txn, preview, ring)?; OriginalPromptDraftOutcome::Completed(pending) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs index 700691a1..2ca5567a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs @@ -57,20 +57,6 @@ fn check_retained_matrices<'ctx>( retained: &Rc>, ) -> Result<()> { // Exact Original acquisition order, authentic pack descriptor checks. - // The retained scalar weights come from the same owner the drafter was built with: the pinned pack's cache, or with an RT - // directory (--mtp-rt-dir) its own bank, whose buffers are not the MoE cache's. Check against that owner. - let matrix = |role, expected| -> Result>> { - let (kind, rows, columns, buffer) = mtp.matrix(binding, context, role)?; - if (kind, rows, columns) != expected { - crate::bringup_trace!( - "DBG scalar draft-kv matrix {role:?}: pack has {:?} {rows}x{columns}, expected {:?}", - kind, - expected - ); - return Err(Error::InvalidDimension); - } - Ok(buffer) - }; retained .with_whole_loans(context, |weights, _| { for (buffer, role, shape) in [ @@ -86,22 +72,51 @@ fn check_retained_matrices<'ctx>( (weights.input.key_norm, MtpRole::KeyNorm, (MtpKind::F32, 1, 256)), (weights.gr_inject, MtpRole::AttentionInject, (MtpKind::Bf16, 4, 10240)), ] { - match matrix(role, shape) { - Ok(b) if std::ptr::eq(buffer, &*b) => {} - Ok(_) => { - crate::bringup_trace!("DBG scalar draft-kv matrix {role:?}: buffer is not the retained one"); - return Err(leleka_cuda_driver::Error::InvalidProjectionShape); - } - Err(e) => { - crate::bringup_trace!("DBG scalar draft-kv matrix {role:?} err {e:?}"); - return Err(leleka_cuda_driver::Error::InvalidProjectionShape); - } - } + check_role(buffer, role, pack_matrix(mtp, binding, context, role, shape))?; } Ok(()) }) - .map_err(micro_driver_error)?; - Ok(()) + .map_err(micro_driver_error) +} + +/// The retained scalar weights come from the same owner the drafter was built with: the pinned pack's cache, or with an RT +/// directory (--mtp-rt-dir) its own bank, whose buffers are not the MoE cache's. Check against that owner. +fn pack_matrix<'ctx>( + mtp: &RetainedOriginalMtpWeights<'ctx>, + binding: &ModelBinding, + context: &'ctx leleka_cuda_driver::Context<'ctx>, + role: MtpRole, + expected: (MtpKind, usize, usize), +) -> Result>> { + let (kind, rows, columns, buffer) = mtp.matrix(binding, context, role)?; + if (kind, rows, columns) != expected { + crate::bringup_trace!( + "DBG scalar draft-kv matrix {role:?}: pack has {:?} {rows}x{columns}, expected {:?}", + kind, + expected + ); + return Err(Error::InvalidDimension); + } + Ok(buffer) +} + +/// The pack's matrix of `role` must be the very buffer the retained loans hold. +fn check_role( + buffer: &leleka_cuda_driver::DeviceBuffer<'_>, + role: MtpRole, + found: Result>>, +) -> std::result::Result<(), leleka_cuda_driver::Error> { + match found { + Ok(b) if std::ptr::eq(buffer, &*b) => Ok(()), + Ok(_) => { + crate::bringup_trace!("DBG scalar draft-kv matrix {role:?}: buffer is not the retained one"); + Err(leleka_cuda_driver::Error::InvalidProjectionShape) + } + Err(e) => { + crate::bringup_trace!("DBG scalar draft-kv matrix {role:?} err {e:?}"); + Err(leleka_cuda_driver::Error::InvalidProjectionShape) + } + } } impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs index 9f0f3ae8..3f5515e1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/direct_parts.rs @@ -78,21 +78,13 @@ pub(super) fn compute_into_sink( return Err(leleka_cuda_driver::Error::InvalidQwenShape); } let zero_span = super::super::original_serve_profile::span("cpu.zero"); - if let Some(mask) = include { - for (entry, _) in mask.iter().enumerate().filter(|(_, computed)| !**computed) { - out[entry * HIDDEN..(entry + 1) * HIDDEN].fill(0.0); - } - } + zero_unselected(out, include); drop(zero_span); let _compute_span = super::super::original_serve_profile::span("cpu.compute"); - if let Some((gu, down)) = formats { - // At most 80 distinct experts per group, so one dispatch (MAX_JOBS is 96). - for chunk in experts.chunks(leleka_native_cpu_expert::MAX_JOBS) { - let group = BorrowedGroup { tokens: rows.activation, experts: chunk, stride: TOP_K }; - if let Err(e) = pool.compute_group(gu, down, &group, out) { - failure = Some(runtime_error(native_cpu_error(e))); - return Err(leleka_cuda_driver::Error::InvalidQwenShape); - } + if let Some(formats) = formats { + if let Err(error) = compute_chunks(pool, (rows, experts), formats, out) { + failure = Some(error); + return Err(leleka_cuda_driver::Error::InvalidQwenShape); } } Ok(()) @@ -100,6 +92,31 @@ pub(super) fn compute_into_sink( (written, failure) } +/// The entries the GPU tier owns (`include` false) read as zeros. +fn zero_unselected(out: &mut [f32], include: Option<&[bool]>) { + if let Some(mask) = include { + for (entry, _) in mask.iter().enumerate().filter(|(_, computed)| !**computed) { + out[entry * HIDDEN..(entry + 1) * HIDDEN].fill(0.0); + } + } +} + +/// At most 80 distinct experts per group, so one dispatch (MAX_JOBS is 96). +fn compute_chunks( + pool: &mut DirectCpuPool, + work: (&OriginalVerifyCpuRows<'_>, &[BorrowedExpert<'_>]), + formats: (GateUpFormat, DownFormat), + out: &mut [f32], +) -> std::result::Result<(), Error> { + let (rows, experts) = work; + let (gu, down) = formats; + for chunk in experts.chunks(leleka_native_cpu_expert::MAX_JOBS) { + let group = BorrowedGroup { tokens: rows.activation, experts: chunk, stride: TOP_K }; + pool.compute_group(gu, down, &group, out).map_err(|e| runtime_error(native_cpu_error(e)))?; + } + Ok(()) +} + impl DirectTier { /// Once: the routers' BF16 host copies and the bank layout of every layer, then the thread. pub(super) fn start_lookahead_once(&mut self, binding: &ModelBinding, opened: &[Opened]) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs index c9764f68..50ec2ecb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs @@ -15,6 +15,12 @@ impl TtftMarks { pub(super) fn since(&self, clock: &impl Clock) -> f64 { self.started.map_or(f64::NAN, |at| clock.since(at).as_secs_f64() * 1e3) } + /// The first round of the request delivered tokens: mark it once. + pub(super) fn note_first_round(&mut self, clock: &impl Clock) { + if self.first_round.is_nan() { + self.first_round = self.since(clock); + } + } pub(super) fn as_array(&self) -> [f64; 4] { [self.resumed, self.prefilled, self.assembled, self.first_round] } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs index 904cad38..8f6baebc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs @@ -109,14 +109,7 @@ pub(super) fn load_weights<'ctx>( .map_err(at("OriginalNativeOutput::load"))? ); let embedding = staged!("embedding table", context, load_embedding(binding, context, &output)?); - let kar = staged!( - "KAR PLE cache", - context, - match binding.kar_ple_binding() { - Some(provider) => Some(KarPleCache::new(context, provider).map_err(at("KarPleCache::new"))?), - None => None, - } - ); + let kar = staged!("KAR PLE cache", context, load_kar(binding, context)?); let dense = staged!( "dense weights", context, @@ -128,6 +121,16 @@ pub(super) fn load_weights<'ctx>( Ok(Weights { output, embedding, kar, dense, moe }) } +fn load_kar<'ctx>( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, +) -> std::result::Result>, ServeFailure> { + Ok(match binding.kar_ple_binding() { + Some(provider) => Some(KarPleCache::new(context, provider).map_err(at("KarPleCache::new"))?), + None => None, + }) +} + fn load_embedding<'ctx>( binding: &ModelBinding, context: &'ctx Context<'ctx>, @@ -349,20 +352,19 @@ pub(super) fn loan_ladder( } } if !loan_tiers.is_empty() { - operator_note(&format!( - "prompt loan ladder: {}, up to {} rows {full} slots", - loan_tiers - .iter() - .map(|t| format!("up to {} rows {} slots", t.rows, t.slots)) - .collect::>() - .join(", "), - config.capacity - )); + note_loan_ladder(&loan_tiers, full, config.capacity); } } Ok(loan_tiers) } +fn note_loan_ladder(loan_tiers: &[LoanTier], full: usize, capacity: usize) { + operator_note(&format!( + "prompt loan ladder: {}, up to {capacity} rows {full} slots", + loan_tiers.iter().map(|t| format!("up to {} rows {} slots", t.rows, t.slots)).collect::>().join(", ") + )); +} + /// The governor's startup log: the inventory of allocation classes and the load ledger. pub(super) fn log_open_inventory() { if let Some(governor) = leleka_memory::Governor::global() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs index d33047bb..e9647877 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs @@ -76,9 +76,7 @@ fn run_engine( request.spec_min_p, &request.eos, |tokens| { - if marks.first_round.is_nan() { - marks.first_round = marks.since(&config.clock); - } + marks.note_first_round(&config.clock); emit(tokens) }, &mut *cancel, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs index 88b0352a..eb13146f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs @@ -50,6 +50,54 @@ impl RoundFacts { } } +/// The chain of this round: the request's (`mtp_t - 1` drafts down to `min_p`) or the adaptive plan, clamped to the cells +/// that exist. Draft j writes its K/V at the cell p+a+j, and cells end at `max_context`: near the context's end the +/// round drafts only the cells that exist (upstream `max_steps = min(.., max_cells - (p + a))`, mtp.cpp). +/// Draft 0 always fits: the window's rows did, and a < t. Returns the chain, the floor and whether it was clamped. +fn round_chain(plan: Option, config: &SpecConfig, min_p: f32, at: (i64, usize)) -> (usize, f32, bool) { + let (chain, floor) = match plan { + Some(p) => (p.max_drafts, p.min_p), + None => (config.mtp_t - 1, min_p), + }; + let cell = at.0.saturating_add(at.1 as i64); + let room = usize::try_from(config.max_context.saturating_sub(cell)).unwrap_or(0).max(1); + (chain.min(room), floor, chain > room) +} + +/// The adaptive policy's trace line of a round (only when the spec trace is on). +fn trace_adaptive(round: &RoundFacts, c: &Choice, ms: f64, drafts_after: usize, pol: &AdaptivePolicy) { + let plan = pol.draft_plan(); + eprintln!( + "DBG spec-trace r={} t={} src={:?} acc={} ms={:.2} E={:.2} rate={:.4} explored={} drafts={} next_plan={}/{:.2} bar={:.3} slope={:.2}", + round.round_number, + round.t, + c.origin, + round.accepted, + ms, + c.expected, + c.rate, + c.explored as u8, + drafts_after, + plan.max_drafts, + plan.min_p, + pol.bar(), + pol.row_slope_ms() + ); +} + +/// The fixed-width policy's trace line of a round (only when the spec trace is on). +fn trace_fixed(round: &RoundFacts, ms: f64, drafts_after: usize) { + eprintln!( + "DBG spec-trace r={} t={} src={} acc={} ms={:.2} drafts={}", + round.round_number, + round.t, + if round.from_lookup { "Lookup" } else { "Mtp" }, + round.accepted, + ms, + drafts_after + ); +} + impl OriginalSpecController { /// The receipt belongs to this controller's pending round. pub(super) fn round_admission(&self, round: &CommittedRound) -> Result<()> { @@ -78,18 +126,7 @@ impl OriginalSpecController { if r.finished && !self.final_draft { return Ok(None); } - // the chain of this round: the request's (`mtp_t - 1` drafts down to `min_p`) or the adaptive plan - let (chain, floor) = match self.plan { - Some(p) => (p.max_drafts, p.min_p), - None => (self.config.mtp_t - 1, r.min_p), - }; - // Draft j writes its K/V at the cell p+a+j, and cells end at `max_context`: near the context's end the - // round drafts only the cells that exist (upstream `max_steps = min(.., max_cells - (p + a))`, mtp.cpp). - // Draft 0 always fits: the window's rows did, and a < t. - let cell = round.position.saturating_add(round.accepted as i64); - let room = usize::try_from(self.config.max_context.saturating_sub(cell)).unwrap_or(0).max(1); - let clamped = chain > room; - let chain = chain.min(room); + let (chain, floor, clamped) = round_chain(self.plan, &self.config, r.min_p, (round.position, round.accepted)); // A fixed chain never needed a plan; a clamped one does (and restores the full chain on the next round). let planned = if self.plan.is_some() || clamped || self.chain_clamped { engine.set_draft_plan(chain, floor) @@ -160,23 +197,7 @@ impl OriginalSpecController { pol.observe(c, round.accepted, ms, drafts_after); self.plan = Some(pol.draft_plan()); if trace_enabled() { - let plan = self.plan.unwrap_or(DraftPlan { max_drafts: 0, min_p: 0.0 }); - eprintln!( - "DBG spec-trace r={} t={} src={:?} acc={} ms={:.2} E={:.2} rate={:.4} explored={} drafts={} next_plan={}/{:.2} bar={:.3} slope={:.2}", - round.round_number, - round.t, - c.origin, - round.accepted, - ms, - c.expected, - c.rate, - c.explored as u8, - drafts_after, - plan.max_drafts, - plan.min_p, - pol.bar(), - pol.row_slope_ms() - ); + trace_adaptive(round, c, ms, drafts_after, pol); } } _ => { @@ -189,15 +210,7 @@ impl OriginalSpecController { } } if trace_enabled() { - eprintln!( - "DBG spec-trace r={} t={} src={} acc={} ms={:.2} drafts={}", - round.round_number, - round.t, - if round.from_lookup { "Lookup" } else { "Mtp" }, - round.accepted, - ms, - drafts_after - ); + trace_fixed(round, ms, drafts_after); } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs index ba34ad44..6a93dc7a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs @@ -90,6 +90,24 @@ pub(super) fn window_inputs(r: &Request, plan: &WindowPlan) -> [i32; MAX_T] { inputs } +/// The window's outputs are one per row and every one a token of the vocabulary. +fn admit_outputs( + engine: &E, + round: &Round<'_, E>, + v: &E::Verified, + vocabulary: u32, +) -> std::result::Result<(), Error> { + engine.validate_verified(v, round.p, &round.inputs[..round.t])?; + let out = engine.outputs(v); + if out.len() != round.t { + return Err(Error::IdentityMismatch); + } + if out.iter().any(|&x| x < 0 || x as u32 >= vocabulary) { + return Err(Error::InvalidToken); + } + Ok(()) +} + /// One verify attempt: stage and run the window, admit its outputs, apply the debug injection. A failure hands back the /// window (when there is one) so the caller can drain it. fn run_window( @@ -108,18 +126,7 @@ fn run_window( Err(e) => return Err((e, None)), Ok(v) => v, }; - let admission = (|| { - engine.validate_verified(&v, p, &inputs[..t])?; - let out = engine.outputs(&v); - if out.len() != t { - return Err(Error::IdentityMismatch); - } - if out.iter().any(|&x| x < 0 || x as u32 >= vocabulary) { - return Err(Error::InvalidToken); - } - Ok(()) - })(); - match admission { + match admit_outputs(engine, round, &v, vocabulary) { Err(e) => Err((e, Some(v))), // the debug injection of upstream's STRATA_NAN_INJECT: the n-th checked window (first `times` attempts) reads as non-finite Ok(()) => { @@ -248,15 +255,9 @@ impl OriginalSpecController { ); return None; } - // the checkpoint could not be restored or the window not taken back: the state is unknown, nothing to retry on - self.failed = true; - if let Some(rq) = self.request.as_mut() { - rq.finished = true; - } - leleka_memory::telemetry::nan_guard_unhealed(&format!("{what}; the round could not be undone")); - eprintln!( - "leleka-serve nan-guard: a non-finite window ({what}) and the round could not be undone (restore target {:?}, restore draft {:?}, take back {:?})", - restored.0, restored.1, taken_back + self.fail_undone( + &what, + format!("{:?}, restore draft {:?}, take back {:?}", restored.0, restored.1, taken_back), ); return Some(e.into()); } @@ -267,6 +268,18 @@ impl OriginalSpecController { Some(self.abort(engine, round.target, round.draft, e.into())) } + /// The checkpoint could not be restored or the window not taken back: the state is unknown, nothing to retry on. + fn fail_undone(&mut self, what: &str, outcomes: String) { + self.failed = true; + if let Some(rq) = self.request.as_mut() { + rq.finished = true; + } + leleka_memory::telemetry::nan_guard_unhealed(&format!("{what}; the round could not be undone")); + eprintln!( + "leleka-serve nan-guard: a non-finite window ({what}) and the round could not be undone (restore target {outcomes})" + ); + } + /// The prefix is committed: the request's tokens, position and completion, and the suffix drafter's history. pub(super) fn book_round( &mut self, diff --git a/crates/engine-qwen35-cuda/src/serve_tuning.rs b/crates/engine-qwen35-cuda/src/serve_tuning.rs index 18b0bc02..69462c4c 100644 --- a/crates/engine-qwen35-cuda/src/serve_tuning.rs +++ b/crates/engine-qwen35-cuda/src/serve_tuning.rs @@ -156,7 +156,17 @@ impl Tuning { return Ok(()); } let before = applied.next.prefix_cache.clone(); - let mut prefix = before.clone().unwrap_or_default(); + let prefix = self.prefix_members(before.clone().unwrap_or_default())?; + let off = prefix.budget_bytes == Some(0); + applied.next.prefix_cache = if off { None } else { Some(prefix) }; + if applied.next.prefix_cache != before { + self.note_prefix_members(&mut applied.changed); + } + Ok(()) + } + + /// The prefix options with the members the document names replaced. + fn prefix_members(&self, mut prefix: PrefixCacheOptions) -> Result { if let Some(text) = &self.prefix_cache_mib { prefix.budget_bytes = prefix_budget(text)?; } @@ -177,21 +187,20 @@ impl Tuning { if let Some(minutes) = self.prefix_retention_min { prefix.retention_s = Some(minutes.saturating_mul(60)); } - let off = prefix.budget_bytes == Some(0); - applied.next.prefix_cache = if off { None } else { Some(prefix) }; - if applied.next.prefix_cache != before { - for (given, name) in [ - (self.prefix_cache_mib.is_some(), "prefix_cache_mib"), - (self.prefix_cache_tail.is_some(), "prefix_cache_tail"), - (self.prefix_cache_block.is_some(), "prefix_cache_block"), - (self.prefix_retention_min.is_some(), "prefix_retention_min"), - ] { - if given { - applied.changed.push(name); - } + Ok(prefix) + } + + fn note_prefix_members(&self, changed: &mut Vec<&'static str>) { + for (given, name) in [ + (self.prefix_cache_mib.is_some(), "prefix_cache_mib"), + (self.prefix_cache_tail.is_some(), "prefix_cache_tail"), + (self.prefix_cache_block.is_some(), "prefix_cache_block"), + (self.prefix_retention_min.is_some(), "prefix_retention_min"), + ] { + if given { + changed.push(name); } } - Ok(()) } }