diff --git a/architecture-baseline.json b/architecture-baseline.json index d0b0c0ee..9244cf6b 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -2,8 +2,6 @@ "_comment": "Debt that exists today. Every number may only fall (scripts/check-architecture.py --update-baseline refuses to raise one). Do not edit by hand; regenerate. Policy: architecture.json.", "violations": [], "oversize": {}, - "source": { - "dyn-trait:leleka-engine-qwen35-cuda": 3 - }, + "source": {}, "mechanical_names": [] } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs index d9e11b41..5e5a6a2d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs @@ -66,7 +66,9 @@ pub(in crate::qwen_forward) struct HostOutcome { pub(in crate::qwen_forward) position: u64, } -pub(in crate::qwen_forward) struct OriginalServeHost<'a, 'ctx> { +/// Generic over the routed-expert pool `P` (the CPU pool alone, or the GPU share over it): the window calls the pool +/// through static dispatch, never through a vtable. +pub(in crate::qwen_forward) struct OriginalServeHost<'a, 'ctx, P> { binding: &'a ModelBinding, dense: &'a DenseWeightCache<'ctx>, context: &'ctx Context<'ctx>, @@ -75,7 +77,7 @@ pub(in crate::qwen_forward) struct OriginalServeHost<'a, 'ctx> { executor: &'a mut OriginalPromptExecutor<'ctx>, kar: Option<&'a mut KarPleCache<'ctx>>, history: &'a mut OriginalNativePenaltyHistory<'ctx>, - pool: &'a mut dyn OriginalServePool<'ctx>, + pool: &'a mut P, /// A second reference to the verifier's QSA journal, only to read the committed mapped prefixes. qsa: Rc>, /// Model layer index of journal layer `i`. @@ -97,7 +99,7 @@ pub(in crate::qwen_forward) struct OriginalServeHost<'a, 'ctx> { } /// Everything a host borrows, in one place so the stack can build it in one expression. -pub(in crate::qwen_forward) struct HostOwners<'a, 'ctx> { +pub(in crate::qwen_forward) struct HostOwners<'a, 'ctx, P> { pub(in crate::qwen_forward) binding: &'a ModelBinding, pub(in crate::qwen_forward) dense: &'a DenseWeightCache<'ctx>, pub(in crate::qwen_forward) context: &'ctx Context<'ctx>, @@ -106,7 +108,7 @@ pub(in crate::qwen_forward) struct HostOwners<'a, 'ctx> { pub(in crate::qwen_forward) executor: &'a mut OriginalPromptExecutor<'ctx>, pub(in crate::qwen_forward) kar: Option<&'a mut KarPleCache<'ctx>>, pub(in crate::qwen_forward) history: &'a mut OriginalNativePenaltyHistory<'ctx>, - pub(in crate::qwen_forward) pool: &'a mut dyn OriginalServePool<'ctx>, + pub(in crate::qwen_forward) pool: &'a mut P, pub(in crate::qwen_forward) qsa: Rc>, pub(in crate::qwen_forward) slots: [usize; 12], pub(in crate::qwen_forward) ple_history: &'a DeviceBuffer<'ctx>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/original_serve_host_native_serve_host.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/original_serve_host_native_serve_host.rs index b960bfb6..1711b299 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/original_serve_host_native_serve_host.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/original_serve_host_native_serve_host.rs @@ -4,15 +4,15 @@ use super::{ AcceptedWindow, DraftCompletion, DraftLaunch, Error, LedgerCheckpoint, MtpDraftOwners, NativeServeHost, OriginalCommittedMtpReceipt, OriginalDraftCheckpoint, OriginalGpuEvent, OriginalNativeHeadGraphResources, - OriginalServeHost, OriginalVerifier, OriginalVerifyGraphResources, OriginalVerifyWindowResult, Result, Stage, - adapt_defer, ple_on_chain, profile, report_window, + OriginalServeHost, OriginalServePool, OriginalVerifier, OriginalVerifyGraphResources, OriginalVerifyWindowResult, + Result, Stage, adapt_defer, ple_on_chain, profile, report_window, }; use crate::qwen_forward::original_mtp_verified_adapter::VerifiedWindow; use crate::qwen_forward::original_serve_engine::{DraftLimits, FirstDraftSeed}; use crate::qwen_forward::original_serve_native::NativeCommittedWindow; use ple_on_chain::PleOnChainWork; -impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { +impl<'a, 'ctx, P: OriginalServePool<'ctx>> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx, P> { type TargetCheckpoint = LedgerCheckpoint; type DraftCheckpoint = OriginalDraftCheckpoint; type Adaptive = (); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/ple_on_chain.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/ple_on_chain.rs index 8f292303..254cb026 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/ple_on_chain.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/ple_on_chain.rs @@ -7,7 +7,7 @@ //! only the last draft's row is gathered after the chain. The values are the ones the window would gather itself: //! same provider, same sixteen rows. -use super::{Context, InputStage, KarPleCache, ModelBinding, OriginalServeHost, Result, profile}; +use super::{Context, InputStage, KarPleCache, ModelBinding, OriginalServeHost, OriginalServePool, Result, profile}; use crate::settings::PleOnChain; use leleka_cuda_driver::compute_drain::LocalDrain; @@ -84,7 +84,7 @@ fn window_before(start: WindowStart, k: usize, drafted: &[i32]) -> [i32; 2] { } } -impl OriginalServeHost<'_, '_> { +impl<'ctx, P: OriginalServePool<'ctx>> OriginalServeHost<'_, 'ctx, P> { /// Where the next window starts when its PLE rows may be gathered during the draft, else `None`. pub(super) fn ple_window_start(&mut self) -> Option { let mode = crate::settings::process().decode.ple_on_chain; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/request_sampling.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/request_sampling.rs index 29434adb..19f622b8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/request_sampling.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/request_sampling.rs @@ -4,8 +4,9 @@ use super::{ BoundLayerKind, DraftCompletion, Error, GdnPrior, HostOutcome, HostOwners, OriginalNativeHeadGraphResources, - OriginalServeHost, OriginalVerifier, OriginalVerifyGraphResources, PlePrior, RequestSampling, Result, - SamplerParams, SamplerPath, ServeFailure, ServeLedger, TargetStepOrigin, driver_error, profile, read_ple_history, + OriginalServeHost, OriginalServePool, OriginalVerifier, OriginalVerifyGraphResources, PlePrior, RequestSampling, + Result, SamplerParams, SamplerPath, ServeFailure, ServeLedger, TargetStepOrigin, driver_error, profile, + read_ple_history, }; use crate::qwen_forward::{ original_mtp_verified_adapter::OriginalMtpDraftReceipt, qsa_index::prompt_device::resident_device::ResidentQsaPrior, @@ -47,11 +48,11 @@ pub(super) fn operator_line(what: &str, failure: &ServeFailure) { let _ = writeln!(std::io::stderr().lock(), "leleka-serve {what}: {}", failure.describe()); } -impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { +impl<'a, 'ctx, P: OriginalServePool<'ctx>> OriginalServeHost<'a, 'ctx, P> { /// `committed` is the token sequence the session holds (the prompt without its last token); `limit` is /// the last position a state may end at. The session must stand exactly there, in step. pub(in crate::qwen_forward) fn new( - owners: HostOwners<'a, 'ctx>, + owners: HostOwners<'a, 'ctx, P>, committed: Vec, limit: u64, sampling: RequestSampling, @@ -67,7 +68,7 @@ impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { let ledger = ServeLedger::new(committed, limit)?; Ok(Self::from_owners(owners, sampling, ledger)) } - fn from_owners(owners: HostOwners<'a, 'ctx>, sampling: RequestSampling, ledger: ServeLedger) -> Self { + fn from_owners(owners: HostOwners<'a, 'ctx, P>, sampling: RequestSampling, ledger: ServeLedger) -> Self { Self { binding: owners.binding, dense: owners.dense, @@ -177,7 +178,7 @@ pub(super) fn adapt_defer() -> bool { crate::settings::process().decode.adapt_defer } -impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { +impl<'a, 'ctx, P: OriginalServePool<'ctx>> OriginalServeHost<'a, 'ctx, P> { /// The MTP actor drafts as many chain steps as it is configured for (`set_max_drafts`); an adaptive round's plan is /// applied here (the engine has already bounded it by the request's cap). Equal values cost one comparison. pub(super) fn apply_draft_cap(&mut self, max_drafts: usize) -> Result<()> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/run_window_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/run_window_steps.rs index c7e24b9f..02ee2ff9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/run_window_steps.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/run_window_steps.rs @@ -15,7 +15,7 @@ use std::time::Instant; /// One layer group through the expert pool, with the pool's wall time in the window trace. A pool refusal is kept in /// `pool_error` (it is the cause; the driver error it provokes is its echo). -pub(super) fn run_pool_group<'ctx, P: OriginalServePool<'ctx> + ?Sized>( +pub(super) fn run_pool_group<'ctx, P: OriginalServePool<'ctx>>( pool: &mut P, group: (OriginalVerifyCpuRows<'_>, &mut OriginalVerifyCpuSink<'_, 'ctx>, &mut OriginalGpuStream<'ctx>), pool_error: &mut Option, @@ -65,7 +65,7 @@ fn verify_sampled<'ctx, R, P>( ) -> Result where R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, - P: OriginalServePool<'ctx> + ?Sized, + P: OriginalServePool<'ctx>, { let (first, inputs, ple) = window; let (sampling, pool) = staged; @@ -109,7 +109,7 @@ impl WindowRun { } } -impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { +impl<'a, 'ctx, P: OriginalServePool<'ctx>> OriginalServeHost<'a, 'ctx, P> { /// The penalty history samples the window's rows, and inside it the verifier runs the window over the expert pool. pub(super) fn sample_and_verify( &mut self, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_decode_phase.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_decode_phase.rs index 9f75f6ac..b3ae09d5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_decode_phase.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_decode_phase.rs @@ -3,19 +3,20 @@ use super::{ AssembleFailure, AssembleInputs, Began, Context, CpuExpertPool, DecodeGraphKey, DecodeResources, DenseWeightCache, - DeviceBuffer, DeviceRef, Ending, Error, ExpertBlobSizes, GpuExpertPool, GraphReuse, HostOwners, KarPleCache, - ModelBinding, MoeWeightCache, OriginalExpertCache, OriginalMtpFullPolicy, OriginalNativeOutput, - OriginalNativePenaltyHistory, OriginalPromptExecutor, OriginalServeHost, OriginalServePool, OriginalServeSettings, - OriginalServeStack, OriginalSpecController, OriginalVerifyExpertFormats, QsaOwnerHome, QsaOwners, QwenSession, Rc, - RearmSeed, RefillOwners, RequestSampling, ResidencyState, Result, RopeConstants, ServeConversation, ServeEnv, - ServeOutcome, ServeRequest, SpecError, StackConfig, StackPoint, TailMode, TierResources, TtftMarks, VerifyWeights, - Why, assemble_decode, cluster_topk_requested, dbg_el, decode_pcie_mode, gpu_expert_pool, narrow_window_policy, + DeviceBuffer, DeviceRef, Ending, Error, ExpertBlobSizes, GraphReuse, HostOwners, KarPleCache, ModelBinding, + MoeWeightCache, OriginalExpertCache, OriginalMtpFullPolicy, OriginalNativeOutput, OriginalNativePenaltyHistory, + OriginalPromptExecutor, OriginalServeHost, OriginalServePool, OriginalServeSettings, OriginalServeStack, + OriginalSpecController, OriginalVerifyExpertFormats, QsaOwnerHome, QsaOwners, QwenSession, Rc, RearmSeed, + RefillOwners, RequestSampling, ResidencyState, Result, RopeConstants, ServeConversation, ServeEnv, ServeOutcome, + ServeRequest, SpecError, StackConfig, StackPoint, TailMode, TierResources, TtftMarks, VerifyWeights, Why, + assemble_decode, cluster_topk_requested, dbg_el, decode_pcie_mode, gpu_expert_pool, narrow_window_policy, operator_text, profile, resolve_assembled, retire_kept, return_owners, seed_ple_history, serve_over_host, settle_deferred_refill, teardown_decode, vram_note, }; mod decode_steps; mod decode_view; +mod serve_over_pool; impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { /// Hand the twelve QSA owners to a fresh verifier and run the request's decode phase over it. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_decode_phase/decode_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_decode_phase/decode_steps.rs index 988db864..df83192b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_decode_phase/decode_steps.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_decode_phase/decode_steps.rs @@ -1,18 +1,17 @@ //! The phases of `OriginalServeStack::decode_phase`: the request's start, the assembly of the verifier window, the //! settlement of its outcome and the serve step. Operation order, error paths and log lines are the decode's own. -use super::decode_view::{Book, DecodeView, Extra, Ids, Owners, Policy, Reads, Refill, Tier}; +use super::decode_view::{DecodeView, Refill, Tier}; +use super::serve_over_pool::{ServeJob, ServeParts}; use super::{ - AssembleFailure, AssembleInputs, Began, DecodeGraphKey, DecodeResources, DeviceBuffer, Ending, Error, - GpuExpertPool, HostOwners, ModelBinding, OriginalServeHost, OriginalServePool, OriginalServeStack, QsaOwnerHome, - QsaOwners, Rc, RearmSeed, RefillOwners, RequestSampling, Result, ServeEnv, ServeOutcome, ServeRequest, SpecError, - TailMode, TierResources, VerifyWeights, Why, assemble_decode, cluster_topk_requested, dbg_el, decode_pcie_mode, + AssembleFailure, AssembleInputs, Began, DecodeGraphKey, DecodeResources, Error, ModelBinding, OriginalServeStack, + QsaOwnerHome, QsaOwners, RearmSeed, RefillOwners, RequestSampling, Result, ServeOutcome, ServeRequest, SpecError, + TierResources, VerifyWeights, Why, assemble_decode, cluster_topk_requested, dbg_el, decode_pcie_mode, gpu_expert_pool, narrow_window_policy, operator_text, profile, resolve_assembled, retire_kept, return_owners, - seed_ple_history, serve_over_host, settle_deferred_refill, teardown_decode, vram_note, + seed_ple_history, settle_deferred_refill, vram_note, }; use crate::qwen_forward::moe_weight_cache::SharedKeys; use crate::qwen_forward::session::original_verified::OriginalVerifiedBase; -use leleka_cuda_driver::OriginalVerifyQsaJournal; /// What the request's start settles before the window is assembled. pub(super) struct Staged<'ctx> { @@ -24,12 +23,6 @@ pub(super) struct Staged<'ctx> { /// The assembly's outcome: the window width it settled on and the resources or the failure. pub(super) type Assembled<'ctx> = (usize, std::result::Result, AssembleFailure<'ctx>>); -/// The expert pool a request runs over: the GPU share over the CPU pool, or the CPU pool alone (decided at run time). -type PoolRef<'q, 'ctx> = &'q mut dyn OriginalServePool<'ctx>; - -/// The pool, the QSA journal with its layer slots, and the PLE history image a host is built over. -type HostTail<'h, 'ctx> = (PoolRef<'h, 'ctx>, Rc>, [usize; 12], &'h DeviceBuffer<'ctx>); - impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { /// The request's start: a poisoned controller is renewed, the base position is checked, the PLE history is seeded /// and the shared experts of all layers are loaded for the window. @@ -245,105 +238,33 @@ impl<'s, 'a, 'ctx> DecodeView<'s, 'a, 'ctx> { Ok(resources) } - /// Run the request over the assembled verifier and take the owners back. + /// Run the request over the assembled verifier and take the owners back. The expert pool is chosen here, once per + /// request: the GPU share over the CPU pool, or the CPU pool alone. The rest of the serve is generic over it. pub(super) fn serve( - mut self, + self, request: &ServeRequest, sampling: RequestSampling, resources: DecodeResources<'ctx>, (mut emit, mut cancel): (impl FnMut(&[i32]) -> Result<()>, impl FnMut() -> bool), ) -> std::result::Result { let key = self.held.enabled().then(|| self.graph_key()).and_then(std::result::Result::ok); - let DecodeResources { verifier, qsa, slots } = resources; // the NaN guard's retry takes a refused window back from these (OriginalVerifier::discard_window) - qsa.set_window_snapshots(self.policy.settings.nan_guard.retries > 0); + resources.qsa.set_window_snapshots(self.policy.settings.nan_guard.retries > 0); let committed = request.prompt[..request.prompt.len() - 1].to_vec(); - let mut gpu_pool = None; - let groups = (&self.ids, &self.reads, &mut self.tier, &self.policy); - let pool = expert_pool(groups, &mut gpu_pool)?; - let want_tail = begin_tail(&mut self.policy, &mut self.book); - let tail = (pool, Rc::clone(&qsa), slots, &**self.ple_history); - let owners = host_owners((&self.ids, &self.reads, &mut self.owners, &mut self.extra), tail); - let host = OriginalServeHost::new(owners, committed, self.policy.config.max_context as u64, sampling); - let env = serve_env(&mut self.policy, &mut self.book, want_tail); + let job = ServeJob { request, sampling, key, committed, resources }; let channels = (&mut emit, &mut cancel); - let (served, verifier, outcome) = serve_over_host(verifier, host, request, channels, env)?; - let resources = DecodeResources { verifier, qsa, slots }; - let (executor, session) = (&mut *self.owners.executor, &mut *self.owners.session); - let home = QsaOwnerHome { executor, binding: self.ids.binding, dense: self.reads.dense, session }; - let tail = (self.reads.moe, self.ids.shared); - let ending = Ending::of(outcome, (key, served.is_ok()), &mut *self.held, tail); - teardown_decode(resources, ending, home, self.ids.context, &mut *self.book.broken); - served - } -} - -/// Whether the request ends on a reply checkpoint; the controller drafts past the last round for it, and the settled -/// tail of the previous request is forgotten. -fn begin_tail(policy: &mut Policy<'_>, book: &mut Book<'_, '_>) -> bool { - let want_tail = policy.config.prefix.as_ref().is_some_and(|p| p.tail == TailMode::Reply) && book.prefix_live; - policy.controller.set_final_draft(want_tail); - *book.tail_consumed = None; - want_tail -} - -/// The window's expert pool: the GPU share first and the CPU pool on the rest, or the CPU pool alone. -fn expert_pool<'q, 'p: 'q, 'a, 'ctx>( - groups: (&Ids<'_, 'a, 'ctx>, &Reads<'p, 'ctx>, &'p mut Tier<'_, 'a, 'ctx>, &Policy<'_>), - slot: &'q mut Option>, -) -> std::result::Result, SpecError> { - let (ids, reads, tier, policy) = groups; - match tier.expert_cache.as_mut() { - Some(cache) => { - let tier_config = &policy.config.expert_tier; - let (cpu, state) = (&mut *tier.pool, &mut *tier.residency); - let pool = gpu_expert_pool(ids.binding, TierResources { moe: reads.moe, cache, cpu, state }, tier_config); - Ok(slot.insert(pool.map_err(SpecError::Forward)?)) + let DecodeView { ids, reads, owners, extra, tier, policy, book, ple_history, held, .. } = self; + let parts = ServeParts { ids, reads, owners, extra, policy, book, ple_history, held }; + match tier.expert_cache.as_mut() { + Some(cache) => { + let (cpu, state) = (&mut *tier.pool, &mut *tier.residency); + let tier_resources = TierResources { moe: parts.reads.moe, cache, cpu, state }; + let tier_config = &parts.policy.config.expert_tier; + let mut pool = + gpu_expert_pool(parts.ids.binding, tier_resources, tier_config).map_err(SpecError::Forward)?; + parts.serve_over(&mut pool, job, channels) + } + None => parts.serve_over(&mut *tier.pool, job, channels), } - None => Ok(&mut *tier.pool), - } -} - -/// The owners of a host from the view's groups, over the pool, journal and PLE history of `tail`. -fn host_owners<'h, 'ctx>( - groups: (&'h Ids<'_, '_, 'ctx>, &'h Reads<'_, 'ctx>, &'h mut Owners<'_, 'ctx>, &'h mut Extra<'_, 'ctx>), - tail: HostTail<'h, 'ctx>, -) -> HostOwners<'h, 'ctx> { - let (ids, reads, owners, extra) = groups; - let (pool, qsa, slots, ple_history) = tail; - HostOwners { - binding: ids.binding, - dense: reads.dense, - context: ids.context, - session: &mut *owners.session, - draft: &mut *owners.draft, - executor: &mut *owners.executor, - kar: extra.kar.as_deref_mut(), - history: &mut *extra.history, - pool, - qsa, - slots, - ple_history, - policy: extra.policy, - } -} - -/// The borrowed state the serve step reads and writes besides the verifier and the host. -fn serve_env<'r, 'ctx>( - policy: &'r mut Policy<'_>, - book: &'r mut Book<'_, 'ctx>, - want_tail: bool, -) -> ServeEnv<'r, 'ctx> { - ServeEnv { - config: policy.config, - settings: &*policy.settings, - controller: &mut *policy.controller, - marks: &mut *book.marks, - arm_label: book.arm_label, - conversation: &mut *book.conversation, - prefix_live: book.prefix_live, - tail_consumed: &mut *book.tail_consumed, - broken: &mut *book.broken, - want_tail, } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_decode_phase/serve_over_pool.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_decode_phase/serve_over_pool.rs new file mode 100644 index 00000000..cf551419 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_decode_phase/serve_over_pool.rs @@ -0,0 +1,116 @@ +//! The serve step of `OriginalServeStack::decode_phase` once the expert pool is chosen. The pool is a type parameter: +//! the host calls it through static dispatch on every window group and every round, never through a vtable. + +use super::decode_view::{Book, Extra, Ids, Owners, Policy, Reads}; +use super::{ + DecodeGraphKey, DecodeResources, DeviceBuffer, DeviceRef, Ending, GraphReuse, HostOwners, OriginalServeHost, + OriginalServePool, QsaOwnerHome, Rc, RequestSampling, Result, ServeEnv, ServeOutcome, ServeRequest, SpecError, + TailMode, serve_over_host, teardown_decode, +}; +use leleka_cuda_driver::OriginalVerifyQsaJournal; + +/// What one request is served with, besides the expert pool and the view's owners. +pub(super) struct ServeJob<'r, 'ctx> { + pub(super) request: &'r ServeRequest, + pub(super) sampling: RequestSampling, + /// The inputs the kept decode graphs are specific to, taken when the switch is on. + pub(super) key: Option, + /// The token sequence the session holds (the prompt without its last token). + pub(super) committed: Vec, + pub(super) resources: DecodeResources<'ctx>, +} + +/// The groups of the decode view the serve step uses; the view's tier is left out, the pool borrows it. +pub(super) struct ServeParts<'s, 'a, 'ctx> { + pub(super) ids: Ids<'s, 'a, 'ctx>, + pub(super) reads: Reads<'s, 'ctx>, + pub(super) owners: Owners<'s, 'ctx>, + pub(super) extra: Extra<'s, 'ctx>, + pub(super) policy: Policy<'s>, + pub(super) book: Book<'s, 'ctx>, + pub(super) ple_history: &'s DeviceRef<'ctx>, + pub(super) held: &'s mut GraphReuse>, +} + +/// The pool, the QSA journal with its layer slots, and the PLE history image a host is built over. +type HostTail<'h, 'ctx, P> = (&'h mut P, Rc>, [usize; 12], &'h DeviceBuffer<'ctx>); + +impl<'s, 'a, 'ctx> ServeParts<'s, 'a, 'ctx> { + /// Serve the request over `pool`: build the host, run the engine over the verifier and the host, and take the + /// owners back. + pub(super) fn serve_over>( + mut self, + pool: &mut P, + job: ServeJob<'_, 'ctx>, + channels: (&mut impl FnMut(&[i32]) -> Result<()>, &mut impl FnMut() -> bool), + ) -> std::result::Result { + let ServeJob { request, sampling, key, committed, resources } = job; + let DecodeResources { verifier, qsa, slots } = resources; + let want_tail = begin_tail(&mut self.policy, &mut self.book); + let tail = (pool, Rc::clone(&qsa), slots, &**self.ple_history); + let owners = host_owners((&self.ids, &self.reads, &mut self.owners, &mut self.extra), tail); + let host = OriginalServeHost::new(owners, committed, self.policy.config.max_context as u64, sampling); + let env = serve_env(&mut self.policy, &mut self.book, want_tail); + let (served, verifier, outcome) = serve_over_host(verifier, host, request, channels, env)?; + let resources = DecodeResources { verifier, qsa, slots }; + let (executor, session) = (&mut *self.owners.executor, &mut *self.owners.session); + let home = QsaOwnerHome { executor, binding: self.ids.binding, dense: self.reads.dense, session }; + let tail = (self.reads.moe, self.ids.shared); + let ending = Ending::of(outcome, (key, served.is_ok()), &mut *self.held, tail); + teardown_decode(resources, ending, home, self.ids.context, &mut *self.book.broken); + served + } +} + +/// Whether the request ends on a reply checkpoint; the controller drafts past the last round for it, and the settled +/// tail of the previous request is forgotten. +fn begin_tail(policy: &mut Policy<'_>, book: &mut Book<'_, '_>) -> bool { + let want_tail = policy.config.prefix.as_ref().is_some_and(|p| p.tail == TailMode::Reply) && book.prefix_live; + policy.controller.set_final_draft(want_tail); + *book.tail_consumed = None; + want_tail +} + +/// The owners of a host from the view's groups, over the pool, journal and PLE history of `tail`. +fn host_owners<'h, 'ctx, P>( + groups: (&'h Ids<'_, '_, 'ctx>, &'h Reads<'_, 'ctx>, &'h mut Owners<'_, 'ctx>, &'h mut Extra<'_, 'ctx>), + tail: HostTail<'h, 'ctx, P>, +) -> HostOwners<'h, 'ctx, P> { + let (ids, reads, owners, extra) = groups; + let (pool, qsa, slots, ple_history) = tail; + HostOwners { + binding: ids.binding, + dense: reads.dense, + context: ids.context, + session: &mut *owners.session, + draft: &mut *owners.draft, + executor: &mut *owners.executor, + kar: extra.kar.as_deref_mut(), + history: &mut *extra.history, + pool, + qsa, + slots, + ple_history, + policy: extra.policy, + } +} + +/// The borrowed state the serve step reads and writes besides the verifier and the host. +fn serve_env<'r, 'ctx>( + policy: &'r mut Policy<'_>, + book: &'r mut Book<'_, 'ctx>, + want_tail: bool, +) -> ServeEnv<'r, 'ctx> { + ServeEnv { + config: policy.config, + settings: &*policy.settings, + controller: &mut *policy.controller, + marks: &mut *book.marks, + arm_label: book.arm_label, + conversation: &mut *book.conversation, + prefix_live: book.prefix_live, + tail_consumed: &mut *book.tail_consumed, + broken: &mut *book.broken, + want_tail, + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/serve_request_step.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/serve_request_step.rs index a2c331b3..94d3a85d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/serve_request_step.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/serve_request_step.rs @@ -2,7 +2,7 @@ //! end of the request and settle the served state. Separate from `decode_phase_steps`, which prepares its inputs. use super::{ - Clock, Error, NativeServePort, OriginalServeEngine, OriginalServeHost, OriginalServeSettings, + Clock, Error, NativeServePort, OriginalServeEngine, OriginalServeHost, OriginalServePool, OriginalServeSettings, OriginalSpecController, Result, ServeConversation, ServeOutcome, ServeRequest, SpecError, StackConfig, StackPoint, TtftMarks, VOCABULARY, dbg_el, operator_text, profile, serve_request, }; @@ -31,9 +31,9 @@ pub(super) type Served<'a, 'ctx> = (std::result::Result, Verifier<'a, 'ctx>, Option); /// Run the request over the engine built from `verifier` and `host`, settle the state and finish the host. -pub(super) fn serve_over_host<'a, 'ctx>( +pub(super) fn serve_over_host<'a, 'ctx, P: OriginalServePool<'ctx>>( verifier: Verifier<'a, 'ctx>, - host: Result>, + host: Result>, request: &ServeRequest, channels: (&mut impl FnMut(&[i32]) -> Result<()>, &mut impl FnMut() -> bool), mut env: ServeEnv<'_, 'ctx>, @@ -104,9 +104,9 @@ fn note_request_end( } /// After the request: the GPU profile line, then the state settle that the conversation cache or the prefix tail needs. -fn settle_served<'a, 'ctx>( +fn settle_served<'a, 'ctx, P: OriginalServePool<'ctx>>( verifier: &mut Verifier<'a, 'ctx>, - host: &mut OriginalServeHost<'_, 'ctx>, + host: &mut OriginalServeHost<'_, 'ctx, P>, result: &std::result::Result, env: &mut ServeEnv<'_, 'ctx>, ) { @@ -124,8 +124,8 @@ fn settle_served<'a, 'ctx>( /// Whether the session can be continued as is (`live`: conversation cache) and whether the prefix tail checkpoints /// (`tail`). -fn settle_wanted( - host: &OriginalServeHost<'_, '_>, +fn settle_wanted<'ctx, P: OriginalServePool<'ctx>>( + host: &OriginalServeHost<'_, 'ctx, P>, result: &std::result::Result, env: &ServeEnv<'_, '_>, ) -> (bool, bool) { @@ -144,9 +144,9 @@ fn settle_wanted( } /// Settle the verifier's recurrent state into the session and note what the settled session is good for. -fn settle_state_into<'a, 'ctx>( +fn settle_state_into<'a, 'ctx, P: OriginalServePool<'ctx>>( verifier: &mut Verifier<'a, 'ctx>, - host: &mut OriginalServeHost<'_, 'ctx>, + host: &mut OriginalServeHost<'_, 'ctx, P>, env: &mut ServeEnv<'_, 'ctx>, wanted: (bool, bool), ) {