diff --git a/architecture-baseline.json b/architecture-baseline.json index 040f6759..07b4646f 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -4,9 +4,7 @@ "forbidden-dep leleka-memory libc", "forbidden-dep leleka-memory windows-sys" ], - "oversize": { - "crates/backend-api/src/lib.rs": 756 - }, + "oversize": {}, "source": { "dyn-trait:leleka-backend-api": 1, "dyn-trait:leleka-cpu-worker": 4, @@ -14,7 +12,7 @@ "dyn-trait:leleka-deploy": 17, "dyn-trait:leleka-engine-core": 18, "dyn-trait:leleka-engine-fake": 1, - "dyn-trait:leleka-engine-qwen35-cuda": 51, + "dyn-trait:leleka-engine-qwen35-cuda": 50, "dyn-trait:leleka-experimental-ref": 3, "dyn-trait:leleka-gateway-domain": 5, "dyn-trait:leleka-gptoss": 10, diff --git a/crates/backend-api/src/event_sender_types.rs b/crates/backend-api/src/event_sender_types.rs new file mode 100644 index 00000000..c8143a5c --- /dev/null +++ b/crates/backend-api/src/event_sender_types.rs @@ -0,0 +1,21 @@ +//! Moved out of the parent module by STRA-338: EventSender, GenerationStream, StreamError. + +#[allow(unused_imports)] +use super::*; + +pub(super) enum EventSender { + Unbounded(Sender), + Bounded(SyncSender), +} + +/// Consumer side. End-of-channel without a terminal event is a protocol error. +pub struct GenerationStream { + pub(super) receiver: Receiver, + pub(super) receiver_closed: Arc, + pub(super) terminal_seen: bool, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum StreamError { + MissingTerminal, +} diff --git a/crates/backend-api/src/impl_backendidentity.rs b/crates/backend-api/src/impl_backendidentity.rs new file mode 100644 index 00000000..d85fe763 --- /dev/null +++ b/crates/backend-api/src/impl_backendidentity.rs @@ -0,0 +1,226 @@ +//! Moved out of the parent module by STRA-338: impl BackendIdentity, impl ModelDescriptor, impl BackendCapabilities, impl fmt_Display_for, impl std_error_Error, impl fmt_Display_for .... + +#[allow(unused_imports)] +use super::*; + +impl BackendIdentity { + pub fn supports_current_api(&self) -> bool { + self.api_version == BACKEND_API_VERSION + } +} + +impl ModelDescriptor { + pub fn validate(&self) -> Result<(), ContractError> { + for (field, value) in [ + ("family", self.family.as_str()), + ("architecture", self.architecture.as_str()), + ("weight_format", self.weight_format.as_str()), + ] { + if value.is_empty() + || value + .chars() + .any(|ch| ch.is_whitespace() || ch.is_control()) + { + return Err(ContractError::InvalidField(field)); + } + } + let Some(hex) = self.artifact_digest.strip_prefix("sha256:") else { + return Err(ContractError::InvalidField("artifact_digest")); + }; + if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(ContractError::InvalidField("artifact_digest")); + } + Ok(()) + } +} + +impl BackendCapabilities { + /// Refuse malformed descriptors and combinations not explicitly advertised. + /// + /// This checks declared compatibility only; it does not verify artifact bytes + /// or admit memory, concurrency, hardware, or an experimental runtime mode. + pub fn supports(&self, model: &ModelDescriptor) -> bool { + model.validate().is_ok() + && self.supported_models.iter().any(|supported| { + supported.family == model.family + && supported.architecture == model.architecture + && supported.weight_format == model.weight_format + }) + } +} + +impl fmt::Display for ContractError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidField(field) => write!(f, "invalid {field}"), + Self::UnsupportedApiVersion(version) => { + write!(f, "backend API version {version} is unsupported") + } + Self::GenerationAlreadyTerminal => { + f.write_str("generation already has a terminal event") + } + Self::GenerationBackpressure => f.write_str("generation event queue is full"), + Self::GenerationClosed => f.write_str("generation event stream is closed"), + } + } +} + +impl std::error::Error for ContractError {} + +impl fmt::Display for BackendError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}: {}", self.code, self.message) + } +} + +impl std::error::Error for BackendError {} + +impl GenerationSink { + pub fn channel() -> (Self, GenerationStream) { + let (sender, receiver) = mpsc::channel(); + let closed = Arc::new(AtomicBool::new(false)); + ( + Self { + sender: EventSender::Unbounded(sender), + receiver_closed: Arc::clone(&closed), + terminal_sent: Mutex::new(false), + }, + GenerationStream { + receiver, + receiver_closed: closed, + terminal_seen: false, + }, + ) + } + + /// A finite event queue of 1..=16 events; invalid capacities are refused + /// before the channel can allocate or become a rendezvous channel. + pub fn bounded_channel(capacity: usize) -> Result<(Self, GenerationStream), ContractError> { + if !(1..=16).contains(&capacity) { + return Err(ContractError::InvalidField("event_capacity")); + } + let (sender, receiver) = mpsc::sync_channel(capacity); + let closed = Arc::new(AtomicBool::new(false)); + Ok(( + Self { + sender: EventSender::Bounded(sender), + receiver_closed: Arc::clone(&closed), + terminal_sent: Mutex::new(false), + }, + GenerationStream { + receiver, + receiver_closed: closed, + terminal_seen: false, + }, + )) + } + + /// Receiver destruction is observable without sending a token/event. + pub fn is_closed(&self) -> bool { + self.receiver_closed.load(Ordering::Acquire) + } + + /// Never block cancellation behind a full event queue. A rejected terminal + /// has not been published and may be retried until capacity becomes available. + pub fn try_emit(&self, event: GenerationEvent) -> Result<(), ContractError> { + let is_terminal = matches!(event, GenerationEvent::Terminal(_)); + let mut terminal_sent = self + .terminal_sent + .lock() + .map_err(|_| ContractError::GenerationClosed)?; + if *terminal_sent { + return Err(ContractError::GenerationAlreadyTerminal); + } + match &self.sender { + EventSender::Unbounded(sender) => sender + .send(event) + .map_err(|_| ContractError::GenerationClosed)?, + EventSender::Bounded(sender) => { + sender.try_send(event).map_err(|error| match error { + TrySendError::Full(_) => ContractError::GenerationBackpressure, + TrySendError::Disconnected(_) => ContractError::GenerationClosed, + })? + } + } + if is_terminal { + *terminal_sent = true; + } + Ok(()) + } + + pub fn emit(&self, event: GenerationEvent) -> Result<(), ContractError> { + let is_terminal = matches!(event, GenerationEvent::Terminal(_)); + let mut terminal_sent = self.terminal_sent.lock().expect("generation lock poisoned"); + if *terminal_sent { + return Err(ContractError::GenerationAlreadyTerminal); + } + match &self.sender { + EventSender::Unbounded(sender) => sender.send(event), + EventSender::Bounded(sender) => sender.send(event), + } + .map_err(|SendError(_)| ContractError::GenerationClosed)?; + if is_terminal { + *terminal_sent = true; + } + Ok(()) + } + + pub fn complete(&self, reason: FinishReason, usage: Usage) -> Result<(), ContractError> { + self.emit(GenerationEvent::Terminal(GenerationTerminal::Completed { + reason, + usage, + })) + } + + pub fn fail( + &self, + code: ErrorCode, + message: impl Into, + retryable: bool, + ) -> Result<(), ContractError> { + self.emit(GenerationEvent::Terminal(GenerationTerminal::Failed { + code, + message: message.into(), + retryable, + })) + } + + pub fn cancel(&self) -> Result<(), ContractError> { + self.emit(GenerationEvent::Terminal(GenerationTerminal::Cancelled)) + } +} + +impl Drop for GenerationStream { + fn drop(&mut self) { + self.receiver_closed.store(true, Ordering::Release); + } +} + +impl GenerationStream { + pub fn recv(&mut self) -> Result, StreamError> { + if self.terminal_seen { + return Ok(None); + } + match self.receiver.recv() { + Ok(event) => { + if matches!(event, GenerationEvent::Terminal(_)) { + self.terminal_seen = true; + } + Ok(Some(event)) + } + Err(RecvError) => Err(StreamError::MissingTerminal), + } + } +} + +impl fmt::Display for StreamError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MissingTerminal => { + f.write_str("generation stream closed without a terminal event") + } + } + } +} + +impl std::error::Error for StreamError {} diff --git a/crates/backend-api/src/lib.rs b/crates/backend-api/src/lib.rs index e98b88b9..b16c6c96 100644 --- a/crates/backend-api/src/lib.rs +++ b/crates/backend-api/src/lib.rs @@ -17,473 +17,6 @@ pub mod scripted; pub use load_mode::{InferenceMode, KarExpertLoad, KarPrefillMode, LOAD_CONFIG_VERSION}; pub use recent_ids::{DEFAULT_RECENT_IDS, RecentIds}; -/// The most output tokens one generation may ask for. A single agent turn that writes a whole source file in one tool call -/// needs well over the 4,096 this used to be (found by the Codex run of the e2e job 943: three 4,096-token turns in a row -/// ended the session); 32,768 is the default budget of the HTTP layer. -pub const MAX_OUTPUT_TOKENS: u32 = 32_768; - -/// Version understood by this crate and advertised in [`BackendIdentity`]. -// Version 2 replaces independent capability axes with explicit model tuples. -// Version 1 identities must be refused rather than reinterpreted as version 2. -pub const BACKEND_API_VERSION: u16 = 2; - -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct BackendIdentity { - pub name: String, - pub implementation_version: String, - pub api_version: u16, -} - -impl BackendIdentity { - pub fn supports_current_api(&self) -> bool { - self.api_version == BACKEND_API_VERSION - } -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct ModelDescriptor { - /// Stable family identifier, for example `qwen3_moe` or `mixtral`. - pub family: String, - /// Architecture revision understood by the backend. - pub architecture: String, - /// Exact model artifact digest, formatted as `sha256:`. - pub artifact_digest: String, - /// Weight format and quantization, for example `gguf:iq3_s`. - pub weight_format: String, -} - -impl ModelDescriptor { - pub fn validate(&self) -> Result<(), ContractError> { - for (field, value) in [ - ("family", self.family.as_str()), - ("architecture", self.architecture.as_str()), - ("weight_format", self.weight_format.as_str()), - ] { - if value.is_empty() - || value - .chars() - .any(|ch| ch.is_whitespace() || ch.is_control()) - { - return Err(ContractError::InvalidField(field)); - } - } - let Some(hex) = self.artifact_digest.strip_prefix("sha256:") else { - return Err(ContractError::InvalidField("artifact_digest")); - }; - if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { - return Err(ContractError::InvalidField("artifact_digest")); - } - Ok(()) - } -} - -/// One explicitly supported family, architecture and weight format combination. -/// -/// Advertising two tuples does not advertise any combination of their fields. -/// An artifact digest is supplied by the descriptor and verified during loading. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct SupportedModelTuple { - pub family: String, - pub architecture: String, - pub weight_format: String, -} - -#[derive(Clone, Debug, Default, Eq, PartialEq)] -pub struct BackendCapabilities { - /// Exact supported combinations. An empty list advertises no model support. - pub supported_models: Vec, - pub max_concurrent_generations: usize, - pub supports_cancellation: bool, - pub supports_tool_call_streaming: bool, -} - -impl BackendCapabilities { - /// Refuse malformed descriptors and combinations not explicitly advertised. - /// - /// This checks declared compatibility only; it does not verify artifact bytes - /// or admit memory, concurrency, hardware, or an experimental runtime mode. - pub fn supports(&self, model: &ModelDescriptor) -> bool { - model.validate().is_ok() - && self.supported_models.iter().any(|supported| { - supported.family == model.family - && supported.architecture == model.architecture - && supported.weight_format == model.weight_format - }) - } -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct RuntimeConfig { - /// Version of the operator's load configuration, separate from transport. - pub load_config_version: u16, - /// Fixed for this load; experimental consent never selects a mode. - pub inference_mode: InferenceMode, - /// Requested GPU memory ceiling in bytes. `None` leaves policy to the host. - pub gpu_memory_limit_bytes: Option, - /// Whether the caller explicitly permits an experimental/lossy path. - pub allow_experimental: bool, -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct LoadedModel { - pub handle: String, - pub descriptor: ModelDescriptor, - pub load_config_version: u16, - /// The path actually admitted, not merely a requested or available option. - pub effective_mode: InferenceMode, - /// Verified model/profile/archive/implementation identity used by caches. - pub mode_identity_digest: String, -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct GenerationRequest { - pub request_id: String, - pub prompt: String, - pub max_output_tokens: u32, - /// Thousandths; 0 is greedy. - pub temperature_milli: u32, - /// Remaining sampling controls. All-`None` keeps the Original defaults. - pub sampling: SamplingOptions, -} - -/// Sampling controls beyond temperature, as the Original serving layer takes them. -/// Fractions are fixed-point millionths so a request stays `Eq`; the runtime -/// validates ranges (see `leleka-sampler-ref`). `None` keeps the Original's default. -#[derive(Clone, Debug, Default, Eq, PartialEq)] -pub struct SamplingOptions { - /// `0..=1_000_000`; 1_000_000 disables nucleus filtering. - pub top_p_micro: Option, - /// Integer; 0 or above 64 selects the widest list (64). - pub top_k: Option, - /// `0..=1_000_000`. - pub min_p_micro: Option, - /// `> 0`; 1_000_000 is off. - pub repetition_penalty_micro: Option, - /// `-2_000_000..=2_000_000`. - pub frequency_penalty_micro: Option, - /// `-2_000_000..=2_000_000`. - pub presence_penalty_micro: Option, - pub penalty_last_n: Option, - /// `None` or 0 draws a fresh seed per request. - pub seed: Option, -} - -#[derive(Clone, Debug, Default, Eq, PartialEq)] -pub struct Usage { - pub input_tokens: u64, - pub output_tokens: u64, - pub reused_input_tokens: u64, -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum FinishReason { - Stop, - Length, - ToolCalls, -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum ErrorCode { - InvalidRequest, - UnsupportedModel, - ResourceExhausted, - BackendUnavailable, - Internal, -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum GenerationEvent { - TextDelta { - text: String, - }, - ToolCallDelta { - index: u32, - id: Option, - name: Option, - arguments_delta: String, - }, - Usage(Usage), - Terminal(GenerationTerminal), -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum GenerationTerminal { - Completed { - reason: FinishReason, - usage: Usage, - }, - Failed { - code: ErrorCode, - message: String, - retryable: bool, - }, - Cancelled, -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum ContractError { - InvalidField(&'static str), - UnsupportedApiVersion(u16), - GenerationAlreadyTerminal, - GenerationClosed, - GenerationBackpressure, -} - -impl fmt::Display for ContractError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidField(field) => write!(f, "invalid {field}"), - Self::UnsupportedApiVersion(version) => { - write!(f, "backend API version {version} is unsupported") - } - Self::GenerationAlreadyTerminal => { - f.write_str("generation already has a terminal event") - } - Self::GenerationBackpressure => f.write_str("generation event queue is full"), - Self::GenerationClosed => f.write_str("generation event stream is closed"), - } - } -} - -impl std::error::Error for ContractError {} - -/// Implemented by runtime backends. A backend must not advertise a model tuple -/// until it can load and serve that combination with the declared semantics. -pub trait Backend: Send { - fn identity(&self) -> BackendIdentity; - fn capabilities(&self) -> BackendCapabilities; - fn load( - &mut self, - model: ModelDescriptor, - config: RuntimeConfig, - ) -> Result; - fn start_generation( - &mut self, - model: &LoadedModel, - request: GenerationRequest, - ) -> Result; - fn cancel(&mut self, request_id: &str) -> Result<(), BackendError>; - fn unload(&mut self, model: LoadedModel) -> Result<(), BackendError>; - /// JSON summary of the backend's cross-session prefix cache for a pool router (`docs/prefix-cache.md`, - /// "Pool protocol"): the checkpoint heads it holds as block-hash-chain values with the tokens each covers. - /// `None`: no such cache (the default), or nothing to report yet. Cheap and non-blocking by contract. - fn prefix_cache_summary(&self) -> Option { - None - } - /// JSON report of the backend's memory governor (`docs/memory-safety.md`): the pressure level and Retry-After the front end gates - /// requests with, the plan, the allocation inventory and the counters. `None`: this backend has no governor (the default). - /// Cheap and non-blocking by contract (the text was rendered by the governor's own thread). - fn memory_report(&self) -> Option { - None - } - /// JSON telemetry of the backend for the operator (`leleka status`): GPU load and VRAM, host RAM, CPU cores in use, prefill and - /// decode tokens per second, prefix-cache hits and the context in use. `None`: this backend reports none (the default). - /// Cheap and non-blocking by contract (the text was rendered by the backend's sampler thread). - fn telemetry_report(&self) -> Option { - None - } - /// Change the inference settings of a running engine (context length, caches, resources) by reopening its serve stack without - /// reloading the model. `settings_json` is a JSON object whose members are all optional; the reply is the effective settings as - /// JSON. Refused while a generation is active. The default: not supported. - fn reconfigure(&mut self, _settings_json: &str) -> Result { - Err(BackendError { - code: ErrorCode::UnsupportedModel, - message: "this backend cannot be reconfigured at run time".into(), - retryable: false, - }) - } -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct BackendError { - pub code: ErrorCode, - pub message: String, - pub retryable: bool, -} - -impl fmt::Display for BackendError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}: {}", self.code, self.message) - } -} - -impl std::error::Error for BackendError {} - -/// Producer side of a generation stream. It serializes sends and allows only -/// one terminal event; deltas after completion are rejected. -pub struct GenerationSink { - sender: EventSender, - receiver_closed: Arc, - terminal_sent: Mutex, -} - -impl GenerationSink { - pub fn channel() -> (Self, GenerationStream) { - let (sender, receiver) = mpsc::channel(); - let closed = Arc::new(AtomicBool::new(false)); - ( - Self { - sender: EventSender::Unbounded(sender), - receiver_closed: Arc::clone(&closed), - terminal_sent: Mutex::new(false), - }, - GenerationStream { - receiver, - receiver_closed: closed, - terminal_seen: false, - }, - ) - } - - /// A finite event queue of 1..=16 events; invalid capacities are refused - /// before the channel can allocate or become a rendezvous channel. - pub fn bounded_channel(capacity: usize) -> Result<(Self, GenerationStream), ContractError> { - if !(1..=16).contains(&capacity) { - return Err(ContractError::InvalidField("event_capacity")); - } - let (sender, receiver) = mpsc::sync_channel(capacity); - let closed = Arc::new(AtomicBool::new(false)); - Ok(( - Self { - sender: EventSender::Bounded(sender), - receiver_closed: Arc::clone(&closed), - terminal_sent: Mutex::new(false), - }, - GenerationStream { - receiver, - receiver_closed: closed, - terminal_seen: false, - }, - )) - } - - /// Receiver destruction is observable without sending a token/event. - pub fn is_closed(&self) -> bool { - self.receiver_closed.load(Ordering::Acquire) - } - - /// Never block cancellation behind a full event queue. A rejected terminal - /// has not been published and may be retried until capacity becomes available. - pub fn try_emit(&self, event: GenerationEvent) -> Result<(), ContractError> { - let is_terminal = matches!(event, GenerationEvent::Terminal(_)); - let mut terminal_sent = self - .terminal_sent - .lock() - .map_err(|_| ContractError::GenerationClosed)?; - if *terminal_sent { - return Err(ContractError::GenerationAlreadyTerminal); - } - match &self.sender { - EventSender::Unbounded(sender) => sender - .send(event) - .map_err(|_| ContractError::GenerationClosed)?, - EventSender::Bounded(sender) => { - sender.try_send(event).map_err(|error| match error { - TrySendError::Full(_) => ContractError::GenerationBackpressure, - TrySendError::Disconnected(_) => ContractError::GenerationClosed, - })? - } - } - if is_terminal { - *terminal_sent = true; - } - Ok(()) - } - - pub fn emit(&self, event: GenerationEvent) -> Result<(), ContractError> { - let is_terminal = matches!(event, GenerationEvent::Terminal(_)); - let mut terminal_sent = self.terminal_sent.lock().expect("generation lock poisoned"); - if *terminal_sent { - return Err(ContractError::GenerationAlreadyTerminal); - } - match &self.sender { - EventSender::Unbounded(sender) => sender.send(event), - EventSender::Bounded(sender) => sender.send(event), - } - .map_err(|SendError(_)| ContractError::GenerationClosed)?; - if is_terminal { - *terminal_sent = true; - } - Ok(()) - } - - pub fn complete(&self, reason: FinishReason, usage: Usage) -> Result<(), ContractError> { - self.emit(GenerationEvent::Terminal(GenerationTerminal::Completed { - reason, - usage, - })) - } - - pub fn fail( - &self, - code: ErrorCode, - message: impl Into, - retryable: bool, - ) -> Result<(), ContractError> { - self.emit(GenerationEvent::Terminal(GenerationTerminal::Failed { - code, - message: message.into(), - retryable, - })) - } - - pub fn cancel(&self) -> Result<(), ContractError> { - self.emit(GenerationEvent::Terminal(GenerationTerminal::Cancelled)) - } -} - -enum EventSender { - Unbounded(Sender), - Bounded(SyncSender), -} - -/// Consumer side. End-of-channel without a terminal event is a protocol error. -pub struct GenerationStream { - receiver: Receiver, - receiver_closed: Arc, - terminal_seen: bool, -} - -impl Drop for GenerationStream { - fn drop(&mut self) { - self.receiver_closed.store(true, Ordering::Release); - } -} - -impl GenerationStream { - pub fn recv(&mut self) -> Result, StreamError> { - if self.terminal_seen { - return Ok(None); - } - match self.receiver.recv() { - Ok(event) => { - if matches!(event, GenerationEvent::Terminal(_)) { - self.terminal_seen = true; - } - Ok(Some(event)) - } - Err(RecvError) => Err(StreamError::MissingTerminal), - } - } -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum StreamError { - MissingTerminal, -} - -impl fmt::Display for StreamError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::MissingTerminal => { - f.write_str("generation stream closed without a terminal event") - } - } - } -} - -impl std::error::Error for StreamError {} - #[cfg(test)] mod tests { use super::*; @@ -754,3 +287,52 @@ mod tests { ); } } + +mod max_output_tokens_types; +#[allow(unused_imports)] +pub use max_output_tokens_types::BACKEND_API_VERSION; +#[allow(unused_imports)] +pub use max_output_tokens_types::Backend; +#[allow(unused_imports)] +pub use max_output_tokens_types::BackendCapabilities; +#[allow(unused_imports)] +pub use max_output_tokens_types::BackendError; +#[allow(unused_imports)] +pub use max_output_tokens_types::BackendIdentity; +#[allow(unused_imports)] +pub use max_output_tokens_types::ContractError; +#[allow(unused_imports)] +pub use max_output_tokens_types::ErrorCode; +#[allow(unused_imports)] +pub use max_output_tokens_types::FinishReason; +#[allow(unused_imports)] +pub use max_output_tokens_types::GenerationEvent; +#[allow(unused_imports)] +pub use max_output_tokens_types::GenerationRequest; +#[allow(unused_imports)] +pub use max_output_tokens_types::GenerationSink; +#[allow(unused_imports)] +pub use max_output_tokens_types::GenerationTerminal; +#[allow(unused_imports)] +pub use max_output_tokens_types::LoadedModel; +#[allow(unused_imports)] +pub use max_output_tokens_types::MAX_OUTPUT_TOKENS; +#[allow(unused_imports)] +pub use max_output_tokens_types::ModelDescriptor; +#[allow(unused_imports)] +pub use max_output_tokens_types::RuntimeConfig; +#[allow(unused_imports)] +pub use max_output_tokens_types::SamplingOptions; +#[allow(unused_imports)] +pub use max_output_tokens_types::SupportedModelTuple; +#[allow(unused_imports)] +pub use max_output_tokens_types::Usage; +mod event_sender_types; +#[allow(unused_imports)] +use event_sender_types::EventSender; +#[allow(unused_imports)] +pub use event_sender_types::GenerationStream; +#[allow(unused_imports)] +pub use event_sender_types::StreamError; + +mod impl_backendidentity; diff --git a/crates/backend-api/src/max_output_tokens_types.rs b/crates/backend-api/src/max_output_tokens_types.rs new file mode 100644 index 00000000..5257e3d8 --- /dev/null +++ b/crates/backend-api/src/max_output_tokens_types.rs @@ -0,0 +1,232 @@ +//! Moved out of the parent module by STRA-338: MAX_OUTPUT_TOKENS, BACKEND_API_VERSION, BackendIdentity, ModelDescriptor, SupportedModelTuple, BackendCapabilities .... + +#[allow(unused_imports)] +use super::*; + +/// The most output tokens one generation may ask for. A single agent turn that writes a whole source file in one tool call +/// needs well over the 4,096 this used to be (found by the Codex run of the e2e job 943: three 4,096-token turns in a row +/// ended the session); 32,768 is the default budget of the HTTP layer. +pub const MAX_OUTPUT_TOKENS: u32 = 32_768; + +/// Version understood by this crate and advertised in [`BackendIdentity`]. +// Version 2 replaces independent capability axes with explicit model tuples. +// Version 1 identities must be refused rather than reinterpreted as version 2. +pub const BACKEND_API_VERSION: u16 = 2; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct BackendIdentity { + pub name: String, + pub implementation_version: String, + pub api_version: u16, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ModelDescriptor { + /// Stable family identifier, for example `qwen3_moe` or `mixtral`. + pub family: String, + /// Architecture revision understood by the backend. + pub architecture: String, + /// Exact model artifact digest, formatted as `sha256:`. + pub artifact_digest: String, + /// Weight format and quantization, for example `gguf:iq3_s`. + pub weight_format: String, +} + +/// One explicitly supported family, architecture and weight format combination. +/// +/// Advertising two tuples does not advertise any combination of their fields. +/// An artifact digest is supplied by the descriptor and verified during loading. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SupportedModelTuple { + pub family: String, + pub architecture: String, + pub weight_format: String, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct BackendCapabilities { + /// Exact supported combinations. An empty list advertises no model support. + pub supported_models: Vec, + pub max_concurrent_generations: usize, + pub supports_cancellation: bool, + pub supports_tool_call_streaming: bool, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RuntimeConfig { + /// Version of the operator's load configuration, separate from transport. + pub load_config_version: u16, + /// Fixed for this load; experimental consent never selects a mode. + pub inference_mode: InferenceMode, + /// Requested GPU memory ceiling in bytes. `None` leaves policy to the host. + pub gpu_memory_limit_bytes: Option, + /// Whether the caller explicitly permits an experimental/lossy path. + pub allow_experimental: bool, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct LoadedModel { + pub handle: String, + pub descriptor: ModelDescriptor, + pub load_config_version: u16, + /// The path actually admitted, not merely a requested or available option. + pub effective_mode: InferenceMode, + /// Verified model/profile/archive/implementation identity used by caches. + pub mode_identity_digest: String, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct GenerationRequest { + pub request_id: String, + pub prompt: String, + pub max_output_tokens: u32, + /// Thousandths; 0 is greedy. + pub temperature_milli: u32, + /// Remaining sampling controls. All-`None` keeps the Original defaults. + pub sampling: SamplingOptions, +} + +/// Sampling controls beyond temperature, as the Original serving layer takes them. +/// Fractions are fixed-point millionths so a request stays `Eq`; the runtime +/// validates ranges (see `leleka-sampler-ref`). `None` keeps the Original's default. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct SamplingOptions { + /// `0..=1_000_000`; 1_000_000 disables nucleus filtering. + pub top_p_micro: Option, + /// Integer; 0 or above 64 selects the widest list (64). + pub top_k: Option, + /// `0..=1_000_000`. + pub min_p_micro: Option, + /// `> 0`; 1_000_000 is off. + pub repetition_penalty_micro: Option, + /// `-2_000_000..=2_000_000`. + pub frequency_penalty_micro: Option, + /// `-2_000_000..=2_000_000`. + pub presence_penalty_micro: Option, + pub penalty_last_n: Option, + /// `None` or 0 draws a fresh seed per request. + pub seed: Option, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct Usage { + pub input_tokens: u64, + pub output_tokens: u64, + pub reused_input_tokens: u64, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum FinishReason { + Stop, + Length, + ToolCalls, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ErrorCode { + InvalidRequest, + UnsupportedModel, + ResourceExhausted, + BackendUnavailable, + Internal, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum GenerationEvent { + TextDelta { + text: String, + }, + ToolCallDelta { + index: u32, + id: Option, + name: Option, + arguments_delta: String, + }, + Usage(Usage), + Terminal(GenerationTerminal), +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum GenerationTerminal { + Completed { + reason: FinishReason, + usage: Usage, + }, + Failed { + code: ErrorCode, + message: String, + retryable: bool, + }, + Cancelled, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ContractError { + InvalidField(&'static str), + UnsupportedApiVersion(u16), + GenerationAlreadyTerminal, + GenerationClosed, + GenerationBackpressure, +} + +/// Implemented by runtime backends. A backend must not advertise a model tuple +/// until it can load and serve that combination with the declared semantics. +pub trait Backend: Send { + fn identity(&self) -> BackendIdentity; + fn capabilities(&self) -> BackendCapabilities; + fn load( + &mut self, + model: ModelDescriptor, + config: RuntimeConfig, + ) -> Result; + fn start_generation( + &mut self, + model: &LoadedModel, + request: GenerationRequest, + ) -> Result; + fn cancel(&mut self, request_id: &str) -> Result<(), BackendError>; + fn unload(&mut self, model: LoadedModel) -> Result<(), BackendError>; + /// JSON summary of the backend's cross-session prefix cache for a pool router (`docs/prefix-cache.md`, + /// "Pool protocol"): the checkpoint heads it holds as block-hash-chain values with the tokens each covers. + /// `None`: no such cache (the default), or nothing to report yet. Cheap and non-blocking by contract. + fn prefix_cache_summary(&self) -> Option { + None + } + /// JSON report of the backend's memory governor (`docs/memory-safety.md`): the pressure level and Retry-After the front end gates + /// requests with, the plan, the allocation inventory and the counters. `None`: this backend has no governor (the default). + /// Cheap and non-blocking by contract (the text was rendered by the governor's own thread). + fn memory_report(&self) -> Option { + None + } + /// JSON telemetry of the backend for the operator (`leleka status`): GPU load and VRAM, host RAM, CPU cores in use, prefill and + /// decode tokens per second, prefix-cache hits and the context in use. `None`: this backend reports none (the default). + /// Cheap and non-blocking by contract (the text was rendered by the backend's sampler thread). + fn telemetry_report(&self) -> Option { + None + } + /// Change the inference settings of a running engine (context length, caches, resources) by reopening its serve stack without + /// reloading the model. `settings_json` is a JSON object whose members are all optional; the reply is the effective settings as + /// JSON. Refused while a generation is active. The default: not supported. + fn reconfigure(&mut self, _settings_json: &str) -> Result { + Err(BackendError { + code: ErrorCode::UnsupportedModel, + message: "this backend cannot be reconfigured at run time".into(), + retryable: false, + }) + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct BackendError { + pub code: ErrorCode, + pub message: String, + pub retryable: bool, +} + +/// Producer side of a generation stream. It serializes sends and allows only +/// one terminal event; deltas after completion are rejected. +pub struct GenerationSink { + pub(super) sender: EventSender, + pub(super) receiver_closed: Arc, + pub(super) terminal_sent: Mutex, +} diff --git a/crates/cuda-driver/src/native_prompt_device.rs b/crates/cuda-driver/src/native_prompt_device.rs index 9ce2b07d..7da47a90 100644 --- a/crates/cuda-driver/src/native_prompt_device.rs +++ b/crates/cuda-driver/src/native_prompt_device.rs @@ -11,6 +11,7 @@ use std::ffi::CStr; const RESERVE: usize = 128 << 20; #[path = "native_prompt_device_stage.rs"] mod stage_impl; +mod stage_phases; pub use stage_impl::PromptInputStage; const PLE_PTX: &[u8] = concat!(include_str!("ple_prompt_device.ptx"), "\0").as_bytes(); const PLE_SHA: [u8; 32] = [ diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originaldeviceblock.rs b/crates/cuda-driver/src/native_prompt_device/impl_originaldeviceblock.rs index 848d8871..59ea01ff 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originaldeviceblock.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originaldeviceblock.rs @@ -25,6 +25,16 @@ impl<'ctx> Context<'ctx> { if prior.iter().any(|x| !x.is_finite()) { return Err(Error::NonFiniteMmqOutput("PLE prior")); } + self.check_history_budget()?; + let staging = encode(prior)?; + let mut buffer = self.allocate(368640)?; + if let Err(e) = buffer.copy_from_owned(staging) { + let _ = buffer.release(); + return Err(e); + } + Ok(OriginalPleHistory { context: self, buffer: Some(buffer), failed: false }) + } + fn check_history_budget(&self) -> Result<()> { if self.is_poisoned() { return Err(Error::ContextPoisoned); } @@ -34,13 +44,7 @@ impl<'ctx> Context<'ctx> { { return Err(Error::BudgetExceeded); } - let staging = encode(prior)?; - let mut buffer = self.allocate(368640)?; - if let Err(e) = buffer.copy_from_owned(staging) { - let _ = buffer.release(); - return Err(e); - } - Ok(OriginalPleHistory { context: self, buffer: Some(buffer), failed: false }) + Ok(()) } } impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> { @@ -93,6 +97,11 @@ impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> { return Err(Error::InvalidQwenShape); } self.lease.drain()?; + let raw = self.read_row_bytes(index)?; + decode_final_row(&raw) + } + /// Copies one R row down under the context guard; an uncertain drain leaks the staging. + fn read_row_bytes(&mut self, index: usize) -> Result> { let context = self.lease.context(); let (handle, span_bytes) = self.lease.common_span(S::R)?; let row = handle.checked_subspan(span_bytes, index.checked_mul(40960).ok_or(Error::InvalidSize)?, 40960)?; @@ -108,64 +117,38 @@ impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> { let operation = context.driver.api.copy_to(row, &mut raw); let drain = context.driver.api.synchronize(); let restore = guard.finish(); + self.settle_row_read([operation, drain, restore], raw) + } + /// Marks the lease failed on any error; an uncertain drain leaks the staging. + fn settle_row_read(&mut self, [operation, drain, restore]: [Result<()>; 3], raw: Vec) -> Result> { if operation.is_err() || drain.is_err() || restore.is_err() { self.lease.mark_failed(); } if drain.is_err() || restore.is_err() { std::mem::forget(raw); - context.retain_driver(); + self.lease.context().retain_driver(); return combine(combine(operation, drain), restore).map(|()| unreachable!("failed final row drain")); } combine(combine(operation, drain), restore)?; - let mut values = Vec::new(); - values.try_reserve_exact(10240).map_err(|_| Error::HostAllocation)?; - values.extend(raw.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); - if values.iter().any(|value| !value.is_finite()) { - return Err(Error::NonFiniteMmqOutput("Original final prompt row")); - } - Ok(values.into_boxed_slice()) + Ok(raw) } /// Actual final prompt row at a canonical host handoff. This consumes the /// physical lease; it cannot be used as an intermediate layer certificate. /// The runtime authenticates the final phase and requested row separately. pub fn finish_prompt_row(mut self, index: usize) -> Result> { - if index >= self.lease.rows() || self.lease.is_failed() { - return Err(Error::InvalidQwenShape); - } - self.lease.drain()?; - let context = self.lease.context(); - let (handle, span_bytes) = self.lease.common_span(S::R)?; - let row = handle.checked_subspan(span_bytes, index.checked_mul(40960).ok_or(Error::InvalidSize)?, 40960)?; - let mut raw = bytes(40960)?; - let guard = match context.enter() { - Ok(guard) => guard, - Err(error) => { - self.lease.mark_failed(); - context.retain_driver(); - return Err(error); - } - }; - let operation = context.driver.api.copy_to(row, &mut raw); - let drain = context.driver.api.synchronize(); - let restore = guard.finish(); - if operation.is_err() || drain.is_err() || restore.is_err() { - self.lease.mark_failed(); - } - if drain.is_err() || restore.is_err() { - std::mem::forget(raw); - context.retain_driver(); - return combine(combine(operation, drain), restore).map(|()| unreachable!("failed final row drain")); - } - combine(combine(operation, drain), restore)?; - let mut values = Vec::new(); - values.try_reserve_exact(10240).map_err(|_| Error::HostAllocation)?; - values.extend(raw.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); - if values.iter().any(|value| !value.is_finite()) { - return Err(Error::NonFiniteMmqOutput("Original final prompt row")); - } - Ok(values.into_boxed_slice()) + self.read_prompt_row(index) } } +/// The row's 10240 little-endian f32 values, all finite. +fn decode_final_row(raw: &[u8]) -> Result> { + let mut values = Vec::new(); + values.try_reserve_exact(10240).map_err(|_| Error::HostAllocation)?; + values.extend(raw.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); + if values.iter().any(|value| !value.is_finite()) { + return Err(Error::NonFiniteMmqOutput("Original final prompt row")); + } + Ok(values.into_boxed_slice()) +} impl<'arena, 'loan, 'ctx> OriginalDeviceGrRead<'arena, 'loan, 'ctx> { pub fn rows(&self) -> usize { self.lease.rows() diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs index 946f9864..30806277 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs @@ -11,3 +11,6 @@ mod impl_originalpromptdevice_4; mod impl_originalpromptdevice_5; mod impl_originalpromptdevice_6; mod impl_originalpromptdevice_7; +mod inject_phases; +mod ple_apply_phases; +mod run_phases; diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/gr_read_phases.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/gr_read_phases.rs index cb65cdc9..99d8702b 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/gr_read_phases.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/gr_read_phases.rs @@ -3,6 +3,18 @@ #[allow(unused_imports)] use super::*; +pub(super) const GR_READ_ORDER: [usize; 7] = [0, 1, 2, 3, 6, 4, 5]; +pub(super) const GR_READ_NAMES: [&str; 8] = [ + "GR native norm", + "GR native down", + "GR native silu", + "GR native up", + "GR native products", + "GR native mixed", + "GR native inject", + "GR native candidate", +]; + /// Spans, weights and scalars every command of one GR read shares. pub(super) struct GrReadPlan { h: [BufferHandle; 15], @@ -23,6 +35,17 @@ impl GrReadPlan { Self { h, w, flags, t, low_half } } + /// All commands of one GR read: norm, projections, mix. + pub(super) fn commands(&self, epsilon: f32, normed: bool) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?; + let fused = fused_scans(); + self.push_norm(&mut v, epsilon, normed, fused); + self.push_projections(&mut v, fused); + self.push_mix(&mut v, fused); + Ok(v) + } + fn low(&self, i: usize) -> A { if self.low_half { A::Address(self.h[i]) } else { A::NullAddress } } diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2.rs index fa4cd453..50399bd8 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2.rs @@ -3,6 +3,39 @@ #[allow(unused_imports)] use super::*; +const COMMON_ROLES: [S; 12] = [ + S::R, + S::PleEmbedding, + S::GrRS, + S::XHigh, + S::Lo, + S::LoHigh, + S::Gated, + S::Mixed, + S::MixedHigh, + S::MixedHalf, + S::Inject, + S::Block, +]; + +/// The precise PLE and GR PTX must be their pinned, NUL-terminated, NUL-free selves and the stage admitted. +fn check_sealed_assets() -> Result<()> { + // Separate new precise PLE arithmetic asset must be genuinely sealed. + if PLE_PTX.len() < 2 + || PLE_PTX.last() != Some(&0) + || PLE_PTX[..PLE_PTX.len() - 1].contains(&0) + || crate::qwen_ffi::sha256(&PLE_PTX[..PLE_PTX.len() - 1]) != PLE_SHA + || GR_PTX.len() < 2 + || GR_PTX.last() != Some(&0) + || GR_PTX[..GR_PTX.len() - 1].contains(&0) + || crate::qwen_ffi::sha256(&GR_PTX[..GR_PTX.len() - 1]) != GR_SHA + || crate::prefill_stage::admit().is_err() + { + return Err(Error::UnsupportedQwenOperation); + } + Ok(()) +} + impl<'ctx> OriginalPromptDevice<'ctx> { pub fn device_bytes(capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { @@ -17,19 +50,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { profile: GrNativeProfile, ) -> Result { let count = Self::device_bytes(capacity)?; - // Separate new precise PLE arithmetic asset must be genuinely sealed. - if PLE_PTX.len() < 2 - || PLE_PTX.last() != Some(&0) - || PLE_PTX[..PLE_PTX.len() - 1].contains(&0) - || crate::qwen_ffi::sha256(&PLE_PTX[..PLE_PTX.len() - 1]) != PLE_SHA - || GR_PTX.len() < 2 - || GR_PTX.last() != Some(&0) - || GR_PTX[..GR_PTX.len() - 1].contains(&0) - || crate::qwen_ffi::sha256(&GR_PTX[..GR_PTX.len() - 1]) != GR_SHA - || crate::prefill_stage::admit().is_err() - { - return Err(Error::UnsupportedQwenOperation); - } + check_sealed_assets()?; if context.is_poisoned() { return Err(Error::ContextPoisoned); } @@ -39,7 +60,15 @@ impl<'ctx> OriginalPromptDevice<'ctx> { { return Err(Error::BudgetExceeded); } - let mut owner = Self { + let mut owner = Self::blank(context, capacity, mode, profile); + if let Err(e) = owner.init_resources(count) { + let _ = owner.close(); + return Err(e); + } + Ok(owner) + } + fn blank(context: &'ctx Context<'ctx>, capacity: usize, mode: PleBf16Mode, profile: GrNativeProfile) -> Self { + Self { context, capacity, mode, @@ -52,40 +81,38 @@ impl<'ctx> OriginalPromptDevice<'ctx> { stage_scratch: None, profile_tag: "prompt", failed: false, - }; - let operation = (|| -> Result<()> { - owner.status = Some(context.allocate(count)?); - let guard = match context.enter() { - Ok(g) => g, - Err(e) => { - context.poison(); - context.retain_driver(); - return Err(e); - } - }; - let load = (|| -> Result<()> { - owner.pack = Some(KernelModule::load(PACK_PTX, &[c"ple_pack"])?); - owner.ple = Some(KernelModule::load(PLE_PTX, PLE_ENTRIES)?); - owner.gr = Some(KernelModule::load(GR_PTX, GR_ENTRIES)?); - owner.stage = Some(KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES)?); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poison(); - context.retain_driver() - } - combine(load, pop)?; - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = operation { - let _ = owner.close(); - return Err(e); } - Ok(owner) + } + /// Allocates the status words, loads the four kernel modules under the context guard and re-checks the reserve. + fn init_resources(&mut self, count: usize) -> Result<()> { + let context = self.context; + self.status = Some(context.allocate(count)?); + let guard = match context.enter() { + Ok(g) => g, + Err(e) => { + context.poison(); + context.retain_driver(); + return Err(e); + } + }; + let load = self.load_modules(); + let pop = guard.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver() + } + combine(load, pop)?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + fn load_modules(&mut self) -> Result<()> { + self.pack = Some(KernelModule::load(PACK_PTX, &[c"ple_pack"])?); + self.ple = Some(KernelModule::load(PLE_PTX, PLE_ENTRIES)?); + self.gr = Some(KernelModule::load(GR_PTX, GR_ENTRIES)?); + self.stage = Some(KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES)?); + Ok(()) } pub fn allocated_bytes(&self) -> usize { self.status.as_ref().map_or(0, DeviceBuffer::len) @@ -110,6 +137,19 @@ impl<'ctx> OriginalPromptDevice<'ctx> { rows: &OriginalPromptRows<'_, '_, '_>, workspace: &NativeBatchWorkspace<'_>, ) -> Result<()> { + self.check_live(rows)?; + workspace.validate_context(self.context)?; + workspace.reject_alias(self.status()?, self.capacity * 40)?; + // All whole common spans used by this owner must be actual disjoint + // arena spans, not fresh handles minted from addresses. + self.roles_clear_of_status(rows, workspace, &COMMON_ROLES)?; + if self.profile == GrNativeProfile::HighAndLow { + self.roles_clear_of_status(rows, workspace, &[S::XLow, S::LoLow])?; + self.roles_clear_of_status(rows, workspace, &[S::MixedLow, S::MixedLow])?; + } + Ok(()) + } + fn check_live(&self, rows: &OriginalPromptRows<'_, '_, '_>) -> Result<()> { if self.is_failed() || rows.is_failed() { return Err(Error::ContextPoisoned); } @@ -119,44 +159,22 @@ impl<'ctx> OriginalPromptDevice<'ctx> { if rows.rows() > self.capacity { return Err(Error::InvalidQwenShape); } - workspace.validate_context(self.context)?; - workspace.reject_alias(self.status()?, self.capacity * 40)?; - // All whole common spans used by this owner must be actual disjoint - // arena spans, not fresh handles minted from addresses. - for role in [ - S::R, - S::PleEmbedding, - S::GrRS, - S::XHigh, - S::Lo, - S::LoHigh, - S::Gated, - S::Mixed, - S::MixedHigh, - S::MixedHalf, - S::Inject, - S::Block, - ] { + Ok(()) + } + /// Each role's whole span must be a workspace-clear arena span disjoint from the status words. + fn roles_clear_of_status( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + workspace: &NativeBatchWorkspace<'_>, + roles: &[S], + ) -> Result<()> { + for &role in roles { let (h, n) = rows.common_span(role)?; workspace.reject_alias(h, n)?; if h.overlaps(n, self.status()?, self.capacity * 40) { return Err(Error::OutputAliasesInput); } } - for enabled_roles in [ - (self.profile == GrNativeProfile::HighAndLow, [S::XLow, S::LoLow]), - (self.profile == GrNativeProfile::HighAndLow, [S::MixedLow, S::MixedLow]), - ] { - if enabled_roles.0 { - for role in enabled_roles.1 { - let (h, n) = rows.common_span(role)?; - workspace.reject_alias(h, n)?; - if h.overlaps(n, self.status()?, self.capacity * 40) { - return Err(Error::OutputAliasesInput); - } - } - } - } Ok(()) } pub(in super::super) fn span(rows: &OriginalPromptRows<'_, '_, '_>, role: S, width: usize) -> Result { @@ -171,6 +189,19 @@ impl<'ctx> OriginalPromptDevice<'ctx> { size: usize, alignment: u64, ) -> Result { + let h = self.weight_handle(b, size, alignment)?; + workspace.reject_alias(h, size)?; + if h.overlaps(size, self.status()?, self.capacity * 40) { + return Err(Error::OutputAliasesInput); + } + self.weight_clear_of_roles(rows, h, size, &COMMON_ROLES)?; + if self.profile == GrNativeProfile::HighAndLow { + self.weight_clear_of_roles(rows, h, size, &[S::XLow, S::LoLow, S::MixedLow])?; + } + Ok(h) + } + /// The weight must belong to this context, have exactly `size` bytes and a valid extent. + fn weight_handle(&self, b: &DeviceBuffer<'_>, size: usize, alignment: u64) -> Result { if !std::ptr::eq(self.context, b.context) { return Err(Error::ContextMismatch); } @@ -179,38 +210,22 @@ impl<'ctx> OriginalPromptDevice<'ctx> { } let h = b.handle.ok_or(Error::ContextPoisoned)?; h.validate_projection_extent(size, alignment)?; - workspace.reject_alias(h, size)?; - if h.overlaps(size, self.status()?, self.capacity * 40) { - return Err(Error::OutputAliasesInput); - } - for role in [ - S::R, - S::PleEmbedding, - S::GrRS, - S::XHigh, - S::Lo, - S::LoHigh, - S::Gated, - S::Mixed, - S::MixedHigh, - S::MixedHalf, - S::Inject, - S::Block, - ] { + Ok(h) + } + fn weight_clear_of_roles( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + h: BufferHandle, + size: usize, + roles: &[S], + ) -> Result<()> { + for &role in roles { let (a, n) = rows.common_span(role)?; if h.overlaps(size, a, n) { return Err(Error::OutputAliasesInput); } } - if self.profile == GrNativeProfile::HighAndLow { - for role in [S::XLow, S::LoLow, S::MixedLow] { - let (a, n) = rows.common_span(role)?; - if h.overlaps(size, a, n) { - return Err(Error::OutputAliasesInput); - } - } - } - Ok(h) + Ok(()) } /// Initial authentic prompt staging only. Later phases never download R. pub fn initialize<'arena, 'loan>( diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2_2.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2_2.rs index 7d09aa3b..490bdb3b 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2_2.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2_2.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (2). #[allow(unused_imports)] +use super::run_phases::RunBuffers; use super::*; impl<'ctx> OriginalPromptDevice<'ctx> { @@ -18,24 +19,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { if rows.len() != t || rows.iter().any(|(s, e)| s.len() != 10240 || e.len() != 2560) { return Err(Error::InvalidQwenShape); } - let mut s = Vec::new(); - s.try_reserve_exact(t * 10240 * 4).map_err(|_| Error::HostAllocation)?; - let mut e = Vec::new(); - e.try_reserve_exact(t * 2560 * 4).map_err(|_| Error::HostAllocation)?; - let mut finite = true; - for (streams, embedding) in rows { - for x in streams.iter() { - finite &= x.is_finite(); - s.extend_from_slice(&x.to_le_bytes()); - } - for x in embedding.iter() { - finite &= x.is_finite(); - e.extend_from_slice(&x.to_le_bytes()); - } - } - if !finite { - return Err(Error::NonFiniteMmqOutput("Original prompt input")); - } + let (s, e) = stage_rows(rows, t)?; self.upload_initial(lease, workspace, s, e) } pub(in super::super) fn upload_initial<'arena, 'loan>( @@ -59,139 +43,77 @@ impl<'ctx> OriginalPromptDevice<'ctx> { let op = self.context.driver.api.copy_from(rh, &s).and_then(|()| self.context.driver.api.copy_from(eh, &e)); let sync = self.context.driver.api.synchronize(); let pop = guard.finish(); + self.settle_upload(&mut lease, workspace, [op, sync, pop], (s, e))?; + Ok(OriginalDeviceResidual { lease }) + } + fn settle_upload( + &mut self, + lease: &mut OriginalPromptRows<'_, '_, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + [op, sync, pop]: [Result<()>; 3], + staged: (Vec, Vec), + ) -> Result<()> { if op.is_err() || sync.is_err() || pop.is_err() { self.failed = true; lease.mark_failed(); workspace.mark_failed() } if sync.is_err() || pop.is_err() { - std::mem::forget((s, e)); + std::mem::forget(staged); self.context.retain_driver() } - combine(combine(op, sync), pop)?; - Ok(OriginalDeviceResidual { lease }) + combine(combine(op, sync), pop) } // Own every actual ABI argument until the vendor stream and readback drain. pub(in super::super) fn run( &mut self, lease: &mut OriginalPromptRows<'_, '_, '_>, workspace: &mut NativeBatchWorkspace<'ctx>, - mut commands: Vec, + commands: Vec, t: usize, stride: usize, order: &[usize], labels: &[&'static str], ) -> Result<()> { let status = self.status()?; - let zero = bytes(t * stride * 4)?; - let mut readback = bytes(t * stride * 4)?; + let mut buffers = RunBuffers::new(commands, t * stride * 4)?; let blas = workspace.blas()?; - let guard = match self.context.enter() { - Ok(g) => g, - Err(e) => { - self.failed = true; - lease.mark_failed(); - self.context.retain_driver(); - return Err(e); - } - }; - // LELEKA_PREFILL_DEFER_GUARDS (experimental, deferred_status.rs): the status words are zeroed and read back on the stream and - // looked at later (ring full, or before results leave the device); PLE (stride 10) and the profiling mode stay immediate. + let guard = self.enter_for_run(lease)?; + // LELEKA_PREFILL_DEFER_GUARDS (experimental, deferred_status.rs): the status words are zeroed and read back on + // the stream and looked at later (ring full, or before results leave the device); PLE (stride 10) and the + // profiling mode stay immediate. let defer = crate::deferred_status::enabled() && stride != 10 && !crate::command_profile::enabled(); - let status_bytes = t * stride * 4; - let mut op = if defer { - crate::deferred_status::begin(self.context, status, status_bytes, blas.stream(), self.capacity * 40) - } else { - self.context.driver.api.copy_from(status, &zero) - }; - if op.is_ok() && !defer { - op = self.context.driver.api.synchronize() - } - // LELEKA_PREFILL_PROFILE_SYNC: each command drained on its own and charged to (tag, position) - let timed = crate::command_profile::enabled(); - for (position, cmd) in commands.iter_mut().enumerate() { - if op.is_err() { - break; - } - let started = std::time::Instant::now(); - let mut label = "gemm"; - op = match cmd { - C::Kernel { family, index, grid, block, args } => { - let module = match family { - 0 => self.pack.as_ref(), - 1 => self.ple.as_ref(), - 3 => self.stage.as_ref(), - _ => self.gr.as_ref(), - } - .ok_or(Error::ContextPoisoned)?; - if timed { - let entries = match family { - 1 => PLE_ENTRIES, - 3 => crate::prefill_stage::ENTRIES, - _ => GR_ENTRIES, - }; - label = entries.get(*index).and_then(|e| e.to_str().ok()).unwrap_or("kernel"); - } - module.launch(*index, *grid, *block, blas.stream(), args) - } - C::Gemm { input, weight, output, t, n, k, alpha, beta } => { - blas.gemm_bf16(*input, *weight, *output, *t, *n, *k, alpha, beta) - } - }; - if timed && op.is_ok() { - op = blas.synchronize(); - crate::command_profile::add(self.profile_tag, position + 1, label, started.elapsed()); - } - } + let spec = (status, t * stride * 4, stride); + let op = self.begin_status(blas, spec, defer, &buffers.zero); + let op = self.launch_commands(blas, &mut buffers.commands, op)?; + let parts = ((lease, workspace), (guard, op, buffers), (spec, order, labels)); if defer { - // no host wait: the words and the cross-stream ordering are queued on the stream (deferred_status.rs) - let queued = if op.is_ok() { - crate::deferred_status::finish(self.context, status, status_bytes, blas.stream(), stride, order, labels) - } else { - op - }; - let pop = guard.finish(); - if queued.is_err() || pop.is_err() { - self.failed = true; - lease.mark_failed(); - workspace.mark_failed(); - std::mem::forget((commands, zero, readback)); - self.context.retain_driver(); - return combine(queued, pop); - } - // cuLaunchKernel copies its parameter values at the call and cuBLAS (host pointer mode) reads alpha/beta at the - // call, so the argument vectors need not outlive the enqueue (the immediate path keeps them until its drain - // as a conservative audit rule; the failure path above still leaks them) - drop(commands); - return Ok(()); + self.finish_deferred(parts.0, parts.1, parts.2) + } else { + self.finish_immediate(parts.0, parts.1, parts.2) } - let sync = blas.synchronize(); - if op.is_ok() && sync.is_ok() { - op = self.context.driver.api.copy_to(status, &mut readback) - } - let all = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if op.is_err() || sync.is_err() || all.is_err() || pop.is_err() { - self.failed = true; - lease.mark_failed(); - workspace.mark_failed() - } - if sync.is_err() || all.is_err() || pop.is_err() { - std::mem::forget((commands, zero, readback)); - self.context.retain_driver(); - return combine(combine(combine(op, sync), all), pop); - } - combine(combine(combine(op, sync), all), pop)?; - // Unknown status is never a usable finite product, including a later word after an earlier numerical flag. All actual - // kernels write 0/1. The evaluation is shared with the deferred path (deferred_status::evaluate). - if let Err(e) = crate::deferred_status::evaluate(&readback, stride, order, labels) { - if matches!(e, Error::InvalidDriverValue(_)) { - self.failed = true; - lease.mark_failed(); - self.context.retain_driver(); - } - return Err(e); - } - Ok(()) } } + +/// Each row's 10240 stream values and 2560 PLE embedding values as little-endian bytes, finite-checked in one pass. +fn stage_rows(rows: &[(&[f32], &[f32])], t: usize) -> Result<(Vec, Vec)> { + let mut s = Vec::new(); + s.try_reserve_exact(t * 10240 * 4).map_err(|_| Error::HostAllocation)?; + let mut e = Vec::new(); + e.try_reserve_exact(t * 2560 * 4).map_err(|_| Error::HostAllocation)?; + let mut finite = true; + for (streams, embedding) in rows { + for x in streams.iter() { + finite &= x.is_finite(); + s.extend_from_slice(&x.to_le_bytes()); + } + for x in embedding.iter() { + finite &= x.is_finite(); + e.extend_from_slice(&x.to_le_bytes()); + } + } + if !finite { + return Err(Error::NonFiniteMmqOutput("Original prompt input")); + } + Ok((s, e)) +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_3.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_3.rs index 322c487c..973b6d67 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_3.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_3.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (3). #[allow(unused_imports)] +use super::ple_apply_phases::ple_commands; use super::*; impl<'ctx> OriginalPromptDevice<'ctx> { @@ -14,158 +15,15 @@ impl<'ctx> OriginalPromptDevice<'ctx> { self.profile_tag = "ple"; let lease = &mut residual.lease; self.validate(lease, workspace)?; - if history.failed || !std::ptr::eq(history.context, self.context) { - return Err(Error::ContextMismatch); - } - let hb = history.buffer.as_ref().ok_or(Error::ContextPoisoned)?; - if hb.len() != 368640 { - return Err(Error::InvalidQwenShape); - } - let hist = hb.handle.ok_or(Error::ContextPoisoned)?; - hist.validate_projection_extent(368640, 4)?; - workspace.reject_alias(hist, 368640)?; - let key = self.weight(lease, workspace, weights.key, 52428800, 2)?; - let value = self.weight(lease, workspace, weights.value, 13107200, 2)?; - let mut aux = [key; 4]; - for (i, w) in weights.aux.iter().enumerate() { - aux[i] = - self.weight(lease, workspace, w, if i == 3 { 81920 } else { 40960 }, if i == 3 { 2 } else { 4 })?; - } + let hist = self.ple_history_handle(history, workspace)?; + let pw = self.ple_weights(lease, workspace, &weights)?; let sb = lease.ple_subbatch_capacity()?; let total = lease.rows(); for first in (0..total).step_by(sb) { let t = sb.min(total - first); - let rh = Self::span(lease, S::R, 40960)?.checked_subspan(total * 40960, first * 40960, t * 40960)?; - let eh = - Self::span(lease, S::PleEmbedding, 10240)?.checked_subspan(total * 10240, first * 10240, t * 10240)?; - let get = |role: P| -> Result { - let (h, n) = lease.ple_span(role, t)?; - workspace.reject_alias(h, n)?; - if h.overlaps(n, hist, 368640) || h.overlaps(n, self.status()?, self.capacity * 40) { - return Err(Error::OutputAliasesInput); - } - for (w, wn) in [ - (key, 52428800), - (value, 13107200), - (aux[0], 40960), - (aux[1], 40960), - (aux[2], 40960), - (aux[3], 81920), - ] { - if h.overlaps(n, w, wn) { - return Err(Error::OutputAliasesInput); - } - } - Ok(h) - }; - let kh = get(P::Key)?; - let qn = get(P::Qn)?; - let gated = get(P::Gated)?; - let val = get(P::Value)?; - let gate = get(P::Gate)?; - let packed = get(P::PackedEmbedding)?; - let low = if self.mode == PleBf16Mode::HighAndLow { Some(get(P::PackedEmbeddingLow)?) } else { None }; - for (h, n) in [(rh, t * 40960), (eh, t * 10240), (self.status()?, self.capacity * 40)] { - if h.overlaps(n, hist, 368640) { - return Err(Error::OutputAliasesInput); - } - } - for (w, n) in - [(key, 52428800), (value, 13107200), (aux[0], 40960), (aux[1], 40960), (aux[2], 40960), (aux[3], 81920)] - { - if w.overlaps(n, hist, 368640) { - return Err(Error::OutputAliasesInput); - } - } - let flags = self.status()?; - let mut v = Vec::new(); - v.try_reserve_exact(28).map_err(|_| Error::HostAllocation)?; - // Candidate history is source bytes, never a caller finite witness. - scan_ple(&mut v, hist, flags, 92160, 1, 8); - kernel( - &mut v, - 0, - 0, - (t * 2560).div_ceil(256), - 256, - vec![ - A::Address(eh), - A::Address(packed), - low.map_or(A::NullAddress, A::Address), - A::I64((t * 2560) as i64), - ], - ); - for (out, n, w, role) in [(kh, 10240, key, 0), (val, 2560, value, 1)] { - v.push(C::Gemm { input: packed, weight: w, output: out, t: t as i32, n, k: 2560, alpha: 1., beta: 0. }); - if let Some(l) = low { - v.push(C::Gemm { input: l, weight: w, output: out, t: t as i32, n, k: 2560, alpha: 1., beta: 1. }) - } - scan_ple(&mut v, out, flags, n as usize, t, role); - } - // Literal native_ple_postops_batch reuses Key and Qn in place. - kernel(&mut v, 1, 0, t * 4, 1024, vec![A::Address(kh), A::Address(aux[0]), A::Address(kh)]); - scan_ple(&mut v, kh, flags, 10240, t, 2); - kernel(&mut v, 1, 0, t * 4, 1024, vec![A::Address(rh), A::Address(aux[1]), A::Address(qn)]); - scan_ple(&mut v, qn, flags, 10240, t, 3); - kernel( - &mut v, - 1, - 1, - t * 4, - 512, - vec![A::Address(kh), A::Address(qn), A::Address(gate), A::F32(1. / 2560.0f32.sqrt())], - ); - scan_ple(&mut v, gate, flags, 4, t, 4); - kernel( - &mut v, - 1, - 2, - t * 40, - 256, - vec![A::Address(val), A::Address(gate), A::Address(gated), A::I32(t as i32)], - ); - scan_ple(&mut v, gated, flags, 10240, t, 5); - kernel(&mut v, 1, 0, t * 4, 1024, vec![A::Address(gated), A::Address(aux[2]), A::Address(qn)]); - scan_ple(&mut v, qn, flags, 10240, t, 6); - kernel( - &mut v, - 1, - 3, - t * 40, - 256, - vec![ - A::Address(hist), - A::Address(qn), - A::Address(aux[3]), - A::Address(rh), - A::Address(gated), - A::Address(flags), - A::I32(t as i32), - ], - ); - kernel(&mut v, 1, 4, 40, 256, vec![A::Address(hist), A::Address(qn), A::I32(t as i32)]); - scan_ple(&mut v, hist, flags, 92160, 1, 8); - scan_ple(&mut v, rh, flags, 10240, t, 9); - if let Err(e) = self.run( - lease, - workspace, - v, - t, - 10, - &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], - &[ - "PLE key", - "PLE value", - "PLE key norm", - "PLE query norm", - "PLE gate", - "PLE gated", - "PLE normalized", - "PLE conv", - "PLE history", - "PLE streams", - ], - ) { + let chunk = self.ple_chunk(lease, workspace, (hist, &pw), (first, t, total))?; + let v = ple_commands(&chunk, &pw, hist, t)?; + if let Err(e) = self.run_ple_chunk(lease, workspace, v, t) { history.failed = true; return Err(e); } diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs index 86198bec..7ea27ad3 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs @@ -1,7 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (5). #[allow(unused_imports)] -use super::gr_read_phases::GrReadPlan; +use super::gr_read_phases::{GR_READ_NAMES, GR_READ_ORDER, GrReadPlan}; use super::*; impl<'ctx> OriginalPromptDevice<'ctx> { @@ -20,38 +20,25 @@ impl<'ctx> OriginalPromptDevice<'ctx> { return Err(Error::InvalidQwenShape); } let t = lease.rows(); + let plan = self.gr_read_plan(lease, workspace, weights)?; + let v = plan.commands(epsilon, normed)?; + self.run(lease, workspace, v, t, 8, &GR_READ_ORDER, &GR_READ_NAMES)?; + Ok(OriginalDeviceGrRead { lease: residual.lease }) + } + /// The spans and weights of a GR read of the lease's rows. + fn gr_read_plan( + &self, + lease: &OriginalPromptRows<'_, '_, 'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + weights: [&DeviceBuffer<'_>; 4], + ) -> Result { let h = self.gr_read_spans(lease)?; let mut w = [h[0]; 4]; for (i, n) in [40960, 6553600, 6553600, 81920].into_iter().enumerate() { w[i] = self.weight(lease, workspace, weights[i], n, if i == 0 { 4 } else { 2 })?; } let low_half = self.profile == GrNativeProfile::HighAndLow; - let plan = GrReadPlan::new(h, w, self.status()?, t, low_half); - let mut v = Vec::new(); - v.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?; - let fused = fused_scans(); - plan.push_norm(&mut v, epsilon, normed, fused); - plan.push_projections(&mut v, fused); - plan.push_mix(&mut v, fused); - self.run( - lease, - workspace, - v, - t, - 8, - &[0, 1, 2, 3, 6, 4, 5], - &[ - "GR native norm", - "GR native down", - "GR native silu", - "GR native up", - "GR native products", - "GR native mixed", - "GR native inject", - "GR native candidate", - ], - )?; - Ok(OriginalDeviceGrRead { lease: residual.lease }) + Ok(GrReadPlan::new(h, w, self.status()?, lease.rows(), low_half)) } /// The device spans a GR read touches; the low-half ones only when the profile keeps a low half. fn gr_read_spans(&self, lease: &OriginalPromptRows<'_, '_, 'ctx>) -> Result<[BufferHandle; 15]> { diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_6.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_6.rs index 5c8e1b97..dbeb2f78 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_6.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_6.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (6). #[allow(unused_imports)] +use super::inject_phases::{inject_commands, inject_fused_commands}; use super::*; impl<'ctx> OriginalPromptDevice<'ctx> { @@ -15,56 +16,10 @@ impl<'ctx> OriginalPromptDevice<'ctx> { let lease = &mut block.read.lease; self.validate(lease, workspace)?; let t = lease.rows(); - let flags = self.status()?; - let r = Self::span(lease, S::R, 40960)?; - let b = Self::span(lease, S::Block, 10240)?; - let inj = Self::span(lease, S::Inject, 16)?; - // Prewrite full Block scan/drain rejects numerical errors before R is - // modified. No host floats are treated as a device-completion witness. - let mut check = Vec::new(); - check.try_reserve_exact(1).map_err(|_| Error::HostAllocation)?; - scan_gr(&mut check, b, flags, 2560, t, 7); - self.run( - lease, - workspace, - check, - t, - 8, - &[7], - &["unused", "unused", "unused", "unused", "unused", "unused", "unused", "GR native block"], - )?; + let sp = self.inject_spans(lease)?; + self.check_block(lease, workspace, (sp.b, sp.flags), t)?; self.profile_tag = "inject"; - let mut v = Vec::new(); - v.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; - if fused_scans() { - kernel( - &mut v, - 3, - 6, - (t * 10240).div_ceil(256), - 256, - vec![A::Address(r), A::Address(b), A::Address(inj), A::I64(4), A::I64(t as i64), A::Address(flags)], - ); - } else { - kernel( - &mut v, - 2, - 3, - (t * 10240).div_ceil(256), - 256, - vec![A::Address(r), A::Address(b), A::Address(inj), A::I64(4), A::I64(t as i64)], - ); - scan_gr(&mut v, r, flags, 10240, t, 7); - } - self.run( - lease, - workspace, - v, - t, - 8, - &[7], - &["unused", "unused", "unused", "unused", "unused", "unused", "unused", "GR native candidate"], - )?; + self.run_inject(lease, workspace, inject_commands(&sp, t)?, t)?; Ok(OriginalDeviceResidual { lease: block.read.lease }) } pub fn inject_gr_fused<'weight, 'arena, 'loan>( @@ -82,96 +37,13 @@ impl<'ctx> OriginalPromptDevice<'ctx> { } let w = self.weight(lease, workspace, gamma, 40960, 4)?; let t = lease.rows(); - let flags = self.status()?; - let r = Self::span(lease, S::R, 40960)?; - let b = Self::span(lease, S::Block, 10240)?; - let inj = Self::span(lease, S::Inject, 16)?; - let rs = Self::span(lease, S::GrRS, 16)?; - let high = Self::span(lease, S::XHigh, 20480)?; - let low = if self.profile == GrNativeProfile::HighAndLow { - A::Address(Self::span(lease, S::XLow, 20480)?) - } else { - A::NullAddress - }; - let mut check = Vec::new(); - check.try_reserve_exact(1).map_err(|_| Error::HostAllocation)?; - scan_gr(&mut check, b, flags, 2560, t, 7); - self.run( - lease, - workspace, - check, - t, - 8, - &[7], - &["unused", "unused", "unused", "unused", "unused", "unused", "unused", "GR native block"], - )?; + let sp = self.inject_spans(lease)?; + let fs = self.fused_spans(lease, w)?; + self.check_block(lease, workspace, (sp.b, sp.flags), t)?; self.profile_tag = "injectf"; - let mut v = Vec::new(); - v.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; - if fused_scans() { - // write + the guards of R after the write (7) and of the next half's norm (0) - kernel( - &mut v, - 3, - 5, - t * 4, - 256, - vec![ - A::Address(r), - A::Address(b), - A::Address(inj), - A::I64(4), - A::Address(w), - A::F32(epsilon), - A::Address(rs), - A::Address(high), - low, - A::Address(flags), - ], - ); - } else { - kernel( - &mut v, - 2, - 8, - t * 4, - 256, - vec![ - A::Address(r), - A::Address(b), - A::Address(inj), - A::I64(4), - A::Address(w), - A::F32(epsilon), - A::Address(rs), - A::Address(high), - low, - ], - ); - scan_gr(&mut v, r, flags, 10240, t, 7); - kernel( - &mut v, - 2, - 5, - (t * 10240).div_ceil(256), - 256, - vec![A::Address(r), A::Address(rs), A::Address(w), A::Address(flags), A::I64(t as i64)], - ); - } - self.run( - lease, - workspace, - v, - t, - 8, - &[7, 0], - &["GR native next norm", "unused", "unused", "unused", "unused", "unused", "unused", "GR native candidate"], - )?; - Ok(OriginalDeviceNormedResidual { - residual: OriginalDeviceResidual { lease: block.read.lease }, - gamma, - epsilon, - }) + self.run_inject_fused(lease, workspace, inject_fused_commands(&sp, &fs, epsilon, t)?, t)?; + let residual = OriginalDeviceResidual { lease: block.read.lease }; + Ok(OriginalDeviceNormedResidual { residual, gamma, epsilon }) } pub fn close(mut self) -> Result<()> { self.close_inner() diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_7.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_7.rs index 428013b6..55c54ca1 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_7.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_7.rs @@ -6,39 +6,49 @@ use super::*; impl<'ctx> OriginalPromptDevice<'ctx> { pub(in super::super) fn close_inner(&mut self) -> Result<()> { self.failed = true; + let context = self.context; let mut result = Ok(()); for m in [self.pack.take(), self.ple.take(), self.gr.take(), self.stage.take()].into_iter().flatten() { - let r = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - std::mem::forget(m); - Err(e) - } - } - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver() - } - result = combine(result, r); + result = combine(result, close_module(context, m)); } for b in [self.status.take(), self.stage_scratch.take()].into_iter().flatten() { - let r = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver() - } - result = combine(result, r) + result = combine(result, release_owner(context, b)); } result } } + +fn poison_on_error(context: &Context<'_>, r: Result<()>) -> Result<()> { + if r.is_err() { + context.poison(); + context.retain_driver() + } + r +} + +/// A kernel module closes under the context guard, or leaks when the context is unusable; a failure poisons. +fn close_module(context: &Context<'_>, m: KernelModule) -> Result<()> { + let r = if context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + std::mem::forget(m); + Err(e) + } + } + }; + poison_on_error(context, r) +} + +fn release_owner<'ctx>(context: &Context<'ctx>, b: DeviceBuffer<'ctx>) -> Result<()> { + let r = if context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + }; + poison_on_error(context, r) +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/inject_phases.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/inject_phases.rs new file mode 100644 index 00000000..a8992365 --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/inject_phases.rs @@ -0,0 +1,127 @@ +//! STRA-338 size: the phases of `OriginalPromptDevice::{inject_gr, inject_gr_fused}`. + +#[allow(unused_imports)] +use super::*; + +pub(super) const INJECT_NAMES: [&str; 8] = + ["unused", "unused", "unused", "unused", "unused", "unused", "unused", "GR native candidate"]; +const BLOCK_NAMES: [&str; 8] = + ["unused", "unused", "unused", "unused", "unused", "unused", "unused", "GR native block"]; +const FUSED_NAMES: [&str; 8] = + ["GR native next norm", "unused", "unused", "unused", "unused", "unused", "unused", "GR native candidate"]; + +/// R, Block and Inject spans of an injection plus the status words. +#[derive(Clone, Copy)] +pub(super) struct InjectSpans { + pub(super) r: BufferHandle, + pub(super) b: BufferHandle, + pub(super) inj: BufferHandle, + pub(super) flags: BufferHandle, +} + +/// What the fused injection adds: the norm weight, the row scales and the high/low X halves. +pub(super) struct FusedSpans { + w: BufferHandle, + rs: BufferHandle, + high: BufferHandle, + low: Option, +} + +impl<'ctx> OriginalPromptDevice<'ctx> { + pub(super) fn inject_spans(&self, lease: &OriginalPromptRows<'_, '_, 'ctx>) -> Result { + let flags = self.status()?; + let r = Self::span(lease, S::R, 40960)?; + let b = Self::span(lease, S::Block, 10240)?; + let inj = Self::span(lease, S::Inject, 16)?; + Ok(InjectSpans { r, b, inj, flags }) + } + + pub(super) fn fused_spans(&self, lease: &OriginalPromptRows<'_, '_, 'ctx>, w: BufferHandle) -> Result { + let rs = Self::span(lease, S::GrRS, 16)?; + let high = Self::span(lease, S::XHigh, 20480)?; + let low = + if self.profile == GrNativeProfile::HighAndLow { Some(Self::span(lease, S::XLow, 20480)?) } else { None }; + Ok(FusedSpans { w, rs, high, low }) + } + + /// Prewrite full Block scan/drain rejects numerical errors before R is + /// modified. No host floats are treated as a device-completion witness. + pub(super) fn check_block( + &mut self, + lease: &mut OriginalPromptRows<'_, '_, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + (b, flags): (BufferHandle, BufferHandle), + t: usize, + ) -> Result<()> { + let mut check = Vec::new(); + check.try_reserve_exact(1).map_err(|_| Error::HostAllocation)?; + scan_gr(&mut check, b, flags, 2560, t, 7); + self.run(lease, workspace, check, t, 8, &[7], &BLOCK_NAMES) + } + + pub(super) fn run_inject( + &mut self, + lease: &mut OriginalPromptRows<'_, '_, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + v: Vec, + t: usize, + ) -> Result<()> { + self.run(lease, workspace, v, t, 8, &[7], &INJECT_NAMES) + } + + pub(super) fn run_inject_fused( + &mut self, + lease: &mut OriginalPromptRows<'_, '_, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + v: Vec, + t: usize, + ) -> Result<()> { + self.run(lease, workspace, v, t, 8, &[7, 0], &FUSED_NAMES) + } +} + +/// The plain injection: add the Block into R, scanning R after it (fused scans fold the guard in). +pub(super) fn inject_commands(sp: &InjectSpans, t: usize) -> Result> { + let (r, b, inj, flags) = (sp.r, sp.b, sp.inj, sp.flags); + let mut v = Vec::new(); + v.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; + if fused_scans() { + let args = vec![A::Address(r), A::Address(b), A::Address(inj), A::I64(4), A::I64(t as i64), A::Address(flags)]; + kernel(&mut v, 3, 6, (t * 10240).div_ceil(256), 256, args); + } else { + let args = vec![A::Address(r), A::Address(b), A::Address(inj), A::I64(4), A::I64(t as i64)]; + kernel(&mut v, 2, 3, (t * 10240).div_ceil(256), 256, args); + scan_gr(&mut v, r, flags, 10240, t, 7); + } + Ok(v) +} + +/// The injection that also writes the next half's row scales and high/low X (the norm rides along). +pub(super) fn inject_fused_commands(sp: &InjectSpans, fs: &FusedSpans, epsilon: f32, t: usize) -> Result> { + let (r, flags) = (sp.r, sp.flags); + let low = fs.low.map_or(A::NullAddress, A::Address); + let mut v = Vec::new(); + v.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; + let mut args = vec![ + A::Address(r), + A::Address(sp.b), + A::Address(sp.inj), + A::I64(4), + A::Address(fs.w), + A::F32(epsilon), + A::Address(fs.rs), + A::Address(fs.high), + low, + ]; + if fused_scans() { + // write + the guards of R after the write (7) and of the next half's norm (0) + args.push(A::Address(flags)); + kernel(&mut v, 3, 5, t * 4, 256, args); + } else { + kernel(&mut v, 2, 8, t * 4, 256, args); + scan_gr(&mut v, r, flags, 10240, t, 7); + let norm = vec![A::Address(r), A::Address(fs.rs), A::Address(fs.w), A::Address(flags), A::I64(t as i64)]; + kernel(&mut v, 2, 5, (t * 10240).div_ceil(256), 256, norm); + } + Ok(v) +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/ple_apply_phases.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/ple_apply_phases.rs new file mode 100644 index 00000000..da12aab1 --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/ple_apply_phases.rs @@ -0,0 +1,219 @@ +//! STRA-338 size: the phases of `OriginalPromptDevice::apply_ple`, extracted in call order. + +#[allow(unused_imports)] +use super::*; + +const PLE_ORDER: [usize; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; +const PLE_NAMES: [&str; 10] = [ + "PLE key", + "PLE value", + "PLE key norm", + "PLE query norm", + "PLE gate", + "PLE gated", + "PLE normalized", + "PLE conv", + "PLE history", + "PLE streams", +]; + +/// The validated key, value and auxiliary weight handles of one PLE application. +#[derive(Clone, Copy)] +pub(super) struct PleWeights { + key: BufferHandle, + value: BufferHandle, + aux: [BufferHandle; 4], +} + +impl PleWeights { + fn all(&self) -> [(BufferHandle, usize); 6] { + let aux = &self.aux; + [ + (self.key, 52428800), + (self.value, 13107200), + (aux[0], 40960), + (aux[1], 40960), + (aux[2], 40960), + (aux[3], 81920), + ] + } +} + +/// The spans one PLE sub-batch reads and writes. +pub(super) struct PleChunk { + rh: BufferHandle, + eh: BufferHandle, + /// Key, Qn, Gated, Value, Gate, PackedEmbedding. + roles: [BufferHandle; 6], + low: Option, + flags: BufferHandle, +} + +impl<'ctx> OriginalPromptDevice<'ctx> { + /// The history buffer handle, validated against the context, its size and the workspace. + pub(super) fn ple_history_handle( + &self, + history: &OriginalPleHistory<'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + ) -> Result { + if history.failed || !std::ptr::eq(history.context, self.context) { + return Err(Error::ContextMismatch); + } + let hb = history.buffer.as_ref().ok_or(Error::ContextPoisoned)?; + if hb.len() != 368640 { + return Err(Error::InvalidQwenShape); + } + let hist = hb.handle.ok_or(Error::ContextPoisoned)?; + hist.validate_projection_extent(368640, 4)?; + workspace.reject_alias(hist, 368640)?; + Ok(hist) + } + + pub(super) fn ple_weights( + &self, + lease: &OriginalPromptRows<'_, '_, 'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + weights: &PleClosedWeights<'_, '_>, + ) -> Result { + let key = self.weight(lease, workspace, weights.key, 52428800, 2)?; + let value = self.weight(lease, workspace, weights.value, 13107200, 2)?; + let mut aux = [key; 4]; + for (i, w) in weights.aux.iter().enumerate() { + let (bytes, alignment) = if i == 3 { (81920, 2) } else { (40960, 4) }; + aux[i] = self.weight(lease, workspace, w, bytes, alignment)?; + } + Ok(PleWeights { key, value, aux }) + } + + /// One role span of a sub-batch of `t` rows: it must not alias the workspace, the history, the status words + /// or any weight. + fn ple_role( + &self, + lease: &OriginalPromptRows<'_, '_, 'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + (hist, pw): (BufferHandle, &PleWeights), + (role, t): (P, usize), + ) -> Result { + let (h, n) = lease.ple_span(role, t)?; + workspace.reject_alias(h, n)?; + if h.overlaps(n, hist, 368640) || h.overlaps(n, self.status()?, self.capacity * 40) { + return Err(Error::OutputAliasesInput); + } + if pw.all().iter().any(|(w, wn)| h.overlaps(n, *w, *wn)) { + return Err(Error::OutputAliasesInput); + } + Ok(h) + } + + /// Resolves and admits the spans of the sub-batch starting at row `first`. + pub(super) fn ple_chunk( + &self, + lease: &OriginalPromptRows<'_, '_, 'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + (hist, pw): (BufferHandle, &PleWeights), + (first, t, total): (usize, usize, usize), + ) -> Result { + let rh = Self::span(lease, S::R, 40960)?.checked_subspan(total * 40960, first * 40960, t * 40960)?; + let eh = Self::span(lease, S::PleEmbedding, 10240)?.checked_subspan(total * 10240, first * 10240, t * 10240)?; + let get = |role: P| self.ple_role(lease, workspace, (hist, pw), (role, t)); + let mut roles = [rh; 6]; + for (i, role) in [P::Key, P::Qn, P::Gated, P::Value, P::Gate, P::PackedEmbedding].into_iter().enumerate() { + roles[i] = get(role)?; + } + let low = (self.mode == PleBf16Mode::HighAndLow).then(|| get(P::PackedEmbeddingLow)).transpose()?; + self.check_clear_of_history((rh, eh), hist, pw, t)?; + Ok(PleChunk { rh, eh, roles, low, flags: self.status()? }) + } + + /// The row, embedding and status spans and every weight must stay clear of the history. + fn check_clear_of_history( + &self, + (rh, eh): (BufferHandle, BufferHandle), + hist: BufferHandle, + pw: &PleWeights, + t: usize, + ) -> Result<()> { + for (h, n) in [(rh, t * 40960), (eh, t * 10240), (self.status()?, self.capacity * 40)] { + if h.overlaps(n, hist, 368640) { + return Err(Error::OutputAliasesInput); + } + } + if pw.all().iter().any(|(w, n)| w.overlaps(*n, hist, 368640)) { + return Err(Error::OutputAliasesInput); + } + Ok(()) + } + + /// Runs one sub-batch's commands; a failure marks the history failed. + pub(super) fn run_ple_chunk( + &mut self, + lease: &mut OriginalPromptRows<'_, '_, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + v: Vec, + t: usize, + ) -> Result<()> { + self.run(lease, workspace, v, t, 10, &PLE_ORDER, &PLE_NAMES) + } +} + +/// The launches of one sub-batch: candidate-history scan, packing, projections, norms, gate, conv, history. +pub(super) fn ple_commands(c: &PleChunk, pw: &PleWeights, hist: BufferHandle, t: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(28).map_err(|_| Error::HostAllocation)?; + push_ple_projections(&mut v, c, pw, hist, t); + push_ple_norms(&mut v, c, pw, t); + push_ple_tail(&mut v, c, pw, hist, t); + Ok(v) +} + +fn push_ple_projections(v: &mut Vec, c: &PleChunk, pw: &PleWeights, hist: BufferHandle, t: usize) { + let [kh, _, _, val, _, packed] = c.roles; + // Candidate history is source bytes, never a caller finite witness. + scan_ple(v, hist, c.flags, 92160, 1, 8); + let pack = + vec![A::Address(c.eh), A::Address(packed), c.low.map_or(A::NullAddress, A::Address), A::I64((t * 2560) as i64)]; + kernel(v, 0, 0, (t * 2560).div_ceil(256), 256, pack); + for (out, n, w, role) in [(kh, 10240, pw.key, 0), (val, 2560, pw.value, 1)] { + v.push(C::Gemm { input: packed, weight: w, output: out, t: t as i32, n, k: 2560, alpha: 1., beta: 0. }); + if let Some(l) = c.low { + v.push(C::Gemm { input: l, weight: w, output: out, t: t as i32, n, k: 2560, alpha: 1., beta: 1. }) + } + scan_ple(v, out, c.flags, n as usize, t, role); + } +} + +/// Literal native_ple_postops_batch reuses Key and Qn in place. +fn push_ple_norms(v: &mut Vec, c: &PleChunk, pw: &PleWeights, t: usize) { + let [kh, qn, _, _, gate, _] = c.roles; + let (aux, flags, rh) = (&pw.aux, c.flags, c.rh); + kernel(v, 1, 0, t * 4, 1024, vec![A::Address(kh), A::Address(aux[0]), A::Address(kh)]); + scan_ple(v, kh, flags, 10240, t, 2); + kernel(v, 1, 0, t * 4, 1024, vec![A::Address(rh), A::Address(aux[1]), A::Address(qn)]); + scan_ple(v, qn, flags, 10240, t, 3); + let gate_args = vec![A::Address(kh), A::Address(qn), A::Address(gate), A::F32(1. / 2560.0f32.sqrt())]; + kernel(v, 1, 1, t * 4, 512, gate_args); + scan_ple(v, gate, flags, 4, t, 4); +} + +fn push_ple_tail(v: &mut Vec, c: &PleChunk, pw: &PleWeights, hist: BufferHandle, t: usize) { + let [_, qn, gated, val, gate, _] = c.roles; + let (aux, flags, rh) = (&pw.aux, c.flags, c.rh); + let gated_args = vec![A::Address(val), A::Address(gate), A::Address(gated), A::I32(t as i32)]; + kernel(v, 1, 2, t * 40, 256, gated_args); + scan_ple(v, gated, flags, 10240, t, 5); + kernel(v, 1, 0, t * 4, 1024, vec![A::Address(gated), A::Address(aux[2]), A::Address(qn)]); + scan_ple(v, qn, flags, 10240, t, 6); + let conv = vec![ + A::Address(hist), + A::Address(qn), + A::Address(aux[3]), + A::Address(rh), + A::Address(gated), + A::Address(flags), + A::I32(t as i32), + ]; + kernel(v, 1, 3, t * 40, 256, conv); + kernel(v, 1, 4, 40, 256, vec![A::Address(hist), A::Address(qn), A::I32(t as i32)]); + scan_ple(v, hist, flags, 92160, 1, 8); + scan_ple(v, rh, flags, 10240, t, 9); +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/run_phases.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/run_phases.rs new file mode 100644 index 00000000..544e392e --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/run_phases.rs @@ -0,0 +1,194 @@ +//! STRA-338 size: the phases of `OriginalPromptDevice::run`, extracted in call order. + +#[allow(unused_imports)] +use super::*; +use crate::CurrentGuard; +use crate::ple_batch_ffi::Blas; + +/// The host buffers a run owns until the vendor stream and readback drain; leaked on an uncertain drain. +pub(super) struct RunBuffers { + pub(super) commands: Vec, + pub(super) zero: Vec, + readback: Vec, +} + +impl RunBuffers { + pub(super) fn new(commands: Vec, bytes_len: usize) -> Result { + let zero = bytes(bytes_len)?; + let readback = bytes(bytes_len)?; + Ok(Self { commands, zero, readback }) + } +} + +/// The status words of a run: device span, byte length and per-row stride. +pub(super) type StatusSpec = (BufferHandle, usize, usize); + +fn kernel_label(family: u8, index: usize) -> &'static str { + let entries = match family { + 1 => PLE_ENTRIES, + 3 => crate::prefill_stage::ENTRIES, + _ => GR_ENTRIES, + }; + entries.get(index).and_then(|e| e.to_str().ok()).unwrap_or("kernel") +} + +impl<'ctx> OriginalPromptDevice<'ctx> { + pub(super) fn enter_for_run( + &mut self, + lease: &mut OriginalPromptRows<'_, '_, '_>, + ) -> Result> { + match self.context.enter() { + Ok(g) => Ok(g), + Err(e) => { + self.failed = true; + lease.mark_failed(); + self.context.retain_driver(); + Err(e) + } + } + } + + /// Zeroes the status words (immediate) or queues their zeroing on the stream (deferred). + pub(super) fn begin_status( + &self, + blas: &Blas, + (status, bytes, _): StatusSpec, + defer: bool, + zero: &[u8], + ) -> Result<()> { + if defer { + return crate::deferred_status::begin(self.context, status, bytes, blas.stream(), self.capacity * 40); + } + self.context.driver.api.copy_from(status, zero)?; + self.context.driver.api.synchronize() + } + + fn family_module(&self, family: u8) -> Result<&KernelModule> { + match family { + 0 => self.pack.as_ref(), + 1 => self.ple.as_ref(), + 3 => self.stage.as_ref(), + _ => self.gr.as_ref(), + } + .ok_or(Error::ContextPoisoned) + } + + /// Launches one command; the outer error is a missing module, which leaves the run at once. + fn launch_one(&self, blas: &Blas, cmd: &mut C, timed: bool) -> Result<(Result<()>, &'static str)> { + match cmd { + C::Kernel { family, index, grid, block, args } => { + let module = self.family_module(*family)?; + let label = if timed { kernel_label(*family, *index) } else { "gemm" }; + Ok((module.launch(*index, *grid, *block, blas.stream(), args), label)) + } + C::Gemm { input, weight, output, t, n, k, alpha, beta } => { + Ok((blas.gemm_bf16(*input, *weight, *output, *t, *n, *k, alpha, beta), "gemm")) + } + } + } + + /// Launches the commands in order while `op` holds; LELEKA_PREFILL_PROFILE_SYNC drains and charges each one. + pub(super) fn launch_commands(&self, blas: &Blas, commands: &mut [C], mut op: Result<()>) -> Result> { + let timed = crate::command_profile::enabled(); + for (position, cmd) in commands.iter_mut().enumerate() { + if op.is_err() { + break; + } + let started = std::time::Instant::now(); + let (launched, label) = self.launch_one(blas, cmd, timed)?; + op = launched; + if timed && op.is_ok() { + op = blas.synchronize(); + crate::command_profile::add(self.profile_tag, position + 1, label, started.elapsed()); + } + } + Ok(op) + } + + /// No host wait: the words and the cross-stream ordering are queued on the stream (deferred_status.rs). + pub(super) fn finish_deferred( + &mut self, + (lease, workspace): (&mut OriginalPromptRows<'_, '_, '_>, &mut NativeBatchWorkspace<'ctx>), + (guard, op, buffers): (CurrentGuard<'ctx, 'ctx>, Result<()>, RunBuffers), + (spec, order, labels): (StatusSpec, &[usize], &[&'static str]), + ) -> Result<()> { + let (status, status_bytes, stride) = spec; + let stream = workspace.blas()?.stream(); + let queued = if op.is_ok() { + crate::deferred_status::finish(self.context, status, status_bytes, stream, stride, order, labels) + } else { + op + }; + let pop = guard.finish(); + if queued.is_err() || pop.is_err() { + self.failed = true; + lease.mark_failed(); + workspace.mark_failed(); + std::mem::forget(buffers); + self.context.retain_driver(); + return combine(queued, pop); + } + // cuLaunchKernel copies its parameter values at the call and cuBLAS (host pointer mode) reads alpha/beta at the + // call, so the argument vectors need not outlive the enqueue (the immediate path keeps them until its drain + // as a conservative audit rule; the failure path above still leaks them) + drop(buffers.commands); + Ok(()) + } + + /// Drains both streams, reads the status words back and evaluates them. + pub(super) fn finish_immediate( + &mut self, + (lease, workspace): (&mut OriginalPromptRows<'_, '_, '_>, &mut NativeBatchWorkspace<'ctx>), + (guard, mut op, mut buffers): (CurrentGuard<'ctx, 'ctx>, Result<()>, RunBuffers), + (spec, order, labels): (StatusSpec, &[usize], &[&'static str]), + ) -> Result<()> { + let sync = workspace.blas()?.synchronize(); + if op.is_ok() && sync.is_ok() { + op = self.context.driver.api.copy_to(spec.0, &mut buffers.readback) + } + let all = self.context.driver.api.synchronize(); + let pop = guard.finish(); + let buffers = self.settle_run((lease, workspace), [op, sync, all, pop], buffers)?; + self.evaluate_status(lease, &buffers.readback, (spec.2, order, labels)) + } + + /// Marks everything failed on any error; an uncertain drain leaks the buffers. + fn settle_run( + &mut self, + (lease, workspace): (&mut OriginalPromptRows<'_, '_, '_>, &mut NativeBatchWorkspace<'ctx>), + [op, sync, all, pop]: [Result<()>; 4], + buffers: RunBuffers, + ) -> Result { + if op.is_err() || sync.is_err() || all.is_err() || pop.is_err() { + self.failed = true; + lease.mark_failed(); + workspace.mark_failed() + } + if sync.is_err() || all.is_err() || pop.is_err() { + std::mem::forget(buffers); + self.context.retain_driver(); + return combine(combine(combine(op, sync), all), pop).map(|()| unreachable!("uncertain drain")); + } + combine(combine(combine(op, sync), all), pop)?; + Ok(buffers) + } + + /// Unknown status is never a usable finite product, including a later word after an earlier numerical flag. All actual + /// kernels write 0/1. The evaluation is shared with the deferred path (deferred_status::evaluate). + fn evaluate_status( + &mut self, + lease: &mut OriginalPromptRows<'_, '_, '_>, + readback: &[u8], + (stride, order, labels): (usize, &[usize], &[&'static str]), + ) -> Result<()> { + if let Err(e) = crate::deferred_status::evaluate(readback, stride, order, labels) { + if matches!(e, Error::InvalidDriverValue(_)) { + self.failed = true; + lease.mark_failed(); + self.context.retain_driver(); + } + return Err(e); + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/native_prompt_device/stage_phases.rs b/crates/cuda-driver/src/native_prompt_device/stage_phases.rs new file mode 100644 index 00000000..42d47381 --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/stage_phases.rs @@ -0,0 +1,262 @@ +//! STRA-338 size: the phases of `OriginalPromptDevice::initialize_staged`, extracted in call order. +use super::*; + +const STAGE_ORDER: [usize; 3] = [5, 6, 7]; +const STAGE_NAMES: [&str; 8] = [ + "unused", + "unused", + "unused", + "unused", + "unused", + "Original prompt embedding", + "Original prompt PLE", + "Original prompt input", +]; + +/// Device spans of one staged initialization. +pub(super) struct StageSpans { + t: usize, + unique: usize, + misses: usize, + parts: usize, + rh: BufferHandle, + eh: BufferHandle, + bh: BufferHandle, + cache_h: BufferHandle, + books_h: BufferHandle, + slots_h: BufferHandle, + index_h: BufferHandle, + updates_h: Option, + flags: BufferHandle, +} + +/// The PLE cache and books handles, validated and rejected against the workspace. +fn ple_handles( + input: &PromptInputStage<'_, '_>, + workspace: &NativeBatchWorkspace<'_>, +) -> Result<(BufferHandle, BufferHandle)> { + let cache_h = input.ple_cache.handle.ok_or(Error::ContextPoisoned)?; + let books_h = input.ple_books.handle.ok_or(Error::ContextPoisoned)?; + cache_h.validate_projection_extent(64 << 20, 1)?; + books_h.validate_projection_extent(input.ple_books.bytes, 2)?; + workspace.reject_alias(cache_h, 64 << 20)?; + workspace.reject_alias(books_h, input.ple_books.bytes)?; + Ok((cache_h, books_h)) +} + +/// Row and embedding counts of the chunk agree. +fn rows_well_formed(t: usize, input: &PromptInputStage<'_, '_>, unique: usize) -> bool { + t != 0 + && input.embedding_index.len() == t + && input.ple_slots.len() == t * 16 + && !input.embedding_rows.is_empty() + && input.embedding_rows.len().is_multiple_of(10240) + && unique <= t +} + +/// The cache update records, cache buffer and books are of the expected sizes. +fn cache_well_formed(t: usize, input: &PromptInputStage<'_, '_>, (misses, parts): (usize, usize)) -> bool { + input.ple_updates.len().is_multiple_of(56) + && misses <= t * 16 + && input.ple_cache.bytes == 64 << 20 + && input.ple_books.bytes != 0 + && input.ple_books.bytes.is_multiple_of(8) + && parts <= 65535 +} + +impl<'ctx> OriginalPromptDevice<'ctx> { + /// The row counts (distinct embeddings, cache misses, PLE partitions) of a well-formed staged chunk. + pub(super) fn check_stage_input( + &self, + t: usize, + input: &PromptInputStage<'_, 'ctx>, + ) -> Result<(usize, usize, usize)> { + let unique = input.embedding_rows.len() / 10240; + let misses = input.ple_updates.len() / 56; + let parts = input.ple_books.bytes / 8; + if !rows_well_formed(t, input, unique) || !cache_well_formed(t, input, (misses, parts)) { + return Err(Error::InvalidQwenShape); + } + if !std::ptr::eq(input.ple_cache.context, self.context) || !std::ptr::eq(input.ple_books.context, self.context) + { + return Err(Error::ContextMismatch); + } + Ok((unique, misses, parts)) + } + + /// Resolves and admits every span of the chunk; allocates the landing scratch on first use. + pub(super) fn stage_spans( + &mut self, + lease: &OriginalPromptRows<'_, '_, 'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + input: &PromptInputStage<'_, 'ctx>, + (t, unique, misses, parts): (usize, usize, usize, usize), + ) -> Result { + let rh = Self::span(lease, S::R, 40960)?; + let eh = Self::span(lease, S::PleEmbedding, 10240)?; + let bh = Self::span(lease, S::Block, 10240)?.checked_subspan(t * 10240, 0, unique * 10240)?; + let (cache_h, books_h) = ple_handles(input, workspace)?; + let (slots_h, index_h, updates_h) = self.landing_spans(workspace, t, misses)?; + let flags = self.status()?; + Ok(StageSpans { t, unique, misses, parts, rh, eh, bh, cache_h, books_h, slots_h, index_h, updates_h, flags }) + } + + /// The landing scratch of exactly `total` bytes, allocated on first use. + fn scratch_handle(&mut self, workspace: &NativeBatchWorkspace<'ctx>, total: usize) -> Result { + if self.stage_scratch.is_none() { + self.stage_scratch = Some(self.context.allocate(total)?); + } + let scratch = self.stage_scratch.as_ref().ok_or(Error::ContextPoisoned)?; + if scratch.bytes != total { + return Err(Error::InvalidQwenShape); + } + let sh = scratch.handle.ok_or(Error::ContextPoisoned)?; + sh.validate_projection_extent(total, 4)?; + workspace.reject_alias(sh, total)?; + Ok(sh) + } + + /// Landing area: slot indices | embedding row indices | cache update records. + fn landing_spans( + &mut self, + workspace: &NativeBatchWorkspace<'ctx>, + t: usize, + misses: usize, + ) -> Result<(BufferHandle, BufferHandle, Option)> { + let cap = self.capacity; + let slot_bytes = cap * 64; + let index_bytes = (cap * 4).next_multiple_of(16); + let total = slot_bytes + index_bytes + cap * 16 * 56; + let sh = self.scratch_handle(workspace, total)?; + let slots_h = sh.checked_subspan(total, 0, t * 64)?; + let index_h = sh.checked_subspan(total, slot_bytes, t * 4)?; + let updates_h = + if misses > 0 { Some(sh.checked_subspan(total, slot_bytes + index_bytes, misses * 56)?) } else { None }; + Ok((slots_h, index_h, updates_h)) + } + + /// Uploads the embedding rows, slot and index words and cache updates under the context guard. + pub(super) fn upload_stage( + &mut self, + lease: &mut OriginalPromptRows<'_, '_, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + input: &PromptInputStage<'_, 'ctx>, + sp: &StageSpans, + ) -> Result<()> { + let (slot_raw, index_raw) = word_bytes(input, sp.t)?; + let guard = match self.context.enter() { + Ok(g) => g, + Err(err) => { + lease.mark_failed(); + workspace.mark_failed(); + self.context.retain_driver(); + return Err(err); + } + }; + let op = self.upload_words(input, sp, (&slot_raw, &index_raw)); + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + self.settle_stage_upload((lease, workspace), [op, sync, pop], (slot_raw, index_raw)) + } + + fn settle_stage_upload( + &mut self, + (lease, workspace): (&mut OriginalPromptRows<'_, '_, 'ctx>, &mut NativeBatchWorkspace<'ctx>), + [op, sync, pop]: [Result<()>; 3], + raw: (Vec, Vec), + ) -> Result<()> { + if op.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + lease.mark_failed(); + workspace.mark_failed() + } + if sync.is_err() || pop.is_err() { + std::mem::forget(raw); + self.context.retain_driver() + } + combine(combine(op, sync), pop) + } + + fn upload_words( + &self, + input: &PromptInputStage<'_, 'ctx>, + sp: &StageSpans, + (slot_raw, index_raw): (&[u8], &[u8]), + ) -> Result<()> { + let api = &self.context.driver.api; + api.copy_from(sp.bh, input.embedding_rows)?; + api.copy_from(sp.slots_h, &slot_raw[..sp.t * 64])?; + api.copy_from(sp.index_h, index_raw)?; + match sp.updates_h { + Some(h) => api.copy_from(h, input.ple_updates), + None => Ok(()), + } + } +} + +/// The slot and embedding-index words of the chunk as little-endian bytes. +fn word_bytes(input: &PromptInputStage<'_, '_>, t: usize) -> Result<(Vec, Vec)> { + let mut slot_raw = bytes(t * 64)?; + for (x, b) in input.ple_slots.iter().zip(slot_raw.as_chunks_mut::<4>().0) { + b.copy_from_slice(&x.to_le_bytes()) + } + let mut index_raw = bytes(t * 4)?; + for (x, b) in input.embedding_index.iter().zip(index_raw.as_chunks_mut::<4>().0) { + b.copy_from_slice(&x.to_le_bytes()) + } + Ok((slot_raw, index_raw)) +} + +/// The launches of one staged initialization: cache update, PLE decode, embedding broadcast, finite scan. +pub(super) fn stage_commands(sp: &StageSpans) -> Result> { + let (t, flags) = (sp.t, sp.flags); + let mut v = Vec::new(); + v.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; + if let Some(h) = sp.updates_h { + let update = vec![A::Address(sp.cache_h), A::Address(h), A::U32(sp.misses as u32)]; + kernel(&mut v, 3, 0, (sp.misses * 64).div_ceil(256), 256, update); + } + kernel(&mut v, 3, 1, (t * 16 * 160).div_ceil(256), 256, decode_arguments(sp)); + kernel(&mut v, 3, 2, (t * 2560).div_ceil(256), 256, broadcast_arguments(sp)); + scan_gr(&mut v, sp.rh, flags, 10240, t, 7); + Ok(v) +} + +fn decode_arguments(sp: &StageSpans) -> Vec { + vec![ + A::Address(sp.cache_h), + A::Address(sp.slots_h), + A::Address(sp.books_h), + A::Address(sp.eh), + A::U32(sp.parts as u32), + A::I64((sp.t * 16) as i64), + A::Address(sp.flags), + A::U32(8), + A::U32(6), + ] +} + +fn broadcast_arguments(sp: &StageSpans) -> Vec { + vec![ + A::Address(sp.bh), + A::Address(sp.index_h), + A::Address(sp.rh), + A::I64(sp.t as i64), + A::U32(sp.unique as u32), + A::Address(sp.flags), + A::U32(8), + A::U32(5), + ] +} + +impl<'ctx> OriginalPromptDevice<'ctx> { + pub(super) fn run_stage( + &mut self, + lease: &mut OriginalPromptRows<'_, '_, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + v: Vec, + t: usize, + ) -> Result<()> { + self.run(lease, workspace, v, t, 8, &STAGE_ORDER, &STAGE_NAMES) + } +} diff --git a/crates/cuda-driver/src/native_prompt_device_stage.rs b/crates/cuda-driver/src/native_prompt_device_stage.rs index 2871fa05..8cea10ab 100644 --- a/crates/cuda-driver/src/native_prompt_device_stage.rs +++ b/crates/cuda-driver/src/native_prompt_device_stage.rs @@ -1,5 +1,6 @@ //! Batched initial staging of an Original prompt chunk (child of `native_prompt_device`, which owns the private //! command/arena helpers used here). See `OriginalPromptDevice::initialize_staged`. +use super::stage_phases::stage_commands; use super::*; /// The chunk's initial rows in their cheap form: what `initialize_rows` would assemble on the host, as it is @@ -34,160 +35,10 @@ impl<'ctx> OriginalPromptDevice<'ctx> { self.profile_tag = "init"; self.validate(&lease, workspace)?; let t = lease.rows(); - let unique = input.embedding_rows.len() / 10240; - let misses = input.ple_updates.len() / 56; - let parts = input.ple_books.bytes / 8; - if t == 0 - || input.embedding_index.len() != t - || input.ple_slots.len() != t * 16 - || input.embedding_rows.is_empty() - || !input.embedding_rows.len().is_multiple_of(10240) - || unique > t - || !input.ple_updates.len().is_multiple_of(56) - || misses > t * 16 - || input.ple_cache.bytes != 64 << 20 - || input.ple_books.bytes == 0 - || !input.ple_books.bytes.is_multiple_of(8) - || parts > 65535 - { - return Err(Error::InvalidQwenShape); - } - if !std::ptr::eq(input.ple_cache.context, self.context) || !std::ptr::eq(input.ple_books.context, self.context) - { - return Err(Error::ContextMismatch); - } - let rh = Self::span(&lease, S::R, 40960)?; - let eh = Self::span(&lease, S::PleEmbedding, 10240)?; - let bh = Self::span(&lease, S::Block, 10240)?.checked_subspan(t * 10240, 0, unique * 10240)?; - let cache_h = input.ple_cache.handle.ok_or(Error::ContextPoisoned)?; - let books_h = input.ple_books.handle.ok_or(Error::ContextPoisoned)?; - cache_h.validate_projection_extent(64 << 20, 1)?; - books_h.validate_projection_extent(input.ple_books.bytes, 2)?; - workspace.reject_alias(cache_h, 64 << 20)?; - workspace.reject_alias(books_h, input.ple_books.bytes)?; - // landing area: slot indices | embedding row indices | cache update records - let cap = self.capacity; - let slot_bytes = cap * 64; - let index_bytes = (cap * 4).next_multiple_of(16); - let total = slot_bytes + index_bytes + cap * 16 * 56; - if self.stage_scratch.is_none() { - self.stage_scratch = Some(self.context.allocate(total)?); - } - let scratch = self.stage_scratch.as_ref().ok_or(Error::ContextPoisoned)?; - if scratch.bytes != total { - return Err(Error::InvalidQwenShape); - } - let sh = scratch.handle.ok_or(Error::ContextPoisoned)?; - sh.validate_projection_extent(total, 4)?; - workspace.reject_alias(sh, total)?; - let slots_h = sh.checked_subspan(total, 0, t * 64)?; - let index_h = sh.checked_subspan(total, slot_bytes, t * 4)?; - let updates_h = - if misses > 0 { Some(sh.checked_subspan(total, slot_bytes + index_bytes, misses * 56)?) } else { None }; - let flags = self.status()?; - let mut slot_raw = bytes(t * 64)?; - for (x, b) in input.ple_slots.iter().zip(slot_raw.as_chunks_mut::<4>().0) { - b.copy_from_slice(&x.to_le_bytes()) - } - let mut index_raw = bytes(t * 4)?; - for (x, b) in input.embedding_index.iter().zip(index_raw.as_chunks_mut::<4>().0) { - b.copy_from_slice(&x.to_le_bytes()) - } - let guard = match self.context.enter() { - Ok(g) => g, - Err(err) => { - lease.mark_failed(); - workspace.mark_failed(); - self.context.retain_driver(); - return Err(err); - } - }; - let api = &self.context.driver.api; - let mut op = api - .copy_from(bh, input.embedding_rows) - .and_then(|()| api.copy_from(slots_h, &slot_raw[..t * 64])) - .and_then(|()| api.copy_from(index_h, &index_raw)); - if let (Ok(()), Some(h)) = (&op, updates_h) { - op = api.copy_from(h, input.ple_updates) - } - let sync = api.synchronize(); - let pop = guard.finish(); - if op.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - lease.mark_failed(); - workspace.mark_failed() - } - if sync.is_err() || pop.is_err() { - std::mem::forget((slot_raw, index_raw)); - self.context.retain_driver() - } - combine(combine(op, sync), pop)?; - let mut v = Vec::new(); - v.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; - if let Some(h) = updates_h { - kernel( - &mut v, - 3, - 0, - (misses * 64).div_ceil(256), - 256, - vec![A::Address(cache_h), A::Address(h), A::U32(misses as u32)], - ); - } - kernel( - &mut v, - 3, - 1, - (t * 16 * 160).div_ceil(256), - 256, - vec![ - A::Address(cache_h), - A::Address(slots_h), - A::Address(books_h), - A::Address(eh), - A::U32(parts as u32), - A::I64((t * 16) as i64), - A::Address(flags), - A::U32(8), - A::U32(6), - ], - ); - kernel( - &mut v, - 3, - 2, - (t * 2560).div_ceil(256), - 256, - vec![ - A::Address(bh), - A::Address(index_h), - A::Address(rh), - A::I64(t as i64), - A::U32(unique as u32), - A::Address(flags), - A::U32(8), - A::U32(5), - ], - ); - scan_gr(&mut v, rh, flags, 10240, t, 7); - self.run( - &mut lease, - workspace, - v, - t, - 8, - &[5, 6, 7], - &[ - "unused", - "unused", - "unused", - "unused", - "unused", - "Original prompt embedding", - "Original prompt PLE", - "Original prompt input", - ], - )?; + let (unique, misses, parts) = self.check_stage_input(t, &input)?; + let sp = self.stage_spans(&lease, workspace, &input, (t, unique, misses, parts))?; + self.upload_stage(&mut lease, workspace, &input, &sp)?; + self.run_stage(&mut lease, workspace, stage_commands(&sp)?, t)?; Ok(OriginalDeviceResidual { lease }) } } diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs index e692d235..2aeec91a 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs @@ -4,6 +4,7 @@ use super::*; mod build_phases; +mod fill_workers; mod impl_originalfileexpertsource_2; mod impl_originalfileexpertsource_2_2; mod impl_originalfileexpertsource_3; diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/build_phases.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/build_phases.rs index 5801d276..67bcb843 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/build_phases.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/build_phases.rs @@ -1,7 +1,9 @@ //! STRA-338 size: the phases of `OriginalFileExpertSource::build_cache_complement`, extracted in call order. #[allow(unused_imports)] +use super::fill_workers::{run_fill_workers, straddling_cut}; use super::*; +use crate::CurrentGuard; type Primary = Vec<(i32, i32, usize)>; @@ -22,6 +24,32 @@ pub(super) fn poison_parts(failed: &mut bool, context: &Context<'_>) { context.retain_driver(); } +/// The arena allocation failed: leave the context, and poison it on a driver error or a failed pop. +pub(super) fn alloc_failed( + failed: &mut bool, + context: &Context<'_>, + guard: CurrentGuard<'_, '_>, + primary: Error, +) -> Result<()> { + let pop = guard.finish(); + if matches!(primary, Error::Driver { .. }) || pop.is_err() { + poison_parts(failed, context); + } + combine(Err(primary), pop) +} + +/// The context pop failed, so the arena may still be in use by the device: poison and leak it. +pub(super) fn leak_arena( + failed: &mut bool, + context: &Context<'_>, + arena: abi::Arena, + result: Result<()>, +) -> Result<()> { + poison_parts(failed, context); + std::mem::forget(arena); + result +} + /// Closes a half-built arena after its fill failed, returning the fill error combined with the cleanup result. pub(super) fn discard_arena( failed: &mut bool, @@ -46,66 +74,6 @@ pub(super) fn discard_arena( combine(Err(primary), cleanup) } -/// The first offset at or below `want` whose expert straddles `want`, else `want`. -fn straddling_cut(layer_bytes: &[usize; LAYERS], offsets: &[usize], want: usize) -> usize { - for (i, &off) in offsets.iter().enumerate() { - if off != NONE && off < want && off.checked_add(layer_bytes[i / EXPERTS]).is_some_and(|end| end > want) { - return off; - } - } - want -} - -/// One worker: claims layers until none are left or an earlier error was recorded. -fn fill_worker(per_layer: &[Vec], next: &AtomicUsize, first: &Mutex>) { - loop { - let l = next.fetch_add(1, Ordering::Relaxed); - if l >= LAYERS { - break; - } - if first.lock().is_ok_and(|e| e.is_some()) { - break; - } - for j in &per_layer[l] { - if let Err(e) = j.run() { - if let Ok(mut f) = first.lock() { - if f.is_none() { - *f = Some(e); - } - } - break; - } - } - } -} - -/// Six Original layer workers; one actor participates. No Context/Rc is sent. -fn run_fill_workers(per_layer: &[Vec], stack: usize) -> Result<()> { - let next = AtomicUsize::new(0); - let first = Mutex::new(None); - let work = || fill_worker(per_layer, &next, &first); - thread::scope(|s| { - let mut workers = Vec::new(); - workers.try_reserve_exact(5).map_err(|_| Error::HostAllocation)?; - for _ in 0..5 { - workers.push( - thread::Builder::new().stack_size(stack).spawn_scoped(s, work).map_err(|_| Error::HostAllocation)?, - ); - } - work(); - for w in workers { - if w.join().is_err() { - return Err(Error::HostAllocation); - } - } - Ok(()) - })?; - if let Some(e) = first.into_inner().map_err(|_| Error::HostAllocation)? { - return Err(e); - } - Ok(()) -} - impl<'ctx> OriginalFileExpertSource<'ctx> { pub(super) fn build_preflight(&mut self, cache: &OriginalExpertCache<'ctx>) -> Result<()> { self.live()?; @@ -273,17 +241,10 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { headroom: usize, ) -> Result { let stack = abi::worker_stack_bytes()?; - let prospective_meta = self - .metadata_bytes()? - .checked_add( - layout.offsets.capacity() * size_of::() - + 2 * primary.capacity() * size_of::<(i32, i32, usize)>() - + slot_bytes.capacity() * size_of::() - + N * (size_of::() + size_of::() + size_of::()) - + LAYERS * size_of::>() - + 5 * size_of::>(), - ) - .ok_or(Error::BudgetExceeded)?; + let bookkeeping = layout.offsets.capacity() * size_of::() + + 2 * primary.capacity() * size_of::<(i32, i32, usize)>() + + slot_bytes.capacity() * size_of::(); + let prospective_meta = self.prospective_meta(bookkeeping)?; let bytes = layout.bytes; if prospective_meta > META_CAP || bytes.checked_add(prospective_meta).is_none_or(|n| n > SOURCE_CAP) @@ -298,6 +259,26 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { Ok(stack) } + /// The source metadata plus the build's own bookkeeping and the worker tables. + fn prospective_meta(&self, bookkeeping: usize) -> Result { + self.metadata_bytes()? + .checked_add( + bookkeeping + + N * (size_of::() + size_of::() + size_of::()) + + LAYERS * size_of::>() + + 5 * size_of::>(), + ) + .ok_or(Error::BudgetExceeded) + } + + /// Takes the filled arena and its layout into the source. + pub(super) fn commit_arena(&mut self, arena: abi::Arena, layout: Layout, slots: usize) { + self.arena = Some(arena); + self.offsets = layout.offsets; + self.ready = true; + self.lent_slots = if layout.lend.is_some() { slots - layout.keep_from } else { 0 }; + } + /// Pins the arena as asked, then copies every planned expert from the mapped source with worker threads. pub(super) fn fill_arena( &self, diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/fill_workers.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/fill_workers.rs new file mode 100644 index 00000000..bde62f0c --- /dev/null +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/fill_workers.rs @@ -0,0 +1,64 @@ +//! STRA-338 size: the fill workers of `OriginalFileExpertSource::build_cache_complement`. + +#[allow(unused_imports)] +use super::*; + +/// The first offset at or below `want` whose expert straddles `want`, else `want`. +pub(super) fn straddling_cut(layer_bytes: &[usize; LAYERS], offsets: &[usize], want: usize) -> usize { + for (i, &off) in offsets.iter().enumerate() { + if off != NONE && off < want && off.checked_add(layer_bytes[i / EXPERTS]).is_some_and(|end| end > want) { + return off; + } + } + want +} + +/// One worker: claims layers until none are left or an earlier error was recorded. +fn fill_worker(per_layer: &[Vec], next: &AtomicUsize, first: &Mutex>) { + loop { + let l = next.fetch_add(1, Ordering::Relaxed); + if l >= LAYERS { + break; + } + if first.lock().is_ok_and(|e| e.is_some()) { + break; + } + for j in &per_layer[l] { + if let Err(e) = j.run() { + if let Ok(mut f) = first.lock() { + if f.is_none() { + *f = Some(e); + } + } + break; + } + } + } +} + +/// Six Original layer workers; one actor participates. No Context/Rc is sent. +pub(super) fn run_fill_workers(per_layer: &[Vec], stack: usize) -> Result<()> { + let next = AtomicUsize::new(0); + let first = Mutex::new(None); + let work = || fill_worker(per_layer, &next, &first); + thread::scope(|s| { + let mut workers = Vec::new(); + workers.try_reserve_exact(5).map_err(|_| Error::HostAllocation)?; + for _ in 0..5 { + workers.push( + thread::Builder::new().stack_size(stack).spawn_scoped(s, work).map_err(|_| Error::HostAllocation)?, + ); + } + work(); + for w in workers { + if w.join().is_err() { + return Err(Error::HostAllocation); + } + } + Ok(()) + })?; + if let Some(e) = first.into_inner().map_err(|_| Error::HostAllocation)? { + return Err(e); + } + Ok(()) +} diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs index 9e4eb783..a0fd9af8 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs @@ -1,7 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalFileExpertSource (2). #[allow(unused_imports)] -use super::build_phases::{discard_arena, poison_parts}; +use super::build_phases::{alloc_failed, discard_arena, leak_arena, poison_parts}; use super::*; impl<'ctx> OriginalFileExpertSource<'ctx> { @@ -18,38 +18,21 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { let (primary, slot_bytes) = self.collect_primary(cache)?; let layout = self.plan_layout(cache, (&primary, &slot_bytes), (additional, rank), options)?; let stack = self.check_host_budget(&layout, (&primary, &slot_bytes), options.headroom_bytes)?; - let guard = self.context.enter().inspect_err(|_| { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - })?; + let guard = self.context.enter().inspect_err(|_| poison_parts(&mut self.failed, self.context))?; let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; let mut arena = match api.allocate(layout.bytes, options.pin) { Ok(a) => a, - Err(primary) => { - let pop = guard.finish(); - if matches!(primary, Error::Driver { .. }) || pop.is_err() { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - return combine(Err(primary), pop); - } + Err(primary) => return alloc_failed(&mut self.failed, self.context, guard, primary), }; let prepare = self.fill_arena(api, &mut arena, &layout, options, stack); let pop = guard.finish(); if pop.is_err() { - poison_parts(&mut self.failed, self.context); - std::mem::forget(arena); - return combine(prepare, pop); + return leak_arena(&mut self.failed, self.context, arena, combine(prepare, pop)); } if let Err(primary) = prepare { return discard_arena(&mut self.failed, self.context, api, arena, primary); } - self.arena = Some(arena); - self.offsets = layout.offsets; - self.ready = true; - self.lent_slots = if layout.lend.is_some() { cache.slots() - layout.keep_from } else { 0 }; + self.commit_arena(arena, layout, cache.slots()); Ok(()) } } diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice.rs index 787888c2..2fd136ac 100644 --- a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice.rs +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice.rs @@ -6,3 +6,4 @@ use super::*; mod impl_originalmoepromptdevice_2; mod impl_originalmoepromptdevice_2_2; mod impl_originalmoepromptdevice_3; +mod prepare_phases; diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2_2.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2_2.rs index 29134905..936391f5 100644 --- a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2_2.rs +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2_2.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalMoePromptDevice (2). #[allow(unused_imports)] +use super::prepare_phases::{MOE_NAMES, route_plan}; use super::*; impl<'ctx> OriginalMoePromptDevice<'ctx> { @@ -20,157 +21,12 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { let rows = read.lease(); let t = rows.rows(); workspace.validate_context(self.context)?; - let high = common(rows, S::MixedHigh, 5120)?; - let half = common(rows, S::MixedHalf, 5120)?; - let low_image = if low { Some(common(rows, S::MixedLow, 5120)?) } else { None }; - let logits = phase(rows, "logits", 512 * 4)?; - let ids = phase(rows, "ids", 10 * 4)?; - let w = phase(rows, "w", 10 * 4)?; - let gate = phase(rows, "sgate", 640 * 4)?; - let up = phase(rows, "sup", 640 * 4)?; - let h = phase(rows, "sh_h", 640 * 2)?; - let shared = phase(rows, "shared", 2560 * 4)?; - let sg = phase(rows, "sg", 4)?; - let router = self.weight(rows, workspace, weights[0], 512 * 2560 * 2)?; - let scalar = self.weight(rows, workspace, weights[1], 2560 * 2)?; - let dims = [(640, 2560), (640, 2560), (2560, 640)]; - let mut native = Vec::new(); - native.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; - for (index, (n, k)) in dims.iter().copied().enumerate() { - native.push(self.weight(rows, workspace, weights[index + 2], formats[index].matrix_bytes(n, k)?)?); - } - let scratch = self.handle(&self.scratch, SCRATCH)?; - let mut commands = Vec::new(); - commands.try_reserve_exact(32).map_err(|_| Error::HostAllocation)?; - self.scan(&mut commands, half, t * 2560, true, 0)?; - gemm(&mut commands, true, high, router, logits, t, 512, 2560, 0.0)?; - if let Some(lo) = low_image { - gemm(&mut commands, true, lo, router, logits, t, 512, 2560, 1.0)?; - } - self.scan(&mut commands, logits, t * 512, false, 1)?; - // route_kernel<16>: one warp/token, eight token rows per256-thread CTA. - commands.push(Command::Kernel { - dequant: false, - index: 4, - grid: t.div_ceil(8) as u32, - args: KernelArguments::new(vec![A::Address(logits), A::Address(ids), A::Address(w), A::I64(t as i64)]), - }); - self.scan(&mut commands, w, t * 10, false, 2)?; - for index in 0..3 { - let (n, k) = dims[index]; - let destination = [gate, up, shared][index]; - kernel( - &mut commands, - true, - dequant_index(formats[index]), - n * (k / 32), - vec![ - A::Address(native[index]), - A::I64(formats[index].matrix_bytes(1, k)? as i64), - A::I64(0), - A::I64(n as i64), - A::I64((k / 32) as i64), - A::Address(scratch), - ], - )?; - gemm(&mut commands, false, if index == 2 { h } else { half }, scratch, destination, t, n, k, 0.0)?; - self.scan(&mut commands, destination, t * n, false, [3, 4, 6][index])?; - if index == 1 { - kernel( - &mut commands, - false, - 5, - t * 640, - vec![A::Address(gate), A::Address(up), A::Address(h), A::I64(t as i64)], - )?; - self.scan(&mut commands, h, t * 640, true, 5)?; - } - } - gemm(&mut commands, true, high, scalar, sg, t, 1, 2560, 0.0)?; - if let Some(lo) = low_image { - gemm(&mut commands, true, lo, scalar, sg, t, 1, 2560, 1.0)?; - } - self.scan(&mut commands, sg, t, false, 7)?; - self.run( - workspace, - commands, - &[ - "MixedH", - "router", - "route weights", - "shared Gate", - "shared Up", - "shared SwiGLU", - "shared Down", - "shared scalar", - ], - )?; - let mut raw = blank(t * 10 * 4)?; - let guard = self.context.enter()?; - let copy = self.context.driver.api.copy_to(ids, &mut raw); - let wait = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if wait.is_err() || pop.is_err() { - std::mem::forget(raw); - self.failed = true; - self.context.poison(); - return combine(combine(copy, wait), pop).map(|()| unreachable!()); - } - combine(combine(copy, wait), pop)?; - let mut counts = [0u32; 512]; - for row in raw.chunks_exact(40) { - let mut seen = [0u64; 8]; - for word in row.as_chunks::<4>().0 { - let id = i32::from_le_bytes(*word); - if !(0..512).contains(&id) { - return Err(Error::InvalidDriverValue("Original routed ID")); - } - let id = id as usize; - let bit = 1u64 << (id % 64); - if seen[id / 64] & bit != 0 { - return Err(Error::InvalidDriverValue("Original duplicate routed ID")); - } - seen[id / 64] |= bit; - counts[id] += 1; - } - } - let mut offsets = [0usize; 513]; - for expert in 0..512 { - offsets[expert + 1] = offsets[expert] + counts[expert] as usize; - } - let mut cursor = offsets; - let mut source_rows = Vec::new(); - source_rows.try_reserve_exact(t * 10).map_err(|_| Error::HostAllocation)?; - source_rows.resize(t * 10, 0); - let mut slot_map = Vec::new(); - slot_map.try_reserve_exact(t * 10).map_err(|_| Error::HostAllocation)?; - for (i, word) in raw.as_chunks::<4>().0.iter().enumerate() { - let id = i32::from_le_bytes(*word) as usize; - let p = cursor[id]; - cursor[id] += 1; - slot_map.push(p as i32); - source_rows[p] = (i / 10) as u32; - } - let mut order = Vec::new(); - let mut actual_counts = Vec::new(); - order.try_reserve_exact(512).map_err(|_| Error::HostAllocation)?; - actual_counts.try_reserve_exact(512).map_err(|_| Error::HostAllocation)?; - for (id, count) in counts.iter().copied().enumerate() { - if count > 0 { - order.push(id as u32); - actual_counts.push(count); - } - } - Ok(OriginalMoePromptLayer { - program: self, - read, - order, - counts: actual_counts, - source_rows, - slot_map, - slot_uploaded: false, - completed_experts: 0, - }) + let (sp, mw) = self.moe_inputs(rows, workspace, weights, (formats, low))?; + let commands = self.moe_commands((&sp, &mw), formats, t)?; + self.run(workspace, commands, &MOE_NAMES)?; + let raw = self.read_route_ids(sp.ids, t)?; + let plan = route_plan(&raw, t)?; + Ok(OriginalMoePromptLayer::new(self, read, plan)) } pub fn close(mut self) -> Result<()> { self.close_inner() diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/prepare_phases.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/prepare_phases.rs new file mode 100644 index 00000000..6f470447 --- /dev/null +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/prepare_phases.rs @@ -0,0 +1,252 @@ +//! STRA-338 size: the phases of `OriginalMoePromptDevice::prepare`, extracted in call order. + +#[allow(unused_imports)] +use super::*; + +pub(super) const MOE_NAMES: [&str; 8] = + ["MixedH", "router", "route weights", "shared Gate", "shared Up", "shared SwiGLU", "shared Down", "shared scalar"]; + +/// The device spans one MoE prepare reads and writes. +pub(super) struct MoeSpans { + high: BufferHandle, + half: BufferHandle, + low: Option, + logits: BufferHandle, + pub(super) ids: BufferHandle, + w: BufferHandle, + /// Shared gate, up and down outputs. + shared: [BufferHandle; 3], + h: BufferHandle, + sg: BufferHandle, +} + +impl MoeSpans { + pub(super) fn new(rows: &OriginalPromptRows<'_, '_, '_>, low: bool) -> Result { + let high = common(rows, S::MixedHigh, 5120)?; + let half = common(rows, S::MixedHalf, 5120)?; + let low = if low { Some(common(rows, S::MixedLow, 5120)?) } else { None }; + let (logits, ids, w) = + (phase(rows, "logits", 512 * 4)?, phase(rows, "ids", 10 * 4)?, phase(rows, "w", 10 * 4)?); + let shared = shared_spans(rows)?; + Ok(Self { high, half, low, logits, ids, w, shared: shared.0, h: shared.1, sg: shared.2 }) + } +} + +/// The shared gate, up and down outputs, the SwiGLU result and the scalar gate span. +fn shared_spans(rows: &OriginalPromptRows<'_, '_, '_>) -> Result<([BufferHandle; 3], BufferHandle, BufferHandle)> { + let gate = phase(rows, "sgate", 640 * 4)?; + let up = phase(rows, "sup", 640 * 4)?; + let h = phase(rows, "sh_h", 640 * 2)?; + let down = phase(rows, "shared", 2560 * 4)?; + Ok(([gate, up, down], h, phase(rows, "sg", 4)?)) +} + +/// The router, scalar gate and three shared native weights. +pub(super) struct MoeWeights { + router: BufferHandle, + scalar: BufferHandle, + native: Vec, +} + +/// The host plan of one routed layer: experts in use, their row counts and the row/slot maps. +pub(super) struct RoutePlan { + pub(super) order: Vec, + pub(super) counts: Vec, + pub(super) source_rows: Vec, + pub(super) slot_map: Vec, +} + +const DIMS: [(usize, usize); 3] = [(640, 2560), (640, 2560), (2560, 640)]; + +impl<'ctx> OriginalMoePromptDevice<'ctx> { + /// The spans, then the weights, of one prepare. + pub(super) fn moe_inputs( + &self, + rows: &OriginalPromptRows<'_, '_, 'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + weights: [&DeviceBuffer<'_>; 5], + (formats, low): ([GdnNativeFormat; 3], bool), + ) -> Result<(MoeSpans, MoeWeights)> { + let sp = MoeSpans::new(rows, low)?; + Ok((sp, self.moe_weights(rows, workspace, weights, formats)?)) + } + + fn moe_weights( + &self, + rows: &OriginalPromptRows<'_, '_, 'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + weights: [&DeviceBuffer<'_>; 5], + formats: [GdnNativeFormat; 3], + ) -> Result { + let router = self.weight(rows, workspace, weights[0], 512 * 2560 * 2)?; + let scalar = self.weight(rows, workspace, weights[1], 2560 * 2)?; + let mut native = Vec::new(); + native.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; + for (index, (n, k)) in DIMS.iter().copied().enumerate() { + native.push(self.weight(rows, workspace, weights[index + 2], formats[index].matrix_bytes(n, k)?)?); + } + Ok(MoeWeights { router, scalar, native }) + } + + /// The launches of one prepare: route, shared experts and the shared scalar gate. + pub(super) fn moe_commands( + &self, + (sp, mw): (&MoeSpans, &MoeWeights), + formats: [GdnNativeFormat; 3], + t: usize, + ) -> Result> { + let scratch = self.handle(&self.scratch, SCRATCH)?; + let mut commands = Vec::new(); + commands.try_reserve_exact(32).map_err(|_| Error::HostAllocation)?; + self.push_route(&mut commands, (sp, mw), t)?; + for index in 0..3 { + self.push_shared(&mut commands, (sp, mw), (index, formats[index]), scratch, t)?; + } + gemm(&mut commands, true, sp.high, mw.scalar, sp.sg, t, 1, 2560, 0.0)?; + if let Some(lo) = sp.low { + gemm(&mut commands, true, lo, mw.scalar, sp.sg, t, 1, 2560, 1.0)?; + } + self.scan(&mut commands, sp.sg, t, false, 7)?; + Ok(commands) + } + + fn push_route(&self, commands: &mut Vec, (sp, mw): (&MoeSpans, &MoeWeights), t: usize) -> Result<()> { + self.scan(commands, sp.half, t * 2560, true, 0)?; + gemm(commands, true, sp.high, mw.router, sp.logits, t, 512, 2560, 0.0)?; + if let Some(lo) = sp.low { + gemm(commands, true, lo, mw.router, sp.logits, t, 512, 2560, 1.0)?; + } + self.scan(commands, sp.logits, t * 512, false, 1)?; + // route_kernel<16>: one warp/token, eight token rows per256-thread CTA. + commands.push(Command::Kernel { + dequant: false, + index: 4, + grid: t.div_ceil(8) as u32, + args: KernelArguments::new(vec![ + A::Address(sp.logits), + A::Address(sp.ids), + A::Address(sp.w), + A::I64(t as i64), + ]), + }); + self.scan(commands, sp.w, t * 10, false, 2) + } + + /// Shared expert stage `index` (gate, up, down): dequantize the weight, multiply, guard; SwiGLU after up. + fn push_shared( + &self, + commands: &mut Vec, + (sp, mw): (&MoeSpans, &MoeWeights), + (index, format): (usize, GdnNativeFormat), + scratch: BufferHandle, + t: usize, + ) -> Result<()> { + let (n, k) = DIMS[index]; + let destination = sp.shared[index]; + let dequant = vec![ + A::Address(mw.native[index]), + A::I64(format.matrix_bytes(1, k)? as i64), + A::I64(0), + A::I64(n as i64), + A::I64((k / 32) as i64), + A::Address(scratch), + ]; + kernel(commands, true, dequant_index(format), n * (k / 32), dequant)?; + gemm(commands, false, if index == 2 { sp.h } else { sp.half }, scratch, destination, t, n, k, 0.0)?; + self.scan(commands, destination, t * n, false, [3, 4, 6][index])?; + if index == 1 { + let swiglu = vec![A::Address(sp.shared[0]), A::Address(sp.shared[1]), A::Address(sp.h), A::I64(t as i64)]; + kernel(commands, false, 5, t * 640, swiglu)?; + self.scan(commands, sp.h, t * 640, true, 5)?; + } + Ok(()) + } + + /// Copies the routed ids back; an uncertain drain leaks the buffer. + pub(super) fn read_route_ids(&mut self, ids: BufferHandle, t: usize) -> Result> { + let mut raw = blank(t * 10 * 4)?; + let guard = self.context.enter()?; + let copy = self.context.driver.api.copy_to(ids, &mut raw); + let wait = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if wait.is_err() || pop.is_err() { + std::mem::forget(raw); + self.failed = true; + self.context.poison(); + return combine(combine(copy, wait), pop).map(|()| unreachable!()); + } + combine(combine(copy, wait), pop)?; + Ok(raw) + } +} + +/// Validates the routed ids (in range, no repeat per row) and builds the per-expert layout of the rows. +pub(super) fn route_plan(raw: &[u8], t: usize) -> Result { + let counts = count_routes(raw)?; + let (source_rows, slot_map) = place_routes(raw, &counts, t)?; + let mut order = Vec::new(); + let mut actual_counts = Vec::new(); + order.try_reserve_exact(512).map_err(|_| Error::HostAllocation)?; + actual_counts.try_reserve_exact(512).map_err(|_| Error::HostAllocation)?; + for (id, count) in counts.iter().copied().enumerate() { + if count > 0 { + order.push(id as u32); + actual_counts.push(count); + } + } + Ok(RoutePlan { order, counts: actual_counts, source_rows, slot_map }) +} + +fn count_routes(raw: &[u8]) -> Result<[u32; 512]> { + let mut counts = [0u32; 512]; + for row in raw.chunks_exact(40) { + let mut seen = [0u64; 8]; + for word in row.as_chunks::<4>().0 { + let id = i32::from_le_bytes(*word); + if !(0..512).contains(&id) { + return Err(Error::InvalidDriverValue("Original routed ID")); + } + let id = id as usize; + let bit = 1u64 << (id % 64); + if seen[id / 64] & bit != 0 { + return Err(Error::InvalidDriverValue("Original duplicate routed ID")); + } + seen[id / 64] |= bit; + counts[id] += 1; + } + } + Ok(counts) +} + +/// Row `p` of the expert-major order is the source row of the `p`-th (expert, row) pair; `slot_map` inverts it. +fn place_routes(raw: &[u8], counts: &[u32; 512], t: usize) -> Result<(Vec, Vec)> { + let mut offsets = [0usize; 513]; + for expert in 0..512 { + offsets[expert + 1] = offsets[expert] + counts[expert] as usize; + } + let mut cursor = offsets; + let mut source_rows = Vec::new(); + source_rows.try_reserve_exact(t * 10).map_err(|_| Error::HostAllocation)?; + source_rows.resize(t * 10, 0); + let mut slot_map = Vec::new(); + slot_map.try_reserve_exact(t * 10).map_err(|_| Error::HostAllocation)?; + for (i, word) in raw.as_chunks::<4>().0.iter().enumerate() { + let id = i32::from_le_bytes(*word) as usize; + let p = cursor[id]; + cursor[id] += 1; + slot_map.push(p as i32); + source_rows[p] = (i / 10) as u32; + } + Ok((source_rows, slot_map)) +} + +impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'loan, 'ctx> { + pub(super) fn new( + program: &'program mut OriginalMoePromptDevice<'ctx>, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + plan: RoutePlan, + ) -> Self { + let RoutePlan { order, counts, source_rows, slot_map } = plan; + Self { program, read, order, counts, source_rows, slot_map, slot_uploaded: false, completed_experts: 0 } + } +} diff --git a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs index 771fcab9..7c24d7cb 100644 --- a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs +++ b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs @@ -1,7 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalExpertStager. #[allow(unused_imports)] -use super::stream_phases::{arm_scope, finish_scope, start_issuer}; +use super::stream_phases::{arm_scope, finish_scope, open_scope, start_or_cleanup}; use super::*; impl<'ctx> OriginalExpertStager<'ctx> { @@ -26,24 +26,10 @@ impl<'ctx> OriginalExpertStager<'ctx> { let layer_start = self.queue_stream_jobs(&rows, (first, end), &mut entries)?; self.ensure_stream_events()?; let issuer = self.new_issuer(entries, targets, ring)?; - let mut scope = OriginalStreamAll { - stager: self, - rows: Some(rows), - copy: Some(copy), - compute: Some(compute), - issuer, - thread: None, - layer_start, - first, - end, - next_layer: first, - cursor: layer_start[first as usize], - finished: false, - }; + let streams = (rows, copy, compute); + let mut scope = open_scope(self, streams, (issuer, layer_start), (first, end)); arm_scope(&mut scope, generation)?; - if let Err(primary) = start_issuer(&mut scope, options, ring)? { - return combine(Err(primary), scope.cleanup()); - } + start_or_cleanup(&mut scope, options, ring)?; finish_scope(&mut scope, end, consumer) } } diff --git a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/stream_phases.rs b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/stream_phases.rs index bdd5a8d9..d446a0a5 100644 --- a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/stream_phases.rs +++ b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/stream_phases.rs @@ -59,6 +59,41 @@ pub(super) fn arm_scope(scope: &mut OriginalStreamAll<'_, '_, '_, '_>, generatio Ok(()) } +/// The scope over the stager, the genuine rows and both streams, positioned at the first layer. +pub(super) fn open_scope<'s, 'arena, 'loan, 'ctx>( + stager: &'s mut OriginalExpertStager<'ctx>, + (rows, copy, compute): (OriginalPromptRows<'arena, 'loan, 'ctx>, OriginalGpuStream<'ctx>, OriginalGpuStream<'ctx>), + (issuer, layer_start): (Arc, [usize; 49]), + (first, end): (u8, u8), +) -> OriginalStreamAll<'s, 'arena, 'loan, 'ctx> { + OriginalStreamAll { + stager, + rows: Some(rows), + copy: Some(copy), + compute: Some(compute), + issuer, + thread: None, + layer_start, + first, + end, + next_layer: first, + cursor: layer_start[first as usize], + finished: false, + } +} + +/// Starts the issuer; a start failure cleans the scope up and is returned with the cleanup result. +pub(super) fn start_or_cleanup( + scope: &mut OriginalStreamAll<'_, '_, '_, '_>, + options: OriginalStreamAllOptions, + ring: usize, +) -> Result<()> { + if let Err(primary) = start_issuer(scope, options, ring)? { + return combine(Err(primary), scope.cleanup()); + } + Ok(()) +} + /// Starts the issuer thread or issues inline. The outer error returns straight from the caller; the inner one /// is the start failure the caller cleans up after. pub(super) fn start_issuer( diff --git a/crates/cuda-driver/src/original_verify_gpu_plan.rs b/crates/cuda-driver/src/original_verify_gpu_plan.rs index a300dd7d..42217687 100644 --- a/crates/cuda-driver/src/original_verify_gpu_plan.rs +++ b/crates/cuda-driver/src/original_verify_gpu_plan.rs @@ -59,6 +59,8 @@ pub(crate) use impl_originalverifygpuplan::encode_plan_block; use impl_originalverifygpuplan::span_layer; #[path = "original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs"] mod impl_schedule_originalverifycpusink; +#[path = "original_verify_gpu_plan/plan_phases.rs"] +mod plan_phases; #[allow(unused_imports)] pub(crate) use impl_schedule_originalverifycpusink::dma_options; #[path = "original_verify_gpu_plan/dma_options_for_fn.rs"] diff --git a/crates/cuda-driver/src/original_verify_gpu_plan/impl_originalverifygpuplan.rs b/crates/cuda-driver/src/original_verify_gpu_plan/impl_originalverifygpuplan.rs index 77cd2e4e..18e0fbe3 100644 --- a/crates/cuda-driver/src/original_verify_gpu_plan/impl_originalverifygpuplan.rs +++ b/crates/cuda-driver/src/original_verify_gpu_plan/impl_originalverifygpuplan.rs @@ -43,50 +43,65 @@ pub(crate) fn encode_plan_block( if k == 0 || n_entries > cap || n_entries > 128 || vram.len() > cap || pcie.len() > cap.min(MAX_PCIE_FETCHES) { return Err(Error::InvalidQwenShape); } - let mut words = vec![0i32; layout.words]; - let mut seen = [false; 128]; - let mut entries = 0usize; - let put_u64 = |words: &mut Vec, at: usize, value: u64| { - words[at] = value as u32 as i32; - words[at + 1] = (value >> 32) as u32 as i32; - }; - let mut add_entries = |words: &mut Vec, list: &[u16], entries: &mut usize| -> Result<()> { + let mut w = + PlanWriter { layout, cap, k, n_entries, words: vec![0i32; layout.words], seen: [false; 128], entries: 0 }; + for (g, (ptr, list)) in vram.iter().enumerate() { + w.group((layout.ptr + 2 * g, layout.start + g), *ptr, list)?; + } + w.words[layout.start + vram.len()] = w.entries as i32; + for (q, (ptr, list)) in pcie.iter().enumerate() { + w.group((layout.ptr2 + 2 * q, layout.start2 + q), *ptr, list)?; + } + w.words[layout.start2 + pcie.len()] = w.entries as i32; + w.words[layout.counts] = vram.len() as i32; + w.words[layout.counts + 1] = w.entries as i32; + w.words[layout.counts + 2] = pcie.len() as i32; + Ok(w.words.iter().flat_map(|w| w.to_le_bytes()).collect()) +} + +/// The plan block under construction: words, the entries already taken and their count. +struct PlanWriter<'a> { + layout: &'a PlanLayout, + cap: usize, + k: usize, + n_entries: usize, + words: Vec, + seen: [bool; 128], + entries: usize, +} + +impl PlanWriter<'_> { + fn put_u64(&mut self, at: usize, value: u64) { + self.words[at] = value as u32 as i32; + self.words[at + 1] = (value >> 32) as u32 as i32; + } + + /// Takes each entry of the group once: `dst[e] = i`, `tok[e] = i / k`. + fn add_entries(&mut self, list: &[u16]) -> Result<()> { if list.is_empty() { return Err(Error::InvalidQwenShape); } for &i in list { let i = usize::from(i); - if i >= n_entries || std::mem::replace(&mut seen[i], true) || *entries >= cap { + if i >= self.n_entries || std::mem::replace(&mut self.seen[i], true) || self.entries >= self.cap { return Err(Error::InvalidQwenShape); } - words[layout.dst + *entries] = i as i32; - words[layout.tok + *entries] = (i / k) as i32; - *entries += 1; + self.words[self.layout.dst + self.entries] = i as i32; + self.words[self.layout.tok + self.entries] = (i / self.k) as i32; + self.entries += 1; } Ok(()) - }; - for (g, (ptr, list)) in vram.iter().enumerate() { - if *ptr == 0 { + } + + /// One group: its pointer words, its start index and its entries. + fn group(&mut self, (ptr_at, start_at): (usize, usize), ptr: u64, list: &[u16]) -> Result<()> { + if ptr == 0 { return Err(Error::InvalidQwenShape); } - put_u64(&mut words, layout.ptr + 2 * g, *ptr); - words[layout.start + g] = entries as i32; - add_entries(&mut words, list, &mut entries)?; + self.put_u64(ptr_at, ptr); + self.words[start_at] = self.entries as i32; + self.add_entries(list) } - words[layout.start + vram.len()] = entries as i32; - for (q, (ptr, list)) in pcie.iter().enumerate() { - if *ptr == 0 { - return Err(Error::InvalidQwenShape); - } - put_u64(&mut words, layout.ptr2 + 2 * q, *ptr); - words[layout.start2 + q] = entries as i32; - add_entries(&mut words, list, &mut entries)?; - } - words[layout.start2 + pcie.len()] = entries as i32; - words[layout.counts] = vram.len() as i32; - words[layout.counts + 1] = entries as i32; - words[layout.counts + 2] = pcie.len() as i32; - Ok(words.iter().flat_map(|w| w.to_le_bytes()).collect()) } pub(super) fn span_layer(span: &ResidentExpertBankSpan) -> Option { diff --git a/crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs b/crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs index d94828b3..22610dbe 100644 --- a/crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs +++ b/crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs @@ -43,190 +43,15 @@ impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> { pcie: Option>, copy: &mut OriginalGpuStream<'ctx>, ) -> Result<()> { - let context = self.bank.physical.context; - self.bank.validate_context(context)?; - cache.validate_file_source_context(context)?; - copy.validate_context(context)?; - let g = self.bank.geometry(); - let layout = PlanLayout::new(g.max_t * g.k); - let cap = g.max_t * g.k; - let a = self.bank.physical.mapped[11] - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .as_ref() - .ok_or(Error::ContextPoisoned)? - .read_u32(0)?; - if a >= self.ring { - return Err(Error::InvalidQwenShape); - } - let ids = self.group_ids()?; - // VRAM groups: a completed slot owned by the routed expert of every entry, in this layer. - let mut vram = Vec::new(); - vram.try_reserve_exact(plan.vram.len()).map_err(|_| Error::HostAllocation)?; - for (slot, entries) in &plan.vram { - let (layer, expert) = cache.slot_owner(*slot).ok_or(Error::InvalidQwenShape)?; - if layer != self.layer || entries.iter().any(|&i| ids.get(usize::from(i)).copied() != Some(expert as i32)) { - return Err(Error::InvalidQwenShape); - } - let (handle, _) = cache.completed_slot(*slot)?; - vram.push((handle.qwen_address(), entries.as_slice())); - } - // PCIe groups: staging slot q of this group's half, each the bank spans of that entry's expert. - let per = staging_blobs_per_group(self.groups); - let mut stride = 0usize; - let spans = match &pcie { - Some(source) => source.spans, - None => &[], - }; - if spans.len() != plan.pcie.len() || plan.pcie.len() > per.min(MAX_PCIE_FETCHES) { - return Err(Error::InvalidQwenShape); - } - for (q, entries) in plan.pcie.iter().enumerate() { - let s = &spans[q]; - let source = pcie.as_ref().ok_or(Error::InvalidQwenShape)?; - if !source.bank.cache_context_matches(context) - || !source.bank.eligible(s) - || span_layer(&s[0]) != Some(self.layer) - || entries.iter().any(|&i| ids.get(usize::from(i)).copied() != Some(s[0].expert() as i32)) - { - return Err(Error::InvalidQwenShape); - } - let bytes = s.iter().try_fold(0usize, |n, x| n.checked_add(x.bytes().len()).ok_or(Error::InvalidSize))?; - if bytes == 0 || bytes > g.max_expert_blob || (stride != 0 && bytes != stride) { - return Err(Error::InvalidQwenShape); - } - stride = bytes; - } - let staging = if plan.pcie.is_empty() { - 0 - } else { - self.bank.physical.span("staging", self.group * per * g.max_expert_blob, per * g.max_expert_blob)? - }; + let (layout, cap, ids) = self.plan_preflight(cache, copy)?; + let vram = self.plan_vram(plan, cache, &ids)?; + let stride = self.check_pcie(plan, pcie.as_ref(), &ids)?; + let staging = self.staging_base(plan)?; let kernel = self.bank.pcie_mode == 2; - // The copy kernel (pcie mode 2) reads every PCIe expert's three spans through their device aliases: each must - // have exactly the length the graphs copy for this layer. - let mut aliases: Vec<[u64; 3]> = Vec::new(); - if kernel && !plan.pcie.is_empty() { - let roles = self - .bank - .pcie_roles - .as_ref() - .and_then(|r| r.get(self.layer)) - .copied() - .ok_or(Error::InvalidQwenShape)?; - let source = pcie.as_ref().ok_or(Error::InvalidQwenShape)?; - if 3 * plan.pcie.len() > cap { - return Err(Error::InvalidQwenShape); - } - aliases.try_reserve_exact(spans.len()).map_err(|_| Error::HostAllocation)?; - for s in spans { - let mut a = [0u64; 3]; - for (r, part) in s.iter().enumerate() { - if part.bytes().len() != roles[r] { - return Err(Error::InvalidQwenShape); - } - a[r] = source.bank.pcie_alias(part)?; - } - aliases.push(a); - } - } - let pcie_ptrs: Vec<(u64, &[u16])> = plan - .pcie - .iter() - .enumerate() - .map(|(q, e)| (if kernel { aliases[q][0] } else { staging + (q * stride) as u64 }, e.as_slice())) - .collect(); - let mut block = encode_plan_block(&layout, cap, g.k, self.rows * g.k, &vram, &pcie_ptrs)?; - // pcie mode 2: `ptr2[3 q + r]` = span r of PCIe group q; the graph's copy kernel stages them and rebases ptr2[q]. - for (q, a) in aliases.iter().enumerate() { - for (r, &alias) in a.iter().enumerate() { - let at = (layout.ptr2 + 2 * (3 * q + r)) * 4; - block[at..at + 8].copy_from_slice(&alias.to_le_bytes()); - } - } - { - let m = &self.bank.physical.mapped; - let mut slot = m[14].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; - slot.as_mut().ok_or(Error::ContextPoisoned)?.write(self.group * layout.mapped_stride() * 4, &block)?; - m[11] - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)? - .as_mut() - .ok_or(Error::ContextPoisoned)? - .publish_u32(0, self.ring)?; - } - let flag_b = self.bank.physical.mapped[12] - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .as_ref() - .ok_or(Error::ContextPoisoned)? - .host_address(0, 4)?; - if kernel { - // No host CUDA call inside the window (generate.cpp's reason for `--pcie-mode kernel`): the copy kernel - // reads the registered bytes after flag B, so the bank stays retained until the window's fence. - if !plan.pcie.is_empty() { - self.bank.retain_pcie_source(Rc::clone(pcie.as_ref().ok_or(Error::InvalidQwenShape)?.bank))?; - } - return self.bank.physical.mapped[12] - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)? - .as_mut() - .ok_or(Error::ContextPoisoned)? - .raise_u32(0, self.ring); - } - match pcie { - None => self.bank.physical.mapped[12] - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)? - .as_mut() - .ok_or(Error::ContextPoisoned)? - .raise_u32(0, self.ring), - Some(source) => { - if !plan.pcie.is_empty() { - // The bank's registered bytes are read by the copy engine after this call returns: the bank - // stays retained by the verifier until the window's copy-stream fence. - self.bank.retain_pcie_source(Rc::clone(source.bank))?; - } - let (many, batch, write) = dma_options(); - if many { - let mut pieces: Vec<(u64, &[u8])> = Vec::new(); - for (q, s) in spans.iter().enumerate() { - let mut offset = staging + (q * stride) as u64; - for part in s { - let bytes = source.bank.cache_source(part)?; - for (at, n) in source.bank.copy_pieces(bytes) { - pieces.push((offset + at as u64, &bytes[at..at + n])); - } - offset += bytes.len() as u64; - } - } - if !pieces.is_empty() { - copy.enqueue_copy_h2d_many(&pieces, batch)?; - } - } else { - for (q, s) in spans.iter().enumerate() { - let mut offset = staging + (q * stride) as u64; - for part in s { - let bytes = source.bank.cache_source(part)?; - for (at, n) in source.bank.copy_pieces(bytes) { - copy.enqueue_copy_h2d(offset + at as u64, &bytes[at..at + n])?; - } - offset += bytes.len() as u64; - } - } - } - if write { - let device_b = self.bank.physical.mapped[12] - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .as_ref() - .ok_or(Error::ContextPoisoned)? - .address(0, 4)?; - return copy.enqueue_raise_flag(flag_b, device_b, self.ring); - } - copy.enqueue_raise_u32(flag_b, self.ring) - } - } + let aliases = self.kernel_aliases(plan, pcie.as_ref(), cap, kernel)?; + let block = self.build_plan_block(plan, &layout, cap, (&vram, &aliases), (kernel, staging, stride))?; + self.publish_plan_block(&layout, &block)?; + self.raise_after_staging(plan, pcie, copy, (kernel, staging, stride)) } } diff --git a/crates/cuda-driver/src/original_verify_gpu_plan/plan_phases.rs b/crates/cuda-driver/src/original_verify_gpu_plan/plan_phases.rs new file mode 100644 index 00000000..75c05268 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_gpu_plan/plan_phases.rs @@ -0,0 +1,322 @@ +//! STRA-338 size: the phases of `OriginalVerifyCpuSink::publish_gpu_plan`, extracted in call order. + +use super::impl_schedule_originalverifycpusink::dma_options; +#[allow(unused_imports)] +use super::*; + +type PcieSource<'a, 'ctx> = Option<&'a OriginalVerifyPcieSource<'a, 'ctx>>; + +/// The PCIe spans of the source, or none without one. +pub(super) fn pcie_spans<'a>(pcie: Option<&OriginalVerifyPcieSource<'a, '_>>) -> &'a [[ResidentExpertBankSpan; 3]] { + match pcie { + Some(source) => source.spans, + None => &[], + } +} + +impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> { + /// Validates the contexts, refuses a group whose flag A already reached this ring; returns the plan layout, + /// its entry capacity and the group's routed ids. + pub(super) fn plan_preflight( + &self, + cache: &OriginalExpertCache<'ctx>, + copy: &OriginalGpuStream<'ctx>, + ) -> Result<(PlanLayout, usize, Vec)> { + let context = self.bank.physical.context; + self.bank.validate_context(context)?; + cache.validate_file_source_context(context)?; + copy.validate_context(context)?; + let g = self.bank.geometry(); + let cap = g.max_t * g.k; + let a = self.bank.physical.mapped[11] + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .read_u32(0)?; + if a >= self.ring { + return Err(Error::InvalidQwenShape); + } + Ok((PlanLayout::new(cap), cap, self.group_ids()?)) + } + + /// VRAM groups: a completed slot owned by the routed expert of every entry, in this layer. + pub(super) fn plan_vram<'p>( + &self, + plan: &'p OriginalVerifyGpuPlan, + cache: &OriginalExpertCache<'ctx>, + ids: &[i32], + ) -> Result> { + let mut vram = Vec::new(); + vram.try_reserve_exact(plan.vram.len()).map_err(|_| Error::HostAllocation)?; + for (slot, entries) in &plan.vram { + let (layer, expert) = cache.slot_owner(*slot).ok_or(Error::InvalidQwenShape)?; + if layer != self.layer || entries.iter().any(|&i| ids.get(usize::from(i)).copied() != Some(expert as i32)) { + return Err(Error::InvalidQwenShape); + } + let (handle, _) = cache.completed_slot(*slot)?; + vram.push((handle.qwen_address(), entries.as_slice())); + } + Ok(vram) + } + + /// PCIe groups: staging slot q of this group's half, each the bank spans of that entry's expert; returns the + /// common byte stride of the staged experts (zero without PCIe groups). + pub(super) fn check_pcie( + &self, + plan: &OriginalVerifyGpuPlan, + pcie: PcieSource<'_, 'ctx>, + ids: &[i32], + ) -> Result { + let per = staging_blobs_per_group(self.groups); + let mut stride = 0usize; + let spans = pcie_spans(pcie); + if spans.len() != plan.pcie.len() || plan.pcie.len() > per.min(MAX_PCIE_FETCHES) { + return Err(Error::InvalidQwenShape); + } + for (q, entries) in plan.pcie.iter().enumerate() { + let source = pcie.ok_or(Error::InvalidQwenShape)?; + let bytes = self.pcie_entry_bytes(source, &spans[q], entries, ids)?; + if stride != 0 && bytes != stride { + return Err(Error::InvalidQwenShape); + } + stride = bytes; + } + Ok(stride) + } + + /// One PCIe entry: the bank must be eligible and own the spans of exactly the routed expert of this layer. + fn pcie_entry_bytes( + &self, + source: &OriginalVerifyPcieSource<'_, 'ctx>, + s: &[ResidentExpertBankSpan; 3], + entries: &[u16], + ids: &[i32], + ) -> Result { + let context = self.bank.physical.context; + if !source.bank.cache_context_matches(context) + || !source.bank.eligible(s) + || span_layer(&s[0]) != Some(self.layer) + || entries.iter().any(|&i| ids.get(usize::from(i)).copied() != Some(s[0].expert() as i32)) + { + return Err(Error::InvalidQwenShape); + } + let bytes = s.iter().try_fold(0usize, |n, x| n.checked_add(x.bytes().len()).ok_or(Error::InvalidSize))?; + if bytes == 0 || bytes > self.bank.geometry().max_expert_blob { + return Err(Error::InvalidQwenShape); + } + Ok(bytes) + } + + /// Device address of this group's staging half, or zero without PCIe groups. + pub(super) fn staging_base(&self, plan: &OriginalVerifyGpuPlan) -> Result { + if plan.pcie.is_empty() { + return Ok(0); + } + let per = staging_blobs_per_group(self.groups); + let max_blob = self.bank.geometry().max_expert_blob; + self.bank.physical.span("staging", self.group * per * max_blob, per * max_blob) + } + + /// The device aliases of the PCIe spans; only the copy kernel (pcie mode 2) needs them. + pub(super) fn kernel_aliases( + &self, + plan: &OriginalVerifyGpuPlan, + pcie: PcieSource<'_, 'ctx>, + cap: usize, + kernel: bool, + ) -> Result> { + if kernel && !plan.pcie.is_empty() { self.pcie_aliases(plan, pcie, cap) } else { Ok(Vec::new()) } + } + + /// The copy kernel (pcie mode 2) reads every PCIe expert's three spans through their device aliases: each must + /// have exactly the length the graphs copy for this layer. + pub(super) fn pcie_aliases( + &self, + plan: &OriginalVerifyGpuPlan, + pcie: PcieSource<'_, 'ctx>, + cap: usize, + ) -> Result> { + let mut aliases: Vec<[u64; 3]> = Vec::new(); + let roles = + self.bank.pcie_roles.as_ref().and_then(|r| r.get(self.layer)).copied().ok_or(Error::InvalidQwenShape)?; + let source = pcie.ok_or(Error::InvalidQwenShape)?; + if 3 * plan.pcie.len() > cap { + return Err(Error::InvalidQwenShape); + } + aliases.try_reserve_exact(source.spans.len()).map_err(|_| Error::HostAllocation)?; + for s in source.spans { + let mut a = [0u64; 3]; + for (r, part) in s.iter().enumerate() { + if part.bytes().len() != roles[r] { + return Err(Error::InvalidQwenShape); + } + a[r] = source.bank.pcie_alias(part)?; + } + aliases.push(a); + } + Ok(aliases) + } + + /// Encodes the plan block; pcie mode 2: `ptr2[3 q + r]` = span r of PCIe group q, which the graph's copy kernel + /// stages while it rebases ptr2[q]. + pub(super) fn build_plan_block( + &self, + plan: &OriginalVerifyGpuPlan, + layout: &PlanLayout, + cap: usize, + (vram, aliases): (&[(u64, &[u16])], &[[u64; 3]]), + (kernel, staging, stride): (bool, u64, usize), + ) -> Result> { + let k = self.bank.geometry().k; + let pcie_ptrs: Vec<(u64, &[u16])> = plan + .pcie + .iter() + .enumerate() + .map(|(q, e)| (if kernel { aliases[q][0] } else { staging + (q * stride) as u64 }, e.as_slice())) + .collect(); + let mut block = encode_plan_block(layout, cap, k, self.rows * k, vram, &pcie_ptrs)?; + for (q, a) in aliases.iter().enumerate() { + for (r, &alias) in a.iter().enumerate() { + let at = (layout.ptr2 + 2 * (3 * q + r)) * 4; + block[at..at + 8].copy_from_slice(&alias.to_le_bytes()); + } + } + Ok(block) + } + + /// Writes the plan block into the group's mapped slot and raises flag A. + pub(super) fn publish_plan_block(&self, layout: &PlanLayout, block: &[u8]) -> Result<()> { + let m = &self.bank.physical.mapped; + let mut slot = m[14].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + slot.as_mut().ok_or(Error::ContextPoisoned)?.write(self.group * layout.mapped_stride() * 4, block)?; + m[11] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .publish_u32(0, self.ring) + } + + /// Raises flag B from the host at once. + fn raise_flag_b(&self) -> Result<()> { + self.bank.physical.mapped[12] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .raise_u32(0, self.ring) + } + + /// Raises flag B: at once for the copy kernel (no host CUDA call inside the window, so the bank stays retained + /// until the window's fence) or without a PCIe source; otherwise after the DMA staging copies on `copy`. + pub(super) fn raise_after_staging( + &mut self, + plan: &OriginalVerifyGpuPlan, + pcie: Option>, + copy: &mut OriginalGpuStream<'ctx>, + (kernel, staging, stride): (bool, u64, usize), + ) -> Result<()> { + let flag_b = self.flag_b_host_address()?; + if kernel { + if !plan.pcie.is_empty() { + self.bank.retain_pcie_source(Rc::clone(pcie.as_ref().ok_or(Error::InvalidQwenShape)?.bank))?; + } + return self.raise_flag_b(); + } + let Some(source) = pcie else { + return self.raise_flag_b(); + }; + if !plan.pcie.is_empty() { + // The bank's registered bytes are read by the copy engine after this call returns: the bank + // stays retained by the verifier until the window's copy-stream fence. + self.bank.retain_pcie_source(Rc::clone(source.bank))?; + } + let (many, batch, write) = dma_options(); + stage_pcie(copy, &source, (staging, stride), (many, batch))?; + self.raise_after_copies(copy, flag_b, write) + } + + /// Queues the flag B write behind the staging copies: a stream write when supported, else a host callback. + fn raise_after_copies(&self, copy: &mut OriginalGpuStream<'ctx>, flag_b: usize, write: bool) -> Result<()> { + if write { + let device_b = self.flag_b_device_address()?; + return copy.enqueue_raise_flag(flag_b, device_b, self.ring); + } + copy.enqueue_raise_u32(flag_b, self.ring) + } + + fn flag_b_host_address(&self) -> Result { + self.bank.physical.mapped[12] + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .host_address(0, 4) + } + + fn flag_b_device_address(&self) -> Result { + self.bank.physical.mapped[12] + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .address(0, 4) + } +} + +/// Enqueues the host-to-device copies of every PCIe expert's spans into its staging slot: one batched call for all +/// pieces (`many`), or one per piece. +fn stage_pcie<'ctx>( + copy: &mut OriginalGpuStream<'ctx>, + source: &OriginalVerifyPcieSource<'_, 'ctx>, + (staging, stride): (u64, usize), + (many, batch): (bool, bool), +) -> Result<()> { + if many { + return stage_pcie_many(copy, source, (staging, stride), batch); + } + for (q, s) in source.spans.iter().enumerate() { + let mut offset = staging + (q * stride) as u64; + for part in s { + let bytes = source.bank.cache_source(part)?; + for (at, n) in source.bank.copy_pieces(bytes) { + copy.enqueue_copy_h2d(offset + at as u64, &bytes[at..at + n])?; + } + offset += bytes.len() as u64; + } + } + Ok(()) +} + +fn stage_pcie_many<'ctx>( + copy: &mut OriginalGpuStream<'ctx>, + source: &OriginalVerifyPcieSource<'_, 'ctx>, + (staging, stride): (u64, usize), + batch: bool, +) -> Result<()> { + let mut pieces: Vec<(u64, &[u8])> = Vec::new(); + for (q, s) in source.spans.iter().enumerate() { + collect_pieces(source, s, staging + (q * stride) as u64, &mut pieces)?; + } + if !pieces.is_empty() { + copy.enqueue_copy_h2d_many(&pieces, batch)?; + } + Ok(()) +} + +fn collect_pieces<'a>( + source: &'a OriginalVerifyPcieSource<'_, '_>, + s: &[ResidentExpertBankSpan; 3], + mut offset: u64, + pieces: &mut Vec<(u64, &'a [u8])>, +) -> Result<()> { + for part in s { + let bytes = source.bank.cache_source(part)?; + for (at, n) in source.bank.copy_pieces(bytes) { + pieces.push((offset + at as u64, &bytes[at..at + n])); + } + offset += bytes.len() as u64; + } + Ok(()) +} diff --git a/crates/cuda-driver/src/ple_batch_queue/assets_fn.rs b/crates/cuda-driver/src/ple_batch_queue/assets_fn.rs index 6a23d864..6ff5f360 100644 --- a/crates/cuda-driver/src/ple_batch_queue/assets_fn.rs +++ b/crates/cuda-driver/src/ple_batch_queue/assets_fn.rs @@ -4,28 +4,24 @@ use super::*; pub(super) fn assets() -> Result<[&'static [u8]; 2]> { - let expected = PTX_SHA256.ok_or(Error::UnsupportedQwenOperation)?; - let bytes = PTX_BYTES.ok_or(Error::UnsupportedQwenOperation)?; - if bytes.checked_add(1) != Some(PTX.len()) - || PTX.last() != Some(&0) - || PTX[..bytes].contains(&0) - || !PTX[..bytes].is_ascii() - || crate::qwen_ffi::sha256(&PTX[..bytes]) != expected - { - return Err(Error::UnsupportedQwenOperation); - } - let expected = PACK_PTX_SHA256.ok_or(Error::UnsupportedQwenOperation)?; - let bytes = PACK_PTX_BYTES.ok_or(Error::UnsupportedQwenOperation)?; - if bytes.checked_add(1) != Some(PACK_PTX.len()) - || PACK_PTX.last() != Some(&0) - || PACK_PTX[..bytes].contains(&0) - || !PACK_PTX[..bytes].is_ascii() - || crate::qwen_ffi::sha256(&PACK_PTX[..bytes]) != expected - { - return Err(Error::UnsupportedQwenOperation); - } + check_ptx(PTX_SHA256, PTX_BYTES, PTX)?; + check_ptx(PACK_PTX_SHA256, PACK_PTX_BYTES, PACK_PTX)?; Ok([PACK_PTX, PTX]) } +/// A sealed PTX is a pinned, NUL-terminated, NUL-free ASCII text of exactly the pinned length and digest. +fn check_ptx(sha: Option<[u8; 32]>, length: Option, ptx: &[u8]) -> Result<()> { + let expected = sha.ok_or(Error::UnsupportedQwenOperation)?; + let bytes = length.ok_or(Error::UnsupportedQwenOperation)?; + if bytes.checked_add(1) != Some(ptx.len()) + || ptx.last() != Some(&0) + || ptx[..bytes].contains(&0) + || !ptx[..bytes].is_ascii() + || crate::qwen_ffi::sha256(&ptx[..bytes]) != expected + { + return Err(Error::UnsupportedQwenOperation); + } + Ok(()) +} impl PleBatchCompletion<'_, '_> { pub fn rows(&self) -> usize { self.rows @@ -47,34 +43,50 @@ impl PleBatchCompletion<'_, '_> { let handles = self.owner.handles()?; let streams = handles[1].checked_subspan(self.owner.sizes[1], index * 40960, 40960)?; let history = handles[11].checked_subspan(self.owner.sizes[11], index * 368640, 368640)?; + let (sv, hv) = self.owner.read_row(streams, history)?; + self.next += 1; + Ok(Some(PleBatchRow { streams: sv.into_boxed_slice(), history: hv.into_boxed_slice() })) + } +} +impl PleBatchQueue<'_> { + /// Downloads one row's streams and history; an uncertain drain leaks the staging buffers. + fn read_row(&mut self, streams: BufferHandle, history: BufferHandle) -> Result<(Vec, Vec)> { let mut sb = staging(40960)?; let mut hb = staging(368640)?; let mut sv = float_owner(10240)?; let mut hv = float_owner(92160)?; - let context = self.owner.context; + let context = self.context; let guard = context.enter()?; - let mut operation = context.driver.api.copy_to(streams, &mut sb); - if operation.is_ok() { - operation = context.driver.api.copy_to(history, &mut hb); - } + let operation = + context.driver.api.copy_to(streams, &mut sb).and_then(|()| context.driver.api.copy_to(history, &mut hb)); let sync = context.driver.api.synchronize(); let pop = guard.finish(); + self.settle_row([operation, sync, pop], (sb, hb, sv, hv)).map(|(sb, hb, mut sv, mut hv)| { + decode(&sb, &mut sv); + decode(&hb, &mut hv); + (sv, hv) + }) + } + /// Marks the queue failed on any error; an uncertain drain leaks the host buffers. + #[allow(clippy::type_complexity)] + fn settle_row( + &mut self, + [operation, sync, pop]: [Result<()>; 3], + bufs: (Vec, Vec, Vec, Vec), + ) -> Result<(Vec, Vec, Vec, Vec)> { if operation.is_err() || sync.is_err() || pop.is_err() { - self.owner.failed = true; - context.poisoned.set(true); + self.failed = true; + self.context.poisoned.set(true); } if sync.is_err() || pop.is_err() { - std::mem::forget((sb, hb, sv, hv)); - context.retain_driver(); + std::mem::forget(bufs); + self.context.retain_driver(); // Those genuine owners were retained, so no later statement may // borrow them even if a compiler cannot infer the failed drain. return combine(combine(operation, sync), pop).and_then(|()| Err(Error::ContextPoisoned)); } combine(combine(operation, sync), pop)?; - decode(&sb, &mut sv); - decode(&hb, &mut hv); - self.next += 1; - Ok(Some(PleBatchRow { streams: sv.into_boxed_slice(), history: hv.into_boxed_slice() })) + Ok(bufs) } } impl Context<'_> { diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/compose_phases.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/compose_phases.rs index cde7da7f..c2b9622d 100644 --- a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/compose_phases.rs +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/compose_phases.rs @@ -48,6 +48,20 @@ impl BatchHost { } impl<'ctx> PleBatchQueue<'ctx> { + /// Checks the inputs and weights, builds the launch list and allocates the host staging. + pub(super) fn stage_batch( + &self, + workspace: &NativeBatchWorkspace<'_>, + weights: &PleClosedWeights<'_, '_>, + h: [BufferHandle; 15], + (embedding, streams, history): (&[f32], &[f32], &[f32]), + ) -> Result<(usize, Vec, BatchHost)> { + let rows = self.check_batch_inputs(workspace, h, (embedding, streams, history))?; + let plan = self.batch_plan(workspace, weights, h, rows)?; + let commands = self.batch_commands(&plan)?; + Ok((rows, commands, BatchHost::new(embedding, streams, history, rows)?)) + } + /// Rejects spans aliasing the workspace and sources of the wrong shape or with non-finite values; returns the rows. pub(super) fn check_batch_inputs( &self, @@ -144,6 +158,61 @@ impl<'ctx> PleBatchQueue<'ctx> { api.synchronize() } + pub(super) fn batch_modules(&self) -> Result<(&KernelModule, &KernelModule)> { + let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; + let pack = self.pack_module.as_ref().ok_or(Error::ContextPoisoned)?; + Ok((module, pack)) + } + + /// Reads the status words back once the stream drained cleanly. + pub(super) fn read_batch_statuses( + &self, + operation: Result<()>, + sync: &Result<()>, + status: BufferHandle, + host: &mut BatchHost, + ) -> Result<()> { + if operation.is_ok() && sync.is_ok() { + return self.context.driver.api.copy_to(status, &mut host.statuses); + } + operation + } + + /// Marks the queue failed on any error; an uncertain drain leaks every host buffer the device may still read. + pub(super) fn settle_batch( + &mut self, + workspace: &mut NativeBatchWorkspace<'_>, + [operation, sync, all, pop]: [Result<()>; 4], + (commands, host, weights): (Vec, BatchHost, PleClosedWeights<'_, '_>), + ) -> Result { + if operation.is_err() || sync.is_err() || all.is_err() || pop.is_err() { + self.failed = true; + workspace.mark_failed(); + } + if sync.is_err() || all.is_err() || pop.is_err() { + std::mem::forget((commands, host, weights)); + self.context.retain_driver(); + return combine(combine(combine(operation, sync), all), pop) + .map(|()| unreachable!("uncertain PLE batch drain")); + } + combine(combine(combine(operation, sync), all), pop)?; + Ok(host) + } + + /// Decodes the status words into the completion; a status above 1 fails the queue. + pub(super) fn finish_batch<'loan>( + &'loan mut self, + rows: usize, + mut host: BatchHost, + ) -> Result> { + if !host.decode_flags() { + self.failed = true; + self.context.poisoned.set(true); + return Err(Error::InvalidDriverValue("PLE batch finite status")); + } + Ok(PleBatchCompletion { owner: self, rows, next: 0, flags: host.flags.into_boxed_slice() }) + } + /// Launches every command in order; the first failure stops the rest. pub(super) fn launch_batch( &self, diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2.rs index e84f1ba4..3877e706 100644 --- a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2.rs +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2.rs @@ -15,62 +15,44 @@ impl<'ctx> PleBatchQueue<'ctx> { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidQwenShape); } - let mut sizes = SIZES; - for (i, size) in sizes.iter_mut().enumerate() { - if i != 2 { - *size = (*size / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; - } - } + let sizes = batch_sizes(capacity)?; let ptx = assets()?; // explicit pending refusal before any allocation/module. if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } - let required = sizes - .iter() - .try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))? - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; - if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - capacity, - sizes, - context, - buffers: std::array::from_fn(|_| None), - pack_module: None, - module: None, - mode, - failed: false, - }; - let operation = (|| { - for (i, bytes) in sizes.into_iter().enumerate() { - owner.buffers[i] = Some(context.allocate(bytes)?); - } - let guard = context.enter()?; - let load = (|| { - owner.pack_module = Some(KernelModule::load(ptx[0], &PACK_ENTRIES)?); - owner.module = Some(KernelModule::load(ptx[1], &ENTRIES)?); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poisoned.set(true); - } - combine(load, pop)?; - owner.handles()?; - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(error) = operation { + check_required(context, &sizes)?; + let buffers = std::array::from_fn(|_| None); + let mut owner = + Self { capacity, sizes, context, buffers, pack_module: None, module: None, mode, failed: false }; + if let Err(error) = owner.init_resources(ptx) { return combine(Err(error), owner.close()); } Ok(owner) } + /// Allocates every buffer, loads both kernel modules under the context guard and re-checks the free memory. + fn init_resources(&mut self, ptx: [&'static [u8]; 2]) -> Result<()> { + let context = self.context; + for (i, bytes) in self.sizes.into_iter().enumerate() { + self.buffers[i] = Some(context.allocate(bytes)?); + } + let guard = context.enter()?; + let load = self.load_modules(ptx); + let pop = guard.finish(); + if pop.is_err() { + context.poisoned.set(true); + } + combine(load, pop)?; + self.handles()?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + fn load_modules(&mut self, ptx: [&'static [u8]; 2]) -> Result<()> { + self.pack_module = Some(KernelModule::load(ptx[0], &PACK_ENTRIES)?); + self.module = Some(KernelModule::load(ptx[1], &ENTRIES)?); + Ok(()) + } pub fn prompt_device_bytes(capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidQwenShape); @@ -102,27 +84,31 @@ impl<'ctx> PleBatchQueue<'ctx> { let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?; let mut handles = [first; 15]; for (i, bytes) in self.sizes.into_iter().enumerate() { - let b = self.buffer(i)?; - if !std::ptr::eq(b.context, self.context) { - return Err(Error::ContextMismatch); - } - if b.bytes != bytes { - return Err(Error::InvalidQwenShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(bytes, 4)?; - for (j, other) in handles.iter().take(i).enumerate() { - if h.overlaps(bytes, *other, self.sizes[j]) { - return Err(Error::OutputAliasesInput); - } - } - handles[i] = h; + handles[i] = self.checked_buffer(i, bytes, &handles)?; } if self.context.allocated_bytes() > self.context.budget { return Err(Error::BudgetExceeded); } Ok(handles) } + /// Buffer `i` must belong to this context, have exactly `bytes` and overlap no earlier buffer. + fn checked_buffer(&self, i: usize, bytes: usize, handles: &[BufferHandle; 15]) -> Result { + let b = self.buffer(i)?; + if !std::ptr::eq(b.context, self.context) { + return Err(Error::ContextMismatch); + } + if b.bytes != bytes { + return Err(Error::InvalidQwenShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, 4)?; + for (j, other) in handles.iter().take(i).enumerate() { + if h.overlaps(bytes, *other, self.sizes[j]) { + return Err(Error::OutputAliasesInput); + } + } + Ok(h) + } pub(in super::super) fn weight(&self, w: &DeviceBuffer<'_>, bytes: usize, alignment: u64) -> Result { if !std::ptr::eq(w.context, self.context) { return Err(Error::ContextMismatch); @@ -140,3 +126,29 @@ impl<'ctx> PleBatchQueue<'ctx> { Ok(h) } } + +/// Buffer sizes for a queue of `capacity` rows (the history is fixed). +fn batch_sizes(capacity: usize) -> Result<[usize; 15]> { + let mut sizes = SIZES; + for (i, size) in sizes.iter_mut().enumerate() { + if i != 2 { + *size = (*size / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; + } + } + Ok(sizes) +} + +/// The buffers plus the reserve must fit the context budget and the free device memory. +fn check_required(context: &Context<'_>, sizes: &[usize; 15]) -> Result<()> { + let required = sizes + .iter() + .try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))? + .checked_add(RESERVE) + .ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + Ok(()) +} diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs index 14856a89..2b8d11cd 100644 --- a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs @@ -18,41 +18,18 @@ impl<'ctx> PleBatchQueue<'ctx> { ) -> Result> { workspace.validate_context(self.context)?; let h = self.handles()?; - let rows = self.check_batch_inputs(workspace, h, (embedding, streams, history))?; - let plan = self.batch_plan(workspace, &weights, h, rows)?; - let mut commands = self.batch_commands(&plan)?; - let mut host = BatchHost::new(embedding, streams, history, rows)?; + let (rows, mut commands, mut host) = self.stage_batch(workspace, &weights, h, (embedding, streams, history))?; let context = self.context; let guard = context.enter()?; - let mut operation = self.upload_batch(&h, &host); + let operation = self.upload_batch(&h, &host); let blas = workspace.blas()?; - let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; - let pack = self.pack_module.as_ref().ok_or(Error::ContextPoisoned)?; - if operation.is_ok() { - operation = self.launch_batch((blas, pack, module), &mut commands); - } + let (module, pack) = self.batch_modules()?; + let operation = operation.and_then(|()| self.launch_batch((blas, pack, module), &mut commands)); let sync = blas.synchronize(); - if operation.is_ok() && sync.is_ok() { - operation = context.driver.api.copy_to(h[14], &mut host.statuses); - } + let operation = self.read_batch_statuses(operation, &sync, h[14], &mut host); let all = context.driver.api.synchronize(); let pop = guard.finish(); - if operation.is_err() || sync.is_err() || all.is_err() || pop.is_err() { - self.failed = true; - workspace.mark_failed(); - } - if sync.is_err() || all.is_err() || pop.is_err() { - std::mem::forget((commands, host, weights)); - context.retain_driver(); - return combine(combine(combine(operation, sync), all), pop) - .map(|()| unreachable!("uncertain PLE batch drain")); - } - combine(combine(combine(operation, sync), all), pop)?; - if !host.decode_flags() { - self.failed = true; - context.poisoned.set(true); - return Err(Error::InvalidDriverValue("PLE batch finite status")); - } - Ok(PleBatchCompletion { owner: self, rows, next: 0, flags: host.flags.into_boxed_slice() }) + let host = self.settle_batch(workspace, [operation, sync, all, pop], (commands, host, weights))?; + self.finish_batch(rows, host) } } diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_3.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_3.rs index 4c526641..ce2cffe0 100644 --- a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_3.rs +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_3.rs @@ -2,6 +2,7 @@ #[allow(unused_imports)] use super::*; +use crate::CurrentGuard; impl<'ctx> PleBatchQueue<'ctx> { pub fn close(mut self) -> Result<()> { @@ -12,49 +13,16 @@ impl<'ctx> PleBatchQueue<'ctx> { let mut result = Ok(()); // No queued commands survive a successful compose. A poisoned owner // retains vendor/kernel/whole banks and the Driver instead of freeing. - let guard = if self.context.is_poisoned() { - None - } else { - match self.context.enter() { - Ok(g) => Some(g), - Err(e) => { - self.context.poisoned.set(true); - result = Err(e); - None - } - } - }; + let guard = self.close_guard(&mut result); for module in [self.pack_module.take(), self.module.take()].into_iter().flatten() { - let close = if self.context.is_poisoned() { - std::mem::forget(module); - Err(Error::ContextPoisoned) - } else { - module.close() - }; - if close.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, close); + result = combine(result, close_or_leak(self.context, module, |m| m.close())); } if let Some(g) = guard { - let pop = g.finish(); - if pop.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, pop); + result = combine(result, poison_on_error(self.context, g.finish())); } for slot in &mut self.buffers { if let Some(b) = slot.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - if close.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, close); + result = combine(result, close_or_leak(self.context, b, |b| b.release())); } } if self.context.is_poisoned() { @@ -62,4 +30,34 @@ impl<'ctx> PleBatchQueue<'ctx> { } result } + /// Enters the context for the module closes, unless it is already poisoned; an enter failure poisons it. + fn close_guard(&self, result: &mut Result<()>) -> Option> { + if self.context.is_poisoned() { + return None; + } + match self.context.enter() { + Ok(g) => Some(g), + Err(e) => { + self.context.poisoned.set(true); + *result = Err(e); + None + } + } + } +} + +/// Closes an owner, or leaks it when the context is poisoned; a failed close poisons the context. +fn close_or_leak(context: &Context<'_>, owner: T, close: impl FnOnce(T) -> Result<()>) -> Result<()> { + if context.is_poisoned() { + std::mem::forget(owner); + return Err(Error::ContextPoisoned); + } + poison_on_error(context, close(owner)) +} + +fn poison_on_error(context: &Context<'_>, r: Result<()>) -> Result<()> { + if r.is_err() { + context.poisoned.set(true); + } + r } diff --git a/crates/cuda-driver/src/ple_closed_queue/compose_phases.rs b/crates/cuda-driver/src/ple_closed_queue/compose_phases.rs index 5cce9455..0dcc4587 100644 --- a/crates/cuda-driver/src/ple_closed_queue/compose_phases.rs +++ b/crates/cuda-driver/src/ple_closed_queue/compose_phases.rs @@ -187,4 +187,72 @@ impl<'ctx> PleClosedQueue<'ctx> { context.driver.api.copy_to(handles[12], &mut host.streams_out)?; context.driver.api.copy_to(handles[11], &mut host.history_out) } + + /// Marks the queue failed on any error; an uncertain drain leaks every host buffer the device may still read. + pub(super) fn settle_compose( + &mut self, + [operation, sync, pop]: [Result<()>; 3], + (commands, reset, host, weights): ( + Vec, + ffi::MmqResidentArguments, + ComposeHost, + PleClosedWeights<'_, '_>, + ), + ) -> Result { + if operation.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + self.context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + std::mem::forget((commands, reset, host, weights)); + self.context.retain_driver(); + return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain PLE drain")); + } + combine(combine(operation, sync), pop)?; + Ok(host) + } + + /// Decodes the drained results into the completion; a status above 1 fails the queue. + pub(super) fn finish_compose<'loan>( + &'loan mut self, + mut host: ComposeHost, + ) -> Result> { + let Some(flags) = host.decode_flags() else { + self.failed = true; + self.context.poisoned.set(true); + return Err(Error::InvalidDriverValue("PLE finite status")); + }; + // Staging is no longer exposed or used once the actual completion drains. + host.embedding_bytes.clear(); + host.streams_bytes.clear(); + host.history_bytes.clear(); + Ok(PleClosedCompletion { + owner: self, + flags, + streams: host.streams_values.into_boxed_slice(), + history: host.history_values.into_boxed_slice(), + }) + } + + /// Unloads the kernel module under the context guard, or leaks it on a poisoned context. + pub(super) fn unload_module(&self, module: ffi::ModuleHandle) -> Result<()> { + let release = if self.context.is_poisoned() { + self.context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(guard) => { + let unload = self.context.driver.api.unload(module); + let pop = guard.finish(); + combine(unload, pop) + } + Err(error) => Err(error), + } + }; + if release.is_err() { + self.context.poisoned.set(true); + self.context.retain_driver(); + } + release + } } diff --git a/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedcompletion.rs b/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedcompletion.rs index 652dc53f..33a020c7 100644 --- a/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedcompletion.rs +++ b/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedcompletion.rs @@ -16,6 +16,16 @@ impl PleClosedCompletion<'_, '_> { Ok((self.streams, self.history)) } } +/// The queue's charge plus the reserve must fit the context budget and the free device memory. +fn check_charge(context: &Context<'_>) -> Result<()> { + let required = CHARGE.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + Ok(()) +} impl Context<'_> { pub fn ple_closed_queue(&self) -> Result> { PleClosedQueue::new(self) @@ -29,56 +39,49 @@ impl<'ctx> PleClosedQueue<'ctx> { for operation in OPS { qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?.validate(operation)?; } - let required = CHARGE.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - context, - buffers: std::array::from_fn(|_| None), - module: None, - functions: None, - finite: None, - failed: false, - }; - let operation = (|| { - for (i, bytes) in SIZES.into_iter().enumerate() { - owner.buffers[i] = Some(context.allocate(bytes)?); - } - let guard = context.enter()?; - let load = (|| { - let mut functions = [None; 6]; - for (i, operation) in OPS.into_iter().enumerate() { - let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; - functions[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); - } - owner.functions = Some(functions.map(|f| f.expect("six admitted original PLE operators"))); - let module = context.driver.api.load_mmq_resident()?; - owner.module = Some(module); - owner.finite = Some([ - context.driver.api.mmq_resident_function(module, 0)?, - context.driver.api.mmq_resident_function(module, 1)?, - ]); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poisoned.set(true); - } - combine(load, pop)?; - owner.handles()?; - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(error) = operation { + check_charge(context)?; + let buffers = std::array::from_fn(|_| None); + let mut owner = Self { context, buffers, module: None, functions: None, finite: None, failed: false }; + if let Err(error) = owner.init_resources() { return combine(Err(error), owner.close()); } Ok(owner) } + /// Allocates every buffer, registers the operators and loads the finite kernels under the context guard. + fn init_resources(&mut self) -> Result<()> { + let context = self.context; + for (i, bytes) in SIZES.into_iter().enumerate() { + self.buffers[i] = Some(context.allocate(bytes)?); + } + let guard = context.enter()?; + let load = self.load_kernels(); + let pop = guard.finish(); + if pop.is_err() { + context.poisoned.set(true); + } + combine(load, pop)?; + self.handles()?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + fn load_kernels(&mut self) -> Result<()> { + let context = self.context; + let mut functions = [None; 6]; + for (i, operation) in OPS.into_iter().enumerate() { + let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; + functions[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); + } + self.functions = Some(functions.map(|f| f.expect("six admitted original PLE operators"))); + let module = context.driver.api.load_mmq_resident()?; + self.module = Some(module); + self.finite = Some([ + context.driver.api.mmq_resident_function(module, 0)?, + context.driver.api.mmq_resident_function(module, 1)?, + ]); + Ok(()) + } pub fn validate_context(&self, context: &Context<'_>) -> Result<()> { if !std::ptr::eq(self.context, context) { return Err(Error::ContextMismatch); @@ -101,27 +104,31 @@ impl<'ctx> PleClosedQueue<'ctx> { let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?; let mut handles = [first; 14]; for (i, bytes) in SIZES.into_iter().enumerate() { - let buffer = self.buffer(i)?; - if !std::ptr::eq(buffer.context, self.context) { - return Err(Error::ContextMismatch); - } - if buffer.bytes != bytes { - return Err(Error::InvalidQwenShape); - } - let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_projection_extent(bytes, 4)?; - for (j, other) in handles.iter().take(i).enumerate() { - if handle.overlaps(bytes, *other, SIZES[j]) { - return Err(Error::OutputAliasesInput); - } - } - handles[i] = handle; + handles[i] = self.checked_buffer(i, bytes, &handles)?; } if self.context.allocated_bytes() > self.context.budget { return Err(Error::BudgetExceeded); } Ok(handles) } + /// Buffer `i` must belong to this context, have exactly `bytes` and overlap no earlier buffer. + fn checked_buffer(&self, i: usize, bytes: usize, handles: &[ffi::BufferHandle; 14]) -> Result { + let buffer = self.buffer(i)?; + if !std::ptr::eq(buffer.context, self.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != bytes { + return Err(Error::InvalidQwenShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(bytes, 4)?; + for (j, other) in handles.iter().take(i).enumerate() { + if handle.overlaps(bytes, *other, SIZES[j]) { + return Err(Error::OutputAliasesInput); + } + } + Ok(handle) + } pub(super) fn weight(&self, weight: &DeviceBuffer<'_>, bytes: usize, alignment: u64) -> Result<()> { if !std::ptr::eq(weight.context, self.context) { return Err(Error::ContextMismatch); diff --git a/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs b/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs index c6ef160e..ee6efa72 100644 --- a/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs +++ b/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs @@ -24,31 +24,8 @@ impl<'ctx> PleClosedQueue<'ctx> { let operation = self.drain_ops(&handles, &mut commands, &mut reset, &mut host); let sync = context.driver.api.synchronize(); let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - std::mem::forget((commands, reset, host, weights)); - context.retain_driver(); - return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain PLE drain")); - } - combine(combine(operation, sync), pop)?; - let Some(flags) = host.decode_flags() else { - self.failed = true; - context.poisoned.set(true); - return Err(Error::InvalidDriverValue("PLE finite status")); - }; - // Staging is no longer exposed or used once the actual completion drains. - host.embedding_bytes.clear(); - host.streams_bytes.clear(); - host.history_bytes.clear(); - Ok(PleClosedCompletion { - owner: self, - flags, - streams: host.streams_values.into_boxed_slice(), - history: host.history_values.into_boxed_slice(), - }) + let host = self.settle_compose([operation, sync, pop], (commands, reset, host, weights))?; + self.finish_compose(host) } pub fn close(mut self) -> Result<()> { self.close_inner() @@ -60,37 +37,11 @@ impl<'ctx> PleClosedQueue<'ctx> { let mut result = Ok(()); for slot in &mut self.buffers { if let Some(buffer) = slot.take() { - let release = if self.context.is_poisoned() { - std::mem::forget(buffer); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if release.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, release); + result = combine(result, release_buffer(self.context, buffer)); } } if let Some(module) = self.module.take() { - let release = if self.context.is_poisoned() { - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(guard) => { - let unload = self.context.driver.api.unload(module); - let pop = guard.finish(); - combine(unload, pop) - } - Err(error) => Err(error), - } - }; - if release.is_err() { - self.context.poisoned.set(true); - self.context.retain_driver(); - } - result = combine(result, release); + result = combine(result, self.unload_module(module)); } result } @@ -113,3 +64,17 @@ pub(super) fn float_staging(values: &[f32]) -> Result> { } Ok(bytes) } + +/// A buffer is released, or leaked on a poisoned context; a failed release poisons the context. +fn release_buffer<'ctx>(context: &Context<'ctx>, buffer: DeviceBuffer<'ctx>) -> Result<()> { + let release = if context.is_poisoned() { + std::mem::forget(buffer); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if release.is_err() { + context.poisoned.set(true); + } + release +} diff --git a/crates/cuda-driver/src/qsa_prompt_device.rs b/crates/cuda-driver/src/qsa_prompt_device.rs index a3a1881b..d77844c3 100644 --- a/crates/cuda-driver/src/qsa_prompt_device.rs +++ b/crates/cuda-driver/src/qsa_prompt_device.rs @@ -53,9 +53,13 @@ use impl_context::common; use impl_context::native_block; #[allow(unused_imports)] use impl_context::native_entry; +#[path = "qsa_prompt_device/device_phases.rs"] +mod device_phases; #[path = "qsa_prompt_device/impl_originalqsapromptdevice.rs"] mod impl_originalqsapromptdevice; #[path = "qsa_prompt_device/impl_originalqsapromptdevice_2.rs"] mod impl_originalqsapromptdevice_2; #[path = "qsa_prompt_device/impl_originalqsapromptdevice_3.rs"] mod impl_originalqsapromptdevice_3; +#[path = "qsa_prompt_device/project_phases.rs"] +mod project_phases; diff --git a/crates/cuda-driver/src/qsa_prompt_device/device_phases.rs b/crates/cuda-driver/src/qsa_prompt_device/device_phases.rs new file mode 100644 index 00000000..a57b4f46 --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_device/device_phases.rs @@ -0,0 +1,358 @@ +//! STRA-338 size: the phases of `OriginalQsaPromptDevice::{new, admit, prepare, close_inner}` and `complete`. + +#[allow(unused_imports)] +use super::*; + +type Spans = Vec<(ffi::BufferHandle, usize)>; + +/// The gate PTX must be its pinned, NUL-terminated self; the index assets must be sealed. +pub(super) fn check_assets() -> Result<()> { + if GATE_PTX.len() < 2 + || GATE_PTX.last() != Some(&0) + || GATE_PTX[..GATE_PTX.len() - 1].contains(&0) + || crate::qwen_ffi::sha256(&GATE_PTX[..GATE_PTX.len() - 1]) != GATE_SHA + { + return Err(Error::UnsupportedQwenOperation); + } + if [INDEX, SELECT, POSTOPS, DECODE_POSTOPS].iter().any(|x| x.starts_with(b"// UNSEALED")) { + return Err(Error::UnsupportedQwenOperation); + } + Ok(()) +} + +/// The device buffers and the one-element index workspace sizes for `capacity` rows. +pub(super) fn index_for<'ctx>( + context: &'ctx Context<'ctx>, + capacity: usize, +) -> ([usize; 11], QsaPromptIndexWorkspace<'ctx>) { + let mut sizes = sizes(); + for i in [4, 5, 6, 7, 8] { + sizes[i] = 4 + } + sizes[9] = capacity.min(256) * max_blocks() * 4; + let index = QsaPromptIndexWorkspace { + capacity, + sizes, + context, + buffers: std::array::from_fn(|_| None), + module: None, + late: None, + failed: false, + }; + (sizes, index) +} + +fn load_dequant() -> Result { + if crate::prefill_stage::fast_dequant() { + return KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES); + } + KernelModule::load( + concat!(include_str!("../offline_native_dequant_f16.ptx"), "\0").as_bytes(), + &[ + c"leleka_native_dequant_f16_q4_k", + c"leleka_native_dequant_f16_q5_k", + c"leleka_native_dequant_f16_q6_k", + c"leleka_native_dequant_f16_iq4_xs", + ], + ) +} + +/// A kernel module closes under the context guard, or leaks when the context is unusable; a failure poisons. +fn close_module(context: &Context<'_>, m: KernelModule) -> Result<()> { + let r = if context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + std::mem::forget(m); + Err(e) + } + } + }; + poison_on_error(context, r) +} + +fn close_scratch<'ctx>(context: &Context<'ctx>, b: DeviceBuffer<'ctx>) -> Result<()> { + let r = if context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + }; + poison_on_error(context, r) +} + +fn poison_on_error(context: &Context<'_>, r: Result<()>) -> Result<()> { + if r.is_err() { + context.poison(); + context.retain_driver() + } + r +} + +impl<'ctx> OriginalQsaPromptDevice<'ctx> { + /// Allocates the index buffers, scratch and steps, then loads every kernel module under the context guard. + pub(super) fn init_resources(&mut self, sizes: [usize; 11]) -> Result<()> { + let context = self.context; + self.allocate_buffers(sizes)?; + let guard = context.enter().map_err(|e| { + context.poison(); + context.retain_driver(); + e + })?; + let load = self.load_kernels(); + let pop = guard.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver() + } + combine(load, pop)?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + + fn allocate_buffers(&mut self, sizes: [usize; 11]) -> Result<()> { + for (i, n) in sizes.into_iter().enumerate() { + self.index.as_mut().ok_or(Error::ContextPoisoned)?.buffers[i] = Some(self.context.allocate(n)?) + } + self.scratch = Some(self.context.allocate(SCRATCH)?); + self.steps = Some(self.context.allocate(self.capacity * 16)?); + Ok(()) + } + + fn load_kernels(&mut self) -> Result<()> { + self.index.as_mut().ok_or(Error::ContextPoisoned)?.module = + Some(Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS)?); + self.dequant = Some(load_dequant()?); + self.pack = Some(KernelModule::load( + concat!(include_str!("../qsa_native_batch.ptx"), "\0").as_bytes(), + &[c"qsa_pack", c"qsa_gate_pack", c"qsa_scan_half"], + )?); + self.gate = Some(KernelModule::load(GATE_PTX, &[c"qsa_prompt_device_gate"])?); + Ok(()) + } + + pub(super) fn close_resources(&mut self) -> Result<()> { + let context = self.context; + self.failed = true; + let mut result = Ok(()); + for m in [self.dequant.take(), self.pack.take(), self.gate.take()].into_iter().flatten() { + result = combine(result, close_module(context, m)); + } + for b in [self.scratch.take(), self.steps.take()].into_iter().flatten() { + result = combine(result, close_scratch(context, b)); + } + if let Some(i) = self.index.take() { + let r = if context.is_poisoned() { + std::mem::forget(i); + Err(Error::ContextPoisoned) + } else { + i.close() + }; + result = combine(result, r) + } + result + } + + /// The device and read must be live, from this context and within the row capacity. + pub(super) fn check_admit_state( + &self, + read: &OriginalDeviceGrRead<'_, '_, '_>, + ws: &NativeBatchWorkspace<'_>, + ) -> Result<()> { + if self.is_failed() || read.lease().is_failed() { + return Err(Error::ContextPoisoned); + } + if !read.context_matches(self.context) { + return Err(Error::ContextMismatch); + } + if !(1..=self.capacity).contains(&read.rows()) { + return Err(Error::InvalidQwenShape); + } + ws.validate_context(self.context) + } + + /// The projection and norm weight handles with their byte sizes, each rejected when aliasing the workspace. + pub(super) fn weight_handles( + &self, + w: &OriginalQsaPromptWeights<'_, 'ctx>, + ws: &NativeBatchWorkspace<'_>, + ) -> Result<([ffi::BufferHandle; 6], [usize; 6], [ffi::BufferHandle; 4])> { + let sizes = [ + 512 * (2560 / 256) * native_block(w.kinds[0]), + 512 * (2560 / 256) * native_block(w.kinds[1]), + 12288 * (2560 / 256) * native_block(w.kinds[2]), + 128 * 2560 * 2, + 512 * 2560 * 2, + 2560 * (6144 / 256) * native_block(w.kinds[3]), + ]; + let mut matrices = [self.own(w.projections[0], sizes[0], 2)?; 6]; + for (i, b) in w.projections.iter().enumerate() { + matrices[i] = self.own(b, sizes[i], 2)?; + ws.reject_alias(matrices[i], sizes[i])?; + } + let mut norms = [matrices[0]; 4]; + for (i, b) in w.norms.iter().enumerate() { + let n = if i < 2 { 1024 } else { 512 }; + norms[i] = self.own(b, n, 4)?; + ws.reject_alias(norms[i], n)?; + } + Ok((matrices, sizes, norms)) + } + + /// Every device-resident span of the pipeline: workspace buffers, the read's block roles and the arena spans. + pub(super) fn resident_spans(&self, read: &OriginalDeviceGrRead<'_, '_, '_>) -> Result { + let mut all = Vec::new(); + all.try_reserve_exact(32).map_err(|_| Error::HostAllocation)?; + let index = self.index.as_ref().ok_or(Error::ContextPoisoned)?; + for b in index.buffers.iter().flatten().chain(self.scratch.iter()).chain(self.steps.iter()) { + all.push((self.own(b, b.len(), 4)?, b.len())); + } + for (role, width) in [(S::MixedHalf, 5120), (S::MixedHigh, 5120), (S::Block, 10240)] { + all.push((common(read, role, width)?, read.rows() * width)); + } + if self.packing == QsaNativePacking::HighAndLow { + all.push((common(read, S::MixedLow, 5120)?, read.rows() * 5120)); + } + push_arena_spans(read, &mut all)?; + Ok(all) + } + + /// No span may overlap an earlier span, a projection weight or a norm weight. + pub(super) fn check_spans_disjoint( + all: &Spans, + ws: &NativeBatchWorkspace<'_>, + weights: (&[ffi::BufferHandle; 6], &[usize; 6], &[ffi::BufferHandle; 4]), + ) -> Result<()> { + let (matrices, sizes, norms) = weights; + for (i, (h, n)) in all.iter().enumerate() { + h.validate_projection_extent(*n, 2)?; + ws.reject_alias(*h, *n)?; + if all[..i].iter().any(|(a, b)| h.overlaps(*n, *a, *b)) { + return Err(Error::OutputAliasesInput); + } + let hits_matrix = matrices.iter().enumerate().any(|(j, wh)| h.overlaps(*n, *wh, sizes[j])); + let hits_norm = norms.iter().enumerate().any(|(j, wh)| h.overlaps(*n, *wh, if j < 2 { 1024 } else { 512 })); + if hits_matrix || hits_norm { + return Err(Error::OutputAliasesInput); + } + } + Ok(()) + } + + /// The prior image must have the lengths of a prompt starting at `p` and be finite. + pub(super) fn check_prior(t: usize, p: usize, prior: [&[f32]; 3]) -> Result<()> { + let [pooled, tail, dead] = prior; + if p.checked_add(t).is_none_or(|end| end > crate::serving_context::geometry().cells()) + || pooled.len() != p / 4 * 128 + || tail.len() != 384 + || dead.len() != 128 + { + return Err(Error::InvalidQwenShape); + } + if pooled.iter().chain(tail).chain(dead).any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput("QSA prior")); + } + Ok(()) + } + + /// Projects K, V, Qfull, the raw index rows and the index query into the arena. + pub(super) fn project_prior( + &mut self, + read: &OriginalDeviceGrRead<'_, '_, '_>, + ws: &mut NativeBatchWorkspace<'ctx>, + kinds: &[QsaNativeKind; 4], + w: [ffi::BufferHandle; 6], + ) -> Result<()> { + let half = common(read, S::MixedHalf, 5120)?; + let high = common(read, S::MixedHigh, 5120)?; + for (i, name, n) in [(0, "Kc", 512), (1, "Vc", 512), (2, "Qf", 12288), (3, "idx_raw", 128), (4, "q_idx", 512)] { + let kind = if i < 3 { Some(kinds[i]) } else { None }; + let out = arena_span(read, name, n * 4)?; + self.project(read, ws, w[i], kind, n, 2560, if i < 3 { half } else { high }, out)?; + } + Ok(()) + } + + fn steps_span(&self, t: usize) -> Result { + self.own(self.steps.as_ref().ok_or(Error::ContextPoisoned)?, self.capacity * 16, 4)?.checked_subspan( + self.capacity * 16, + 0, + t * 16, + ) + } + + /// The five output spans of the index program (K, V, Qfull, selected ids, steps) and its raw, Qfull and + /// index-query inputs. + pub(super) fn index_spans( + &self, + read: &OriginalDeviceGrRead<'_, '_, '_>, + t: usize, + ) -> Result<([ffi::BufferHandle; 5], [ffi::BufferHandle; 3])> { + let steps = self.steps_span(t)?; + let out = [ + arena_span(read, "Kc", 2048)?, + arena_span(read, "Vc", 2048)?, + arena_span(read, "q", 24576)?, + arena_span(read, "sel_ids", CAP * 4)?, + steps, + ]; + let inputs = + [arena_span(read, "idx_raw", 512)?, arena_span(read, "Qf", 49152)?, arena_span(read, "q_idx", 2048)?]; + Ok((out, inputs)) + } +} + +fn push_arena_spans(read: &OriginalDeviceGrRead<'_, '_, '_>, all: &mut Spans) -> Result<()> { + for (name, width) in [ + ("Kc", 2048), + ("Vc", 2048), + ("Qf", 49152), + ("q", 24576), + ("idx_raw", 512), + ("q_idx", 2048), + ("attn", 24576), + ("attn_h", 12288), + ("sel_ids", CAP * 4), + ] { + all.push((arena_span(read, name, width)?, read.rows() * width)); + } + Ok(()) +} + +impl<'lease, 'arena, 'loan, 'ctx> OriginalQsaDeviceSelection<'lease, 'arena, 'loan, 'ctx> { + /// The Out weight must not overlap a workspace buffer, the attention, gate or Qf spans or the block span. + pub(super) fn check_out_weight_clear(&self, weight: ffi::BufferHandle, bytes: usize) -> Result<()> { + let t = self.rows(); + let index = self.owner.index.as_ref().ok_or(Error::ContextPoisoned)?; + for b in index.buffers.iter().flatten().chain(self.owner.scratch.iter()).chain(self.owner.steps.iter()) { + if weight.overlaps(bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { + return Err(Error::OutputAliasesInput); + } + } + for (name, width) in [("attn", 24576), ("attn_h", 12288), ("Qf", 49152)] { + if weight.overlaps(bytes, arena_span(&self.read, name, width)?, t * width) { + return Err(Error::OutputAliasesInput); + } + } + if weight.overlaps(bytes, common(&self.read, S::Block, 10240)?, t * 10240) { + return Err(Error::OutputAliasesInput); + } + Ok(()) + } + + /// Native FP16 Out projection of the gated attention rows into the block span. + pub(super) fn project_out( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + weight: ffi::BufferHandle, + (kind, half): (QsaNativeKind, ffi::BufferHandle), + ) -> Result<()> { + let block = common(&self.read, S::Block, 10240)?; + self.owner.project(&self.read, ws, weight, Some(kind), 2560, 6144, half, block) + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice.rs b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice.rs index e81031ff..e1e5bc68 100644 --- a/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice.rs +++ b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalQsaPromptDevice. #[allow(unused_imports)] +use super::device_phases::{check_assets, index_for}; use super::*; impl<'ctx> OriginalQsaPromptDevice<'ctx> { @@ -23,16 +24,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { } pub(super) fn new(context: &'ctx Context<'ctx>, capacity: usize, packing: QsaNativePacking) -> Result { let required = Self::device_bytes(capacity)?.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if GATE_PTX.len() < 2 - || GATE_PTX.last() != Some(&0) - || GATE_PTX[..GATE_PTX.len() - 1].contains(&0) - || crate::qwen_ffi::sha256(&GATE_PTX[..GATE_PTX.len() - 1]) != GATE_SHA - { - return Err(Error::UnsupportedQwenOperation); - } - if [INDEX, SELECT, POSTOPS, DECODE_POSTOPS].iter().any(|x| x.starts_with(b"// UNSEALED")) { - return Err(Error::UnsupportedQwenOperation); - } + check_assets()?; if context.is_poisoned() { return Err(Error::ContextPoisoned); } @@ -41,78 +33,12 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { { return Err(Error::BudgetExceeded); } - let mut sizes = sizes(); - for i in [4, 5, 6, 7, 8] { - sizes[i] = 4 - } - sizes[9] = capacity.min(256) * max_blocks() * 4; - let index = QsaPromptIndexWorkspace { - capacity, - sizes, - context, - buffers: std::array::from_fn(|_| None), - module: None, - late: None, - failed: false, - }; - let mut owner = Self { - context, - capacity, - packing, - index: Some(index), - scratch: None, - steps: None, - dequant: None, - pack: None, - gate: None, - failed: false, - }; - let operation = (|| -> Result<()> { - for (i, n) in sizes.into_iter().enumerate() { - owner.index.as_mut().ok_or(Error::ContextPoisoned)?.buffers[i] = Some(context.allocate(n)?) - } - owner.scratch = Some(context.allocate(SCRATCH)?); - owner.steps = Some(context.allocate(capacity * 16)?); - let guard = context.enter().map_err(|e| { - context.poison(); - context.retain_driver(); - e - })?; - let load = (|| -> Result<()> { - owner.index.as_mut().ok_or(Error::ContextPoisoned)?.module = - Some(Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS)?); - owner.dequant = Some(if crate::prefill_stage::fast_dequant() { - KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES)? - } else { - KernelModule::load( - concat!(include_str!("../offline_native_dequant_f16.ptx"), "\0").as_bytes(), - &[ - c"leleka_native_dequant_f16_q4_k", - c"leleka_native_dequant_f16_q5_k", - c"leleka_native_dequant_f16_q6_k", - c"leleka_native_dequant_f16_iq4_xs", - ], - )? - }); - owner.pack = Some(KernelModule::load( - concat!(include_str!("../qsa_native_batch.ptx"), "\0").as_bytes(), - &[c"qsa_pack", c"qsa_gate_pack", c"qsa_scan_half"], - )?); - owner.gate = Some(KernelModule::load(GATE_PTX, &[c"qsa_prompt_device_gate"])?); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poison(); - context.retain_driver() - } - combine(load, pop)?; - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = operation { + let (sizes, index) = index_for(context, capacity); + let blank = (None, None, None, None, None); + let (scratch, steps, dequant, pack, gate) = blank; + let mut owner = + Self { context, capacity, packing, index: Some(index), scratch, steps, dequant, pack, gate, failed: false }; + if let Err(e) = owner.init_resources(sizes) { let _ = owner.close(); return Err(e); } @@ -143,87 +69,10 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { w: &OriginalQsaPromptWeights<'_, 'ctx>, ws: &NativeBatchWorkspace<'_>, ) -> Result<([ffi::BufferHandle; 6], [ffi::BufferHandle; 4])> { - if self.is_failed() || read.lease().is_failed() { - return Err(Error::ContextPoisoned); - } - if !read.context_matches(self.context) { - return Err(Error::ContextMismatch); - } - if !(1..=self.capacity).contains(&read.rows()) { - return Err(Error::InvalidQwenShape); - } - ws.validate_context(self.context)?; - let sizes = [ - 512 * (2560 / 256) * native_block(w.kinds[0]), - 512 * (2560 / 256) * native_block(w.kinds[1]), - 12288 * (2560 / 256) * native_block(w.kinds[2]), - 128 * 2560 * 2, - 512 * 2560 * 2, - 2560 * (6144 / 256) * native_block(w.kinds[3]), - ]; - let mut matrices = [self.own(w.projections[0], sizes[0], 2)?; 6]; - for (i, b) in w.projections.iter().enumerate() { - matrices[i] = self.own(b, sizes[i], 2)?; - ws.reject_alias(matrices[i], sizes[i])?; - } - let mut norms = [matrices[0]; 4]; - for (i, b) in w.norms.iter().enumerate() { - let n = if i < 2 { 1024 } else { 512 }; - norms[i] = self.own(b, n, 4)?; - ws.reject_alias(norms[i], n)?; - } - let mut all = Vec::new(); - all.try_reserve_exact(32).map_err(|_| Error::HostAllocation)?; - for b in self - .index - .as_ref() - .ok_or(Error::ContextPoisoned)? - .buffers - .iter() - .flatten() - .chain(self.scratch.iter()) - .chain(self.steps.iter()) - { - all.push((self.own(b, b.len(), 4)?, b.len())); - } - for (role, width) in [(S::MixedHalf, 5120), (S::MixedHigh, 5120), (S::Block, 10240)] { - all.push((common(read, role, width)?, read.rows() * width)); - } - if self.packing == QsaNativePacking::HighAndLow { - all.push((common(read, S::MixedLow, 5120)?, read.rows() * 5120)); - } - for (name, width) in [ - ("Kc", 2048), - ("Vc", 2048), - ("Qf", 49152), - ("q", 24576), - ("idx_raw", 512), - ("q_idx", 2048), - ("attn", 24576), - ("attn_h", 12288), - ("sel_ids", CAP * 4), - ] { - all.push((arena_span(read, name, width)?, read.rows() * width)); - } - for (i, (h, n)) in all.iter().enumerate() { - h.validate_projection_extent(*n, 2)?; - ws.reject_alias(*h, *n)?; - for (a, b) in &all[..i] { - if h.overlaps(*n, *a, *b) { - return Err(Error::OutputAliasesInput); - } - } - for (j, wh) in matrices.iter().enumerate() { - if h.overlaps(*n, *wh, sizes[j]) { - return Err(Error::OutputAliasesInput); - } - } - for (j, wh) in norms.iter().enumerate() { - if h.overlaps(*n, *wh, if j < 2 { 1024 } else { 512 }) { - return Err(Error::OutputAliasesInput); - } - } - } + self.check_admit_state(read, ws)?; + let (matrices, sizes, norms) = self.weight_handles(w, ws)?; + let all = self.resident_spans(read)?; + Self::check_spans_disjoint(&all, ws, (&matrices, &sizes, &norms))?; Ok((matrices, norms)) } } diff --git a/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_2.rs b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_2.rs index 9b81748e..f7f5cdd7 100644 --- a/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_2.rs +++ b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_2.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalQsaPromptDevice (2). #[allow(unused_imports)] +use super::project_phases::{ProjectArgs, Projection}; use super::*; impl<'ctx> OriginalQsaPromptDevice<'ctx> { @@ -17,168 +18,12 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { ) -> Result<()> { let t = read.rows(); let status = self.index.as_ref().ok_or(Error::ContextPoisoned)?.handle(10, 64)?; - let scratch = self.own(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, SCRATCH, 4)?.checked_subspan( - SCRATCH, - 0, - n * k * 2, - )?; - // element-parallel dequantization of prefill_stage.cu (same FP16 bits) unless LELEKA_PREFILL_FAST_DEQUANT=0 + let scratch = self.scratch_span(n * k)?; let fast = crate::prefill_stage::fast_dequant(); - let mut dequant = if fast { - KernelArguments::new(vec![ - B::Address(weight), - B::I64((k / 256 * kind.map_or(0, native_block)) as i64), - B::I64((n * k) as i64), - B::I64((k / 32) as i64), - B::Address(scratch), - ]) - } else { - KernelArguments::new(vec![ - B::Address(weight), - B::I64((k / 256 * kind.map_or(0, native_block)) as i64), - B::I64(0), - B::I64(n as i64), - B::I64((k / 32) as i64), - B::Address(scratch), - ]) - }; - let mut input = KernelArguments::new(vec![ - B::Address(x), - B::Address(status), - B::I64((t * k) as i64), - B::U32(0), - B::U32(if kind.is_some() { 0x7c00 } else { 0x7f80 }), - ]); - let lower = if self.packing == QsaNativePacking::HighAndLow && kind.is_none() { - Some(common(read, S::MixedLow, 5120)?) - } else { - None - }; - let mut low = lower.map(|h| { - KernelArguments::new(vec![ - B::Address(h), - B::Address(status), - B::I64((t * k) as i64), - B::U32(0), - B::U32(0x7f80), - ]) - }); - let mut weight_scan = KernelArguments::new(vec![ - B::Address(scratch), - B::Address(status), - B::I64((n * k) as i64), - B::U32(1), - B::U32(0x7c00), - ]); - let mut scan = Arguments::new(vec![A::Address(output), A::I64((t * n) as i64), A::Address(status), A::U32(2)])?; - let zero = [0u8; 64]; - let mut flags = [0u8; 64]; - let context = self.context; - let blas = ws.blas()?; - let guard = context.enter().map_err(|e| { - context.poison(); - context.retain_driver(); - e - })?; - let op = (|| -> Result<()> { - context.driver.api.copy_from(status, &zero)?; - context.driver.api.synchronize()?; - self.pack.as_ref().ok_or(Error::ContextPoisoned)?.launch( - 2, - (t * k).div_ceil(256) as u32, - 256, - blas.stream(), - &mut input, - )?; - if let Some(args) = &mut low { - self.pack.as_ref().ok_or(Error::ContextPoisoned)?.launch( - 2, - (t * k).div_ceil(256) as u32, - 256, - blas.stream(), - args, - )?; - } - if let Some(kind) = kind { - if fast { - self.dequant.as_ref().ok_or(Error::ContextPoisoned)?.launch( - crate::prefill_stage::DEQUANT_FIRST - + match kind { - QsaNativeKind::Q4K => 1, - QsaNativeKind::Q5K => 2, - QsaNativeKind::Q6K => 3, - QsaNativeKind::Iq4Xs => 5, - }, - (n * k).div_ceil(256) as u32, - 256, - blas.stream(), - &mut dequant, - )?; - } else { - self.dequant.as_ref().ok_or(Error::ContextPoisoned)?.launch( - native_entry(kind), - (n * k / 32).div_ceil(256) as u32, - 256, - blas.stream(), - &mut dequant, - )?; - } - self.pack.as_ref().ok_or(Error::ContextPoisoned)?.launch( - 2, - (n * k).div_ceil(256) as u32, - 256, - blas.stream(), - &mut weight_scan, - )?; - blas.gemm_f16(x, scratch, output, t as i32, n as i32, k as i32, &1., &0.)?; - } else { - blas.gemm_bf16(x, weight, output, t as i32, n as i32, k as i32, &1., &0.)?; - if let Some(lower) = lower { - blas.gemm_bf16(lower, weight, output, t as i32, n as i32, k as i32, &1., &1.)?; - } - } - self.index.as_ref().and_then(|i| i.module.as_ref()).ok_or(Error::ContextPoisoned)?.launch( - Launch::Scan((t * n) as u32), - blas.stream(), - &mut scan, - )?; - Ok(()) - })(); - let sync = blas.synchronize(); - let copy = if sync.is_ok() { context.driver.api.copy_to(status, &mut flags) } else { Ok(()) }; - let all = context.driver.api.synchronize(); - let pop = guard.finish(); - if op.is_err() || sync.is_err() || copy.is_err() || all.is_err() || pop.is_err() { - self.failed = true; - context.poison(); - context.retain_driver() - } - if sync.is_err() || all.is_err() || pop.is_err() { - std::mem::forget((dequant, input, low, weight_scan, scan)); - } - let result = combine(combine(combine(combine(op, sync), copy), all), pop); - if result.is_err() { - ws.mark_failed(); - return result; - } - for word in flags.as_chunks::<4>().0 { - if u32::from_le_bytes(*word) > 1 { - self.failed = true; - context.poison(); - context.retain_driver(); - return Err(Error::InvalidDriverValue("QSA projection status")); - } - } - if flags[12..].iter().any(|x| *x != 0) { - self.failed = true; - context.poison(); - context.retain_driver(); - return Err(Error::InvalidDriverValue("QSA unused status")); - } - if flags[..12].iter().any(|x| *x != 0) { - return Err(Error::NonFiniteMmqOutput("QSA native projection")); - } - Ok(()) + let job = Projection { kind, n, k, t, fast, weight, x, output, status, scratch }; + let with_low = self.packing == QsaNativePacking::HighAndLow && kind.is_none(); + let args = ProjectArgs::new(read, &job, with_low)?; + self.run_projection(ws, &job, args) } #[allow(clippy::too_many_arguments)] pub fn prepare<'lease, 'arena, 'loan>( @@ -191,46 +36,11 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { dead: &[f32], weights: OriginalQsaPromptWeights<'_, 'ctx>, ) -> Result> { - let t = read.rows(); - let p = p0 as usize; - if p.checked_add(t).is_none_or(|end| end > crate::serving_context::geometry().cells()) - || pooled.len() != p / 4 * 128 - || tail.len() != 384 - || dead.len() != 128 - { - return Err(Error::InvalidQwenShape); - } - if pooled.iter().chain(tail).chain(dead).any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("QSA prior")); - } + let (t, p) = (read.rows(), p0 as usize); + Self::check_prior(t, p, [pooled, tail, dead])?; let (w, gamma) = self.admit(&read, &weights, ws)?; - let half = common(&read, S::MixedHalf, 5120)?; - let high = common(&read, S::MixedHigh, 5120)?; - for (i, name, n) in [(0, "Kc", 512), (1, "Vc", 512), (2, "Qf", 12288), (3, "idx_raw", 128), (4, "q_idx", 512)] { - self.project( - &read, - ws, - w[i], - if i < 3 { Some(weights.kinds[i]) } else { None }, - n, - 2560, - if i < 3 { half } else { high }, - arena_span(&read, name, n * 4)?, - )?; - } - let steps = self - .own(self.steps.as_ref().ok_or(Error::ContextPoisoned)?, self.capacity * 16, 4)? - .checked_subspan(self.capacity * 16, 0, t * 16)?; - let out = [ - arena_span(&read, "Kc", 2048)?, - arena_span(&read, "Vc", 2048)?, - arena_span(&read, "q", 24576)?, - arena_span(&read, "sel_ids", CAP * 4)?, - steps, - ]; - let raw = arena_span(&read, "idx_raw", 512)?; - let qfull = arena_span(&read, "Qf", 49152)?; - let iq = arena_span(&read, "q_idx", 2048)?; + self.project_prior(&read, ws, &weights.kinds, w)?; + let (out, [raw, qfull, iq]) = self.index_spans(&read, t)?; let index = self.index.as_mut().ok_or(Error::ContextPoisoned)?; index.run_original_arena(p0, t as u32, pooled, tail, dead, raw, qfull, iq, gamma, out, ws, false)?; let state = index.final_state_original_arena(p, t, tail, raw)?; diff --git a/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs index 6b011714..835c267d 100644 --- a/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs +++ b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs @@ -5,50 +5,7 @@ use super::*; impl<'ctx> OriginalQsaPromptDevice<'ctx> { pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut result = Ok(()); - for m in [self.dequant.take(), self.pack.take(), self.gate.take()].into_iter().flatten() { - let r = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - std::mem::forget(m); - Err(e) - } - } - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver() - } - result = combine(result, r) - } - for b in [self.scratch.take(), self.steps.take()].into_iter().flatten() { - let r = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver() - } - result = combine(result, r) - } - if let Some(i) = self.index.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(i); - Err(Error::ContextPoisoned) - } else { - i.close() - }; - result = combine(result, r) - } - result + self.close_resources() } } impl Drop for OriginalQsaPromptDevice<'_> { @@ -96,7 +53,7 @@ impl<'lease, 'arena, 'loan, 'ctx> OriginalQsaDeviceSelection<'lease, 'arena, 'lo /// FP16 Out. Only actual completed source/causal runtime may publish state. #[allow(clippy::too_many_arguments)] pub fn complete( - self, + mut self, ws: &mut NativeBatchWorkspace<'ctx>, kv: &mut QsaPromptKv<'ctx>, stage: &mut QsaPromptStage<'ctx>, @@ -112,75 +69,11 @@ impl<'lease, 'arena, 'loan, 'ctx> OriginalQsaDeviceSelection<'lease, 'arena, 'lo // Real Out owner admission again; no weight identity is inferred from // earlier role bytes or a caller range. Runtime rechecks binding role. ws.reject_alias(weight, bytes)?; - for b in self - .owner - .index - .as_ref() - .ok_or(Error::ContextPoisoned)? - .buffers - .iter() - .flatten() - .chain(self.owner.scratch.iter()) - .chain(self.owner.steps.iter()) - { - if weight.overlaps(bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { - return Err(Error::OutputAliasesInput); - } - } - for (name, width) in [("attn", 24576), ("attn_h", 12288), ("Qf", 49152)] { - if weight.overlaps(bytes, arena_span(&self.read, name, width)?, t * width) { - return Err(Error::OutputAliasesInput); - } - } - if weight.overlaps(bytes, common(&self.read, S::Block, 10240)?, t * 10240) { - return Err(Error::OutputAliasesInput); - } + self.check_out_weight_clear(weight, bytes)?; let appended = kv.append_original_arena(ws, stage, prior, &self)?; attention.attend_original_arena(ws, stage, kv, appended.final_snapshot(), &self)?; - let input = arena_span(&self.read, "attn", 24576)?; - let qf = arena_span(&self.read, "Qf", 49152)?; - let half = arena_span(&self.read, "attn_h", 12288)?; - let mut args = - KernelArguments::new(vec![B::Address(input), B::Address(qf), B::Address(half), B::I64(t as i64)]); - let context = self.owner.context; - let blas = ws.blas()?; - let guard = context.enter().map_err(|e| { - context.poison(); - context.retain_driver(); - e - })?; - let op = self.owner.gate.as_ref().ok_or(Error::ContextPoisoned)?.launch( - 0, - (t * 6144).div_ceil(256) as u32, - 256, - blas.stream(), - &mut args, - ); - let sync = blas.synchronize(); - let pop = guard.finish(); - if op.is_err() || sync.is_err() || pop.is_err() { - self.owner.failed = true; - context.poison(); - context.retain_driver() - } - if sync.is_err() || pop.is_err() { - std::mem::forget(args) - } - let result = combine(combine(op, sync), pop); - if result.is_err() { - ws.mark_failed(); - return result.map(|()| unreachable!("failed gate")); - } - self.owner.project( - &self.read, - ws, - weight, - Some(out_kind), - 2560, - 6144, - half, - common(&self.read, S::Block, 10240)?, - )?; + let half = self.owner.run_gate(ws, t, &self.read)?; + self.project_out(ws, weight, (out_kind, half))?; Ok((self.read.from_completed_block(), self.state, appended)) } } diff --git a/crates/cuda-driver/src/qsa_prompt_device/project_phases.rs b/crates/cuda-driver/src/qsa_prompt_device/project_phases.rs new file mode 100644 index 00000000..d70c6e99 --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_device/project_phases.rs @@ -0,0 +1,283 @@ +//! STRA-338 size: the phases of `OriginalQsaPromptDevice::project` and `OriginalQsaDeviceSelection::complete`. + +#[allow(unused_imports)] +use super::*; +use crate::ple_batch_ffi::Blas; + +/// Shape, handles and mode of one native projection. +#[derive(Clone, Copy)] +pub(super) struct Projection { + pub(super) kind: Option, + pub(super) n: usize, + pub(super) k: usize, + pub(super) t: usize, + pub(super) fast: bool, + pub(super) weight: ffi::BufferHandle, + pub(super) x: ffi::BufferHandle, + pub(super) output: ffi::BufferHandle, + pub(super) status: ffi::BufferHandle, + pub(super) scratch: ffi::BufferHandle, +} + +/// The kernel argument blocks of one projection; leaked on an uncertain drain. +pub(super) struct ProjectArgs { + dequant: KernelArguments, + input: KernelArguments, + low: Option, + lower: Option, + weight_scan: KernelArguments, + scan: Arguments, +} + +impl ProjectArgs { + pub(super) fn new(read: &OriginalDeviceGrRead<'_, '_, '_>, job: &Projection, with_low: bool) -> Result { + let dequant = dequant_arguments(job); + let input = input_arguments(job); + let lower = if with_low { Some(common(read, S::MixedLow, 5120)?) } else { None }; + let low = lower.map(|h| low_arguments(h, job)); + let weight_scan = KernelArguments::new(vec![ + B::Address(job.scratch), + B::Address(job.status), + B::I64((job.n * job.k) as i64), + B::U32(1), + B::U32(0x7c00), + ]); + let scan = scan_arguments(job)?; + Ok(Self { dequant, input, low, lower, weight_scan, scan }) + } +} + +fn input_arguments(job: &Projection) -> KernelArguments { + KernelArguments::new(vec![ + B::Address(job.x), + B::Address(job.status), + B::I64((job.t * job.k) as i64), + B::U32(0), + B::U32(if job.kind.is_some() { 0x7c00 } else { 0x7f80 }), + ]) +} + +fn low_arguments(h: ffi::BufferHandle, job: &Projection) -> KernelArguments { + KernelArguments::new(vec![ + B::Address(h), + B::Address(job.status), + B::I64((job.t * job.k) as i64), + B::U32(0), + B::U32(0x7f80), + ]) +} + +fn scan_arguments(job: &Projection) -> Result { + Arguments::new(vec![A::Address(job.output), A::I64((job.t * job.n) as i64), A::Address(job.status), A::U32(2)]) +} + +/// Element-parallel dequantization of prefill_stage.cu (same FP16 bits) unless LELEKA_PREFILL_FAST_DEQUANT=0. +fn dequant_arguments(job: &Projection) -> KernelArguments { + let blocks = B::I64((job.k / 256 * job.kind.map_or(0, native_block)) as i64); + let groups = B::I64((job.k / 32) as i64); + if job.fast { + KernelArguments::new(vec![ + B::Address(job.weight), + blocks, + B::I64((job.n * job.k) as i64), + groups, + B::Address(job.scratch), + ]) + } else { + KernelArguments::new(vec![ + B::Address(job.weight), + blocks, + B::I64(0), + B::I64(job.n as i64), + groups, + B::Address(job.scratch), + ]) + } +} + +impl<'ctx> OriginalQsaPromptDevice<'ctx> { + /// The scratch span dequantized weights land in (`bytes` of FP16). + pub(super) fn scratch_span(&self, elements: usize) -> Result { + self.own(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, SCRATCH, 4)?.checked_subspan( + SCRATCH, + 0, + elements * 2, + ) + } + + /// Runs the projection under the context guard, settles the outcome and checks the status words. + pub(super) fn run_projection( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + job: &Projection, + mut args: ProjectArgs, + ) -> Result<()> { + let zero = [0u8; 64]; + let mut flags = [0u8; 64]; + let context = self.context; + let blas = ws.blas()?; + let guard = context.enter().map_err(|e| { + context.poison(); + context.retain_driver(); + e + })?; + let op = self.project_ops(blas, job, &mut args, &zero); + let sync = blas.synchronize(); + let copy = if sync.is_ok() { context.driver.api.copy_to(job.status, &mut flags) } else { Ok(()) }; + let all = context.driver.api.synchronize(); + let pop = guard.finish(); + self.settle_projection(ws, [op, sync, copy, all, pop], args)?; + self.check_projection_flags(&flags) + } + + /// Marks the device failed on any error and leaks the argument blocks when the drain is uncertain. + fn settle_projection( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + [op, sync, copy, all, pop]: [Result<()>; 5], + args: ProjectArgs, + ) -> Result<()> { + if op.is_err() || sync.is_err() || copy.is_err() || all.is_err() || pop.is_err() { + self.failed = true; + self.context.poison(); + self.context.retain_driver() + } + if sync.is_err() || all.is_err() || pop.is_err() { + std::mem::forget(args); + } + let result = combine(combine(combine(combine(op, sync), copy), all), pop); + if result.is_err() { + ws.mark_failed(); + } + result + } + + fn check_projection_flags(&mut self, flags: &[u8; 64]) -> Result<()> { + for word in flags.as_chunks::<4>().0 { + if u32::from_le_bytes(*word) > 1 { + self.poison_device(); + return Err(Error::InvalidDriverValue("QSA projection status")); + } + } + if flags[12..].iter().any(|x| *x != 0) { + self.poison_device(); + return Err(Error::InvalidDriverValue("QSA unused status")); + } + if flags[..12].iter().any(|x| *x != 0) { + return Err(Error::NonFiniteMmqOutput("QSA native projection")); + } + Ok(()) + } + + fn poison_device(&mut self) { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + + /// Zeroes the status words, packs the inputs, runs the weight path and guards the output. + fn project_ops(&self, blas: &Blas, job: &Projection, args: &mut ProjectArgs, zero: &[u8; 64]) -> Result<()> { + self.context.driver.api.copy_from(job.status, zero)?; + self.context.driver.api.synchronize()?; + self.launch_pack(blas, job.t * job.k, &mut args.input)?; + if let Some(low) = &mut args.low { + self.launch_pack(blas, job.t * job.k, low)?; + } + self.project_weight(blas, job, args)?; + self.index.as_ref().and_then(|i| i.module.as_ref()).ok_or(Error::ContextPoisoned)?.launch( + Launch::Scan((job.t * job.n) as u32), + blas.stream(), + &mut args.scan, + ) + } + + fn launch_pack(&self, blas: &Blas, count: usize, args: &mut KernelArguments) -> Result<()> { + self.pack.as_ref().ok_or(Error::ContextPoisoned)?.launch( + 2, + count.div_ceil(256) as u32, + 256, + blas.stream(), + args, + ) + } + + /// Quantized weights are dequantized to FP16 and multiplied in FP16; BF16 weights multiply directly. + fn project_weight(&self, blas: &Blas, job: &Projection, args: &mut ProjectArgs) -> Result<()> { + let (t, n, k) = (job.t as i32, job.n as i32, job.k as i32); + let Some(kind) = job.kind else { + blas.gemm_bf16(job.x, job.weight, job.output, t, n, k, &1., &0.)?; + if let Some(lower) = args.lower { + blas.gemm_bf16(lower, job.weight, job.output, t, n, k, &1., &1.)?; + } + return Ok(()); + }; + self.launch_dequant(blas, job, kind, &mut args.dequant)?; + self.launch_pack(blas, job.n * job.k, &mut args.weight_scan)?; + blas.gemm_f16(job.x, job.scratch, job.output, t, n, k, &1., &0.) + } + + fn launch_dequant( + &self, + blas: &Blas, + job: &Projection, + kind: QsaNativeKind, + args: &mut KernelArguments, + ) -> Result<()> { + let module = self.dequant.as_ref().ok_or(Error::ContextPoisoned)?; + if job.fast { + let offset = match kind { + QsaNativeKind::Q4K => 1, + QsaNativeKind::Q5K => 2, + QsaNativeKind::Q6K => 3, + QsaNativeKind::Iq4Xs => 5, + }; + let entry = crate::prefill_stage::DEQUANT_FIRST + offset; + return module.launch(entry, (job.n * job.k).div_ceil(256) as u32, 256, blas.stream(), args); + } + module.launch(native_entry(kind), (job.n * job.k / 32).div_ceil(256) as u32, 256, blas.stream(), args) + } + + /// The gate kernel under the context guard: packs the attention rows against the strided Qf into FP16. + pub(super) fn run_gate( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + t: usize, + read: &OriginalDeviceGrRead<'_, '_, '_>, + ) -> Result { + let input = arena_span(read, "attn", 24576)?; + let qf = arena_span(read, "Qf", 49152)?; + let half = arena_span(read, "attn_h", 12288)?; + let mut args = + KernelArguments::new(vec![B::Address(input), B::Address(qf), B::Address(half), B::I64(t as i64)]); + let context = self.context; + let blas = ws.blas()?; + let guard = context.enter().map_err(|e| { + context.poison(); + context.retain_driver(); + e + })?; + let gate = self.gate.as_ref().ok_or(Error::ContextPoisoned)?; + let op = gate.launch(0, (t * 6144).div_ceil(256) as u32, 256, blas.stream(), &mut args); + let sync = blas.synchronize(); + let pop = guard.finish(); + self.settle_gate(ws, [op, sync, pop], args)?; + Ok(half) + } + + fn settle_gate( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + [op, sync, pop]: [Result<()>; 3], + args: KernelArguments, + ) -> Result<()> { + if op.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + self.context.poison(); + self.context.retain_driver() + } + if sync.is_err() || pop.is_err() { + std::mem::forget(args) + } + combine(combine(op, sync), pop).inspect_err(|_| ws.mark_failed()) + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_device_index.rs b/crates/cuda-driver/src/qsa_prompt_device_index.rs index 8a1a7891..03ce63ae 100644 --- a/crates/cuda-driver/src/qsa_prompt_device_index.rs +++ b/crates/cuda-driver/src/qsa_prompt_device_index.rs @@ -1,5 +1,5 @@ //! Private real-arena continuation of the exact old prompt program. -use super::run_phases::{HostStaging, run_theta, step_bytes}; +use super::run_phases::HostStaging; use super::*; impl<'ctx> QsaPromptIndexWorkspace<'ctx> { #[allow(clippy::too_many_arguments)] @@ -18,24 +18,11 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { ws: &mut NativeBatchWorkspace<'ctx>, decode: bool, ) -> Result<()> { - let n = t as usize; - let p = p0 as usize; + let (n, p) = (t as usize, p0 as usize); self.upload_run_state(p, pooled, tail, dead)?; - let steps = step_bytes(p, n)?; - let status = self.handle(10, 64)?; - let mut commands: Vec<(Launch, Arguments)> = Vec::new(); - commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?; - let theta = run_theta()?; - let (decode_positions, positions) = if decode { - let (words, span) = self.decode_position_words(p0, n)?; - (words, Some(span)) - } else { - (Vec::new(), None) - }; - let plan = self.arena_plan((t, p0, decode), (raw_h, iq_h, out[0]), status, (positions, theta))?; - self.push_run_commands(&mut commands, &plan, Some(qfull_h), gamma, out)?; - let mut host = - HostStaging { commands, steps, zero: vec![0u8; 64], flags: vec![0u8; 64], kv: None, decode_positions }; + let mut prepared = self.prepare_run((t, p0, decode), Some((raw_h, iq_h)), out[0])?; + self.push_run_commands(&mut prepared.commands, &prepared.plan, Some(qfull_h), gamma, out)?; + let (mut host, plan) = HostStaging::new(prepared, None); self.execute_run(&plan, out, ws, &mut host)?; self.check_run_flags(&host.flags)?; self.check_selected_ids(out[3], p, n) @@ -47,38 +34,6 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { initial_tail: &[f32], raw_h: ffi::BufferHandle, ) -> Result { - let end = p0 + t; - let sizes = [(end / 4 + 1) * 128 * 4, 384 * 4, 128 * 4]; - let mut values: Vec> = Vec::new(); - values.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; - for (i, size) in sizes.into_iter().enumerate() { - let bytes = self.read(self.handle(i, size)?, size)?; - let mut v = Vec::new(); - v.try_reserve_exact(size / 4).map_err(|_| Error::HostAllocation)?; - v.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); - if v.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("QSA final index")); - } - values.push(v.into_boxed_slice()); - } - let bytes = self.read(raw_h, t * 128 * 4)?; - let mut rounded = Vec::new(); - rounded.try_reserve_exact(t * 128).map_err(|_| Error::HostAllocation)?; - rounded.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); - if rounded.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("QSA rounded index rows")); - } - let mut old_tail = [0.0; 384]; - old_tail.copy_from_slice(initial_tail); - Ok(QsaPromptIndexState { - end: end as u32, - p0: p0 as u32, - t: t as u32, - initial_tail: old_tail, - rounded: rounded.into_boxed_slice(), - pooled: values.remove(0), - tail: values.remove(0), - dead: values.remove(0), - }) + self.final_state_with(p0, t, initial_tail, Some(raw_h)) } } diff --git a/crates/cuda-driver/src/qsa_prompt_device_kv.rs b/crates/cuda-driver/src/qsa_prompt_device_kv.rs index 711f5071..4f520aa3 100644 --- a/crates/cuda-driver/src/qsa_prompt_device_kv.rs +++ b/crates/cuda-driver/src/qsa_prompt_device_kv.rs @@ -15,125 +15,27 @@ impl<'ctx> QsaPromptKv<'ctx> { self.validate_snapshot(prior)?; stage.validate(self.context)?; workspace.validate_context(self.context)?; - if !(1..=8192).contains(&t) - || prior.0.end.checked_add(t).is_none_or(|n| n > crate::serving_context::geometry().cells()) - { - return Err(Error::InvalidQwenShape); - } - let end = prior.0.end + t; + Self::check_rows(prior, t, 8192)?; let (kh, vh) = inputs.kv_spans(self.context)?; - let (k, v) = (kh.qwen_address(), vh.qwen_address()); - self.reject_original_span(kh, t * 512 * 4)?; - self.reject_original_span(vh, t * 512 * 4)?; - stage.reject_original_span(kh, t * 512 * 4)?; - stage.reject_original_span(vh, t * 512 * 4)?; - workspace.reject_alias(kh, t * 512 * 4)?; - workspace.reject_alias(vh, t * 512 * 4)?; - // Reserve snapshot metadata and completed page storage BEFORE device writes. - let mut pages = Vec::new(); - pages.try_reserve_exact(end.div_ceil(4)).map_err(|_| Error::HostAllocation)?; - pages.extend(prior.0.pages[..prior.0.end.div_ceil(4)].iter().cloned()); - let first = prior.0.end / 4; - let mut completed = Vec::new(); - completed.try_reserve_exact(end.div_ceil(4) - first).map_err(|_| Error::HostAllocation)?; - for _ in first..end.div_ceil(4) { - let mut a = Vec::new(); - a.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; - for n in PAGE { - let mut b = Vec::new(); - b.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; - b.resize(n, 0); - a.push(b); - } - completed.push(a); - } - stage.restore(self, prior)?; - self.restore(workspace, prior)?; - // Initialize new host-page tails; no uninitialized bytes enter canonical snapshots. - for p in prior.0.end.div_ceil(4)..end.div_ceil(4) { - for i in 0..4 { - stage.pools.buffers[i] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from_range(p * PAGE[i], &completed[p - first][i])?; - } - } - let status = stage.status.as_mut().ok_or(Error::ContextPoisoned)?; - status.copy_from(&[0; 4])?; - let sa = checked(self.context, status, 4)?; - let rp = self.pools.addresses()?; - let sp = stage.pools.addresses()?; - let hp = self.host_addresses()?; - let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((t * 512) as i32), Arg::U64(sa)])?; - stage.run(workspace, 0, [(t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?; - if stage.flags()? != 0 { - return Err(Error::InvalidQ8Activation); - } - let args = Arguments::new(vec![ - Arg::U64(k), - Arg::U64(v), - Arg::I64(prior.0.end as i64), - Arg::U64(self.pools.table()?), - Arg::I64(4), - Arg::U64(rp[0]), - Arg::U64(rp[1]), - Arg::U64(rp[2]), - Arg::U64(rp[3]), - Arg::U64(sp[0]), - Arg::U64(sp[1]), - Arg::U64(sp[2]), - Arg::U64(sp[3]), - Arg::U64(hp[0]), - Arg::U64(hp[1]), - Arg::U64(hp[2]), - Arg::U64(hp[3]), - ])?; - let scales = Arguments::new(vec![ - Arg::U64(sp[2]), - Arg::U64(sp[3]), - Arg::I32(prior.0.end as i32), - Arg::I32(end as i32), - Arg::U64(sa), - ])?; - stage.current = None; - self.current = None; - self.mapped_current = None; - stage.run(workspace, 1, [t as u32, 2, 8], 64, args)?; - stage.run(workspace, 2, [1, 1, 1], 256, scales)?; - if stage.flags()? != 0 { - return Err(Error::InvalidQ8Activation); - } - for (p, bufs) in (first..end.div_ceil(4)).zip(completed.iter_mut()) { - for (i, b) in bufs.iter_mut().enumerate() { - let pool = stage.pools.buffers[i].as_ref().ok_or(Error::ContextPoisoned)?; - read_range(pool, p * PAGE[i], b)?; - } - } - for (p, bufs) in (first..end.div_ceil(4)).zip(completed) { - let mut it = bufs.into_iter(); - let page = Rc::new(Page { - bytes: [ - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - ], - }); - if p < pages.len() { - pages[p] = page; - } else { - pages.push(page); - } - } - let result = QsaKvSnapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Rc::new(pages.into_boxed_slice()), - end, - })); - stage.current = Some(result.0.clone()); - self.current = Some(result.0.clone()); - self.mapped_current = Some(result.0.clone()); - Ok(CompletedQsaKvAppend { final_snapshot: result, first: prior.0.end, rows: t }) + self.reject_original_spans((workspace, stage), (kh, vh), t * 512 * 4)?; + let addresses = (kh.qwen_address(), vh.qwen_address(), t); + let (pages, end) = self.append_pages((workspace, stage), prior, addresses, true)?; + Ok(self.publish_append(stage, prior, (pages, end), t)) + } + + /// K and V must not alias the pools, the resolver, the stage or the workspace. + fn reject_original_spans( + &self, + (workspace, stage): (&NativeBatchWorkspace<'ctx>, &QsaPromptStage<'ctx>), + (kh, vh): (crate::ffi::BufferHandle, crate::ffi::BufferHandle), + bytes: usize, + ) -> Result<()> { + self.reject_original_span(kh, bytes)?; + self.reject_original_span(vh, bytes)?; + stage.reject_original_span(kh, bytes)?; + stage.reject_original_span(vh, bytes)?; + workspace.reject_alias(kh, bytes)?; + workspace.reject_alias(vh, bytes) } pub(crate) fn reject_original_span(&self, h: crate::ffi::BufferHandle, n: usize) -> Result<()> { diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs index 281bc150..0dfc0c4f 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs @@ -11,70 +11,46 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidQwenShape); } - let mut sizes = sizes(); - for i in [4, 7, 8] { - sizes[i] = (sizes[i] / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; - } - sizes[9] = capacity.min(256) * max_blocks() * 4; + let sizes = capacity_sizes(capacity)?; let output_bytes = capacity * (512 * 2 + 6144 + CAP + 4) * 4; - if INDEX.starts_with(b"// UNSEALED") - || SELECT.starts_with(b"// UNSEALED") - || POSTOPS.starts_with(b"// UNSEALED") - || DECODE_POSTOPS.starts_with(b"// UNSEALED") - { - return Err(Error::InvalidDriverValue("QSA index assets unsealed")); - } + check_assets_sealed()?; if context.is_poisoned() { return Err(Error::ContextPoisoned); } - let peak = sizes - .iter() - .try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))? - .checked_add(output_bytes + RESERVE) - .ok_or(Error::BudgetExceeded)?; - if context.allocated_bytes().checked_add(peak).is_none_or(|n| n > context.budget_bytes()) - || context.memory_info()?.0 < peak - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - capacity, - sizes, - context, - buffers: std::array::from_fn(|_| None), - module: None, - late: None, - failed: false, - }; - let operation = (|| { - for (i, n) in sizes.into_iter().enumerate() { - owner.buffers[i] = Some(context.allocate(n)?); - } - let g = context.enter().map_err(|error| { - owner.failed = true; - context.poison(); - context.retain_driver(); - error - })?; - let loaded = Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS); - let pop = g.finish(); - if pop.is_err() { - context.poison(); - context.retain_driver(); - } - owner.module = Some(loaded?); - pop?; - if context.memory_info()?.0 < output_bytes + RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(primary) = operation { + check_peak_budget(context, &sizes, output_bytes)?; + let buffers = std::array::from_fn(|_| None); + let mut owner = Self { capacity, sizes, context, buffers, module: None, late: None, failed: false }; + if let Err(primary) = owner.init_resources(output_bytes) { let _ = owner.close(); return Err(primary); } Ok(owner) } + /// Allocates every buffer, loads the kernel module under the context guard and re-checks the free memory. + fn init_resources(&mut self, output_bytes: usize) -> Result<()> { + let context = self.context; + for (i, n) in self.sizes.into_iter().enumerate() { + self.buffers[i] = Some(context.allocate(n)?); + } + let g = context.enter().map_err(|error| { + self.failed = true; + context.poison(); + context.retain_driver(); + error + })?; + let loaded = Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS); + let pop = g.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver(); + } + self.module = Some(loaded?); + pop?; + if context.memory_info()?.0 < output_bytes + RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } pub fn prompt_device_bytes(capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidQwenShape); @@ -131,30 +107,40 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { let mut out = [self.handle(10, 4)?; 4]; for (i, w) in weights.into_iter().enumerate() { let n = if i < 2 { 256 } else { 128 } * 4; - if !std::ptr::eq(w.context, self.context) { - return Err(Error::ContextMismatch); - } - if w.len() != n { - return Err(Error::InvalidQwenShape); - } - out[i] = w.handle.ok_or(Error::ContextPoisoned)?; - out[i].validate_projection_extent(n, 4)?; + out[i] = self.weight_handle(w, n)?; ws.reject_alias(out[i], n)?; - for (j, b) in self.buffers.iter().enumerate() { - let b = b.as_ref().ok_or(Error::ContextPoisoned)?; - let h = self.handle(j, b.len())?; - ws.reject_alias(h, b.len())?; - if h.overlaps(b.len(), out[i], n) { + self.clear_of_buffers(ws, out[i], n)?; + } + Ok(out) + } + /// The weight must belong to this context, have exactly `n` bytes and a valid extent. + fn weight_handle(&self, w: &DeviceBuffer<'_>, n: usize) -> Result { + if !std::ptr::eq(w.context, self.context) { + return Err(Error::ContextMismatch); + } + if w.len() != n { + return Err(Error::InvalidQwenShape); + } + let h = w.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(n, 4)?; + Ok(h) + } + /// A weight span must not overlap any workspace buffer, nor may two workspace buffers overlap each other. + fn clear_of_buffers(&self, ws: &NativeBatchWorkspace<'_>, weight: ffi::BufferHandle, n: usize) -> Result<()> { + for (j, b) in self.buffers.iter().enumerate() { + let b = b.as_ref().ok_or(Error::ContextPoisoned)?; + let h = self.handle(j, b.len())?; + ws.reject_alias(h, b.len())?; + if h.overlaps(b.len(), weight, n) { + return Err(Error::OutputAliasesInput); + } + for earlier in self.buffers[..j].iter().flatten() { + if h.overlaps(b.len(), earlier.handle.ok_or(Error::ContextPoisoned)?, earlier.len()) { return Err(Error::OutputAliasesInput); } - for earlier in self.buffers[..j].iter().flatten() { - if h.overlaps(b.len(), earlier.handle.ok_or(Error::ContextPoisoned)?, earlier.len()) { - return Err(Error::OutputAliasesInput); - } - } } } - Ok(out) + Ok(()) } #[allow(clippy::too_many_arguments)] // Closed original fixed QSA geometry and genuine prior image. pub fn append_select<'lease>( @@ -172,21 +158,8 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { weights: [&DeviceBuffer<'_>; 4], ws: &mut NativeBatchWorkspace<'ctx>, ) -> Result> { - self.append_select_inner( - p0, - t, - prior_pooled, - prior_tail, - prior_dead, - raw, - k, - v, - qfull, - index_q, - weights, - ws, - false, - ) + let inputs = [prior_pooled, prior_tail, prior_dead, raw, k, v, qfull, index_q]; + self.append_select_inner((p0, t), inputs, weights, ws, false) } /// T1 Original decode index: scalar native append and FP32 warp scores. #[allow(clippy::too_many_arguments)] @@ -204,20 +177,43 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { weights: [&DeviceBuffer<'_>; 4], ws: &mut NativeBatchWorkspace<'ctx>, ) -> Result> { - self.append_select_inner( - p0, - 1, - prior_pooled, - prior_tail, - prior_dead, - raw, - k, - v, - qfull, - index_q, - weights, - ws, - true, - ) + let inputs = [prior_pooled, prior_tail, prior_dead, raw, k, v, qfull, index_q]; + self.append_select_inner((p0, 1), inputs, weights, ws, true) } } + +/// Buffer sizes for a workspace of `capacity` rows. +fn capacity_sizes(capacity: usize) -> Result<[usize; 11]> { + let mut sizes = sizes(); + for i in [4, 7, 8] { + sizes[i] = (sizes[i] / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; + } + sizes[9] = capacity.min(256) * max_blocks() * 4; + Ok(sizes) +} + +fn check_assets_sealed() -> Result<()> { + if INDEX.starts_with(b"// UNSEALED") + || SELECT.starts_with(b"// UNSEALED") + || POSTOPS.starts_with(b"// UNSEALED") + || DECODE_POSTOPS.starts_with(b"// UNSEALED") + { + return Err(Error::InvalidDriverValue("QSA index assets unsealed")); + } + Ok(()) +} + +/// The workspace plus its outputs and reserve must fit the context budget and the free device memory. +fn check_peak_budget(context: &Context<'_>, sizes: &[usize; 11], output_bytes: usize) -> Result<()> { + let peak = sizes + .iter() + .try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))? + .checked_add(output_bytes + RESERVE) + .ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(peak).is_none_or(|n| n > context.budget_bytes()) + || context.memory_info()?.0 < peak + { + return Err(Error::BudgetExceeded); + } + Ok(()) +} diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs index 7eace98f..f03774c7 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs @@ -4,49 +4,46 @@ use super::*; impl<'ctx> QsaPromptIndexWorkspace<'ctx> { - #[allow(clippy::too_many_arguments)] pub(super) fn append_select_inner<'lease>( &'lease mut self, - p0: u32, - t: u32, - prior_pooled: &[f32], - prior_tail: &[f32], - prior_dead: &[f32], - raw: &[f32], - k: &[f32], - v: &[f32], - qfull: &[f32], - index_q: &[f32], + (p0, t): (u32, u32), + inputs: [&[f32]; 8], weights: [&DeviceBuffer<'_>; 4], ws: &mut NativeBatchWorkspace<'ctx>, decode: bool, ) -> Result> { + self.check_select_inputs((p0, t, decode), inputs)?; + let gamma = self.weights(weights, ws)?; + let (outputs, handles) = self.admit_outputs(t as usize, gamma, ws)?; + let operation = self.run_selected((p0, t, decode), inputs, (gamma, handles), ws); + self.finish_select(operation, outputs, (p0, t), inputs[1]) + } + /// Checks the geometry, the lengths of the prior image and rows and that every input value is finite. + fn check_select_inputs(&self, (p0, t, decode): (u32, u32, bool), inputs: [&[f32]; 8]) -> Result<()> { if decode && t != 1 { return Err(Error::InvalidQwenShape); } - let n = t as usize; - let p = p0 as usize; - if n == 0 - || n > self.capacity - || p.checked_add(n).is_none_or(|e| e > crate::serving_context::geometry().cells()) - || prior_pooled.len() != p / 4 * 128 - || prior_tail.len() != 384 - || prior_dead.len() != 128 - || raw.len() != n * 128 - || k.len() != n * 512 - || v.len() != n * 512 - || qfull.len() != n * 12288 - || index_q.len() != n * 512 - { + let (n, p) = (t as usize, p0 as usize); + if !self.select_bounds_ok(p, n) || !select_lengths_ok(p, n, inputs) { return Err(Error::InvalidQwenShape); } - if [prior_pooled, prior_tail, prior_dead, raw, k, v, qfull, index_q] - .into_iter() - .any(|x| x.iter().any(|v| !v.is_finite())) - { + if inputs.into_iter().any(|x| x.iter().any(|v| !v.is_finite())) { return Err(Error::NonFiniteMmqOutput("QSA prompt input/prior")); } - let gamma = self.weights(weights, ws)?; + Ok(()) + } + fn select_bounds_ok(&self, p: usize, n: usize) -> bool { + n != 0 + && n <= self.capacity + && p.checked_add(n).is_some_and(|e| e <= crate::serving_context::geometry().cells()) + } + /// Budget check, exact-size allocation and alias admission of the five outputs; releases them on failure. + fn admit_outputs( + &self, + n: usize, + gamma: [ffi::BufferHandle; 4], + ws: &NativeBatchWorkspace<'ctx>, + ) -> Result<(Outputs<'ctx>, [ffi::BufferHandle; 5])> { let output_bytes = n * (512 * 2 + 6144 + CAP + 4) * 4; if self .context @@ -57,93 +54,129 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { { return Err(Error::BudgetExceeded); } - let mut outputs: [Option>; 5] = std::array::from_fn(|_| None); let sizes = [n * 512 * 4, n * 512 * 4, n * 6144 * 4, n * CAP * 4, n * 4 * 4]; - let operation = (|| { - for (i, size) in sizes.iter().enumerate() { - outputs[i] = Some(self.context.allocate(*size)?); - } - Ok(()) - })(); - if let Err(primary) = operation { - for b in outputs.into_iter().flatten() { - let _ = b.release(); - } - return Err(primary); - } + let outputs = self.allocate_outputs(&sizes)?; let handles: [ffi::BufferHandle; 5] = std::array::from_fn(|i| outputs[i].as_ref().and_then(|b| b.handle).expect("allocated exact owner")); - let admission = (|| { - for (i, b) in outputs.iter().enumerate() { - let b = b.as_ref().ok_or(Error::ContextPoisoned)?; - if !std::ptr::eq(b.context, self.context) || b.len() != sizes[i] { - return Err(Error::InvalidQwenShape); - } - handles[i].validate_projection_extent(sizes[i], 4)?; - ws.reject_alias(handles[i], sizes[i])?; - for other in self.buffers.iter().flatten() { - if handles[i].overlaps(sizes[i], other.handle.ok_or(Error::ContextPoisoned)?, other.len()) { - return Err(Error::OutputAliasesInput); - } - } - for j in 0..i { - if handles[i].overlaps(sizes[i], handles[j], sizes[j]) { - return Err(Error::OutputAliasesInput); - } - } - for (j, g) in gamma.iter().enumerate() { - if handles[i].overlaps(sizes[i], *g, if j < 2 { 1024 } else { 512 }) { - return Err(Error::OutputAliasesInput); - } - } - } - Ok(()) - })(); - if let Err(primary) = admission { - for b in outputs.into_iter().flatten() { - let _ = b.release(); - } + if let Err(primary) = self.admit_alias_free(&outputs, &handles, &sizes, (gamma, ws)) { + release_outputs(outputs); return Err(primary); } - let operation = self.run( - p0, - t, - prior_pooled, - prior_tail, - prior_dead, - raw, - k, - v, - qfull, - index_q, - gamma, - handles, - ws, - decode, - ); + Ok((outputs, handles)) + } + fn allocate_outputs(&self, sizes: &[usize; 5]) -> Result> { + let mut outputs: Outputs<'ctx> = std::array::from_fn(|_| None); + for (i, size) in sizes.iter().enumerate() { + match self.context.allocate(*size) { + Ok(b) => outputs[i] = Some(b), + Err(primary) => { + release_outputs(outputs); + return Err(primary); + } + } + } + Ok(outputs) + } + fn admit_alias_free( + &self, + outputs: &Outputs<'ctx>, + handles: &[ffi::BufferHandle; 5], + sizes: &[usize; 5], + (gamma, ws): ([ffi::BufferHandle; 4], &NativeBatchWorkspace<'ctx>), + ) -> Result<()> { + for (i, b) in outputs.iter().enumerate() { + let b = b.as_ref().ok_or(Error::ContextPoisoned)?; + if !std::ptr::eq(b.context, self.context) || b.len() != sizes[i] { + return Err(Error::InvalidQwenShape); + } + handles[i].validate_projection_extent(sizes[i], 4)?; + ws.reject_alias(handles[i], sizes[i])?; + self.output_clear_of(i, handles, sizes, gamma)?; + } + Ok(()) + } + /// Output `i` must not overlap a workspace buffer, an earlier output or a weight. + fn output_clear_of( + &self, + i: usize, + handles: &[ffi::BufferHandle; 5], + sizes: &[usize; 5], + gamma: [ffi::BufferHandle; 4], + ) -> Result<()> { + for other in self.buffers.iter().flatten() { + if handles[i].overlaps(sizes[i], other.handle.ok_or(Error::ContextPoisoned)?, other.len()) { + return Err(Error::OutputAliasesInput); + } + } + for j in 0..i { + if handles[i].overlaps(sizes[i], handles[j], sizes[j]) { + return Err(Error::OutputAliasesInput); + } + } + for (j, g) in gamma.iter().enumerate() { + if handles[i].overlaps(sizes[i], *g, if j < 2 { 1024 } else { 512 }) { + return Err(Error::OutputAliasesInput); + } + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + fn run_selected( + &mut self, + (p0, t, decode): (u32, u32, bool), + inputs: [&[f32]; 8], + (gamma, handles): ([ffi::BufferHandle; 4], [ffi::BufferHandle; 5]), + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result<()> { + let [pooled, tail, dead, raw, k, v, qfull, index_q] = inputs; + self.run(p0, t, pooled, tail, dead, raw, k, v, qfull, index_q, gamma, handles, ws, decode) + } + /// Reads the final state back; any failure releases (or, on a poisoned context, leaks) the outputs. + fn finish_select<'lease>( + &'lease mut self, + operation: Result<()>, + outputs: Outputs<'ctx>, + (p0, t): (u32, u32), + prior_tail: &[f32], + ) -> Result> { if let Err(primary) = operation { - if self.context.is_poisoned() { - std::mem::forget(outputs); - } else { - for b in outputs.into_iter().flatten() { - let _ = b.release(); - } - } + self.discard_outputs(outputs); return Err(primary); } - let state = self.final_state(p, n, prior_tail); - match state { + match self.final_state(p0 as usize, t as usize, prior_tail) { Ok(state) => Ok(QsaPromptSelection { owner: self, outputs, t, p0, state }), Err(primary) => { - if self.context.is_poisoned() { - std::mem::forget(outputs); - } else { - for b in outputs.into_iter().flatten() { - let _ = b.release(); - } - } + self.discard_outputs(outputs); Err(primary) } } } + fn discard_outputs(&self, outputs: Outputs<'ctx>) { + if self.context.is_poisoned() { + std::mem::forget(outputs); + } else { + release_outputs(outputs); + } + } +} + +type Outputs<'ctx> = [Option>; 5]; + +fn release_outputs(outputs: Outputs<'_>) { + for b in outputs.into_iter().flatten() { + let _ = b.release(); + } +} + +/// The prior image and the row inputs must have exactly the lengths of an `n`-row append at position `p`. +fn select_lengths_ok(p: usize, n: usize, inputs: [&[f32]; 8]) -> bool { + let [prior_pooled, prior_tail, prior_dead, raw, k, v, qfull, index_q] = inputs; + prior_pooled.len() == p / 4 * 128 + && prior_tail.len() == 384 + && prior_dead.len() == 128 + && raw.len() == n * 128 + && k.len() == n * 512 + && v.len() == n * 512 + && qfull.len() == n * 12288 + && index_q.len() == n * 512 } diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs index cbf5f0f7..abba20ac 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs @@ -1,6 +1,6 @@ //! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace (3). -use super::run_phases::{HostStaging, RunPlan, run_theta, step_bytes}; +use super::run_phases::{HostStaging, RunPlan}; #[allow(unused_imports)] use super::*; @@ -23,26 +23,12 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { ws: &mut NativeBatchWorkspace<'ctx>, decode: bool, ) -> Result<()> { - let n = t as usize; - let p = p0 as usize; + let (n, p) = (t as usize, p0 as usize); self.upload_run_inputs(p, pooled, tail, dead, raw, qfull, iq)?; - let steps = step_bytes(p, n)?; - let status = self.handle(10, 64)?; - let mut commands: Vec<(Launch, Arguments)> = Vec::new(); - commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?; - let theta = run_theta()?; - let (decode_positions, positions) = if decode { - let (words, span) = self.decode_position_words(p0, n)?; - (words, Some(span)) - } else { - (Vec::new(), None) - }; - let plan = self.run_plan((t, p0, decode), out[0], status, (positions, theta))?; - self.push_run_commands(&mut commands, &plan, None, gamma, out)?; - let k_bytes = encode(k)?; - let v_bytes = encode(v)?; - let kv = Some([k_bytes, v_bytes]); - let mut host = HostStaging { commands, steps, zero: vec![0u8; 64], flags: vec![0u8; 64], kv, decode_positions }; + let mut prepared = self.prepare_run((t, p0, decode), None, out[0])?; + self.push_run_commands(&mut prepared.commands, &prepared.plan, None, gamma, out)?; + let kv = Some([encode(k)?, encode(v)?]); + let (mut host, plan) = HostStaging::new(prepared, kv); self.execute_run(&plan, out, ws, &mut host)?; self.check_run_flags(&host.flags)?; self.check_selected_ids(out[3], p, n) diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs index 5b737012..18af326e 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs @@ -28,39 +28,45 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { Ok(bytes) } pub(super) fn final_state(&mut self, p0: usize, t: usize, initial_tail: &[f32]) -> Result { + self.final_state_with(p0, t, initial_tail, None) + } + /// Reads back pooled, tail, dead and the rounded rows; `raw` overrides the workspace's own raw span. + pub(super) fn final_state_with( + &mut self, + p0: usize, + t: usize, + initial_tail: &[f32], + raw: Option, + ) -> Result { let end = p0 + t; let sizes = [(end / 4 + 1) * 128 * 4, 384 * 4, 128 * 4]; let mut values: Vec> = Vec::new(); values.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; for (i, size) in sizes.into_iter().enumerate() { - let bytes = self.read(self.handle(i, size)?, size)?; - let mut v = Vec::new(); - v.try_reserve_exact(size / 4).map_err(|_| Error::HostAllocation)?; - v.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); - if v.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("QSA final index")); - } - values.push(v.into_boxed_slice()); - } - let bytes = self.read(self.handle(4, t * 128 * 4)?, t * 128 * 4)?; - let mut rounded = Vec::new(); - rounded.try_reserve_exact(t * 128).map_err(|_| Error::HostAllocation)?; - rounded.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); - if rounded.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("QSA rounded index rows")); + let h = self.handle(i, size)?; + values.push(self.read_finite(h, size, "QSA final index")?); } + let h = match raw { + Some(h) => h, + None => self.handle(4, t * 128 * 4)?, + }; + let rounded = self.read_finite(h, t * 128 * 4, "QSA rounded index rows")?; let mut old_tail = [0.0; 384]; old_tail.copy_from_slice(initial_tail); - Ok(QsaPromptIndexState { - end: end as u32, - p0: p0 as u32, - t: t as u32, - initial_tail: old_tail, - rounded: rounded.into_boxed_slice(), - pooled: values.remove(0), - tail: values.remove(0), - dead: values.remove(0), - }) + let (end, p0, t) = (end as u32, p0 as u32, t as u32); + let [pooled, tail, dead] = [values.remove(0), values.remove(0), values.remove(0)]; + Ok(QsaPromptIndexState { end, p0, t, initial_tail: old_tail, rounded, pooled, tail, dead }) + } + /// Reads `bytes` of f32 values from the device and rejects any non-finite one. + fn read_finite(&mut self, h: ffi::BufferHandle, bytes: usize, what: &'static str) -> Result> { + let raw = self.read(h, bytes)?; + let mut v = Vec::new(); + v.try_reserve_exact(bytes / 4).map_err(|_| Error::HostAllocation)?; + v.extend(raw.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); + if v.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput(what)); + } + Ok(v.into_boxed_slice()) } pub fn close(mut self) -> Result<()> { self.close_inner() @@ -69,44 +75,14 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { let mut result = Ok(()); self.failed = true; if let Some(m) = self.late.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - std::mem::forget(m); - Err(e) - } - } - }; - result = combine(result, close); + result = combine(result, self.close_owned(m, |m| m.close())); } if let Some(m) = self.module.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - std::mem::forget(m); - Err(e) - } - } - }; - result = combine(result, close); + result = combine(result, self.close_owned(m, |m| m.close())); } for b in &mut self.buffers { if let Some(b) = b.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - result = combine(result, close); + result = combine(result, close_buffer(self.context, b)); } } if result.is_err() { @@ -115,6 +91,27 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { } result } + /// Closes a kernel module under the context guard, or leaks it when the context is unusable. + fn close_owned(&self, m: M, close: impl FnOnce(M) -> Result<()>) -> Result<()> { + if self.context.is_poisoned() { + std::mem::forget(m); + return Err(Error::ContextPoisoned); + } + match self.context.enter() { + Ok(g) => combine(close(m), g.finish()), + Err(e) => { + std::mem::forget(m); + Err(e) + } + } + } +} +fn close_buffer<'ctx>(context: &Context<'ctx>, b: DeviceBuffer<'ctx>) -> Result<()> { + if context.is_poisoned() { + std::mem::forget(b); + return Err(Error::ContextPoisoned); + } + b.release() } impl Drop for QsaPromptIndexWorkspace<'_> { fn drop(&mut self) { diff --git a/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs b/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs index 9f6cd090..4a796f94 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs @@ -35,6 +35,21 @@ pub(super) struct HostStaging { pub(super) decode_positions: Vec, } +/// Everything `run` stages before it builds the launches. +pub(super) struct Prepared { + pub(super) plan: RunPlan, + pub(super) commands: Commands, + pub(super) steps: Vec, + pub(super) decode_positions: Vec, +} + +impl HostStaging { + pub(super) fn new(prepared: Prepared, kv: Option<[Vec; 2]>) -> (Self, RunPlan) { + let Prepared { plan, commands, steps, decode_positions } = prepared; + (Self { commands, steps, zero: vec![0u8; 64], flags: vec![0u8; 64], kv, decode_positions }, plan) + } +} + pub(super) fn push_launch(commands: &mut Commands, shape: Launch, args: Vec) -> Result<()> { commands.push((shape, Arguments::for_launch(shape, args)?)); Ok(()) @@ -94,6 +109,34 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { self.upload(2, dead) } + /// Builds the step bytes, launch list and plan of one run; `given` carries caller-provided raw and + /// index-query handles (the arena path), else the workspace's own spans are used. + pub(super) fn prepare_run( + &self, + (p0, t, decode): (u32, u32, bool), + given: Option<(ffi::BufferHandle, ffi::BufferHandle)>, + out0: ffi::BufferHandle, + ) -> Result { + let n = t as usize; + let steps = step_bytes(p0 as usize, n)?; + let status = self.handle(10, 64)?; + let mut commands: Commands = Vec::new(); + commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?; + let theta = run_theta()?; + let (decode_positions, positions) = if decode { + let (words, span) = self.decode_position_words(p0, n)?; + (words, Some(span)) + } else { + (Vec::new(), None) + }; + let shape = (t, p0, decode); + let plan = match given { + None => self.run_plan(shape, out0, status, (positions, theta))?, + Some((raw, iq)) => self.arena_plan(shape, (raw, iq, out0), status, (positions, theta))?, + }; + Ok(Prepared { plan, commands, steps, decode_positions }) + } + /// The 24 per-head position words of a decode step and their device span. pub(super) fn decode_position_words(&self, p0: u32, n: usize) -> Result<(Vec, ffi::BufferHandle)> { let mut decode_positions = Vec::new(); diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv.rs index 90ec889d..e14c3d95 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv.rs @@ -3,5 +3,6 @@ #[allow(unused_imports)] use super::*; +mod append_phases; mod impl_qsapromptkv_2; mod impl_qsapromptkv_2_2; diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/append_phases.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/append_phases.rs new file mode 100644 index 00000000..1dcce57e --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/append_phases.rs @@ -0,0 +1,244 @@ +//! STRA-338 size: the phases of `QsaPromptKv::append_bounded`, extracted in call order. + +#[allow(unused_imports)] +use super::*; + +type Completed = Vec>>; + +/// Reserves the new snapshot's page list (seeded with the prior pages) and the host pages the append completes. +fn reserve_pages(prior: &QsaKvSnapshot, end: usize, exact: bool) -> Result<(Vec>, Completed, usize)> { + let mut pages = Vec::new(); + pages.try_reserve_exact(end.div_ceil(4)).map_err(|_| Error::HostAllocation)?; + pages.extend(prior.0.pages[..prior.0.end.div_ceil(4)].iter().cloned()); + let first = prior.0.end / 4; + let mut completed = Vec::new(); + let capacity = if exact { end.div_ceil(4) - first } else { 17 }; + completed.try_reserve_exact(capacity).map_err(|_| Error::HostAllocation)?; + for _ in first..end.div_ceil(4) { + let mut a = Vec::new(); + a.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; + for n in PAGE { + let mut b = Vec::new(); + b.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; + b.resize(n, 0); + a.push(b); + } + completed.push(a); + } + Ok((pages, completed, first)) +} + +/// Initialize new host-page tails; no uninitialized bytes enter canonical snapshots. +fn init_tails( + stage: &mut QsaPromptStage<'_>, + prior: &QsaKvSnapshot, + end: usize, + completed: &Completed, + first: usize, +) -> Result<()> { + for p in prior.0.end.div_ceil(4)..end.div_ceil(4) { + for i in 0..4 { + stage.pools.buffers[i] + .as_mut() + .ok_or(Error::ContextPoisoned)? + .copy_from_range(p * PAGE[i], &completed[p - first][i])?; + } + } + Ok(()) +} + +/// Reads the device pages the append wrote back into the completed host pages. +fn read_completed(stage: &QsaPromptStage<'_>, completed: &mut Completed, (first, end): (usize, usize)) -> Result<()> { + for (p, bufs) in (first..end.div_ceil(4)).zip(completed.iter_mut()) { + for (i, b) in bufs.iter_mut().enumerate() { + let pool = stage.pools.buffers[i].as_ref().ok_or(Error::ContextPoisoned)?; + read_range(pool, p * PAGE[i], b)?; + } + } + Ok(()) +} + +/// Replaces or appends each completed page in the new snapshot's list. +fn install_pages(pages: &mut Vec>, completed: Completed, first: usize, end: usize) -> Result<()> { + for (p, bufs) in (first..end.div_ceil(4)).zip(completed) { + let mut it = bufs.into_iter(); + let page = Rc::new(Page { + bytes: [ + it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), + it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), + it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), + it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), + ], + }); + if p < pages.len() { + pages[p] = page; + } else { + pages.push(page); + } + } + Ok(()) +} + +impl<'ctx> QsaPromptKv<'ctx> { + /// 1..=limit rows, ending within the context's cell count. + pub(in crate::qsa_prompt_kv) fn check_rows(prior: &QsaKvSnapshot, t: usize, limit: usize) -> Result<()> { + if !(1..=limit).contains(&t) || prior.0.end.checked_add(t).is_none_or(|n| n > geometry().cells()) { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + + /// Checks the row range, the K and V buffers and every alias; returns their device addresses. + pub(super) fn check_append( + &self, + (workspace, stage): (&NativeBatchWorkspace<'ctx>, &QsaPromptStage<'ctx>), + prior: &QsaKvSnapshot, + (keys, values, t): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, usize), + limit: usize, + ) -> Result<(u64, u64)> { + Self::check_rows(prior, t, limit)?; + let k = checked(self.context, keys, t * 512 * 4)?; + let v = checked(self.context, values, t * 512 * 4)?; + let (kh, vh) = (keys.handle.ok_or(Error::ContextPoisoned)?, values.handle.ok_or(Error::ContextPoisoned)?); + if kh.overlaps(keys.bytes, vh, values.bytes) { + return Err(Error::OutputAliasesInput); + } + self.pools_clear_of(stage, [keys, values])?; + workspace.reject_alias(kh, keys.bytes)?; + workspace.reject_alias(vh, values.bytes)?; + Ok((k, v)) + } + + /// No pool nor the stage status buffer may overlap K or V. + fn pools_clear_of(&self, stage: &QsaPromptStage<'ctx>, bufs: [&DeviceBuffer<'_>; 2]) -> Result<()> { + for p in self.pools.buffers.iter().chain(stage.pools.buffers.iter()).flatten().chain(stage.status.iter()) { + for b in bufs { + if p.handle.ok_or(Error::ContextPoisoned)?.overlaps( + p.bytes, + b.handle.ok_or(Error::ContextPoisoned)?, + b.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + Ok(()) + } + + /// Reserves, restores and initializes the host pages, runs the guard and append kernels and reads the pages back. + pub(in crate::qsa_prompt_kv) fn append_pages( + &mut self, + (workspace, stage): (&mut NativeBatchWorkspace<'ctx>, &mut QsaPromptStage<'ctx>), + prior: &QsaKvSnapshot, + (k, v, t): (u64, u64, usize), + exact: bool, + ) -> Result<(Vec>, usize)> { + let end = prior.0.end + t; + let (mut pages, mut completed, first) = reserve_pages(prior, end, exact)?; + stage.restore(self, prior)?; + self.restore(workspace, prior)?; + init_tails(stage, prior, end, &completed, first)?; + self.run_append((workspace, stage), prior.0.end, (k, v, t, end))?; + read_completed(stage, &mut completed, (first, end))?; + install_pages(&mut pages, completed, first, end)?; + Ok((pages, end)) + } + + /// The finite guard over K and V, then the append and scale kernels, each followed by a status check. + fn run_append( + &mut self, + (workspace, stage): (&mut NativeBatchWorkspace<'ctx>, &mut QsaPromptStage<'ctx>), + prior_end: usize, + (k, v, t, end): (u64, u64, usize, usize), + ) -> Result<()> { + let (sa, rp, sp, hp) = self.append_addresses(stage)?; + let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((t * 512) as i32), Arg::U64(sa)])?; + stage.run(workspace, 0, [(t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?; + if stage.flags()? != 0 { + return Err(Error::InvalidQ8Activation); + } + let args = self.append_arguments((k, v), prior_end, (rp, sp, hp))?; + self.run_append_kernels((workspace, stage), args, (sp, sa), (prior_end, end, t)) + } + + /// Zeroes the status word; returns its address and the device, stage and host page-pool addresses. + #[allow(clippy::type_complexity)] + fn append_addresses(&self, stage: &mut QsaPromptStage<'ctx>) -> Result<(u64, [u64; 4], [u64; 4], [u64; 4])> { + let status = stage.status.as_mut().ok_or(Error::ContextPoisoned)?; + status.copy_from(&[0; 4])?; + let sa = checked(self.context, status, 4)?; + Ok((sa, self.pools.addresses()?, stage.pools.addresses()?, self.host_addresses()?)) + } + + /// The append kernel and the scale kernel over the freshly written pages; the current snapshots are dropped first. + fn run_append_kernels( + &mut self, + (workspace, stage): (&mut NativeBatchWorkspace<'ctx>, &mut QsaPromptStage<'ctx>), + args: Arguments, + (sp, sa): ([u64; 4], u64), + (prior_end, end, t): (usize, usize, usize), + ) -> Result<()> { + let scales = Arguments::new(vec![ + Arg::U64(sp[2]), + Arg::U64(sp[3]), + Arg::I32(prior_end as i32), + Arg::I32(end as i32), + Arg::U64(sa), + ])?; + stage.current = None; + self.current = None; + self.mapped_current = None; + stage.run(workspace, 1, [t as u32, 2, 8], 64, args)?; + stage.run(workspace, 2, [1, 1, 1], 256, scales)?; + if stage.flags()? != 0 { + return Err(Error::InvalidQ8Activation); + } + Ok(()) + } + + fn append_arguments( + &self, + (k, v): (u64, u64), + prior_end: usize, + (rp, sp, hp): ([u64; 4], [u64; 4], [u64; 4]), + ) -> Result { + Arguments::new(vec![ + Arg::U64(k), + Arg::U64(v), + Arg::I64(prior_end as i64), + Arg::U64(self.pools.table()?), + Arg::I64(4), + Arg::U64(rp[0]), + Arg::U64(rp[1]), + Arg::U64(rp[2]), + Arg::U64(rp[3]), + Arg::U64(sp[0]), + Arg::U64(sp[1]), + Arg::U64(sp[2]), + Arg::U64(sp[3]), + Arg::U64(hp[0]), + Arg::U64(hp[1]), + Arg::U64(hp[2]), + Arg::U64(hp[3]), + ]) + } + + /// The finished snapshot becomes the current one of the stage, the pools and the mapped journal. + pub(in crate::qsa_prompt_kv) fn publish_append( + &mut self, + stage: &mut QsaPromptStage<'ctx>, + prior: &QsaKvSnapshot, + (pages, end): (Vec>, usize), + t: usize, + ) -> CompletedQsaKvAppend { + let result = QsaKvSnapshot(Rc::new(Snapshot { + origin: self.origin.clone(), + pages: Rc::new(pages.into_boxed_slice()), + end, + })); + stage.current = Some(result.0.clone()); + self.current = Some(result.0.clone()); + self.mapped_current = Some(result.0.clone()); + CompletedQsaKvAppend { final_snapshot: result, first: prior.0.end, rows: t } + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs index 3adf6ba8..3ae37bf5 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs @@ -21,55 +21,47 @@ impl<'ctx> QsaPromptKv<'ctx> { slots, failed: false, }; - let r = (|| { - // Asset fails closed before host allocation. Root charges mapped AND immutable - // snapshot payload as separate actual host owners, never transient-cap credit. - o.resolver = Some(Resolver::new(c, slots)?); - #[cfg(windows)] - let available = libc::physical_memory() - .and_then(|(_, available)| usize::try_from(available).ok()) - .ok_or(Error::HostAllocation)?; - #[cfg(unix)] - let text = std::fs::read_to_string("/proc/meminfo").map_err(|_| Error::HostAllocation)?; - #[cfg(unix)] - let available = text - .lines() - .find_map(|line| line.strip_prefix("MemAvailable:")?.split_whitespace().next()?.parse::().ok()) - .and_then(|n| n.checked_mul(1024)) - .ok_or(Error::HostAllocation)?; - let mapped_host = geometry().mapped_host_bytes().map_err(|_| Error::HostAllocation)?; - if available < mapped_host + 8 * 1024 * 1024 * 1024 { - return Err(Error::HostAllocation); - } - let g = c.enter()?; - let mapped = MappedAllocation::new(); - let pop = g.finish(); - match mapped { - Ok(m) => { - o.mapped = Some(m); - if let Err(e) = pop { - c.poisoned.set(true); - return Err(e); - } - } - Err(e) => { - if pop.is_err() { - c.poisoned.set(true); - } - return combine(Err(e), pop); - } - } - o.pools.allocate(c, resident_runs(slots)?)?; - if c.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = r { + if let Err(e) = o.init_resources(slots) { return combine(Err(e), o.close()); } Ok(o) } + /// Asset fails closed before host allocation. Root charges mapped AND immutable + /// snapshot payload as separate actual host owners, never transient-cap credit. + fn init_resources(&mut self, slots: usize) -> Result<()> { + let c = self.context; + self.resolver = Some(Resolver::new(c, slots)?); + check_host_memory()?; + self.map_host()?; + self.pools.allocate(c, resident_runs(slots)?)?; + if c.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + /// Allocates the pinned mapped host area under the context guard. + fn map_host(&mut self) -> Result<()> { + let c = self.context; + let g = c.enter()?; + let mapped = MappedAllocation::new(); + let pop = g.finish(); + match mapped { + Ok(m) => { + self.mapped = Some(m); + if let Err(e) = pop { + c.poisoned.set(true); + return Err(e); + } + Ok(()) + } + Err(e) => { + if pop.is_err() { + c.poisoned.set(true); + } + combine(Err(e), pop) + } + } + } pub fn empty_snapshot(&self) -> Result { self.validate()?; Ok(QsaKvSnapshot(Rc::new(Snapshot { origin: self.origin.clone(), pages: Rc::new(Box::new([])), end: 0 }))) @@ -221,3 +213,24 @@ impl<'ctx> QsaPromptKv<'ctx> { self.append_bounded(workspace, stage, prior, inputs, 8192) } } + +/// The mapped host area plus 8 GiB of headroom must fit the available system memory. +fn check_host_memory() -> Result<()> { + #[cfg(windows)] + let available = libc::physical_memory() + .and_then(|(_, available)| usize::try_from(available).ok()) + .ok_or(Error::HostAllocation)?; + #[cfg(unix)] + let text = std::fs::read_to_string("/proc/meminfo").map_err(|_| Error::HostAllocation)?; + #[cfg(unix)] + let available = text + .lines() + .find_map(|line| line.strip_prefix("MemAvailable:")?.split_whitespace().next()?.parse::().ok()) + .and_then(|n| n.checked_mul(1024)) + .ok_or(Error::HostAllocation)?; + let mapped_host = geometry().mapped_host_bytes().map_err(|_| Error::HostAllocation)?; + if available < mapped_host + 8 * 1024 * 1024 * 1024 { + return Err(Error::HostAllocation); + } + Ok(()) +} diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2_2.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2_2.rs index 744aa67a..30862f52 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2_2.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2_2.rs @@ -17,137 +17,9 @@ impl<'ctx> QsaPromptKv<'ctx> { self.validate_snapshot(prior)?; stage.validate(self.context)?; workspace.validate_context(self.context)?; - if !(1..=limit).contains(&t) || prior.0.end.checked_add(t).is_none_or(|n| n > geometry().cells()) { - return Err(Error::InvalidQwenShape); - } - let end = prior.0.end + t; - let k = checked(self.context, keys, t * 512 * 4)?; - let v = checked(self.context, values, t * 512 * 4)?; - if keys.handle.ok_or(Error::ContextPoisoned)?.overlaps( - keys.bytes, - values.handle.ok_or(Error::ContextPoisoned)?, - values.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - for p in self.pools.buffers.iter().chain(stage.pools.buffers.iter()).flatten().chain(stage.status.iter()) { - for b in [keys, values] { - if p.handle.ok_or(Error::ContextPoisoned)?.overlaps( - p.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - workspace.reject_alias(keys.handle.ok_or(Error::ContextPoisoned)?, keys.bytes)?; - workspace.reject_alias(values.handle.ok_or(Error::ContextPoisoned)?, values.bytes)?; - // Reserve snapshot metadata and completed page storage BEFORE device writes. - let mut pages = Vec::new(); - pages.try_reserve_exact(end.div_ceil(4)).map_err(|_| Error::HostAllocation)?; - pages.extend(prior.0.pages[..prior.0.end.div_ceil(4)].iter().cloned()); - let first = prior.0.end / 4; - let mut completed = Vec::new(); - completed.try_reserve_exact(17).map_err(|_| Error::HostAllocation)?; - for _ in first..end.div_ceil(4) { - let mut a = Vec::new(); - a.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; - for n in PAGE { - let mut b = Vec::new(); - b.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; - b.resize(n, 0); - a.push(b); - } - completed.push(a); - } - stage.restore(self, prior)?; - self.restore(workspace, prior)?; - // Initialize new host-page tails; no uninitialized bytes enter canonical snapshots. - for p in prior.0.end.div_ceil(4)..end.div_ceil(4) { - for i in 0..4 { - stage.pools.buffers[i] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from_range(p * PAGE[i], &completed[p - first][i])?; - } - } - let status = stage.status.as_mut().ok_or(Error::ContextPoisoned)?; - status.copy_from(&[0; 4])?; - let sa = checked(self.context, status, 4)?; - let rp = self.pools.addresses()?; - let sp = stage.pools.addresses()?; - let hp = self.host_addresses()?; - let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((t * 512) as i32), Arg::U64(sa)])?; - stage.run(workspace, 0, [(t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?; - if stage.flags()? != 0 { - return Err(Error::InvalidQ8Activation); - } - let args = Arguments::new(vec![ - Arg::U64(k), - Arg::U64(v), - Arg::I64(prior.0.end as i64), - Arg::U64(self.pools.table()?), - Arg::I64(4), - Arg::U64(rp[0]), - Arg::U64(rp[1]), - Arg::U64(rp[2]), - Arg::U64(rp[3]), - Arg::U64(sp[0]), - Arg::U64(sp[1]), - Arg::U64(sp[2]), - Arg::U64(sp[3]), - Arg::U64(hp[0]), - Arg::U64(hp[1]), - Arg::U64(hp[2]), - Arg::U64(hp[3]), - ])?; - let scales = Arguments::new(vec![ - Arg::U64(sp[2]), - Arg::U64(sp[3]), - Arg::I32(prior.0.end as i32), - Arg::I32(end as i32), - Arg::U64(sa), - ])?; - stage.current = None; - self.current = None; - self.mapped_current = None; - stage.run(workspace, 1, [t as u32, 2, 8], 64, args)?; - stage.run(workspace, 2, [1, 1, 1], 256, scales)?; - if stage.flags()? != 0 { - return Err(Error::InvalidQ8Activation); - } - for (p, bufs) in (first..end.div_ceil(4)).zip(completed.iter_mut()) { - for (i, b) in bufs.iter_mut().enumerate() { - let pool = stage.pools.buffers[i].as_ref().ok_or(Error::ContextPoisoned)?; - read_range(pool, p * PAGE[i], b)?; - } - } - for (p, bufs) in (first..end.div_ceil(4)).zip(completed) { - let mut it = bufs.into_iter(); - let page = Rc::new(Page { - bytes: [ - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - ], - }); - if p < pages.len() { - pages[p] = page; - } else { - pages.push(page); - } - } - let result = QsaKvSnapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Rc::new(pages.into_boxed_slice()), - end, - })); - stage.current = Some(result.0.clone()); - self.current = Some(result.0.clone()); - self.mapped_current = Some(result.0.clone()); - Ok(CompletedQsaKvAppend { final_snapshot: result, first: prior.0.end, rows: t }) + let (k, v) = self.check_append((workspace, stage), prior, (keys, values, t), limit)?; + let (pages, end) = self.append_pages((workspace, stage), prior, (k, v, t), false)?; + Ok(self.publish_append(stage, prior, (pages, end), t)) } pub fn close(mut self) -> Result<()> { self.close_inner() @@ -160,48 +32,52 @@ impl<'ctx> QsaPromptKv<'ctx> { if let Some(o) = self.resolver.take() { r = combine(r, o.close()); } - if let Some(mut m) = self.mapped.take() { - // Closing while failed Context cannot prove DMA complete: retain actual pinned - // host allocation/library just as actual device owners are retained on poison. - if self.context.is_poisoned() { - std::mem::forget(m); - r = combine(r, Err(Error::ContextPoisoned)); - } else { - match self.context.enter() { - Ok(g) => { - let sync = self.context.driver.api.synchronize(); - let pop = g.finish(); - let safe = sync.is_ok() && pop.is_ok(); - r = combine(r, combine(sync, pop)); - if safe { - // Re-enter the exact Context only after drain AND pop proved - // completion. No uncertain launch input is freed by this cleanup. - match self.context.enter() { - Ok(g) => { - let free = m.close(); - let pop = g.finish(); - if free.is_err() || pop.is_err() { - self.context.poisoned.set(true); - } - r = combine(r, combine(free, pop)); - } - Err(e) => { - std::mem::forget(m); - r = combine(r, Err(e)); - } - } - } else { - self.context.poisoned.set(true); - std::mem::forget(m); - } - } - Err(e) => { - std::mem::forget(m); - r = combine(r, Err(e)); - } - } - } + if let Some(m) = self.mapped.take() { + r = combine(r, self.close_mapped(m)); } combine(r, self.pools.close()) } + /// Closing while failed Context cannot prove DMA complete: retain actual pinned host allocation/library just + /// as actual device owners are retained on poison. Otherwise drain, pop, and only then free the allocation. + fn close_mapped(&self, m: MappedAllocation) -> Result<()> { + if self.context.is_poisoned() { + std::mem::forget(m); + return Err(Error::ContextPoisoned); + } + let g = match self.context.enter() { + Ok(g) => g, + Err(e) => { + std::mem::forget(m); + return Err(e); + } + }; + let sync = self.context.driver.api.synchronize(); + let pop = g.finish(); + let safe = sync.is_ok() && pop.is_ok(); + let drained = combine(sync, pop); + if !safe { + self.context.poisoned.set(true); + std::mem::forget(m); + return drained; + } + // Re-enter the exact Context only after drain AND pop proved completion. + // No uncertain launch input is freed by this cleanup. + combine(drained, self.free_mapped(m)) + } + fn free_mapped(&self, mut m: MappedAllocation) -> Result<()> { + match self.context.enter() { + Ok(g) => { + let free = m.close(); + let pop = g.finish(); + if free.is_err() || pop.is_err() { + self.context.poisoned.set(true); + } + combine(free, pop) + } + Err(e) => { + std::mem::forget(m); + Err(e) + } + } + } } diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_drop_for_sharedexpertworkspace.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_drop_for_sharedexpertworkspace.rs index 5ec29fad..269a5ddb 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_drop_for_sharedexpertworkspace.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_drop_for_sharedexpertworkspace.rs @@ -57,7 +57,51 @@ pub(super) fn append_projection( rows: usize, columns: usize, ) -> Result<()> { - let (quant_grid, projection_grid, scratch_bytes) = match kernels.style { + let (quant_grid, projection_grid, scratch_bytes) = projection_numbers(kernels.style, handles, rows, columns)?; + scratch.validate_projection_extent(scratch_bytes, 4)?; + status.validate_projection_extent(4, 4)?; + commands.push(Command::Quant( + kernels.quant, + quant_grid, + ffi::Q8QuantizeArguments::new(handles[1], scratch, status, columns as u32), + )); + push_project(commands, kernels, projection_grid, (handles, scratch), (rows as u32, columns as u32)); + Ok(()) +} +/// The projection launch of the style's kernel. +fn push_project( + commands: &mut Vec, + kernels: Pair, + grid: u32, + (handles, scratch): ([ffi::BufferHandle; 3], ffi::BufferHandle), + (rows, columns): (u32, u32), +) { + commands.push(match kernels.style { + ProjectionStyle::Common(_) => Command::Common( + kernels.project, + grid, + ffi::ProjectionArguments::new(handles[0], scratch, handles[2], rows, columns), + ), + ProjectionStyle::Q5 => Command::Q5( + kernels.project, + grid, + ffi::Q5ProjectionArguments::new(handles[0], scratch, handles[2], rows, columns), + ), + ProjectionStyle::Q6 => Command::Q6( + kernels.project, + grid, + ffi::Q6ProjectionArguments::new(handles[0], scratch, handles[2], rows, columns), + ), + }); +} +/// The quantize grid, projection grid and scratch bytes of a projection of this style. +fn projection_numbers( + style: ProjectionStyle, + handles: [ffi::BufferHandle; 3], + rows: usize, + columns: usize, +) -> Result<(u32, u32, usize)> { + Ok(match style { ProjectionStyle::Common(kind) => { let shape = projection_shape(ProjectionSpec { kind, rows, columns })?; projection_ranges(kind, &shape, handles)?; @@ -71,32 +115,7 @@ pub(super) fn append_projection( let s = crate::q6_k_shape(rows, columns)?; (s.quant_grid, s.projection_grid, s.scratch_bytes) } - }; - scratch.validate_projection_extent(scratch_bytes, 4)?; - status.validate_projection_extent(4, 4)?; - commands.push(Command::Quant( - kernels.quant, - quant_grid, - ffi::Q8QuantizeArguments::new(handles[1], scratch, status, columns as u32), - )); - match kernels.style { - ProjectionStyle::Common(_) => commands.push(Command::Common( - kernels.project, - projection_grid, - ffi::ProjectionArguments::new(handles[0], scratch, handles[2], rows as u32, columns as u32), - )), - ProjectionStyle::Q5 => commands.push(Command::Q5( - kernels.project, - projection_grid, - ffi::Q5ProjectionArguments::new(handles[0], scratch, handles[2], rows as u32, columns as u32), - )), - ProjectionStyle::Q6 => commands.push(Command::Q6( - kernels.project, - projection_grid, - ffi::Q6ProjectionArguments::new(handles[0], scratch, handles[2], rows as u32, columns as u32), - )), - } - Ok(()) + }) } impl Command { pub(super) fn launch(&mut self, context: &Context<'_>) -> Result<()> { diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs index 1562d4c0..a8e30544 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs @@ -9,3 +9,5 @@ mod impl_sharedexpertworkspace_2; mod impl_sharedexpertworkspace_2_2; #[path = "impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs"] mod impl_sharedexpertworkspace_3; +#[path = "impl_sharedexpertworkspace/shared_phases.rs"] +mod shared_phases; diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs index 923083b1..8de563ec 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs @@ -5,78 +5,50 @@ use super::*; impl<'ctx> SharedExpertWorkspace<'ctx> { pub(in super::super) fn new(context: &'ctx Context<'ctx>) -> Result { - if context.is_poisoned() || context.handle.is_none() { - return Err(Error::ContextPoisoned); - } - for operation in OPERATIONS { - qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?.validate(operation)?; - } - let required = TOTAL.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - context, - buffers: std::array::from_fn(|_| None), - module: None, - kernels: None, - generation: 0, - failed: false, - }; - let result = (|| { - for (i, size) in SIZES.into_iter().enumerate() { - owner.buffers[i] = Some(context.allocate(size)?); - } - let guard = context.enter()?; - let load = (|| { - let common = |format| -> Result { - let kind = ProjectionKind::Dense(format); - let (quant, project) = context.common_kernels(kind)?; - Ok(Pair { quant, project, style: ProjectionStyle::Common(kind) }) - }; - let q4 = common(DenseFormat::Q4_K)?; - let q5 = context.q5_kernels()?; - let q6 = context.q6_kernels()?; - let xs = common(DenseFormat::IQ4_XS)?; - let gu = [ - q4, - Pair { quant: q5.quantize, project: q5.project, style: ProjectionStyle::Q5 }, - Pair { quant: q6.quantize, project: q6.project, style: ProjectionStyle::Q6 }, - xs, - ]; - let down = [common(DenseFormat::Q8_0)?, common(DenseFormat::IQ4_NL)?]; - let mut qwen = [None; 4]; - for (i, operation) in OPERATIONS.into_iter().enumerate() { - let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; - qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); - } - let module = context.driver.api.load_mmq_resident()?; - owner.module = Some(module); - let finite = [ - context.driver.api.mmq_resident_function(module, 0)?, - context.driver.api.mmq_resident_function(module, 1)?, - ]; - Ok(Kernels { gu, down, qwen: qwen.map(|x| x.expect("four closed entries resolved")), guard: finite }) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poisoned.set(true); - } - owner.kernels = Some(combine(load, pop)?); - // Real module residency is implicit CUDA memory. Preserve the actual free reserve too. - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - owner.handles()?; - Ok(()) - })(); - if let Err(error) = result { + check_new(context)?; + let buffers = std::array::from_fn(|_| None); + let mut owner = Self { context, buffers, module: None, kernels: None, generation: 0, failed: false }; + if let Err(error) = owner.init_resources() { return combine(Err(error), owner.close()); } Ok(owner) } + /// Allocates every buffer, loads the kernels under the context guard and re-checks the free reserve. + fn init_resources(&mut self) -> Result<()> { + let context = self.context; + for (i, size) in SIZES.into_iter().enumerate() { + self.buffers[i] = Some(context.allocate(size)?); + } + let guard = context.enter()?; + let load = self.load_kernels(); + let pop = guard.finish(); + if pop.is_err() { + context.poisoned.set(true); + } + self.kernels = Some(combine(load, pop)?); + // Real module residency is implicit CUDA memory. Preserve the actual free reserve too. + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + self.handles()?; + Ok(()) + } + fn load_kernels(&mut self) -> Result { + let context = self.context; + let (gu, down) = projection_pairs(context)?; + let mut qwen = [None; 4]; + for (i, operation) in OPERATIONS.into_iter().enumerate() { + let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; + qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); + } + let module = context.driver.api.load_mmq_resident()?; + self.module = Some(module); + let finite = [ + context.driver.api.mmq_resident_function(module, 0)?, + context.driver.api.mmq_resident_function(module, 1)?, + ]; + Ok(Kernels { gu, down, qwen: qwen.map(|x| x.expect("four closed entries resolved")), guard: finite }) + } pub fn allocated_bytes(&self) -> usize { self.buffers.iter().flatten().map(|b| b.bytes).sum() } @@ -93,23 +65,28 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?; let mut handles = [first; 11]; for i in 0..11 { - let buffer = self.buffer(i)?; - if !std::ptr::eq(self.context, buffer.context) { - return Err(Error::ContextMismatch); - } - if buffer.bytes != SIZES[i] { - return Err(Error::InvalidQwenShape); - } - handles[i] = buffer.handle.ok_or(Error::ContextPoisoned)?; - handles[i].validate_projection_extent(SIZES[i], 4)?; - for j in 0..i { - if handles[i].overlaps(SIZES[i], handles[j], SIZES[j]) { - return Err(Error::OutputAliasesInput); - } - } + handles[i] = self.checked_owner(i, &handles[..i])?; } Ok(handles) } + /// Buffer `i` must belong to this context, have exactly its size and overlap no earlier buffer. + fn checked_owner(&self, i: usize, earlier: &[ffi::BufferHandle]) -> Result { + let buffer = self.buffer(i)?; + if !std::ptr::eq(self.context, buffer.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != SIZES[i] { + return Err(Error::InvalidQwenShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(SIZES[i], 4)?; + for (j, other) in earlier.iter().enumerate() { + if handle.overlaps(SIZES[i], *other, SIZES[j]) { + return Err(Error::OutputAliasesInput); + } + } + Ok(handle) + } pub(in super::super) fn inputs( &self, activation: &DeviceBuffer<'_>, @@ -128,19 +105,7 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { ]; let mut handles = [owned[0]; 6]; for (i, buffer) in buffers.into_iter().enumerate() { - if !std::ptr::eq(self.context, buffer.context) { - return Err(Error::ContextMismatch); - } - if buffer.bytes != sizes[i] { - return Err(Error::InvalidQwenShape); - } - handles[i] = buffer.handle.ok_or(Error::ContextPoisoned)?; - handles[i].validate_projection_extent(sizes[i], if i == 4 { 2 } else { 4 })?; - for (j, h) in owned.into_iter().enumerate() { - if handles[i].overlaps(sizes[i], h, SIZES[j]) { - return Err(Error::OutputAliasesInput); - } - } + handles[i] = self.checked_input(buffer, sizes[i], (if i == 4 { 2 } else { 4 }, owned))?; // Immutable inputs may share an owner as in the original per-role APIs. // Every output/scratch/status/route owner must be disjoint from all inputs. } @@ -149,4 +114,64 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { } Ok(handles) } + /// An input must belong to this context, have exactly `size` bytes and overlap no owned buffer. + fn checked_input( + &self, + buffer: &DeviceBuffer<'_>, + size: usize, + (alignment, owned): (u64, [ffi::BufferHandle; 11]), + ) -> Result { + if !std::ptr::eq(self.context, buffer.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != size { + return Err(Error::InvalidQwenShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(size, alignment)?; + for (j, h) in owned.into_iter().enumerate() { + if handle.overlaps(size, h, SIZES[j]) { + return Err(Error::OutputAliasesInput); + } + } + Ok(handle) + } +} + +/// Context must be live, every operation asset valid, and the workspace plus reserve must fit the budget. +fn check_new(context: &Context<'_>) -> Result<()> { + if context.is_poisoned() || context.handle.is_none() { + return Err(Error::ContextPoisoned); + } + for operation in OPERATIONS { + qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?.validate(operation)?; + } + let required = TOTAL.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + Ok(()) +} + +fn common_pair(context: &Context<'_>, format: DenseFormat) -> Result { + let kind = ProjectionKind::Dense(format); + let (quant, project) = context.common_kernels(kind)?; + Ok(Pair { quant, project, style: ProjectionStyle::Common(kind) }) +} + +/// The gate/up projection pairs (Q4_K, Q5_K, Q6_K, IQ4_XS) and the down pairs (Q8_0, IQ4_NL). +fn projection_pairs(context: &Context<'_>) -> Result<([Pair; 4], [Pair; 2])> { + let q4 = common_pair(context, DenseFormat::Q4_K)?; + let q5 = context.q5_kernels()?; + let q6 = context.q6_kernels()?; + let xs = common_pair(context, DenseFormat::IQ4_XS)?; + let gu = [ + q4, + Pair { quant: q5.quantize, project: q5.project, style: ProjectionStyle::Q5 }, + Pair { quant: q6.quantize, project: q6.project, style: ProjectionStyle::Q6 }, + xs, + ]; + Ok((gu, [common_pair(context, DenseFormat::Q8_0)?, common_pair(context, DenseFormat::IQ4_NL)?])) } diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs index 043938ba..aeb2b99d 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl SharedExpertWorkspace (2). #[allow(unused_imports)] +use super::shared_phases::SharedStaging; use super::*; impl<'ctx> SharedExpertWorkspace<'ctx> { @@ -16,146 +17,15 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { let handles = self.handles()?; let inputs = self.inputs(activation, &weights, packed, handles)?; let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; - let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; - let mut route = staging(40)?; - for (value, out) in route_weights.iter().zip(route.as_chunks_mut::<4>().0) { - out.copy_from_slice(&value.to_le_bytes()); - } - let mut status_staging = staging(48)?; - let mut scalar_staging = staging(4)?; - let mut final_staging = staging(10240)?; - let mut values = Vec::new(); - values.try_reserve_exact(2560).map_err(|_| Error::HostAllocation)?; - values.resize(2560, 0.0); - let mut commands = Vec::new(); - commands.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?; - commands.push(Command::Guard(kernels.guard[0], 12, ffi::MmqResidentArguments::zero(handles[9], 12))); - let statuses = status_spans(handles[9])?; - append_projection( - &mut commands, - kernels.gu[weights.gu_kind[0].index()], - [inputs[1], inputs[0], handles[0]], - handles[7], - statuses[0], - 640, - 2560, - )?; - append_finite(&mut commands, kernels.guard[1], handles[0], statuses[1], 640); - append_projection( - &mut commands, - kernels.gu[weights.gu_kind[1].index()], - [inputs[2], inputs[0], handles[1]], - handles[7], - statuses[2], - 640, - 2560, - )?; - append_finite(&mut commands, kernels.guard[1], handles[1], statuses[3], 640); - self.append_qwen( - &mut commands, - kernels.qwen[0], - Operation::MoeSwiglu, - &[self.buffer(0)?, self.buffer(1)?, self.buffer(2)?], - )?; - append_finite(&mut commands, kernels.guard[1], handles[2], statuses[4], 640); - append_projection( - &mut commands, - kernels.down[weights.down_kind.index()], - [inputs[3], handles[2], handles[3]], - handles[8], - statuses[5], - 2560, - 640, - )?; - append_finite(&mut commands, kernels.guard[1], handles[3], statuses[6], 2560); - self.append_qwen( - &mut commands, - kernels.qwen[1], - Operation::MoeSharedScalar, - &[activation, weights.scalar, self.buffer(4)?], - )?; - append_finite(&mut commands, kernels.guard[1], handles[4], statuses[7], 1); - self.append_qwen( - &mut commands, - kernels.qwen[2], - Operation::MoeSharedScale, - &[self.buffer(3)?, self.buffer(4)?, self.buffer(5)?], - )?; - append_finite(&mut commands, kernels.guard[1], handles[5], statuses[8], 2560); - append_finite(&mut commands, kernels.guard[1], inputs[5], statuses[9], 25600); - append_finite(&mut commands, kernels.guard[1], handles[10], statuses[10], 10); - self.append_qwen( - &mut commands, - kernels.qwen[3], - Operation::MoeCombine, - &[packed, self.buffer(10)?, self.buffer(5)?, self.buffer(6)?], - )?; - append_finite(&mut commands, kernels.guard[1], handles[6], statuses[11], 2560); - // All exact shapes/ranges/aliases/assets and owned staging precede the first write. - let guard = match self.context.enter() { - Ok(guard) => guard, - Err(error) => { - self.failed = true; - self.context.poisoned.set(true); - return Err(error); - } - }; - let mut operation = self.context.driver.api.copy_from(handles[10], &route); - for command in &mut commands { - if operation.is_err() { - break; - } - operation = command.launch(self.context); - } - // These are blocking cuMemcpyDtoH calls, in one final drain phase, not async DMA. - if operation.is_ok() { - operation = self.context.driver.api.copy_to(handles[9], &mut status_staging); - } - if operation.is_ok() { - operation = self.context.driver.api.copy_to(handles[4], &mut scalar_staging); - } - if operation.is_ok() { - operation = self.context.driver.api.copy_to(handles[6], &mut final_staging); - } + self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let st = SharedStaging::new(route_weights)?; + let mut commands = self.shared_commands((activation, packed), &weights, (&handles, &inputs))?; + let guard = self.enter_for_drain()?; + let mut st = st; + let operation = self.drain_shared(&handles, &mut commands, &mut st); let sync = self.context.driver.api.synchronize(); let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - self.context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - std::mem::forget((commands, route, status_staging, scalar_staging, final_staging, values)); - return combine(combine(operation, sync), pop).map(|()| unreachable!("failed drain")); - } - combine(combine(operation, sync), pop)?; - let mut result = [0u32; 12]; - for (out, bytes) in result.iter_mut().zip(status_staging.as_chunks::<4>().0) { - *out = u32::from_le_bytes(*bytes); - } - if result.iter().enumerate().any(|(i, status)| { - let permitted = if matches!(i, 0 | 2 | 5) { 3 } else { 1 }; - status & !permitted != 0 - }) { - self.failed = true; - self.context.poisoned.set(true); - return Err(Error::InvalidDriverValue("shared-tail numeric witness")); - } - let scalar = f32::from_le_bytes(scalar_staging.as_chunks::<4>().0[0]); - let refusal = first_refusal(result, scalar); - for (value, bytes) in values.iter_mut().zip(final_staging.as_chunks::<4>().0) { - *value = f32::from_le_bytes(*bytes); - } - self.generation = generation; - Ok(SharedTailCompletion { - workspace: self, - _weights: weights, - _activation: activation, - _packed: packed, - statuses: result, - scalar, - refusal, - values: values.into_boxed_slice(), - generation, - }) + let st = self.settle_shared([operation, sync, pop], (commands, st))?; + self.finish_shared(st, generation, (weights, activation, packed)) } } diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs index ddbb3f32..0e853773 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs @@ -38,38 +38,47 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { let mut result = Ok(()); for buffer in &mut self.buffers { if let Some(buffer) = buffer.take() { - let release = if self.context.is_poisoned() { - std::mem::forget(buffer); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if release.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, release); + result = combine(result, release_buffer(self.context, buffer)); } } if let Some(module) = self.module.take() { - let release = if self.context.is_poisoned() { - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(guard) => { - let unload = self.context.driver.api.unload(module); - let pop = guard.finish(); - combine(unload, pop) - } - Err(error) => Err(error), - } - }; - if release.is_err() { - self.context.poisoned.set(true); - self.context.retain_driver(); - } - result = combine(result, release); + result = combine(result, self.unload_module(module)); } result } + /// Unloads the kernel module under the context guard, or leaks it on a poisoned context. + fn unload_module(&self, module: ffi::ModuleHandle) -> Result<()> { + let release = if self.context.is_poisoned() { + self.context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(guard) => { + let unload = self.context.driver.api.unload(module); + let pop = guard.finish(); + combine(unload, pop) + } + Err(error) => Err(error), + } + }; + if release.is_err() { + self.context.poisoned.set(true); + self.context.retain_driver(); + } + release + } +} + +/// A buffer is released, or leaked on a poisoned context; a failed release poisons the context. +fn release_buffer<'ctx>(context: &Context<'ctx>, buffer: DeviceBuffer<'ctx>) -> Result<()> { + let release = if context.is_poisoned() { + std::mem::forget(buffer); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if release.is_err() { + context.poisoned.set(true); + } + release } diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/shared_phases.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/shared_phases.rs new file mode 100644 index 00000000..96b93b95 --- /dev/null +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/shared_phases.rs @@ -0,0 +1,199 @@ +//! STRA-338 size: the phases of `SharedExpertWorkspace::compose`, extracted in call order. + +#[allow(unused_imports)] +use super::*; +use crate::CurrentGuard; + +/// Host buffers one compose stages through; leaked on an uncertain drain. +pub(super) struct SharedStaging { + route: Vec, + status: Vec, + scalar: Vec, + finals: Vec, + values: Vec, +} + +impl SharedStaging { + pub(super) fn new(route_weights: &[f32; 10]) -> Result { + let mut route = staging(40)?; + for (value, out) in route_weights.iter().zip(route.as_chunks_mut::<4>().0) { + out.copy_from_slice(&value.to_le_bytes()); + } + let status = staging(48)?; + let scalar = staging(4)?; + let finals = staging(10240)?; + let mut values = Vec::new(); + values.try_reserve_exact(2560).map_err(|_| Error::HostAllocation)?; + values.resize(2560, 0.0); + Ok(Self { route, status, scalar, finals, values }) + } + + /// Decodes the twelve status words; a bit outside the permitted ones is a failed witness (`None`). + fn status_words(&self) -> Option<[u32; 12]> { + let mut result = [0u32; 12]; + for (out, bytes) in result.iter_mut().zip(self.status.as_chunks::<4>().0) { + *out = u32::from_le_bytes(*bytes); + } + let bad = result.iter().enumerate().any(|(i, status)| { + let permitted = if matches!(i, 0 | 2 | 5) { 3 } else { 1 }; + status & !permitted != 0 + }); + (!bad).then_some(result) + } +} + +impl<'ctx> SharedExpertWorkspace<'ctx> { + /// The launches of one compose: gate/up projections, SwiGLU, down, scalar gate, scale and combine, each guarded. + pub(super) fn shared_commands( + &self, + (activation, packed): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + weights: &SharedExpertWeights<'_, '_>, + (handles, inputs): (&[ffi::BufferHandle; 11], &[ffi::BufferHandle; 6]), + ) -> Result> { + let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let mut commands = Vec::new(); + commands.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?; + commands.push(Command::Guard(kernels.guard[0], 12, ffi::MmqResidentArguments::zero(handles[9], 12))); + let statuses = status_spans(handles[9])?; + self.append_gate_up(&mut commands, weights, (handles, inputs), &statuses)?; + self.append_down_and_combine(&mut commands, (activation, packed), weights, (handles, inputs), &statuses)?; + Ok(commands) + } + + fn append_gate_up( + &self, + commands: &mut Vec, + weights: &SharedExpertWeights<'_, '_>, + (handles, inputs): (&[ffi::BufferHandle; 11], &[ffi::BufferHandle; 6]), + statuses: &[ffi::BufferHandle; 12], + ) -> Result<()> { + let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let gate = kernels.gu[weights.gu_kind[0].index()]; + append_projection(commands, gate, [inputs[1], inputs[0], handles[0]], handles[7], statuses[0], 640, 2560)?; + append_finite(commands, kernels.guard[1], handles[0], statuses[1], 640); + let up = kernels.gu[weights.gu_kind[1].index()]; + append_projection(commands, up, [inputs[2], inputs[0], handles[1]], handles[7], statuses[2], 640, 2560)?; + append_finite(commands, kernels.guard[1], handles[1], statuses[3], 640); + let swiglu = [self.buffer(0)?, self.buffer(1)?, self.buffer(2)?]; + self.append_qwen(commands, kernels.qwen[0], Operation::MoeSwiglu, &swiglu)?; + append_finite(commands, kernels.guard[1], handles[2], statuses[4], 640); + Ok(()) + } + + fn append_down_and_combine( + &self, + commands: &mut Vec, + (activation, packed): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + weights: &SharedExpertWeights<'_, '_>, + (handles, inputs): (&[ffi::BufferHandle; 11], &[ffi::BufferHandle; 6]), + statuses: &[ffi::BufferHandle; 12], + ) -> Result<()> { + let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let down = kernels.down[weights.down_kind.index()]; + append_projection(commands, down, [inputs[3], handles[2], handles[3]], handles[8], statuses[5], 2560, 640)?; + append_finite(commands, kernels.guard[1], handles[3], statuses[6], 2560); + let scalar = [activation, weights.scalar, self.buffer(4)?]; + self.append_qwen(commands, kernels.qwen[1], Operation::MoeSharedScalar, &scalar)?; + append_finite(commands, kernels.guard[1], handles[4], statuses[7], 1); + self.append_scale_and_combine(commands, packed, (handles, inputs), statuses) + } + + fn append_scale_and_combine( + &self, + commands: &mut Vec, + packed: &DeviceBuffer<'_>, + (handles, inputs): (&[ffi::BufferHandle; 11], &[ffi::BufferHandle; 6]), + statuses: &[ffi::BufferHandle; 12], + ) -> Result<()> { + let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let scale = [self.buffer(3)?, self.buffer(4)?, self.buffer(5)?]; + self.append_qwen(commands, kernels.qwen[2], Operation::MoeSharedScale, &scale)?; + append_finite(commands, kernels.guard[1], handles[5], statuses[8], 2560); + append_finite(commands, kernels.guard[1], inputs[5], statuses[9], 25600); + append_finite(commands, kernels.guard[1], handles[10], statuses[10], 10); + let combine = [packed, self.buffer(10)?, self.buffer(5)?, self.buffer(6)?]; + self.append_qwen(commands, kernels.qwen[3], Operation::MoeCombine, &combine)?; + append_finite(commands, kernels.guard[1], handles[6], statuses[11], 2560); + Ok(()) + } + + /// Enters the context for the drain; an enter failure fails the workspace. + pub(super) fn enter_for_drain(&mut self) -> Result> { + self.context.enter().inspect_err(|_| { + self.failed = true; + self.context.poisoned.set(true); + }) + } + + /// All exact shapes/ranges/aliases/assets and owned staging precede the first write. These are blocking + /// cuMemcpyDtoH calls, in one final drain phase, not async DMA. + pub(super) fn drain_shared( + &self, + handles: &[ffi::BufferHandle; 11], + commands: &mut [Command], + st: &mut SharedStaging, + ) -> Result<()> { + self.context.driver.api.copy_from(handles[10], &st.route)?; + for command in commands { + command.launch(self.context)?; + } + self.context.driver.api.copy_to(handles[9], &mut st.status)?; + self.context.driver.api.copy_to(handles[4], &mut st.scalar)?; + self.context.driver.api.copy_to(handles[6], &mut st.finals) + } + + /// Marks the workspace failed on any error; an uncertain drain leaks every host buffer. + pub(super) fn settle_shared( + &mut self, + [operation, sync, pop]: [Result<()>; 3], + (commands, st): (Vec, SharedStaging), + ) -> Result { + if operation.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + self.context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + std::mem::forget((commands, st)); + return combine(combine(operation, sync), pop).map(|()| unreachable!("failed drain")); + } + combine(combine(operation, sync), pop)?; + Ok(st) + } + + /// Validates the witness words and builds the completion from the drained staging. + pub(super) fn finish_shared<'lease>( + &'lease mut self, + mut st: SharedStaging, + generation: u64, + keep: (SharedExpertWeights<'lease, 'lease>, &'lease DeviceBuffer<'lease>, &'lease DeviceBuffer<'lease>), + ) -> Result> { + let Some(statuses) = st.status_words() else { + self.failed = true; + self.context.poisoned.set(true); + return Err(Error::InvalidDriverValue("shared-tail numeric witness")); + }; + let scalar = f32::from_le_bytes(st.scalar.as_chunks::<4>().0[0]); + for (value, bytes) in st.values.iter_mut().zip(st.finals.as_chunks::<4>().0) { + *value = f32::from_le_bytes(*bytes); + } + self.generation = generation; + Ok(SharedTailCompletion::assemble(self, keep, (statuses, scalar, st.values), generation)) + } +} + +impl<'lease, 'ctx> SharedTailCompletion<'lease, 'ctx> { + fn assemble( + workspace: &'lease mut SharedExpertWorkspace<'ctx>, + (_weights, _activation, _packed): ( + SharedExpertWeights<'lease, 'lease>, + &'lease DeviceBuffer<'lease>, + &'lease DeviceBuffer<'lease>, + ), + (statuses, scalar, values): ([u32; 12], f32, Vec), + generation: u64, + ) -> Self { + let refusal = first_refusal(statuses, scalar); + let values = values.into_boxed_slice(); + Self { workspace, _weights, _activation, _packed, statuses, scalar, refusal, values, generation } + } +} diff --git a/crates/cuda-driver/src/routed_resident_queue.rs b/crates/cuda-driver/src/routed_resident_queue.rs index 65837b81..1e29d8a0 100644 --- a/crates/cuda-driver/src/routed_resident_queue.rs +++ b/crates/cuda-driver/src/routed_resident_queue.rs @@ -58,6 +58,7 @@ enum Command { #[path = "routed_resident_queue_gpu.rs"] mod gpu; +mod compose_phases; mod impl_drop_for_routedresidentqueue; mod impl_routedresidentcompletion; mod impl_routedresidentqueue; diff --git a/crates/cuda-driver/src/routed_resident_queue/compose_phases.rs b/crates/cuda-driver/src/routed_resident_queue/compose_phases.rs new file mode 100644 index 00000000..b3647299 --- /dev/null +++ b/crates/cuda-driver/src/routed_resident_queue/compose_phases.rs @@ -0,0 +1,273 @@ +//! STRA-338 size: the phases of `RoutedResidentQueue::compose`, extracted in call order. + +#[allow(unused_imports)] +use super::*; + +/// Device spans of one routed-resident compose. +pub(super) struct ComposeSpans { + pub(super) t: usize, + pub(super) wh: [ffi::BufferHandle; 3], + pub(super) outputs: [ffi::BufferHandle; 4], + pub(super) table: ffi::BufferHandle, + pub(super) q8: ffi::BufferHandle, + pub(super) flags: [ffi::BufferHandle; 5], +} + +/// Host buffers of one compose; leaked on an uncertain drain. +pub(super) struct ComposeHostBuffers { + pub(super) commands: Vec, + pub(super) pointers: Vec, + pub(super) staging: Vec, +} + +/// The two gate/up kernels' operations and the down kernel's, from the weight formats. +pub(super) fn compose_operations( + weights: &RoutedResidentWeights<'_, '_>, + t: usize, +) -> Result<([FixedOperation; 2], FixedOperation)> { + if !(1..=64).contains(&t) { + return Err(Error::InvalidProjectionShape); + } + let ops = [gu_operation(weights.gu_formats[0], t)?, gu_operation(weights.gu_formats[1], t)?]; + let down_op = match weights.down_format { + RoutedFormat::IQ4_NL => FixedOperation::GroupedDownIq4, + RoutedFormat::Q2_0 => FixedOperation::GroupedDownQ2, + _ => return Err(Error::UnsupportedProjection), + }; + Ok((ops, down_op)) +} + +/// Output `i` must not overlap any weight or an earlier output. +fn check_outputs_clear( + outputs: &[ffi::BufferHandle; 4], + sizes: &[usize; 4], + wh: &[ffi::BufferHandle; 3], + weight_bytes: [usize; 3], +) -> Result<()> { + for (i, &out) in outputs.iter().enumerate() { + for (&weight, bytes) in wh.iter().zip(weight_bytes) { + if out.overlaps(sizes[i], weight, bytes) { + return Err(Error::OutputAliasesInput); + } + } + for j in 0..i { + if out.overlaps(sizes[i], outputs[j], sizes[j]) { + return Err(Error::OutputAliasesInput); + } + } + } + Ok(()) +} + +impl<'ctx> RoutedResidentQueue<'ctx> { + /// All device spans of a compose and the column pointer table, each admitted against the internal buffers. + pub(super) fn compose_spans( + &self, + (weights, columns): (&RoutedResidentWeights<'_, '_>, &[&RoutedGateUpQ8<'_>]), + outs: [&DeviceBuffer<'_>; 4], + internal: [ffi::BufferHandle; 3], + ) -> Result<(ComposeSpans, Vec)> { + let t = columns.len(); + let wh = self.weight_handles(weights, internal)?; + let weight_bytes = [weights.gate.bytes, weights.up.bytes, weights.down.bytes]; + let (outputs, sizes) = self.output_handles(outs, (t, internal), (&wh, weight_bytes))?; + let pointers = self.column_pointers(columns, (&outputs, &sizes), internal)?; + Ok((ComposeSpans::new(t, (wh, outputs), internal)?, pointers)) + } + + fn weight_handles( + &self, + weights: &RoutedResidentWeights<'_, '_>, + internal: [ffi::BufferHandle; 3], + ) -> Result<[ffi::BufferHandle; 3]> { + let mut wh = [None; 3]; + for (i, (buffer, format, rows, cols)) in [ + (weights.gate, weights.gu_formats[0], 640, 2560), + (weights.up, weights.gu_formats[1], 640, 2560), + (weights.down, weights.down_format, 2560, 640), + ] + .into_iter() + .enumerate() + { + let kind = ProjectionKind::Routed(format); + let shape = projection_shape(ProjectionSpec { kind, rows, columns: cols })?; + wh[i] = Some(self.input(buffer, shape.weight_bytes, kind.weight_alignment(), internal)?); + } + Ok(wh.map(|h| h.expect("three whole checked weights"))) + } + + /// The four output spans (gate, up, hidden, down) of `t` columns, each clear of the weights and of each other. + pub(super) fn output_handles( + &self, + outs: [&DeviceBuffer<'_>; 4], + (t, internal): (usize, [ffi::BufferHandle; 3]), + (wh, weight_bytes): (&[ffi::BufferHandle; 3], [usize; 3]), + ) -> Result<([ffi::BufferHandle; 4], [usize; 4])> { + let outputs = [ + self.input(outs[0], t * 2560, 4, internal)?, + self.input(outs[1], t * 2560, 4, internal)?, + self.input(outs[2], t * 2560, 4, internal)?, + self.input(outs[3], t * 10240, 4, internal)?, + ]; + let sizes = [t * 2560, t * 2560, t * 2560, t * 10240]; + check_outputs_clear(&outputs, &sizes, wh, weight_bytes)?; + Ok((outputs, sizes)) + } + + /// The little-endian table of the columns' Q8 scratch addresses; every column input must clear the outputs. + pub(super) fn column_pointers( + &self, + columns: &[&RoutedGateUpQ8<'_>], + (outputs, sizes): (&[ffi::BufferHandle; 4], &[usize; 4]), + internal: [ffi::BufferHandle; 3], + ) -> Result> { + let mut pointers = Vec::new(); + pointers.try_reserve_exact(columns.len() * 8).map_err(|_| Error::HostAllocation)?; + for column in columns { + let scratch = column.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + let activation = self.input(column.activation, 10240, 4, internal)?; + let q8 = self.input(scratch, 2880, 4, internal)?; + if self.context.common_quantizer.get().is_none() { + return Err(Error::InvalidProjectionShape); + } + for (input, size) in [(activation, 10240), (q8, 2880)] { + if outputs.iter().zip(sizes).any(|(out, bytes)| out.overlaps(*bytes, input, size)) { + return Err(Error::OutputAliasesInput); + } + } + pointers.extend_from_slice(&q8.qwen_address().to_le_bytes()); + } + Ok(pointers) + } + + /// The five fixed kernels, looked up under the context guard; a failed pop poisons the queue. + pub(super) fn compose_kernels( + &mut self, + ops: [FixedOperation; 2], + down_op: FixedOperation, + ) -> Result<[ffi::FunctionHandle; 5]> { + self.finite.ok_or(Error::ContextPoisoned)?; + let guard = self.context.enter()?; + let kernels = self.lookup_kernels(ops, down_op); + let pop = guard.finish(); + if pop.is_err() { + self.failed = true; + self.context.poisoned.set(true); + } + combine(kernels, pop) + } + + fn lookup_kernels(&self, ops: [FixedOperation; 2], down_op: FixedOperation) -> Result<[ffi::FunctionHandle; 5]> { + Ok([ + self.context.fixed_kernel(ops[0])?.function, + self.context.fixed_kernel(ops[1])?.function, + self.context.fixed_kernel(FixedOperation::GroupedSwiglu)?.function, + self.context.fixed_kernel(FixedOperation::CommonQuantize)?.function, + self.context.fixed_kernel(down_op)?.function, + ]) + } + + /// Ten commands include reset plus every original producer/finite scan. + pub(super) fn compose_commands( + &self, + sp: &ComposeSpans, + kernels: [ffi::FunctionHandle; 5], + status: ffi::BufferHandle, + ) -> Result> { + let finite = self.finite.ok_or(Error::ContextPoisoned)?; + let (t, wh, outputs, table, flags) = (sp.t, &sp.wh, &sp.outputs, sp.table, &sp.flags); + let mut commands = Vec::new(); + commands.try_reserve_exact(10).map_err(|_| Error::HostAllocation)?; + commands.push(Command::Finite(finite[0], 5, ffi::MmqResidentArguments::zero(status, 5))); + let gate = ffi::ProjectionArguments::new(wh[0], table, outputs[0], 640, 2560); + commands.push(Command::Gu(kernels[0], t as u32, gate)); + commands.push(scan(finite[1], outputs[0], flags[0], (640 * t) as u32)); + let up = ffi::ProjectionArguments::new(wh[1], table, outputs[1], 640, 2560); + commands.push(Command::Gu(kernels[1], t as u32, up)); + commands.push(scan(finite[1], outputs[1], flags[1], (640 * t) as u32)); + let swiglu = ffi::ProjectionArguments::new(outputs[0], outputs[1], outputs[2], 640, 640); + commands.push(Command::Swiglu(kernels[2], t as u32, swiglu)); + commands.push(scan(finite[1], outputs[2], flags[2], (640 * t) as u32)); + let quant = ffi::Q8QuantizeArguments::new(outputs[2], sp.q8, flags[3], (640 * t) as u32); + commands.push(Command::Quant(kernels[3], (640 * t).div_ceil(256) as u32, quant)); + let down = ffi::ProjectionArguments::new(wh[2], sp.q8, outputs[3], 2560, 640); + commands.push(Command::Down(kernels[4], t as u32, down)); + commands.push(scan(finite[1], outputs[3], flags[4], (2560 * t) as u32)); + Ok(commands) + } + + /// Uploads the column table, launches every command and reads the five status words back. + pub(super) fn drain_compose( + &mut self, + (table, status): (ffi::BufferHandle, ffi::BufferHandle), + mut bufs: ComposeHostBuffers, + ) -> Result<[u32; 5]> { + let guard = self.context.enter()?; + let operation = self.drain_ops(table, status, &mut bufs); + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + self.context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + // Real host ABI/staging owners and all device buffers remain retained + // by poison; no receipt exists for unknown completion. + std::mem::forget(bufs); + return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain drain")); + } + combine(combine(operation, sync), pop)?; + let mut result = [0; 5]; + for (value, bytes) in result.iter_mut().zip(bufs.staging.as_chunks::<4>().0) { + *value = u32::from_le_bytes(*bytes); + } + Ok(result) + } + + fn drain_ops( + &self, + table: ffi::BufferHandle, + status: ffi::BufferHandle, + bufs: &mut ComposeHostBuffers, + ) -> Result<()> { + self.context.driver.api.copy_from(table, &bufs.pointers)?; + for command in &mut bufs.commands { + command.launch(self.context)?; + } + self.context.driver.api.copy_to(status, &mut bufs.staging) + } + + /// A status word above its bound is a failed numeric witness and fails the queue. + pub(super) fn check_witness(&mut self, result: [u32; 5]) -> Result<()> { + if result.iter().enumerate().any(|(i, &v)| if i == 3 { v > 3 } else { v > 1 }) { + self.failed = true; + self.context.poisoned.set(true); + return Err(Error::InvalidDriverValue("routed resident numeric witness")); + } + Ok(()) + } +} + +/// The zeroed host staging of the five status words. +pub(super) fn zeroed_staging() -> Result> { + let mut staging = Vec::new(); + staging.try_reserve_exact(STATUS).map_err(|_| Error::HostAllocation)?; + staging.resize(STATUS, 0); + Ok(staging) +} + +impl ComposeSpans { + pub(super) fn new( + t: usize, + (wh, outputs): ([ffi::BufferHandle; 3], [ffi::BufferHandle; 4]), + internal: [ffi::BufferHandle; 3], + ) -> Result { + let table = internal[0].checked_subspan(TABLE, 0, t * 8)?; + table.validate_projection_extent(t * 8, 8)?; + let q8 = internal[1].checked_subspan(Q8, 0, t * 720)?; + q8.validate_projection_extent(t * 720, 4)?; + let flags: [ffi::BufferHandle; 5] = + std::array::from_fn(|i| internal[2].checked_subspan(STATUS, i * 4, 4).expect("five fixed checked words")); + Ok(Self { t, wh, outputs, table, q8, flags }) + } +} diff --git a/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentcompletion.rs b/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentcompletion.rs index aeb7c115..86195de7 100644 --- a/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentcompletion.rs +++ b/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentcompletion.rs @@ -42,49 +42,55 @@ impl<'ctx> Context<'ctx> { finite: None, failed: false, }; - let operation = (|| { - owner.table = Some(self.allocate(TABLE)?); - owner.q8 = Some(self.allocate(Q8)?); - owner.status = Some(self.allocate(STATUS)?); - let guard = self.enter()?; - let load = (|| { - // Original modules are actor-owned/cached. Warm them before lazy fills. - for operation in [ - FixedOperation::GroupedIq3, - FixedOperation::GroupedIq2, - FixedOperation::GroupedIq3S, - FixedOperation::GroupedIq3SNc4, - FixedOperation::GroupedIq4Xs, - FixedOperation::GroupedIq4XsNc4, - FixedOperation::GroupedSwiglu, - FixedOperation::CommonQuantize, - FixedOperation::GroupedDownIq4, - FixedOperation::GroupedDownQ2, - ] { - self.fixed_kernel(operation)?; - } - let module = self.driver.api.load_mmq_resident()?; - owner.module = Some(module); - owner.finite = Some([ - self.driver.api.mmq_resident_function(module, 0)?, - self.driver.api.mmq_resident_function(module, 1)?, - ]); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - self.poisoned.set(true); - } - combine(load, pop)?; - owner.handles()?; - if self.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - match operation { + match owner.init_resources() { Ok(()) => Ok(owner), Err(primary) => combine(Err(primary), owner.close()), } } } +impl<'ctx> RoutedResidentQueue<'ctx> { + /// Allocates the table, Q8 and status buffers, warms the kernels under the context guard and re-checks memory. + fn init_resources(&mut self) -> Result<()> { + let context = self.context; + self.table = Some(context.allocate(TABLE)?); + self.q8 = Some(context.allocate(Q8)?); + self.status = Some(context.allocate(STATUS)?); + let guard = context.enter()?; + let load = self.load_kernels(); + let pop = guard.finish(); + if pop.is_err() { + context.poisoned.set(true); + } + combine(load, pop)?; + self.handles()?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + fn load_kernels(&mut self) -> Result<()> { + let context = self.context; + // Original modules are actor-owned/cached. Warm them before lazy fills. + for operation in [ + FixedOperation::GroupedIq3, + FixedOperation::GroupedIq2, + FixedOperation::GroupedIq3S, + FixedOperation::GroupedIq3SNc4, + FixedOperation::GroupedIq4Xs, + FixedOperation::GroupedIq4XsNc4, + FixedOperation::GroupedSwiglu, + FixedOperation::CommonQuantize, + FixedOperation::GroupedDownIq4, + FixedOperation::GroupedDownQ2, + ] { + context.fixed_kernel(operation)?; + } + let module = context.driver.api.load_mmq_resident()?; + self.module = Some(module); + self.finite = Some([ + context.driver.api.mmq_resident_function(module, 0)?, + context.driver.api.mmq_resident_function(module, 1)?, + ]); + Ok(()) + } +} diff --git a/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentqueue.rs b/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentqueue.rs index e2a16632..b4d938c5 100644 --- a/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentqueue.rs +++ b/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentqueue.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl RoutedResidentQueue. #[allow(unused_imports)] +use super::compose_phases::{ComposeHostBuffers, compose_operations, zeroed_staging}; use super::*; impl<'ctx> RoutedResidentQueue<'ctx> { @@ -18,25 +19,34 @@ impl<'ctx> RoutedResidentQueue<'ctx> { for (i, (buffer, size, align)) in [(&self.table, TABLE, 8), (&self.q8, Q8, 4), (&self.status, STATUS, 4)].into_iter().enumerate() { - let buffer = buffer.as_ref().ok_or(Error::ContextPoisoned)?; - if !std::ptr::eq(buffer.context, self.context) { - return Err(Error::ContextMismatch); - } - if buffer.bytes != size { - return Err(Error::InvalidProjectionShape); - } - let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_projection_extent(size, align)?; - for (j, prior) in out.iter().enumerate().take(i) { - let bytes = [TABLE, Q8, STATUS][j]; - if handle.overlaps(size, prior.ok_or(Error::ContextPoisoned)?, bytes) { - return Err(Error::OutputAliasesInput); - } - } - out[i] = Some(handle); + out[i] = Some(self.checked_owner(buffer, (size, align), &out[..i])?); } Ok(out.map(|h| h.expect("three validated whole owners"))) } + /// A whole internal owner of this context with exactly `size` bytes, overlapping no earlier owner. + fn checked_owner( + &self, + buffer: &Option>, + (size, align): (usize, u64), + prior: &[Option], + ) -> Result { + let buffer = buffer.as_ref().ok_or(Error::ContextPoisoned)?; + if !std::ptr::eq(buffer.context, self.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != size { + return Err(Error::InvalidProjectionShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(size, align)?; + for (j, prior) in prior.iter().enumerate() { + let bytes = [TABLE, Q8, STATUS][j]; + if handle.overlaps(size, prior.ok_or(Error::ContextPoisoned)?, bytes) { + return Err(Error::OutputAliasesInput); + } + } + Ok(handle) + } pub(super) fn input( &self, buffer: &DeviceBuffer<'_>, @@ -73,159 +83,15 @@ impl<'ctx> RoutedResidentQueue<'ctx> { ) -> Result> { let internal = self.handles()?; let t = columns.len(); - if !(1..=64).contains(&t) { - return Err(Error::InvalidProjectionShape); - } - let ops = [gu_operation(weights.gu_formats[0], t)?, gu_operation(weights.gu_formats[1], t)?]; - let down_op = match weights.down_format { - RoutedFormat::IQ4_NL => FixedOperation::GroupedDownIq4, - RoutedFormat::Q2_0 => FixedOperation::GroupedDownQ2, - _ => return Err(Error::UnsupportedProjection), - }; - let mut wh = [None; 3]; - for (i, (buffer, format, rows, cols)) in [ - (weights.gate, weights.gu_formats[0], 640, 2560), - (weights.up, weights.gu_formats[1], 640, 2560), - (weights.down, weights.down_format, 2560, 640), - ] - .into_iter() - .enumerate() - { - let kind = ProjectionKind::Routed(format); - let shape = projection_shape(ProjectionSpec { kind, rows, columns: cols })?; - wh[i] = Some(self.input(buffer, shape.weight_bytes, kind.weight_alignment(), internal)?); - } - let wh = wh.map(|h| h.expect("three whole checked weights")); - let outputs = [ - self.input(gate, t * 2560, 4, internal)?, - self.input(up, t * 2560, 4, internal)?, - self.input(hidden, t * 2560, 4, internal)?, - self.input(down, t * 10240, 4, internal)?, - ]; - let output_sizes = [t * 2560, t * 2560, t * 2560, t * 10240]; - for (i, &out) in outputs.iter().enumerate() { - for (&weight, bytes) in wh.iter().zip([weights.gate.bytes, weights.up.bytes, weights.down.bytes]) { - if out.overlaps(output_sizes[i], weight, bytes) { - return Err(Error::OutputAliasesInput); - } - } - for j in 0..i { - if out.overlaps(output_sizes[i], outputs[j], output_sizes[j]) { - return Err(Error::OutputAliasesInput); - } - } - } - let mut pointers = Vec::new(); - pointers.try_reserve_exact(t * 8).map_err(|_| Error::HostAllocation)?; - for column in columns { - let scratch = column.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - let activation = self.input(column.activation, 10240, 4, internal)?; - let q8 = self.input(scratch, 2880, 4, internal)?; - if self.context.common_quantizer.get().is_none() { - return Err(Error::InvalidProjectionShape); - } - for (input, size) in [(activation, 10240), (q8, 2880)] { - for (out, bytes) in outputs.into_iter().zip(output_sizes) { - if out.overlaps(bytes, input, size) { - return Err(Error::OutputAliasesInput); - } - } - } - pointers.extend_from_slice(&q8.qwen_address().to_le_bytes()); - } - let table = internal[0].checked_subspan(TABLE, 0, t * 8)?; - table.validate_projection_extent(t * 8, 8)?; - let q8 = internal[1].checked_subspan(Q8, 0, t * 720)?; - q8.validate_projection_extent(t * 720, 4)?; - let flags: [ffi::BufferHandle; 5] = - std::array::from_fn(|i| internal[2].checked_subspan(STATUS, i * 4, 4).expect("five fixed checked words")); - let finite = self.finite.ok_or(Error::ContextPoisoned)?; - let guard = self.context.enter()?; - let kernels = (|| { - Ok([ - self.context.fixed_kernel(ops[0])?.function, - self.context.fixed_kernel(ops[1])?.function, - self.context.fixed_kernel(FixedOperation::GroupedSwiglu)?.function, - self.context.fixed_kernel(FixedOperation::CommonQuantize)?.function, - self.context.fixed_kernel(down_op)?.function, - ]) - })(); - let pop = guard.finish(); - if pop.is_err() { - self.failed = true; - self.context.poisoned.set(true); - } - let kernels = combine(kernels, pop)?; - let mut commands = Vec::new(); - commands.try_reserve_exact(10).map_err(|_| Error::HostAllocation)?; - commands.push(Command::Finite(finite[0], 5, ffi::MmqResidentArguments::zero(internal[2], 5))); - commands.push(Command::Gu( - kernels[0], - t as u32, - ffi::ProjectionArguments::new(wh[0], table, outputs[0], 640, 2560), - )); - commands.push(scan(finite[1], outputs[0], flags[0], (640 * t) as u32)); - commands.push(Command::Gu( - kernels[1], - t as u32, - ffi::ProjectionArguments::new(wh[1], table, outputs[1], 640, 2560), - )); - commands.push(scan(finite[1], outputs[1], flags[1], (640 * t) as u32)); - commands.push(Command::Swiglu( - kernels[2], - t as u32, - ffi::ProjectionArguments::new(outputs[0], outputs[1], outputs[2], 640, 640), - )); - commands.push(scan(finite[1], outputs[2], flags[2], (640 * t) as u32)); - commands.push(Command::Quant( - kernels[3], - (640 * t).div_ceil(256) as u32, - ffi::Q8QuantizeArguments::new(outputs[2], q8, flags[3], (640 * t) as u32), - )); - commands.push(Command::Down( - kernels[4], - t as u32, - ffi::ProjectionArguments::new(wh[2], q8, outputs[3], 2560, 640), - )); - commands.push(scan(finite[1], outputs[3], flags[4], (2560 * t) as u32)); - // Ten commands include reset plus every original producer/finite scan. - let mut staging = Vec::new(); - staging.try_reserve_exact(STATUS).map_err(|_| Error::HostAllocation)?; - staging.resize(STATUS, 0); - let guard = self.context.enter()?; - let mut operation = self.context.driver.api.copy_from(table, &pointers); - for command in &mut commands { - if operation.is_err() { - break; - } - operation = command.launch(self.context); - } - if operation.is_ok() { - operation = self.context.driver.api.copy_to(internal[2], &mut staging); - } - let sync = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - self.context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - // Real host ABI/staging owners and all device buffers remain retained - // by poison; no receipt exists for unknown completion. - std::mem::forget((commands, pointers, staging)); - return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain drain")); - } - combine(combine(operation, sync), pop)?; - let mut result = [0; 5]; - for (value, bytes) in result.iter_mut().zip(staging.as_chunks::<4>().0) { - *value = u32::from_le_bytes(*bytes); - } - if result.iter().enumerate().any(|(i, &v)| if i == 3 { v > 3 } else { v > 1 }) { - self.failed = true; - self.context.poisoned.set(true); - return Err(Error::InvalidDriverValue("routed resident numeric witness")); - } - Ok(RoutedResidentCompletion { owner: self, hidden, down, flags: result }) + let (ops, down_op) = compose_operations(&weights, t)?; + let outs = [&*gate, &*up, &*hidden, &*down]; + let (spans, pointers) = self.compose_spans((&weights, columns), outs, internal)?; + let kernels = self.compose_kernels(ops, down_op)?; + let commands = self.compose_commands(&spans, kernels, internal[2])?; + let bufs = ComposeHostBuffers { commands, pointers, staging: zeroed_staging()? }; + let flags = self.drain_compose((spans.table, internal[2]), bufs)?; + self.check_witness(flags)?; + Ok(RoutedResidentCompletion { owner: self, hidden, down, flags }) } pub fn close(mut self) -> Result<()> { self.release() diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt.rs index 4a8e3c19..c1bc29b5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt.rs @@ -25,3 +25,5 @@ pub(crate) use prompt_stream_settings_fn::span_cache_enabled; mod impl_moeweightcache; #[path = "cache_original_prompt/impl_moeweightcache_2.rs"] mod impl_moeweightcache_2; +#[path = "cache_original_prompt/prompt_layer_fns.rs"] +mod prompt_layer_fns; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache.rs index 048be569..174b7c03 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache.rs @@ -25,6 +25,23 @@ impl<'ctx> MoeWeightCache<'ctx> { binding_error(e) })?; crate::bringup_trace!("DBG arena: members ok ({})", members.len()); + let workspace = Self::arena_workspace(context, capacity)?; + let mut cache = Self::assemble_mmq_with_mtp_experts(binding, context, workspace, mtp_pack_experts) + .inspect_err(|e| { + crate::bringup_trace!("DBG arena assemble_mmq err: {e:?}"); + })?; + crate::bringup_trace!("DBG arena: assemble_mmq ok"); + cache.original_prompt_mmq = true; + cache.mmq_policy = MmqRoutingPolicy::NativeIntegerIq3; + if let Err(primary) = cache.attach_arena_owners(binding, context, options, capacity, lease, members) { + let _ = cache.close(); + return Err(primary); + } + Ok(cache) + } + + /// The original-formats integer MMQ workspace with its expert group arena enabled. + fn arena_workspace(context: &'ctx Context<'ctx>, capacity: u32) -> Result> { let mut workspace = context.native_integer_iq3_mmq_original_formats_workspace().map_err(|e| { crate::bringup_trace!("DBG arena step 1 driver err: {e:?}"); driver_error(e) @@ -34,68 +51,51 @@ impl<'ctx> MoeWeightCache<'ctx> { return Err(driver_error(primary)); } crate::bringup_trace!("DBG arena: workspace+group arena ok"); - let mut cache = match Self::assemble_mmq_with_mtp_experts(binding, context, workspace, mtp_pack_experts) { - Ok(c) => c, - Err(e) => { - crate::bringup_trace!("DBG arena assemble_mmq err: {e:?}"); - return Err(e); - } - }; - crate::bringup_trace!("DBG arena: assemble_mmq ok"); - cache.original_prompt_mmq = true; - cache.mmq_policy = MmqRoutingPolicy::NativeIntegerIq3; - let result = (|| { - // Create persistent actual streams/events before model cache fills. - // Slot count comes from the same options used to carve the arena. - cache.original_copy_schedule = Some( - context - .original_mmq_copy_schedule(options.original_ring_slots().map_err(|e| { - crate::bringup_trace!("DBG arena step 2 driver err: {e:?}"); - driver_error(e) - })?) - .map_err(|e| { - crate::bringup_trace!("DBG arena step 3 driver err: {e:?}"); - driver_error(e) - })?, - ); - cache.original_prompt_device = - Some(context.original_moe_prompt_device(capacity as usize).map_err(|e| { - crate::bringup_trace!("DBG arena step 4 driver err: {e:?}"); - driver_error(e) - })?); - cache.original_expert_bank = Some(Rc::new(context.mapped_expert_bank(lease, members).map_err(|e| { - crate::bringup_trace!("DBG arena step 5 driver err: {e:?}"); - driver_error(e) - })?)); - let schedule = cache.original_copy_schedule.as_ref().ok_or(Error::IdentityMismatch)?; - let bank = cache.original_expert_bank.as_ref().ok_or(Error::IdentityMismatch)?; - cache.original_prompt_metadata_bytes = schedule - .metadata_bytes() - .map_err(|e| { - crate::bringup_trace!("DBG arena step 6 driver err: {e:?}"); - driver_error(e) - })? - .checked_add(bank.metadata_bytes()) - .and_then(|n| n.checked_add(leleka_cuda_driver::OriginalPromptLeaseIdentity::metadata_bytes())) - .ok_or(Error::Overflow)?; - if cache.original_prompt_metadata_bytes > 16 << 20 { - return Err(Error::InputAllocation); - } - crate::bringup_trace!("DBG arena: schedule/device/bank ok"); - cache.room(0).map_err(|e| { - crate::bringup_trace!("DBG arena room err: {e:?}"); - e - })?; - cache.validate(binding, context).map_err(|e| { - crate::bringup_trace!("DBG arena validate err: {e:?}"); - e - }) - })(); - if let Err(primary) = result { - let _ = cache.close(); - return Err(primary); + Ok(workspace) + } + + /// The copy schedule, prompt device and registered bank, then the metadata charge, room and validation. + fn attach_arena_owners( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + options: leleka_cuda_driver::PrefillLayoutOptions, + capacity: u32, + lease: leleka_model_format::qwen4exp::ResidentExpertBankLease, + members: Vec, + ) -> Result<()> { + // Create persistent actual streams/events before model cache fills. + // Slot count comes from the same options used to carve the arena. + let slots = options.original_ring_slots().map_err(|e| arena_driver_error(2, e))?; + self.original_copy_schedule = + Some(context.original_mmq_copy_schedule(slots).map_err(|e| arena_driver_error(3, e))?); + let device = context.original_moe_prompt_device(capacity as usize).map_err(|e| arena_driver_error(4, e))?; + self.original_prompt_device = Some(device); + let bank = context.mapped_expert_bank(lease, members).map_err(|e| arena_driver_error(5, e))?; + self.original_expert_bank = Some(Rc::new(bank)); + self.charge_prompt_metadata()?; + crate::bringup_trace!("DBG arena: schedule/device/bank ok"); + self.room(0).inspect_err(|e| { + crate::bringup_trace!("DBG arena room err: {e:?}"); + })?; + self.validate(binding, context).inspect_err(|e| { + crate::bringup_trace!("DBG arena validate err: {e:?}"); + }) + } + + fn charge_prompt_metadata(&mut self) -> Result<()> { + let schedule = self.original_copy_schedule.as_ref().ok_or(Error::IdentityMismatch)?; + let bank = self.original_expert_bank.as_ref().ok_or(Error::IdentityMismatch)?; + self.original_prompt_metadata_bytes = schedule + .metadata_bytes() + .map_err(|e| arena_driver_error(6, e))? + .checked_add(bank.metadata_bytes()) + .and_then(|n| n.checked_add(leleka_cuda_driver::OriginalPromptLeaseIdentity::metadata_bytes())) + .ok_or(Error::Overflow)?; + if self.original_prompt_metadata_bytes > 16 << 20 { + return Err(Error::InputAllocation); } - Ok(cache) + Ok(()) } /// Start (`true`: zeroed counts) or stop collecting the prompt chunks' routed rows per (layer, expert). @@ -137,36 +137,38 @@ impl<'ctx> MoeWeightCache<'ctx> { let bound = binding.moe_expert_weights(layer, selected).map_err(binding_error)?; let members = [(&bound, 0)]; binding.with_moe_routed_source(&members, binding_error, |source| { - let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; - let operation = (|| { - source.validate_binding(binding).map_err(binding_error)?; - for role in roles { - let key = source.descriptor(0, role).map_err(binding_error)?; - if key.layer != layer || key.expert != Some(expert) { - return Err(Error::IdentityMismatch); - } - } - let spans = [ - source.mapped_span(0, roles[0]).map_err(binding_error)?, - source.mapped_span(0, roles[1]).map_err(binding_error)?, - source.mapped_span(0, roles[2]).map_err(binding_error)?, - ]; - if !bank.eligible(&spans) { - return Err(Error::IdentityMismatch); - } - Ok(spans) - })(); + let operation = Self::expert_source_spans(binding, bank, source, layer, expert); let finish = source.finish().map_err(binding_error); - match operation { - Err(e) => Err(e), - Ok(v) => { - finish?; - Ok(v) - } - } + operation.and_then(|spans| finish.map(|()| spans)) }) } + fn expert_source_spans( + binding: &ModelBinding, + bank: &leleka_cuda_driver::MappedExpertBank<'ctx>, + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>, + layer: u32, + expert: u32, + ) -> Result<[ResidentExpertBankSpan; 3]> { + let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + source.validate_binding(binding).map_err(binding_error)?; + for role in roles { + let key = source.descriptor(0, role).map_err(binding_error)?; + if key.layer != layer || key.expert != Some(expert) { + return Err(Error::IdentityMismatch); + } + } + let spans = [ + source.mapped_span(0, roles[0]).map_err(binding_error)?, + source.mapped_span(0, roles[1]).map_err(binding_error)?, + source.mapped_span(0, roles[2]).map_err(binding_error)?, + ]; + if !bank.eligible(&spans) { + return Err(Error::IdentityMismatch); + } + Ok(spans) + } + /// Resolve genuine whole shared G/U/D/scalar buffers before lending any of /// them to the device program. Protect all four against cache eviction. pub(in super::super) fn original_shared_layer( @@ -179,30 +181,53 @@ impl<'ctx> MoeWeightCache<'ctx> { if !weights.matches(&binding.identity(), layer.get()) { return Err(Error::IdentityMismatch); } - let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; - let keys = [ - binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[0]).map_err(binding_error)?, - binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[1]).map_err(binding_error)?, - binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[2]).map_err(binding_error)?, - binding.moe_shared_scalar_descriptor(&weights).map_err(binding_error)?, - ]; - crate::qwen_forward::shared_expert_workspace::validate_descriptors(&keys)?; - if keys.iter().any(|key| key.layer != layer.get()) { - return Err(Error::IdentityMismatch); - } + let keys = shared_descriptors(binding, &weights, layer)?; for (i, key) in keys.iter().enumerate() { - let _ = self.main_entry_protected(*key, &keys, || { - if i == 3 { - binding.moe_shared_scalar(&weights).map_err(binding_error) - } else { - Ok(binding - .moe_expert_block(&weights, MoeExpertSelection::Shared, roles[i], 0, key.rows) - .map_err(binding_error)? - .into_bytes()) - } - })?; + let _ = self.main_entry_protected(*key, &keys, || shared_bytes(binding, &weights, i, key))?; } self.room_protected(0, &keys)?; Ok(keys) } } + +fn arena_driver_error(step: u8, error: leleka_cuda_driver::Error) -> Error { + crate::bringup_trace!("DBG arena step {step} driver err: {error:?}"); + driver_error(error) +} + +/// The shared Gate/Up/Down descriptors and the scalar gate of one layer, all bound to that layer. +fn shared_descriptors( + binding: &ModelBinding, + weights: &MoeExpertWeights, + layer: LayerId, +) -> Result<[MoeWeightDescriptor; 4]> { + let shared = MoeExpertSelection::Shared; + let keys = [ + binding.moe_weight_descriptor(weights, shared, MoeMatrixRole::Gate).map_err(binding_error)?, + binding.moe_weight_descriptor(weights, shared, MoeMatrixRole::Up).map_err(binding_error)?, + binding.moe_weight_descriptor(weights, shared, MoeMatrixRole::Down).map_err(binding_error)?, + binding.moe_shared_scalar_descriptor(weights).map_err(binding_error)?, + ]; + crate::qwen_forward::shared_expert_workspace::validate_descriptors(&keys)?; + if keys.iter().any(|key| key.layer != layer.get()) { + return Err(Error::IdentityMismatch); + } + Ok(keys) +} + +/// The host bytes of shared matrix `index` (the scalar gate is index 3). +fn shared_bytes( + binding: &ModelBinding, + weights: &MoeExpertWeights, + index: usize, + key: &MoeWeightDescriptor, +) -> Result> { + if index == 3 { + return binding.moe_shared_scalar(weights).map_err(binding_error); + } + let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + Ok(binding + .moe_expert_block(weights, MoeExpertSelection::Shared, roles[index], 0, key.rows) + .map_err(binding_error)? + .into_bytes()) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache_2.rs index 0e964041..c3959068 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache_2.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl MoeWeightCache (2). #[allow(unused_imports)] +use super::prompt_layer_fns::{PromptIo, PromptParts, SpanScan, run_prompt_layer}; use super::*; impl<'ctx> MoeWeightCache<'ctx> { @@ -16,6 +17,52 @@ impl<'ctx> MoeWeightCache<'ctx> { read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, shared: &mut NativeBatchWorkspace<'ctx>, ) -> Result> { + self.original_prompt_precheck(binding, dense)?; + let keys = self.original_shared_layer(binding, layer)?; + let formats = shared_formats(&keys)?; + let bank = Rc::clone(self.original_expert_bank.as_ref().ok_or(Error::IdentityMismatch)?); + let context = self.context; + let PromptParts { mut io, mut scan, weights } = + self.original_prompt_parts(binding, dense, layer, &bank, &keys)?; + let result = run_prompt_layer(&mut io, &mut scan, read, shared, weights, formats); + if result.is_err() { + // the stream never outlives a failed layer + let _ = io.schedule.end_prompt_stream(); + } + if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { + self.failed.set(true); + } + result + } + + /// Borrow the disjoint cache owners one layer drives: the shared weights, the copy ring and the span state. + fn original_prompt_parts<'s>( + &'s mut self, + binding: &'s ModelBinding, + dense: &'s DenseWeightCache<'ctx>, + layer: LayerId, + bank: &'s Rc>, + keys: &[MoeWeightDescriptor; 4], + ) -> Result> { + let router = dense.router(binding, layer.get())?; + let main = &self.main; + let weights = shared_weights(router, main, keys)?; + let context = self.context; + let program = self.original_prompt_device.as_mut().ok_or(Error::IdentityMismatch)?; + let mmq = self.mmq_workspace.as_mut().ok_or(Error::IdentityMismatch)?; + let schedule = self.original_copy_schedule.as_mut().ok_or(Error::IdentityMismatch)?; + let span_cache_on = span_cache_enabled(); + let span_cache = &mut self.original_span_cache; + if span_cache_on && span_cache.0 != Rc::as_ptr(bank) as usize { + *span_cache = (Rc::as_ptr(bank) as usize, Vec::new()); + } + schedule.validate_context(context).map_err(driver_error)?; + let io = PromptIo { context, binding, layer, program, mmq, schedule, routing: self.prompt_routing.as_mut() }; + let finite = &mut self.original_finite_experts; + Ok(PromptParts { io, scan: SpanScan { binding, layer, bank, finite, span_cache, span_cache_on }, weights }) + } + + fn original_prompt_precheck(&self, binding: &ModelBinding, dense: &DenseWeightCache<'ctx>) -> Result<()> { self.validate(binding, self.context)?; if !self.original_prompt_mmq || self.original_prompt_device.is_none() || self.original_expert_bank.is_none() { return Err(Error::IdentityMismatch); @@ -24,195 +71,35 @@ impl<'ctx> MoeWeightCache<'ctx> { if !std::ptr::eq(retained, self.context) { return Err(Error::IdentityMismatch); } - let keys = self.original_shared_layer(binding, layer)?; - let formats = [native_format(keys[0])?, native_format(keys[1])?, native_format(keys[2])?]; - let router = dense.router(binding, layer.get())?; - let main = &self.main; - let raw = |i: usize| -> Result<&DeviceBuffer<'ctx>> { - let entry = main.get(&keys[i]).ok_or(Error::IdentityMismatch)?; - if entry.charged_bytes != keys[i].bytes { - return Err(Error::IdentityMismatch); - } - match &entry.weight { - EncodedWeight::Raw(b) => Ok(b), - _ => Err(Error::IdentityMismatch), - } - }; - let weights = [router, raw(3)?, raw(0)?, raw(1)?, raw(2)?]; - let bank = Rc::clone(self.original_expert_bank.as_ref().ok_or(Error::IdentityMismatch)?); - let program = self.original_prompt_device.as_mut().ok_or(Error::IdentityMismatch)?; - let mmq = self.mmq_workspace.as_mut().ok_or(Error::IdentityMismatch)?; - let schedule = self.original_copy_schedule.as_mut().ok_or(Error::IdentityMismatch)?; - let finite = &mut self.original_finite_experts; - let span_cache = &mut self.original_span_cache; - let span_cache_on = span_cache_enabled(); - if span_cache_on && span_cache.0 != Rc::as_ptr(&bank) as usize { - *span_cache = (Rc::as_ptr(&bank) as usize, Vec::new()); - } - schedule.validate_context(self.context).map_err(driver_error)?; - let context = self.context; - let drain = Some(context as &dyn prof::Drain); - let last_layer = layer.get() + 1 == binding.layer_count(); - let result = (|| { - if layer.get() == 0 - && !schedule.prompt_stream_active() - && let Some((minimum, bytes_per_second)) = prompt_stream_settings() - && read.rows() >= minimum - && !bank.pageable() - { - // the whole chunk's expert stream starts with the first MoE layer - schedule.begin_prompt_stream(&read, &bank, 0, bytes_per_second).map_err(driver_error)?; - crate::bringup_trace!("DBG prefill stream: begin rows={}", read.rows()); - } - // High-only is the selected literal Original mixed BF16 policy. - let prepare_span = prof::span(PStage::MoePrepare, drain); - let mut layer_program = program.prepare(read, shared, weights, formats, false).map_err(driver_error)?; - drop(prepare_span); - if let Some((routing, decay)) = self.prompt_routing.as_mut() { - // seed capture: the routed rows per expert are already on the host (grouping read the route IDs); - // the first layer of a chunk fades the earlier chunks' counts (decay 1: none) - if layer.get() == 0 && *decay != 1.0 { - routing.iter_mut().for_each(|v| *v *= *decay); - } - for (&expert, &rows) in layer_program.experts().iter().zip(layer_program.counts()) { - routing[layer.get() as usize * 512 + expert as usize] += rows as f32; - } - } - let spans_span = prof::span(PStage::MoeSpans, None); - let mut sources: Vec<[ResidentExpertBankSpan; 3]> = Vec::new(); - sources.try_reserve_exact(layer_program.experts().len()).map_err(|_| Error::InputAllocation)?; - let mut routed_formats = None; - for &expert in layer_program.experts() { - // These are binding-resolved weights, not a synthetic RouteRow. - // The expert itself is the actual GPU route's authenticated ID. - let selected = std::array::from_fn(|i| (expert + i as u32) % 512); - let bound = binding.moe_expert_weights(layer.get(), selected).map_err(binding_error)?; - let members = [(&bound, 0)]; - let bit = layer.get() as usize * 512 + expert as usize; - let admitted = bit < 48 * 512 && finite[bit / 64] >> (bit % 64) & 1 == 1; - if span_cache_on - && admitted - && let Some((spans, format)) = span_cache.1.get(bit).and_then(Option::as_ref) - { - // the same checks the walk below ends with, on the spans it resolved when this expert was admitted - if !bank.eligible(spans) { - return Err(Error::IdentityMismatch); - } - if routed_formats.is_some_and(|previous| previous != *format) { - return Err(Error::IdentityMismatch); - } - routed_formats = Some(*format); - sources.push(spans.clone()); - continue; - } - let ((span, scanned), format) = binding.with_moe_routed_source(&members, binding_error, |source| { - let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; - let operation = (|| { - source.validate_binding(binding).map_err(binding_error)?; - let keys = [ - source.descriptor(0, roles[0]).map_err(binding_error)?, - source.descriptor(0, roles[1]).map_err(binding_error)?, - source.descriptor(0, roles[2]).map_err(binding_error)?, - ]; - if keys.iter().any(|key| key.layer != layer.get() || key.expert != Some(expert)) { - return Err(Error::IdentityMismatch); - } - let formats = [ - original_dual_layout(keys[0])?.ok_or(Error::InvalidDimension)?.0, - original_dual_layout(keys[1])?.ok_or(Error::InvalidDimension)?.0, - original_dual_layout(keys[2])?.ok_or(Error::InvalidDimension)?.0, - ]; - // The whole finite admission of an expert's immutable bank bytes runs once per bank; - // later chunks take the same descriptor/geometry-checked span without the rescan. An expert - // the copy ring stages through page-locked host buffers (a pageable bank) is checked by the - // stager's helpers on the bytes they copy, so the source is not read twice. - let located = [ - source.bank_span(0, roles[0]).map_err(binding_error)?, - source.bank_span(0, roles[1]).map_err(binding_error)?, - source.bank_span(0, roles[2]).map_err(binding_error)?, - ]; - let (spans, scanned) = if admitted || bank.host_staged(&located) { - (located, false) - } else { - ( - [ - source.mapped_span(0, roles[0]).map_err(binding_error)?, - source.mapped_span(0, roles[1]).map_err(binding_error)?, - source.mapped_span(0, roles[2]).map_err(binding_error)?, - ], - true, - ) - }; - if !bank.eligible(&spans) { - return Err(Error::IdentityMismatch); - } - Ok(((spans, scanned), formats)) - })(); - // Actual retained immutable spans survive this source fence; - // every later DMA holds the real bank owner, not this scope. - let finish = source.finish().map_err(binding_error); - match operation { - Err(e) => Err(e), - Ok(v) => { - finish?; - Ok(v) - } - } - })?; - if bit >= 48 * 512 { - return Err(Error::InvalidExpert); - } - if scanned { - finite[bit / 64] |= 1 << (bit % 64); - } - if routed_formats.is_some_and(|previous| previous != format) { - return Err(Error::IdentityMismatch); - } - routed_formats = Some(format); - if span_cache_on && admitted && !scanned { - if span_cache.1.is_empty() { - span_cache.1.resize_with(48 * 512, || None); - } - span_cache.1[bit] = Some((span.clone(), format)); - } - sources.push(span); - } - let outside = bank - .metadata_bytes() - .checked_add(leleka_cuda_driver::OriginalPromptLeaseIdentity::metadata_bytes()) - .and_then(|n| { - n.checked_add(sources.capacity().checked_mul(std::mem::size_of::<[ResidentExpertBankSpan; 3]>())?) - }) - .and_then(|n| n.checked_add(layer_program.metadata_bytes().ok()?)) - .ok_or(Error::Overflow)?; - schedule.retain_host_metadata_charge(outside).map_err(driver_error)?; - drop(spans_span); - let ring_span = prof::span(PStage::MoeRing, drain); - layer_program - .execute_original_copy_ring( - mmq, - schedule, - layer.get() as usize, - Rc::clone(&bank), - routed_formats.ok_or(Error::IdentityMismatch)?, - &sources, - ) - .map_err(driver_error)?; - drop(ring_span); - let _span = prof::span(PStage::MoeFinish, drain); - let block = layer_program.finish(shared).map_err(driver_error)?; - if last_layer && schedule.prompt_stream_active() { - schedule.end_prompt_stream().map_err(driver_error)?; - } - Ok(block) - })(); - if result.is_err() { - // the stream never outlives a failed layer - let _ = schedule.end_prompt_stream(); - } - if self.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { - self.failed.set(true); - } - result + Ok(()) } } + +/// The raw encoded shared weight of one key, fully charged. +fn raw_weight<'a, 'ctx>( + main: &'a HashMap>, + key: &MoeWeightDescriptor, +) -> Result<&'a DeviceBuffer<'ctx>> { + let entry = main.get(key).ok_or(Error::IdentityMismatch)?; + if entry.charged_bytes != key.bytes { + return Err(Error::IdentityMismatch); + } + match &entry.weight { + EncodedWeight::Raw(b) => Ok(b), + _ => Err(Error::IdentityMismatch), + } +} + +fn shared_formats(keys: &[MoeWeightDescriptor; 4]) -> Result<[GdnNativeFormat; 3]> { + Ok([native_format(keys[0])?, native_format(keys[1])?, native_format(keys[2])?]) +} + +/// Router, scalar gate, then the shared Gate/Up/Down raw weights. +fn shared_weights<'a, 'ctx>( + router: &'a DeviceBuffer<'ctx>, + main: &'a HashMap>, + keys: &[MoeWeightDescriptor; 4], +) -> Result<[&'a DeviceBuffer<'ctx>; 5]> { + let [gate, up, down] = [raw_weight(main, &keys[0])?, raw_weight(main, &keys[1])?, raw_weight(main, &keys[2])?]; + Ok([router, raw_weight(main, &keys[3])?, gate, up, down]) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/prompt_layer_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/prompt_layer_fns.rs new file mode 100644 index 00000000..22897b34 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/prompt_layer_fns.rs @@ -0,0 +1,303 @@ +//! One original-prompt MoE layer: expert spans, copy ring and finish (STRA-338 size: extract-method only). + +#[allow(unused_imports)] +use super::*; +use crate::model_binding::qwen4exp_input::MoeRoutedSourceScope; +use leleka_cuda_driver::{ + MappedExpertBank, MmqFormat, MmqWorkspace, OriginalMmqCopySchedule, OriginalMoePromptDevice, OriginalMoePromptLayer, +}; + +type SpanCache = (usize, Vec>); +type Spans = [ResidentExpertBankSpan; 3]; +const BITS: usize = 48 * 512; + +/// The owners one layer drives through the copy ring (disjoint cache fields). +pub(super) struct PromptIo<'a, 'ctx> { + pub(super) context: &'ctx Context<'ctx>, + pub(super) binding: &'a ModelBinding, + pub(super) layer: LayerId, + pub(super) program: &'a mut OriginalMoePromptDevice<'ctx>, + pub(super) mmq: &'a mut MmqWorkspace<'ctx>, + pub(super) schedule: &'a mut OriginalMmqCopySchedule<'ctx>, + pub(super) routing: Option<&'a mut (Vec, f32)>, +} + +/// The bank span resolution state: admitted-expert bits and the span cache. +pub(super) struct SpanScan<'a, 'ctx> { + pub(super) binding: &'a ModelBinding, + pub(super) layer: LayerId, + pub(super) bank: &'a Rc>, + pub(super) finite: &'a mut [u64; BITS / 64], + pub(super) span_cache: &'a mut SpanCache, + pub(super) span_cache_on: bool, +} + +/// The disjoint owners and shared weights of one layer, borrowed from the cache. +pub(super) struct PromptParts<'a, 'ctx> { + pub(super) io: PromptIo<'a, 'ctx>, + pub(super) scan: SpanScan<'a, 'ctx>, + pub(super) weights: [&'a DeviceBuffer<'ctx>; 5], +} + +/// One expert's resolved bank spans and where they came from. +struct Resolved { + bit: usize, + admitted: bool, + spans: Spans, + format: [MmqFormat; 3], + cached: bool, + scanned: bool, +} + +/// Genuine device FFN read -> router/shared -> ascending groups of16 -> weighted combine. +pub(super) fn run_prompt_layer<'arena, 'loan, 'ctx>( + io: &mut PromptIo<'_, 'ctx>, + scan: &mut SpanScan<'_, 'ctx>, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + shared: &mut NativeBatchWorkspace<'ctx>, + weights: [&DeviceBuffer<'ctx>; 5], + formats: [GdnNativeFormat; 3], +) -> Result> { + let drain = Some(io.context as &dyn prof::Drain); + begin_stream(io.schedule, scan.bank, io.layer, &read)?; + // High-only is the selected literal Original mixed BF16 policy. + let prepare_span = prof::span(PStage::MoePrepare, drain); + let mut layer_program = io.program.prepare(read, shared, weights, formats, false).map_err(driver_error)?; + drop(prepare_span); + record_routing(io.routing.as_deref_mut(), io.layer, layer_program.experts(), layer_program.counts()); + let spans_span = prof::span(PStage::MoeSpans, None); + let (sources, routed) = scan.collect(layer_program.experts())?; + charge_sources(io.schedule, scan.bank, &sources, || layer_program.metadata_bytes().ok())?; + drop(spans_span); + let ring_span = prof::span(PStage::MoeRing, drain); + let ring = RingOwners { mmq: io.mmq, schedule: io.schedule, layer: io.layer, bank: scan.bank }; + copy_ring(&mut layer_program, ring, &sources, routed)?; + drop(ring_span); + let _span = prof::span(PStage::MoeFinish, drain); + let block = layer_program.finish(shared).map_err(driver_error)?; + end_stream_if_last(io)?; + Ok(block) +} + +fn end_stream_if_last(io: &mut PromptIo<'_, '_>) -> Result<()> { + let last_layer = io.layer.get() + 1 == io.binding.layer_count(); + if last_layer && io.schedule.prompt_stream_active() { + io.schedule.end_prompt_stream().map_err(driver_error)?; + } + Ok(()) +} + +/// Charge the host metadata the sources and the layer program keep outside the bank. +fn charge_sources( + schedule: &mut OriginalMmqCopySchedule<'_>, + bank: &MappedExpertBank<'_>, + sources: &Vec, + layer_metadata: impl FnOnce() -> Option, +) -> Result<()> { + let outside = outside_bytes(bank, sources, layer_metadata)?; + schedule.retain_host_metadata_charge(outside).map_err(driver_error) +} + +/// The copy ring's owners, borrowed beside the live layer program. +struct RingOwners<'a, 'ctx> { + mmq: &'a mut MmqWorkspace<'ctx>, + schedule: &'a mut OriginalMmqCopySchedule<'ctx>, + layer: LayerId, + bank: &'a Rc>, +} + +fn copy_ring<'program, 'arena, 'loan, 'ctx>( + layer_program: &mut OriginalMoePromptLayer<'program, 'arena, 'loan, 'ctx>, + ring: RingOwners<'_, 'ctx>, + sources: &[Spans], + routed: Option<[MmqFormat; 3]>, +) -> Result<()> { + let formats = routed.ok_or(Error::IdentityMismatch)?; + let layer = ring.layer.get() as usize; + layer_program + .execute_original_copy_ring(ring.mmq, ring.schedule, layer, Rc::clone(ring.bank), formats, sources) + .map_err(driver_error) +} + +/// The whole chunk's expert stream starts with the first MoE layer. +fn begin_stream<'arena, 'loan, 'ctx>( + schedule: &mut OriginalMmqCopySchedule<'ctx>, + bank: &Rc>, + layer: LayerId, + read: &OriginalDeviceGrRead<'arena, 'loan, 'ctx>, +) -> Result<()> { + if layer.get() == 0 + && !schedule.prompt_stream_active() + && let Some((minimum, bytes_per_second)) = prompt_stream_settings() + && read.rows() >= minimum + && !bank.pageable() + { + schedule.begin_prompt_stream(read, bank, 0, bytes_per_second).map_err(driver_error)?; + crate::bringup_trace!("DBG prefill stream: begin rows={}", read.rows()); + } + Ok(()) +} + +/// Seed capture: the routed rows per expert are already on the host (grouping read the route IDs); the first layer +/// of a chunk fades the earlier chunks' counts (decay 1: none). +fn record_routing(routing: Option<&mut (Vec, f32)>, layer: LayerId, experts: &[u32], counts: &[u32]) { + let Some((routing, decay)) = routing else { + return; + }; + if layer.get() == 0 && *decay != 1.0 { + routing.iter_mut().for_each(|v| *v *= *decay); + } + for (&expert, &rows) in experts.iter().zip(counts) { + routing[layer.get() as usize * 512 + expert as usize] += rows as f32; + } +} + +fn outside_bytes( + bank: &MappedExpertBank<'_>, + sources: &Vec, + layer_metadata: impl FnOnce() -> Option, +) -> Result { + bank.metadata_bytes() + .checked_add(leleka_cuda_driver::OriginalPromptLeaseIdentity::metadata_bytes()) + .and_then(|n| n.checked_add(sources.capacity().checked_mul(std::mem::size_of::())?)) + .and_then(|n| n.checked_add(layer_metadata()?)) + .ok_or(Error::Overflow) +} + +impl SpanScan<'_, '_> { + /// The bank spans of every routed expert, in order, and the one routed format they share. + fn collect(&mut self, experts: &[u32]) -> Result<(Vec, Option<[MmqFormat; 3]>)> { + let mut sources = Vec::new(); + sources.try_reserve_exact(experts.len()).map_err(|_| Error::InputAllocation)?; + let mut routed_formats = None; + for &expert in experts { + let resolved = self.resolve(expert)?; + if routed_formats.is_some_and(|previous| previous != resolved.format) { + return Err(Error::IdentityMismatch); + } + routed_formats = Some(resolved.format); + self.remember(&resolved); + sources.push(resolved.spans); + } + Ok((sources, routed_formats)) + } + + fn resolve(&mut self, expert: u32) -> Result { + let bound = self.bound_weights(expert)?; + let bit = self.layer.get() as usize * 512 + expert as usize; + let admitted = bit < BITS && self.finite[bit / 64] >> (bit % 64) & 1 == 1; + if self.span_cache_on + && admitted + && let Some((spans, format)) = self.span_cache.1.get(bit).and_then(Option::as_ref) + { + // the same checks the walk below ends with, on the spans it resolved when this expert was admitted + if !self.bank.eligible(spans) { + return Err(Error::IdentityMismatch); + } + return Ok(Resolved { bit, admitted, spans: spans.clone(), format: *format, cached: true, scanned: false }); + } + let ((spans, scanned), format) = self.walk(&bound, expert, admitted)?; + if bit >= BITS { + return Err(Error::InvalidExpert); + } + if scanned { + self.finite[bit / 64] |= 1 << (bit % 64); + } + Ok(Resolved { bit, admitted, spans, format, cached: false, scanned }) + } + + fn bound_weights(&self, expert: u32) -> Result { + let selected = std::array::from_fn(|i| (expert + i as u32) % 512); + self.binding.moe_expert_weights(self.layer.get(), selected).map_err(binding_error) + } + + /// Cache the spans of an expert that was admitted before and resolved without a rescan. + fn remember(&mut self, resolved: &Resolved) { + if resolved.cached || !self.span_cache_on || !resolved.admitted || resolved.scanned { + return; + } + if self.span_cache.1.is_empty() { + self.span_cache.1.resize_with(BITS, || None); + } + self.span_cache.1[resolved.bit] = Some((resolved.spans.clone(), resolved.format)); + } + + /// These are binding-resolved weights, not a synthetic RouteRow. The expert itself is the actual GPU route's + /// authenticated ID. Actual retained immutable spans survive the source fence; every later DMA holds the real + /// bank owner, not this scope. + fn walk(&self, bound: &MoeExpertWeights, expert: u32, admitted: bool) -> Result<((Spans, bool), [MmqFormat; 3])> { + let members = [(bound, 0)]; + self.binding.with_moe_routed_source(&members, binding_error, |source| { + let operation = self.walk_source(source, expert, admitted); + let finish = source.finish().map_err(binding_error); + operation.and_then(|value| finish.map(|()| value)) + }) + } + + fn walk_source( + &self, + source: &mut MoeRoutedSourceScope<'_, '_>, + expert: u32, + admitted: bool, + ) -> Result<((Spans, bool), [MmqFormat; 3])> { + let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + let formats = self.source_formats(source, expert)?; + let spans = self.walk_spans(source, &roles, admitted)?; + if !self.bank.eligible(&spans.0) { + return Err(Error::IdentityMismatch); + } + Ok((spans, formats)) + } + + fn source_formats(&self, source: &mut MoeRoutedSourceScope<'_, '_>, expert: u32) -> Result<[MmqFormat; 3]> { + source.validate_binding(self.binding).map_err(binding_error)?; + let keys = source_triplet(source)?; + if keys.iter().any(|key| key.layer != self.layer.get() || key.expert != Some(expert)) { + return Err(Error::IdentityMismatch); + } + dual_formats(&keys) + } + + /// The whole finite admission of an expert's immutable bank bytes runs once per bank; later chunks take the + /// same descriptor/geometry-checked span without the rescan. An expert the copy ring stages through page-locked + /// host buffers (a pageable bank) is checked by the stager's helpers on the bytes they copy, so the source is + /// not read twice. + fn walk_spans( + &self, + source: &mut MoeRoutedSourceScope<'_, '_>, + roles: &[MoeMatrixRole; 3], + admitted: bool, + ) -> Result<(Spans, bool)> { + let located = [ + source.bank_span(0, roles[0]).map_err(binding_error)?, + source.bank_span(0, roles[1]).map_err(binding_error)?, + source.bank_span(0, roles[2]).map_err(binding_error)?, + ]; + if admitted || self.bank.host_staged(&located) { + return Ok((located, false)); + } + let mapped = [ + source.mapped_span(0, roles[0]).map_err(binding_error)?, + source.mapped_span(0, roles[1]).map_err(binding_error)?, + source.mapped_span(0, roles[2]).map_err(binding_error)?, + ]; + Ok((mapped, true)) + } +} + +fn source_triplet(source: &mut MoeRoutedSourceScope<'_, '_>) -> Result<[MoeWeightDescriptor; 3]> { + let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + Ok([ + source.descriptor(0, roles[0]).map_err(binding_error)?, + source.descriptor(0, roles[1]).map_err(binding_error)?, + source.descriptor(0, roles[2]).map_err(binding_error)?, + ]) +} + +fn dual_formats(keys: &[MoeWeightDescriptor; 3]) -> Result<[MmqFormat; 3]> { + Ok([ + original_dual_layout(keys[0])?.ok_or(Error::InvalidDimension)?.0, + original_dual_layout(keys[1])?.ok_or(Error::InvalidDimension)?.0, + original_dual_layout(keys[2])?.ok_or(Error::InvalidDimension)?.0, + ]) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs index b66d15ff..57d67f48 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs @@ -143,3 +143,6 @@ mod impl_moeweightcache_2; mod impl_moeweightcache_3; #[path = "cache_profile_fill/impl_moeweightcache_4.rs"] mod impl_moeweightcache_4; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "cache_profile_fill/profile_build_fns.rs"] +mod profile_build_fns; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs index e79600a4..2aacd2d0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs @@ -1,6 +1,8 @@ //! Moved out of the parent module by STRA-338: impl MoeWeightCache. #[allow(unused_imports)] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +use super::profile_build_fns::ProfileKind; use super::*; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -14,165 +16,7 @@ impl<'ctx> MoeWeightCache<'ctx> { ) -> Result { let profile = RankedProfile::parse(bytes, PROFILE_SHA)?; let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(binding, context)?; - let operation = (|| { - cache.validate(binding, context)?; - cache.admit_mtp_input_workspace(binding)?; - let baseline = cache.counters; - let mut layer_keys = Vec::new(); - layer_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; - let mut shared_keys = Vec::new(); - shared_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; - let mut charges = [[0usize; 3]; 48]; - for (layer, charge) in charges.iter_mut().enumerate() { - let keys = [ - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?, - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up).map_err(binding_error)?, - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?, - ]; - for (n, key) in keys.iter().enumerate() { - charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, bytes)| bytes); - } - layer_keys.push(keys); - shared_keys.push(binding.moe_shared_preload_descriptors(layer as u32).map_err(binding_error)?); - } - let mut shared = cache_profile::SharedPermanentPool::new(shared_keys)?; - shared.baseline = - [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; - let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; - let mut totals = [0usize; 48]; - for (total, roles) in totals.iter_mut().zip(charges) { - *total = roles.into_iter().try_fold(0usize, |n, v| n.checked_add(v)).ok_or(Error::Overflow)?; - } - let minimum = *totals.iter().min().ok_or(Error::InvalidDimension)?; - let largest = *totals.iter().max().ok_or(Error::InvalidDimension)?; - if minimum == 0 { - return Err(Error::InvalidDimension); - } - let window_spill = profile_window_spill_with_floor(1usize << 30)?; - let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; - // Metadata for even the largest possible selected prefix is charged BEFORE H2D. - let maximum_count = remaining_main - .checked_sub(spill) - .ok_or(Error::InputAllocation)? - .checked_div(minimum) - .ok_or(Error::InvalidDimension)? - .min(profile.ordered_pairs().len()) - .checked_mul(3) - .and_then(|n| n.checked_add(shared.descriptor_count())) - .ok_or(Error::Overflow)?; - cache.main.try_reserve(maximum_count.max(1 << 15)).map_err(|_| Error::InputAllocation)?; - let main_slot_limit = cache.main.capacity(); - let mut selected = Vec::new(); - selected.try_reserve_exact(48 * 512).map_err(|_| Error::InputAllocation)?; - selected.resize(48 * 512, false); - let buckets = - main_slot_limit.checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3).ok_or(Error::Overflow)?; - let map_bytes = buckets - .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) - .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) - .ok_or(Error::Overflow)?; - let metadata_bytes = profile - .metadata_bytes() - .checked_add(shared.metadata_bytes()?) - .and_then(|n| n.checked_add(selected.capacity() * std::mem::size_of::())) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| n.checked_add(bytes.len())) - .and_then(|n| n.checked_add(layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>())) - .and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?)) - .and_then(|n| n.checked_add(map_bytes)) - .ok_or(Error::Overflow)?; - if metadata_bytes > HOST_CAP || maximum_count > main_slot_limit { - return Err(Error::InputAllocation); - } - // Closed source/geometry was checked for every descriptor above. Only - // full finite actual owned bytes from the same binding are uploaded. - for layer in 0..48 { - let keys = shared.quartet(layer)?; - cache.preload_shared_quartet(binding, keys, spill, &mut shared)?; - } - if cache.main_bytes != shared.bytes - || cache.main.len() != shared.descriptor_count() - || cache.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != 0 - { - return Err(Error::IdentityMismatch); - } - // Actual owners now appear in both allocated_bytes and physical_free. - // Subtract their bytes ONLY from the remaining main pool. - let (free, _) = context.memory_info().map_err(driver_error)?; - let plan = PrefixPlan::new_shared_with_storage( - &profile, - &charges, - ProfileLimits { - main_cap: remaining_main, - allocated: context.allocated_bytes(), - device_budget: context.budget_bytes(), - physical_free: free, - working_reserve: WORKING_RESERVE, - window_spill, - }, - selected, - )?; - let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?; - if count.checked_add(shared.descriptor_count()).is_none_or(|n| n > main_slot_limit) { - return Err(Error::InputAllocation); - } - let expected_bytes = plan.charged_bytes.checked_add(shared.bytes).ok_or(Error::Overflow)?; - let shared_bytes = shared.bytes as u64; - cache.pinned = Some(PinnedPool { - plan, - loaded_matrices: 0, - shared: Some(shared), - #[cfg(test)] - metadata_bytes, - main_slot_limit, - #[cfg(test)] - fixed_resident_upload_bytes: baseline.upload_bytes, - #[cfg(test)] - fixed_resident_read_bytes: baseline.read_bytes, - pinned_hits: 0, - spill_hits: 0, - spill_misses: 0, - preload_read_bytes: shared_bytes, - preload_upload_bytes: shared_bytes, - }); - let prefix = cache.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.prefix; - for &(layer, expert) in &profile.ordered_pairs()[..prefix] { - let keys = [ - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Gate) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Up) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Down) - .map_err(binding_error)?, - ]; - let mut topology_keys = layer_keys[usize::from(layer)]; - for key in &mut topology_keys { - key.expert = Some(u32::from(expert)); - } - if keys != topology_keys { - return Err(Error::IdentityMismatch); - } - cache.preload_pinned_triplet(binding, keys)?; - } - if cache.main_bytes != expected_bytes - || cache.spill_len()? != 0 - || cache.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count) - { - return Err(Error::IdentityMismatch); - } - cache - .pinned - .as_mut() - .and_then(|pool| pool.shared.as_mut()) - .ok_or(Error::IdentityMismatch)? - .finish_preload(); - cache.validate(binding, context) - })(); - if let Err(primary) = operation { + if let Err(primary) = cache.build_profile(binding, context, &profile, bytes.len(), ProfileKind::Fixed) { let _ = cache.close(); return Err(primary); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs index fa5a4feb..495cbb2e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs @@ -1,6 +1,8 @@ //! Moved out of the parent module by STRA-338: impl MoeWeightCache, impl MoeWeightCache. #[allow(unused_imports)] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +use super::profile_build_fns::ProfileKind; use super::*; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -14,183 +16,7 @@ impl<'ctx> MoeWeightCache<'ctx> { let profile = RankedProfile::parse(bytes, PROFILE_SHA)?; let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru_with_prompt(binding, context, true)?; - let operation = (|| { - cache.validate(binding, context)?; - cache.admit_mtp_input_workspace(binding)?; - let baseline = cache.counters; - let mut layer_keys = Vec::new(); - layer_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; - let mut shared_keys = Vec::new(); - shared_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; - let mut charges = [[0usize; 3]; 48]; - for (layer, charge) in charges.iter_mut().enumerate() { - let keys = [ - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?, - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up).map_err(binding_error)?, - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?, - ]; - for (n, key) in keys.iter().enumerate() { - charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, bytes)| bytes); - } - layer_keys.push(keys); - shared_keys.push(binding.moe_shared_preload_descriptors(layer as u32).map_err(binding_error)?); - } - let mut shared = cache_profile::SharedPermanentPool::new(shared_keys)?; - shared.baseline = - [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; - let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; - let mut totals = [0usize; 48]; - for (total, roles) in totals.iter_mut().zip(charges) { - *total = roles.into_iter().try_fold(0usize, |n, v| n.checked_add(v)).ok_or(Error::Overflow)?; - } - let minimum = *totals.iter().min().ok_or(Error::InvalidDimension)?; - let largest = *totals.iter().max().ok_or(Error::InvalidDimension)?; - if minimum == 0 { - return Err(Error::InvalidDimension); - } - let window_spill = profile_window_spill_with_floor(1usize << 30)?; - let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; - // Metadata for even the largest possible selected prefix is charged BEFORE H2D. - let maximum_count = cache_profile::learned_main_slot_bound(&charges, remaining_main)? - .checked_add(shared.descriptor_count()) - .ok_or(Error::Overflow)?; - cache.main.try_reserve(maximum_count.max(1 << 15)).map_err(|_| Error::InputAllocation)?; - let main_slot_limit = cache.main.capacity(); - let mut selected = Vec::new(); - selected.try_reserve_exact(48 * 512).map_err(|_| Error::InputAllocation)?; - selected.resize(48 * 512, false); - let buckets = - main_slot_limit.checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3).ok_or(Error::Overflow)?; - let map_bytes = buckets - .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) - .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) - .ok_or(Error::Overflow)?; - let metadata_bytes = profile - .metadata_bytes() - .checked_add(shared.metadata_bytes()?) - .and_then(|n| n.checked_add(selected.capacity() * std::mem::size_of::())) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| n.checked_add(bytes.len())) - .and_then(|n| n.checked_add(layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>())) - .and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?)) - .and_then(|n| n.checked_add(map_bytes)) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| n.checked_add(std::mem::size_of::<[usize; 144]>())) - .ok_or(Error::Overflow)?; - if metadata_bytes > HOST_CAP || maximum_count > main_slot_limit { - return Err(Error::InputAllocation); - } - cache.learned_metadata_bytes = metadata_bytes; - // Closed source/geometry was checked for every descriptor above. Only - // full finite actual owned bytes from the same binding are uploaded. - for layer in 0..48 { - let keys = shared.quartet(layer)?; - cache.preload_shared_quartet(binding, keys, spill, &mut shared)?; - } - if cache.main_bytes != shared.bytes - || cache.main.len() != shared.descriptor_count() - || cache.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != 0 - { - return Err(Error::IdentityMismatch); - } - // Actual owners now appear in both allocated_bytes and physical_free. - // Subtract their bytes ONLY from the remaining main pool. - let (free, _) = context.memory_info().map_err(driver_error)?; - let plan = PrefixPlan::new_shared_with_storage( - &profile, - &charges, - ProfileLimits { - main_cap: remaining_main, - allocated: context.allocated_bytes(), - device_budget: context.budget_bytes(), - physical_free: free, - working_reserve: WORKING_RESERVE, - window_spill, - }, - selected, - )?; - let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?; - if count.checked_add(shared.descriptor_count()).is_none_or(|n| n > main_slot_limit) { - return Err(Error::InputAllocation); - } - let expected_bytes = plan.charged_bytes.checked_add(shared.bytes).ok_or(Error::Overflow)?; - let shared_bytes = shared.bytes as u64; - cache.pinned = Some(PinnedPool { - plan, - loaded_matrices: 0, - shared: Some(shared), - #[cfg(test)] - metadata_bytes, - main_slot_limit, - #[cfg(test)] - fixed_resident_upload_bytes: baseline.upload_bytes, - #[cfg(test)] - fixed_resident_read_bytes: baseline.read_bytes, - pinned_hits: 0, - spill_hits: 0, - spill_misses: 0, - preload_read_bytes: shared_bytes, - preload_upload_bytes: shared_bytes, - }); - let prefix = cache.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.prefix; - for &(layer, expert) in &profile.ordered_pairs()[..prefix] { - let keys = [ - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Gate) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Up) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Down) - .map_err(binding_error)?, - ]; - let mut topology_keys = layer_keys[usize::from(layer)]; - for key in &mut topology_keys { - key.expert = Some(u32::from(expert)); - } - if keys != topology_keys { - return Err(Error::IdentityMismatch); - } - cache.preload_pinned_triplet(binding, keys)?; - } - if cache.main_bytes != expected_bytes - || cache.spill_len()? != 0 - || cache.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count) - { - return Err(Error::IdentityMismatch); - } - cache - .pinned - .as_mut() - .and_then(|pool| pool.shared.as_mut()) - .ok_or(Error::IdentityMismatch)? - .finish_preload(); - // The same real owners are already complete. Seed the existing empty - // metadata only; no source read, allocation or H2D occurs here. - let shared = cache.pinned.as_ref().and_then(|pool| pool.shared.as_ref()).ok_or(Error::IdentityMismatch)?; - for (key, entry) in &cache.main { - let expected = cache.weight_layout(*key)?.map_or(key.bytes, |(_, charge)| charge); - if entry.charged_bytes != expected - || entry.age == 0 - || entry.age > cache.age - || (key.expert.is_none() && !shared.contains(*key)) - { - return Err(Error::IdentityMismatch); - } - } - cache.lru.as_mut().ok_or(Error::IdentityMismatch)?.seed_existing( - cache.age, - cache.main.iter().filter(|(key, _)| !shared.contains(**key)).map(|(key, entry)| (*key, entry.age)), - )?; - cache.learned_main = true; - if cache.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != cache.spill_len()? { - return Err(Error::IdentityMismatch); - } - cache.validate(binding, context) - })(); - if let Err(primary) = operation { + if let Err(primary) = cache.build_profile(binding, context, &profile, bytes.len(), ProfileKind::Learned) { let _ = cache.close(); return Err(primary); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs index a80d02be..ca812e98 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs @@ -34,174 +34,283 @@ impl<'ctx> MoeWeightCache<'ctx> { let profile = RankedProfile::parse(bytes, PROFILE_SHA)?; let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru_with_prompt(binding, context, mapped)?; - let operation = (|| { - cache.validate(binding, context)?; - let required = 46_612usize.checked_add(WORKING_RESERVE).ok_or(Error::Overflow)?; - let (free, _) = context.memory_info().map_err(driver_error)?; - if free < required - || context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) - { - return Err(Error::InputAllocation); - } - cache.routed_resident = Some(Rc::new(super::super::RoutedResidentOwner::new(context)?)); - cache.admit_mtp_input_workspace(binding)?; - let mut layer_keys = Vec::new(); - layer_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; - let mut shared_keys = Vec::new(); - shared_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; - let mut largest = 0usize; - for layer in 0..48 { - let keys = [ - binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Gate).map_err(binding_error)?, - binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Up).map_err(binding_error)?, - binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Down).map_err(binding_error)?, - ]; - largest = - largest.max(keys.iter().try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?); - layer_keys.push(keys); - shared_keys.push(binding.moe_shared_preload_descriptors(layer).map_err(binding_error)?); - } - let template: [[MoeWeightDescriptor; 3]; 48] = - layer_keys.try_into().map_err(|_| Error::InvalidDimension)?; - // These are genuine whole owners allocated before PrefixPlan. Their - // bytes are already in Context::allocated_bytes, charged once. - cache.routed_outputs = - Some(Rc::new(super::super::cache_routed_outputs::RoutedOutputBank::new(binding.identity(), context)?)); - if cache.routed_outputs.as_ref().ok_or(Error::IdentityMismatch)?.allocated_bytes() != 37_273_600 { - return Err(Error::IdentityMismatch); - } - let maximum = std::array::from_fn(|role| template.iter().map(|keys| keys[role].bytes).max().unwrap_or(0)); - cache.ephemeral_routed = Some(Rc::new(RefCell::new(if mapped { - super::super::cache_ephemeral_routed::EphemeralRoutedOwner::new_mapped( - binding, - context, - maximum, - super::super::cache_ephemeral_routed::MappedStageShape::Single16, - )? - } else { - super::super::cache_ephemeral_routed::EphemeralRoutedOwner::new(binding, context, maximum)? - }))); - let ephemeral_charge = maximum - .into_iter() - .try_fold(if mapped { 36usize } else { 0 }, |n, b| n.checked_add(b).ok_or(Error::Overflow))? - .checked_mul(if mapped { 16 } else { 2 }) - .ok_or(Error::Overflow)?; - if cache - .ephemeral_routed - .as_ref() - .ok_or(Error::IdentityMismatch)? - .try_borrow() - .map_err(|_| Error::IdentityMismatch)? - .allocated_bytes() - != ephemeral_charge - { - return Err(Error::IdentityMismatch); - } - let mut shared = cache_profile::SharedPermanentPool::new(shared_keys)?; - let baseline = cache.counters; - shared.baseline = - [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; - let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; - let window_spill = profile_window_spill_with_floor(1usize << 30)?; - let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; - // Only the permanent192 descriptor map survives. No second routed - // HashMap/LRU representation competes with the actual slot map. - cache.main.try_reserve(shared.descriptor_count()).map_err(|_| Error::InputAllocation)?; - let buckets = cache - .main - .capacity() - .checked_mul(4) - .and_then(|n| n.checked_add(2)) - .map(|n| n / 3) - .ok_or(Error::Overflow)?; - let map_bytes = buckets - .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) - .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) - .ok_or(Error::Overflow)?; - let metadata = profile - .metadata_bytes() - .checked_add(shared.metadata_bytes()?) - .and_then(|n| n.checked_add(cache.routed_outputs.as_ref()?.metadata_bytes())) - .and_then(|n| n.checked_add(cache.ephemeral_routed.as_ref()?.try_borrow().ok()?.metadata_bytes())) - .and_then(|n| n.checked_add(map_bytes)) - .and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?)) - .and_then(|n| n.checked_add(bytes.len())) - .ok_or(Error::Overflow)?; - // Prove the COMPLETE adaptive allocation bound before first shared - // H2D, not after the remaining physical memory became tight. - let (free, _) = context.memory_info().map_err(driver_error)?; - let before = cache_strata_adaptive::AdaptivePolicy::new( - &profile, - template, - ProfileLimits { - main_cap: remaining_main, - allocated: context.allocated_bytes().checked_add(shared.bytes).ok_or(Error::Overflow)?, - device_budget: context.budget_bytes(), - physical_free: free.checked_sub(shared.bytes).ok_or(Error::InputAllocation)?, - working_reserve: WORKING_RESERVE, - window_spill, - }, - )?; - let adaptive_metadata = before - .metadata_bytes() - .checked_add(before.initial_slots().len() * std::mem::size_of::; 3]>>()) - .and_then(|n| n.checked_add(cache_strata_adaptive::transfer_metadata_bound())) - .and_then(|n| n.checked_add(metadata)) - .ok_or(Error::Overflow)?; - if adaptive_metadata > HOST_CAP { - return Err(Error::InputAllocation); - } - drop(before); - // Persistent15-worker stacks/coordinator/fixed scratch belong to - // the model source lifetime, not every request's CPU job budget. - cpu_budget::admit_pool(binding, adaptive_metadata)?; - let cpu = super::super::super::cpu_expert_miss::CpuMissWorkspace::new(binding, 15) - .map_err(super::super::super::cpu_expert_miss::runtime_error)?; - if cpu.workers() != 15 { - return Err(Error::IdentityMismatch); - } - cache.cpu_miss = Some(Rc::new(RefCell::new(cpu))); - for layer in 0..48 { - cache.preload_shared_quartet(binding, shared.quartet(layer)?, spill, &mut shared)?; - } - if cache.main_bytes != shared.bytes || cache.main.len() != 192 { - return Err(Error::IdentityMismatch); - } - shared.finish_preload(); - let (free, _) = context.memory_info().map_err(driver_error)?; - let owner = cache_strata_adaptive::AdaptiveCache::preload( - binding, - context, - &profile, - template, - ProfileLimits { - main_cap: remaining_main, - allocated: context.allocated_bytes(), - device_budget: context.budget_bytes(), - physical_free: free, - working_reserve: WORKING_RESERVE, - window_spill, - }, - shared.bytes, - metadata, - )?; - let Some(main_bytes) = cache.main_bytes.checked_add(owner.charged_bytes()) else { - let _ = owner.close(); - return Err(Error::Overflow); - }; - cache.adaptive_shared = Some(shared); - cache.adaptive = Some(owner); - cache.main_bytes = main_bytes; - let shared = cache.strata_adaptive_shared_witness()?; - if shared.descriptors != 192 || !shared.successful_bytes_reconcile { - return Err(Error::IdentityMismatch); - } - cache.validate(binding, context) - })(); - if let Err(primary) = operation { + if let Err(primary) = cache.build_adaptive(binding, context, &profile, bytes.len(), mapped) { let _ = cache.close(); return Err(primary); } Ok(cache) } + + fn build_adaptive( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + profile_len: usize, + mapped: bool, + ) -> Result<()> { + self.adaptive_precheck(binding, context)?; + let (template, shared_keys, largest) = adaptive_template(binding)?; + self.adaptive_outputs(binding, context, &template, mapped)?; + let mut shared = self.adaptive_shared_pool(shared_keys)?; + let plan = self.adaptive_plan(profile, profile_len, &mut shared, largest, template)?; + let adaptive_metadata = self.adaptive_admit(context, profile, &plan, &shared)?; + // Persistent15-worker stacks/coordinator/fixed scratch belong to + // the model source lifetime, not every request's CPU job budget. + self.adaptive_cpu_pool(binding, adaptive_metadata)?; + self.adaptive_preload(binding, context, profile, plan, shared) + } + + fn adaptive_precheck(&mut self, binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result<()> { + self.validate(binding, context)?; + let required = 46_612usize.checked_add(WORKING_RESERVE).ok_or(Error::Overflow)?; + let (free, _) = context.memory_info().map_err(driver_error)?; + if free < required || context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) + { + return Err(Error::InputAllocation); + } + self.routed_resident = Some(Rc::new(super::super::RoutedResidentOwner::new(context)?)); + self.admit_mtp_input_workspace(binding) + } + + /// These are genuine whole owners allocated before PrefixPlan. Their bytes are already in + /// Context::allocated_bytes, charged once. + fn adaptive_outputs( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + template: &[[MoeWeightDescriptor; 3]; 48], + mapped: bool, + ) -> Result<()> { + let bank = super::super::cache_routed_outputs::RoutedOutputBank::new(binding.identity(), context)?; + self.routed_outputs = Some(Rc::new(bank)); + if self.routed_outputs.as_ref().ok_or(Error::IdentityMismatch)?.allocated_bytes() != 37_273_600 { + return Err(Error::IdentityMismatch); + } + let maximum = std::array::from_fn(|role| template.iter().map(|keys| keys[role].bytes).max().unwrap_or(0)); + self.adaptive_ephemeral(binding, context, maximum, mapped) + } + + fn adaptive_ephemeral( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + maximum: [usize; 3], + mapped: bool, + ) -> Result<()> { + use super::super::cache_ephemeral_routed::{EphemeralRoutedOwner, MappedStageShape}; + let owner = if mapped { + EphemeralRoutedOwner::new_mapped(binding, context, maximum, MappedStageShape::Single16)? + } else { + EphemeralRoutedOwner::new(binding, context, maximum)? + }; + self.ephemeral_routed = Some(Rc::new(RefCell::new(owner))); + self.check_ephemeral_charge(maximum, mapped) + } + + fn check_ephemeral_charge(&self, maximum: [usize; 3], mapped: bool) -> Result<()> { + let ephemeral_charge = maximum + .into_iter() + .try_fold(if mapped { 36usize } else { 0 }, |n, b| n.checked_add(b).ok_or(Error::Overflow))? + .checked_mul(if mapped { 16 } else { 2 }) + .ok_or(Error::Overflow)?; + let owner = self.ephemeral_routed.as_ref().ok_or(Error::IdentityMismatch)?; + if owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.allocated_bytes() != ephemeral_charge { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + + fn adaptive_shared_pool( + &self, + shared_keys: Vec<[MoeWeightDescriptor; 4]>, + ) -> Result { + let mut shared = cache_profile::SharedPermanentPool::new(shared_keys)?; + let baseline = self.counters; + shared.baseline = + [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; + Ok(shared) + } + + /// Only the permanent192 descriptor map survives. No second routed HashMap/LRU representation competes with + /// the actual slot map. + fn adaptive_plan( + &mut self, + profile: &RankedProfile, + profile_len: usize, + shared: &mut cache_profile::SharedPermanentPool, + largest: usize, + template: [[MoeWeightDescriptor; 3]; 48], + ) -> Result { + let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; + let window_spill = profile_window_spill_with_floor(1usize << 30)?; + let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; + self.main.try_reserve(shared.descriptor_count()).map_err(|_| Error::InputAllocation)?; + let metadata = self.adaptive_host_metadata(profile, profile_len, shared)?; + Ok(AdaptivePlan { template, remaining_main, window_spill, spill, metadata }) + } + + fn adaptive_host_metadata( + &self, + profile: &RankedProfile, + profile_len: usize, + shared: &cache_profile::SharedPermanentPool, + ) -> Result { + let buckets = self.main.capacity().checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3); + let map_bytes = buckets + .ok_or(Error::Overflow)? + .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) + .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) + .ok_or(Error::Overflow)?; + profile + .metadata_bytes() + .checked_add(shared.metadata_bytes()?) + .and_then(|n| n.checked_add(self.routed_outputs.as_ref()?.metadata_bytes())) + .and_then(|n| n.checked_add(self.ephemeral_routed.as_ref()?.try_borrow().ok()?.metadata_bytes())) + .and_then(|n| n.checked_add(map_bytes)) + .and_then(|n| n.checked_add(self.lru.as_ref()?.metadata_bytes().ok()?)) + .and_then(|n| n.checked_add(profile_len)) + .ok_or(Error::Overflow) + } + + /// Prove the COMPLETE adaptive allocation bound before first shared H2D, not after the remaining physical + /// memory became tight. + fn adaptive_admit( + &self, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + plan: &AdaptivePlan, + shared: &cache_profile::SharedPermanentPool, + ) -> Result { + let (free, _) = context.memory_info().map_err(driver_error)?; + let limits = ProfileLimits { + main_cap: plan.remaining_main, + allocated: context.allocated_bytes().checked_add(shared.bytes).ok_or(Error::Overflow)?, + device_budget: context.budget_bytes(), + physical_free: free.checked_sub(shared.bytes).ok_or(Error::InputAllocation)?, + working_reserve: WORKING_RESERVE, + window_spill: plan.window_spill, + }; + let before = cache_strata_adaptive::AdaptivePolicy::new(profile, plan.template, limits)?; + let adaptive_metadata = before + .metadata_bytes() + .checked_add(before.initial_slots().len() * std::mem::size_of::; 3]>>()) + .and_then(|n| n.checked_add(cache_strata_adaptive::transfer_metadata_bound())) + .and_then(|n| n.checked_add(plan.metadata)) + .ok_or(Error::Overflow)?; + if adaptive_metadata > HOST_CAP { + return Err(Error::InputAllocation); + } + Ok(adaptive_metadata) + } + + fn adaptive_cpu_pool(&mut self, binding: &ModelBinding, adaptive_metadata: usize) -> Result<()> { + cpu_budget::admit_pool(binding, adaptive_metadata)?; + let cpu = super::super::super::cpu_expert_miss::CpuMissWorkspace::new(binding, 15) + .map_err(super::super::super::cpu_expert_miss::runtime_error)?; + if cpu.workers() != 15 { + return Err(Error::IdentityMismatch); + } + self.cpu_miss = Some(Rc::new(RefCell::new(cpu))); + Ok(()) + } + + fn adaptive_preload( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + plan: AdaptivePlan, + mut shared: cache_profile::SharedPermanentPool, + ) -> Result<()> { + for layer in 0..48 { + self.preload_shared_quartet(binding, shared.quartet(layer)?, plan.spill, &mut shared)?; + } + if self.main_bytes != shared.bytes || self.main.len() != 192 { + return Err(Error::IdentityMismatch); + } + shared.finish_preload(); + let owner = Self::adaptive_owner(binding, context, profile, &plan, shared.bytes)?; + self.adopt_adaptive(binding, context, shared, owner) + } + + fn adaptive_owner( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + plan: &AdaptivePlan, + shared_bytes: usize, + ) -> Result> { + let (free, _) = context.memory_info().map_err(driver_error)?; + let limits = ProfileLimits { + main_cap: plan.remaining_main, + allocated: context.allocated_bytes(), + device_budget: context.budget_bytes(), + physical_free: free, + working_reserve: WORKING_RESERVE, + window_spill: plan.window_spill, + }; + cache_strata_adaptive::AdaptiveCache::preload( + binding, + context, + profile, + plan.template, + limits, + shared_bytes, + plan.metadata, + ) + } + + fn adopt_adaptive( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + shared: cache_profile::SharedPermanentPool, + owner: cache_strata_adaptive::AdaptiveCache<'ctx>, + ) -> Result<()> { + let Some(main_bytes) = self.main_bytes.checked_add(owner.charged_bytes()) else { + let _ = owner.close(); + return Err(Error::Overflow); + }; + self.adaptive_shared = Some(shared); + self.adaptive = Some(owner); + self.main_bytes = main_bytes; + let shared = self.strata_adaptive_shared_witness()?; + if shared.descriptors != 192 || !shared.successful_bytes_reconcile { + return Err(Error::IdentityMismatch); + } + self.validate(binding, context) + } +} + +/// The fixed inputs of one adaptive build once the shared pool is sized. +struct AdaptivePlan { + template: [[MoeWeightDescriptor; 3]; 48], + remaining_main: usize, + window_spill: usize, + spill: usize, + metadata: usize, +} + +type SharedKeys = Vec<[MoeWeightDescriptor; 4]>; + +/// The first-expert Gate/Up/Down descriptor of every layer, the shared descriptors and the largest layer footprint. +fn adaptive_template(binding: &ModelBinding) -> Result<([[MoeWeightDescriptor; 3]; 48], SharedKeys, usize)> { + let mut layer_keys = Vec::new(); + layer_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; + let mut shared_keys = Vec::new(); + shared_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; + let mut largest = 0usize; + for layer in 0..48 { + let keys = [ + binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Gate).map_err(binding_error)?, + binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Up).map_err(binding_error)?, + binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + largest = largest.max(keys.iter().try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?); + layer_keys.push(keys); + shared_keys.push(binding.moe_shared_preload_descriptors(layer).map_err(binding_error)?); + } + let template = layer_keys.try_into().map_err(|_| Error::InvalidDimension)?; + Ok((template, shared_keys, largest)) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/profile_build_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/profile_build_fns.rs new file mode 100644 index 00000000..ab6d3b21 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/profile_build_fns.rs @@ -0,0 +1,374 @@ +//! The shared-permanent profile build behind the fixed-prefix and learned-main constructors (STRA-338 size: +//! extract-method only). + +#[allow(unused_imports)] +use super::*; + +/// Which sizing and seeding the profile build uses. +#[allow(dead_code)] +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum ProfileKind { + /// Ranked prefix only: the pinned pool is the whole selection. + Fixed, + /// Genuine preload bytes first, then the routed main residency is learned. + Learned, +} + +type LayerKeys = Vec<[MoeWeightDescriptor; 3]>; +type SharedKeys = Vec<[MoeWeightDescriptor; 4]>; + +/// The first-expert descriptors, shared descriptors and per-layer charges of every layer. +struct ProfileLayers { + layer_keys: LayerKeys, + shared_keys: SharedKeys, + charges: [[usize; 3]; 48], +} + +/// The spill window, main slot limit and host metadata the profile build is admitted against. +struct ProfileBudget { + remaining_main: usize, + window_spill: usize, + spill: usize, + main_slot_limit: usize, + selected: Vec, + metadata_bytes: usize, +} + +impl<'ctx> MoeWeightCache<'ctx> { + pub(super) fn build_profile( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + bytes_len: usize, + kind: ProfileKind, + ) -> Result<()> { + let (layers, mut shared, baseline) = self.profile_open(binding, context)?; + let budget = self.profile_budget(kind, profile, bytes_len, &layers, &shared)?; + if kind == ProfileKind::Learned { + self.learned_metadata_bytes = budget.metadata_bytes; + } + // Closed source/geometry was checked for every descriptor above. Only + // full finite actual owned bytes from the same binding are uploaded. + self.profile_preload_shared(binding, &mut shared, budget.spill)?; + let expected_bytes = self.profile_pin(context, profile, &layers, shared, budget, baseline)?; + self.profile_preload_pinned(binding, profile, &layers.layer_keys, expected_bytes)?; + if kind == ProfileKind::Learned { + self.seed_learned_main()?; + } + self.validate(binding, context) + } + + /// Validate, admit the MTP input workspace and size the layers and the shared permanent pool. + fn profile_open( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result<(ProfileLayers, cache_profile::SharedPermanentPool, WeightCacheCounters)> { + self.validate(binding, context)?; + self.admit_mtp_input_workspace(binding)?; + let baseline = self.counters; + let mut layers = self.profile_layers(binding)?; + let mut shared = cache_profile::SharedPermanentPool::new(std::mem::take(&mut layers.shared_keys))?; + shared.baseline = + [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; + Ok((layers, shared, baseline)) + } + + fn profile_layers(&self, binding: &ModelBinding) -> Result { + let mut layer_keys = Vec::new(); + layer_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; + let mut shared_keys = Vec::new(); + shared_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; + let mut charges = [[0usize; 3]; 48]; + for (layer, charge) in charges.iter_mut().enumerate() { + let keys = [ + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?, + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up).map_err(binding_error)?, + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + for (n, key) in keys.iter().enumerate() { + charge[n] = self.weight_layout(*key)?.map_or(key.bytes, |(_, bytes)| bytes); + } + layer_keys.push(keys); + shared_keys.push(binding.moe_shared_preload_descriptors(layer as u32).map_err(binding_error)?); + } + Ok(ProfileLayers { layer_keys, shared_keys, charges }) + } + + fn profile_budget( + &mut self, + kind: ProfileKind, + profile: &RankedProfile, + bytes_len: usize, + layers: &ProfileLayers, + shared: &cache_profile::SharedPermanentPool, + ) -> Result { + let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; + let (minimum, largest) = charge_extremes(&layers.charges)?; + let window_spill = profile_window_spill_with_floor(1usize << 30)?; + let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; + // Metadata for even the largest possible selected prefix is charged BEFORE H2D. + let maximum_count = profile_maximum(kind, profile, &layers.charges, remaining_main, spill, minimum, shared)?; + self.main.try_reserve(maximum_count.max(1 << 15)).map_err(|_| Error::InputAllocation)?; + let main_slot_limit = self.main.capacity(); + let selected = selected_flags()?; + let metadata_bytes = self.profile_metadata(kind, profile, bytes_len, layers, shared, selected.capacity())?; + check_budget(metadata_bytes, maximum_count, main_slot_limit)?; + Ok(ProfileBudget { remaining_main, window_spill, spill, main_slot_limit, selected, metadata_bytes }) + } + + fn profile_metadata( + &self, + kind: ProfileKind, + profile: &RankedProfile, + bytes_len: usize, + layers: &ProfileLayers, + shared: &cache_profile::SharedPermanentPool, + selected_capacity: usize, + ) -> Result { + let map_bytes = self.main_map_bytes()?; + let learned_extra = if kind == ProfileKind::Learned { + std::mem::size_of::() + std::mem::size_of::<[usize; 144]>() + } else { + 0 + }; + profile + .metadata_bytes() + .checked_add(shared.metadata_bytes()?) + .and_then(|n| n.checked_add(selected_capacity * std::mem::size_of::())) + .and_then(|n| n.checked_add(std::mem::size_of::())) + .and_then(|n| n.checked_add(std::mem::size_of::())) + .and_then(|n| n.checked_add(bytes_len)) + .and_then(|n| n.checked_add(layers.layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>())) + .and_then(|n| n.checked_add(self.lru.as_ref()?.metadata_bytes().ok()?)) + .and_then(|n| n.checked_add(map_bytes)) + .and_then(|n| n.checked_add(learned_extra)) + .ok_or(Error::Overflow) + } + + fn main_map_bytes(&self) -> Result { + let buckets = self.main.capacity().checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3); + buckets + .ok_or(Error::Overflow)? + .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) + .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) + .ok_or(Error::Overflow) + } + + fn profile_preload_shared( + &mut self, + binding: &ModelBinding, + shared: &mut cache_profile::SharedPermanentPool, + spill: usize, + ) -> Result<()> { + for layer in 0..48 { + let keys = shared.quartet(layer)?; + self.preload_shared_quartet(binding, keys, spill, shared)?; + } + if self.main_bytes != shared.bytes + || self.main.len() != shared.descriptor_count() + || self.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != 0 + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + + /// Actual owners now appear in both allocated_bytes and physical_free. Subtract their bytes ONLY from the + /// remaining main pool. Returns the byte total the pinned preload must reach. + fn profile_pin( + &mut self, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + layers: &ProfileLayers, + shared: cache_profile::SharedPermanentPool, + budget: ProfileBudget, + baseline: WeightCacheCounters, + ) -> Result { + let limits = profile_limits(context, budget.remaining_main, budget.window_spill)?; + let plan = PrefixPlan::new_shared_with_storage(profile, &layers.charges, limits, budget.selected)?; + let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?; + if count.checked_add(shared.descriptor_count()).is_none_or(|n| n > budget.main_slot_limit) { + return Err(Error::InputAllocation); + } + let expected_bytes = plan.charged_bytes.checked_add(shared.bytes).ok_or(Error::Overflow)?; + self.pinned = Some(pinned_pool(plan, shared, budget.main_slot_limit, budget.metadata_bytes, baseline)); + Ok(expected_bytes) + } + + fn profile_preload_pinned( + &mut self, + binding: &ModelBinding, + profile: &RankedProfile, + layer_keys: &LayerKeys, + expected_bytes: usize, + ) -> Result<()> { + let prefix = self.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.prefix; + let count = prefix.checked_mul(3).ok_or(Error::Overflow)?; + for &(layer, expert) in &profile.ordered_pairs()[..prefix] { + let keys = pinned_keys(binding, layer_keys, layer, expert)?; + self.preload_pinned_triplet(binding, keys)?; + } + self.finish_pinned(expected_bytes, count) + } + + fn finish_pinned(&mut self, expected_bytes: usize, count: usize) -> Result<()> { + if self.main_bytes != expected_bytes + || self.spill_len()? != 0 + || self.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count) + { + return Err(Error::IdentityMismatch); + } + let shared = self.pinned.as_mut().and_then(|pool| pool.shared.as_mut()); + shared.ok_or(Error::IdentityMismatch)?.finish_preload(); + Ok(()) + } + + /// Every cached entry must carry its exact charge, a live age and, if unrouted, a shared permanent identity. + fn check_main_entries(&self, shared: &cache_profile::SharedPermanentPool) -> Result<()> { + for (key, entry) in &self.main { + let expected = self.weight_layout(*key)?.map_or(key.bytes, |(_, charge)| charge); + if entry.charged_bytes != expected + || entry.age == 0 + || entry.age > self.age + || (key.expert.is_none() && !shared.contains(*key)) + { + return Err(Error::IdentityMismatch); + } + } + Ok(()) + } + + /// The same real owners are already complete. Seed the existing empty metadata only; no source read, allocation + /// or H2D occurs here. + fn seed_learned_main(&mut self) -> Result<()> { + let shared = self.pinned.as_ref().and_then(|pool| pool.shared.as_ref()).ok_or(Error::IdentityMismatch)?; + self.check_main_entries(shared)?; + let resident = + self.main.iter().filter(|(key, _)| !shared.contains(**key)).map(|(key, entry)| (*key, entry.age)); + self.lru.as_mut().ok_or(Error::IdentityMismatch)?.seed_existing(self.age, resident)?; + self.learned_main = true; + if self.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != self.spill_len()? { + return Err(Error::IdentityMismatch); + } + Ok(()) + } +} + +fn check_budget(metadata_bytes: usize, maximum_count: usize, main_slot_limit: usize) -> Result<()> { + if metadata_bytes > HOST_CAP || maximum_count > main_slot_limit { + return Err(Error::InputAllocation); + } + Ok(()) +} + +fn selected_flags() -> Result> { + let mut selected = Vec::new(); + selected.try_reserve_exact(48 * 512).map_err(|_| Error::InputAllocation)?; + selected.resize(48 * 512, false); + Ok(selected) +} + +/// The smallest and largest per-layer charge; an empty layer is refused. +fn charge_extremes(charges: &[[usize; 3]; 48]) -> Result<(usize, usize)> { + let mut totals = [0usize; 48]; + for (total, roles) in totals.iter_mut().zip(charges) { + *total = roles.iter().try_fold(0usize, |n, v| n.checked_add(*v)).ok_or(Error::Overflow)?; + } + let minimum = *totals.iter().min().ok_or(Error::InvalidDimension)?; + let largest = *totals.iter().max().ok_or(Error::InvalidDimension)?; + if minimum == 0 { + return Err(Error::InvalidDimension); + } + Ok((minimum, largest)) +} + +/// Metadata slot bound for the fixed prefix or the learned main residency, plus the shared descriptors. +fn profile_maximum( + kind: ProfileKind, + profile: &RankedProfile, + charges: &[[usize; 3]; 48], + remaining_main: usize, + spill: usize, + minimum: usize, + shared: &cache_profile::SharedPermanentPool, +) -> Result { + if kind == ProfileKind::Learned { + return cache_profile::learned_main_slot_bound(charges, remaining_main)? + .checked_add(shared.descriptor_count()) + .ok_or(Error::Overflow); + } + remaining_main + .checked_sub(spill) + .ok_or(Error::InputAllocation)? + .checked_div(minimum) + .ok_or(Error::InvalidDimension)? + .min(profile.ordered_pairs().len()) + .checked_mul(3) + .and_then(|n| n.checked_add(shared.descriptor_count())) + .ok_or(Error::Overflow) +} + +/// The Gate/Up/Down descriptors of one pinned expert; they must equal the layer's topology with the expert filled in. +fn pinned_keys( + binding: &ModelBinding, + layer_keys: &LayerKeys, + layer: u16, + expert: u16, +) -> Result<[MoeWeightDescriptor; 3]> { + let (layer32, expert32) = (u32::from(layer), u32::from(expert)); + let keys = [ + binding.moe_preload_descriptor(layer32, expert32, MoeMatrixRole::Gate).map_err(binding_error)?, + binding.moe_preload_descriptor(layer32, expert32, MoeMatrixRole::Up).map_err(binding_error)?, + binding.moe_preload_descriptor(layer32, expert32, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + let mut topology_keys = layer_keys[usize::from(layer)]; + for key in &mut topology_keys { + key.expert = Some(expert32); + } + if keys != topology_keys { + return Err(Error::IdentityMismatch); + } + Ok(keys) +} + +fn profile_limits(context: &Context<'_>, remaining_main: usize, window_spill: usize) -> Result { + let (free, _) = context.memory_info().map_err(driver_error)?; + Ok(ProfileLimits { + main_cap: remaining_main, + allocated: context.allocated_bytes(), + device_budget: context.budget_bytes(), + physical_free: free, + working_reserve: WORKING_RESERVE, + window_spill, + }) +} + +#[cfg_attr(not(test), allow(unused_variables))] +fn pinned_pool( + plan: PrefixPlan, + shared: cache_profile::SharedPermanentPool, + main_slot_limit: usize, + metadata_bytes: usize, + baseline: WeightCacheCounters, +) -> PinnedPool { + let shared_bytes = shared.bytes as u64; + PinnedPool { + plan, + loaded_matrices: 0, + shared: Some(shared), + #[cfg(test)] + metadata_bytes, + main_slot_limit, + #[cfg(test)] + fixed_resident_upload_bytes: baseline.upload_bytes, + #[cfg(test)] + fixed_resident_read_bytes: baseline.read_bytes, + pinned_hits: 0, + spill_hits: 0, + spill_misses: 0, + preload_read_bytes: shared_bytes, + preload_upload_bytes: shared_bytes, + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs index 6ae90e3a..3f7db81e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs @@ -42,9 +42,7 @@ pub(crate) struct WindowProofReport { } impl WindowProofReport { - /// The root-owned wrapper calls this only AFTER closing its actual - /// caches/output/session/context and verifying actual zero allocations. - pub(crate) fn assert_success_and_print(self) { + fn assert_candidate(&self) { assert_eq!(self.logit_words, 248320); assert_eq!(self.residual_words, 10240); assert_eq!(self.logit_differences, 0); @@ -57,6 +55,9 @@ impl WindowProofReport { for (layer, pair) in pairs.iter().enumerate() { assert_eq!(pair, &[(layer as u32, 0, 2), (layer as u32, 2, 4)]); } + } + + fn assert_partials(&self) { assert_eq!(self.partials.len(), 3); for (p, expected) in self.partials.iter().zip([65, 193, 256]) { assert_eq!(p.rows, expected); @@ -68,11 +69,26 @@ impl WindowProofReport { assert!(p.mtp_refused && p.publication_refused); assert!(p.target_unchanged && p.draft_unchanged); } + } + + /// The root-owned wrapper calls this only AFTER closing its actual + /// caches/output/session/context and verifying actual zero allocations. + pub(crate) fn assert_success_and_print(self) { + self.assert_candidate(); + self.assert_partials(); assert_eq!(self.cancel_observation, Some((193, 192))); assert!(self.cancelled && self.cancel_target_unchanged && self.cancel_draft_unchanged); assert!(self.checkpoint_usable && self.healthy); eprintln!( - "window boundary PASS A_rows=4 A_layers=48 micro=2 full_head_words=248320 residual_words=10240 target_draft_continuation_exact=true B_rows=65,193,256 B_layers=1 B_real_finite_words=5263360 B_micro=64 B_incomplete_publish_and_mtp_refused=true C_rows=256 C_cancel_global_row=193 C_completed_rows=192 target_draft_checkpoint_unchanged=true whole256_full48_numeric=false long_context_quality=false speed_claim=false" + "{}", + concat!( + "window boundary PASS A_rows=4 A_layers=48 micro=2 full_head_words=248320 ", + "residual_words=10240 target_draft_continuation_exact=true B_rows=65,193,256 B_layers=1 ", + "B_real_finite_words=5263360 B_micro=64 B_incomplete_publish_and_mtp_refused=true ", + "C_rows=256 C_cancel_global_row=193 C_completed_rows=192 ", + "target_draft_checkpoint_unchanged=true whole256_full48_numeric=false ", + "long_context_quality=false speed_claim=false" + ) ); } } @@ -110,6 +126,10 @@ fn tokens(count: usize, vocab: Dimension) -> Result> { Ok(result) } +#[path = "executor_window_numeric/proof.rs"] +mod proof; +use proof::{CancelReport, CandidateReport, Proof}; + fn run<'driver>( binding: &ModelBinding, session: &mut QwenSession<'driver>, @@ -118,225 +138,37 @@ fn run<'driver>( moe: &mut MoeWeightCache<'driver>, dense: &DenseWeightCache<'_>, ) -> Result { - let vocab = Dimension::new(248320)?; - let bounds = crate::qwen_forward::contract::position_dimension(); - let ids = tokens(4, vocab)?; - let next = TokenId::new(0, vocab)?; - let follow = TokenId::new(1, vocab)?; - if !session.test_reset_replay_snapshot(binding)?.has_prefix(0, [-1, -1]) { - return Err(Error::IdentityMismatch); - } - output.test_reset_replay_record(true)?; - + let mut proof = Proof::open(binding, session, output, kar, moe, dense)?; // A: unchanged actual Native4 target/draft path FIRST. The new candidate // changes only the sealed window size; no retrospective baseline policy. - let mut baseline_draft = MtpDecoder::new(binding)?; - let baseline = QwenForward::prefill_chunk_cached_joint( - binding, - &ids, - None, - session, - &mut baseline_draft, - output, - Some(&mut *kar), - moe, - dense, - 512 * 1024 * 1024, - || false, - )? - .ok_or(Error::IdentityMismatch)?; - let baseline_logits = output.test_reset_replay_take_logits()?; - let baseline_greedy = baseline.predicted(session)?; - let baseline_stream = baseline.streams(binding, ids[3], Position::new(3, bounds)?, session)?; - let mut baseline_bits = Vec::new(); - baseline_bits.try_reserve_exact(baseline_stream.len()).map_err(|_| Error::InputAllocation)?; - baseline_bits.extend(baseline_stream.iter().map(|v| v.to_bits())); - let baseline_target = session.test_reset_replay_snapshot(binding)?; - let baseline_mtp = baseline_draft.test_chunk_snapshot(); - baseline_draft.warm_retained(binding, session, &baseline, next, moe)?; - let continuation = QwenForward::prefill_for_mtp_cached( - binding, - next, - Position::new(4, bounds)?, - session, - output, - Some(&mut *kar), - moe, - dense, - )?; - baseline_draft.warm_prefill(binding, session, &continuation, follow, moe)?; - let continued_target = session.test_reset_replay_snapshot(binding)?; - let continued_mtp = baseline_draft.test_chunk_snapshot(); - drop(continuation); + let baseline = proof.baseline()?; + let candidate = proof.candidate(&baseline)?; drop(baseline); - drop(baseline_draft); - QwenForward::reset(session)?; - - let mut candidate_draft = MtpDecoder::new(binding)?; - let (candidate, full_journal) = { - let mut txn = QwenForward::prepare_prefill_chunk_with_policy_windowed( - binding, - &ids, - None, - session, - output, - Some(&mut *kar), - moe, - dense, - 512 * 1024 * 1024, - || false, - ChunkMoePolicy::ExperimentalRetainedGr, - true, - Some(BoundaryPlan::FullMicro2), - )?; - let journal = owned_journal(&txn)?; - let ready = candidate_draft.stage_prefill_chunk(binding, &mut txn, moe, || false)?; - let source = txn.publish_joint(ready)?.into_target_product().ok_or(Error::IdentityMismatch)?; - (source, journal) - }; - let candidate_logits = output.test_reset_replay_take_logits()?; - let logit_words = candidate_logits.len(); - let logit_differences = if baseline_logits.len() == candidate_logits.len() { - baseline_logits.iter().zip(candidate_logits.iter()).filter(|(a, b)| a != b).count() - } else { - usize::MAX - }; - let actual_stream = candidate.streams(binding, ids[3], Position::new(3, bounds)?, session)?; - let residual_words = actual_stream.len(); - let residual_differences = if baseline_bits.len() == actual_stream.len() { - baseline_bits.iter().zip(actual_stream.iter()).filter(|(a, b)| **a != b.to_bits()).count() - } else { - usize::MAX - }; - let greedy_equal = baseline_greedy == candidate.predicted(session)?; - let target_equal = baseline_target.numeric_eq(&session.test_reset_replay_snapshot(binding)?); - let draft_equal = candidate_draft.test_chunk_eq(&baseline_mtp); - candidate_draft.validate_resume(binding, session, &candidate, &[0, 1, 0, 1])?; - candidate_draft.warm_retained(binding, session, &candidate, next, moe)?; - let continuation = QwenForward::prefill_for_mtp_cached( - binding, - next, - Position::new(4, bounds)?, - session, - output, - Some(&mut *kar), - moe, - dense, - )?; - candidate_draft.warm_prefill(binding, session, &continuation, follow, moe)?; - let continued_target_equal = continued_target.numeric_eq(&session.test_reset_replay_snapshot(binding)?); - let continued_draft_equal = candidate_draft.test_chunk_eq(&continued_mtp); - drop(continuation); - drop(candidate); - drop(candidate_draft); - drop(baseline_logits); - drop(candidate_logits); - drop(baseline_target); - drop(baseline_mtp); - drop(continued_target); - drop(continued_mtp); - // B: genuine65/193/256 row inputs and real first-layer outputs, not a // metadata-only fabricated completion. No finish/head/MTP publication. - let mut partials = Vec::new(); - partials.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; - for count in [65, 193, 256] { - QwenForward::reset(session)?; - let fresh = session.test_reset_replay_snapshot(binding)?; - let actual_ids = tokens(count, vocab)?; - let mut draft = MtpDecoder::new(binding)?; - let original_draft = draft.test_chunk_snapshot(); - let (finite_words, journal, publication_refused, mtp_refused) = { - let mut txn = QwenForward::prepare_prefill_chunk_with_policy_windowed( - binding, - &actual_ids, - Some(next), - session, - output, - Some(&mut *kar), - moe, - dense, - 512 * 1024 * 1024, - || false, - ChunkMoePolicy::ExperimentalRetainedGr, - true, - Some(BoundaryPlan::FirstLayer), - )?; - let finite_words = txn.test_partial_words(); - let journal = owned_journal(&txn)?; - let publication_refused = txn.test_publication_preflight_refused(); - let mtp_refused = - matches!(draft.stage_prefill_chunk(binding, &mut txn, moe, || false), Err(Error::IdentityMismatch)); - (finite_words, journal, publication_refused, mtp_refused) - }; - partials.push(PartialReport { - rows: count, - finite_words, - journal, - publication_refused, - mtp_refused, - target_unchanged: fresh.numeric_eq(&session.test_reset_replay_snapshot(binding)?), - draft_unchanged: draft.test_chunk_eq(&original_draft), - }); - } + let partials = proof.partials()?; + let cancel = proof.cancellation()?; + Ok(window_report(candidate, partials, cancel)) +} - // C: exactly256 real rows, cancellation when the actual fourth-window - // attention producer reaches globalposition193. Original committed state - // and a genuine checkpoint remain untouched; no fake draft branch warm. - QwenForward::reset(session)?; - let checkpoint = session.checkpoint()?; - let fresh = session.test_reset_replay_snapshot(binding)?; - let draft = MtpDecoder::new(binding)?; - let original_draft = draft.test_chunk_snapshot(); - let actual_ids = tokens(256, vocab)?; - let observation = Rc::new(Cell::new(None)); - let cancellation = Rc::new(Cell::new(false)); - let cancelled = matches!( - QwenForward::prepare_prefill_chunk_with_policy_windowed( - binding, - &actual_ids, - Some(next), - session, - output, - Some(&mut *kar), - moe, - dense, - 512 * 1024 * 1024, - || cancellation.get(), - ChunkMoePolicy::ExperimentalRetainedGr, - true, - Some(BoundaryPlan::CancelFirstLayerAt193 { - observed: Rc::clone(&observation), - cancelled: Rc::clone(&cancellation), - }), - ), - Err(Error::Unsupported(Stage::Executor)) - ); - let cancel_target_unchanged = fresh.numeric_eq(&session.test_reset_replay_snapshot(binding)?); - let cancel_draft_unchanged = draft.test_chunk_eq(&original_draft); - session.restore_checkpoint(&checkpoint)?; - let checkpoint_usable = fresh.numeric_eq(&session.test_reset_replay_snapshot(binding)?); - let context = session.mtp_context()?; - moe.validate(binding, context)?; - dense.validate(binding)?; - let healthy = !context.is_poisoned(); - Ok(WindowProofReport { - logit_words, - logit_differences, - residual_words, - residual_differences, - greedy_equal, - target_equal, - draft_equal, - continued_target_equal, - continued_draft_equal, - full_journal, +fn window_report(candidate: CandidateReport, partials: Vec, cancel: CancelReport) -> WindowProofReport { + WindowProofReport { + logit_words: candidate.logit_words, + logit_differences: candidate.logit_differences, + residual_words: candidate.residual_words, + residual_differences: candidate.residual_differences, + greedy_equal: candidate.greedy_equal, + target_equal: candidate.target_equal, + draft_equal: candidate.draft_equal, + continued_target_equal: candidate.continued_target_equal, + continued_draft_equal: candidate.continued_draft_equal, + full_journal: candidate.full_journal, partials, - cancel_observation: observation.get(), - cancelled, - cancel_target_unchanged, - cancel_draft_unchanged, - checkpoint_usable, - healthy, - }) + cancel_observation: cancel.observation, + cancelled: cancel.cancelled, + cancel_target_unchanged: cancel.target_unchanged, + cancel_draft_unchanged: cancel.draft_unchanged, + checkpoint_usable: cancel.checkpoint_usable, + healthy: cancel.healthy, + } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric/proof.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric/proof.rs new file mode 100644 index 00000000..408cd2be --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric/proof.rs @@ -0,0 +1,332 @@ +//! The proof phases of the window boundary observer (STRA-338 size: extract-method only). + +#[allow(unused_imports)] +use super::*; +use crate::qwen_forward::mtp::MtpChunkNumericSnapshot; +use crate::qwen_forward::session::ResetReplaySnapshot; + +const HOST_BUDGET: usize = 512 * 1024 * 1024; + +type Journal = Vec<(u32, usize, usize)>; + +/// The unchanged Native4 target/draft path, measured first. +pub(super) struct Baseline { + logits: Box<[u32]>, + greedy: TokenId, + bits: Vec, + target: ResetReplaySnapshot, + mtp: MtpChunkNumericSnapshot, + continued_target: ResetReplaySnapshot, + continued_mtp: MtpChunkNumericSnapshot, +} + +/// The windowed candidate compared against the baseline. +pub(super) struct CandidateReport { + pub(super) logit_words: usize, + pub(super) logit_differences: usize, + pub(super) residual_words: usize, + pub(super) residual_differences: usize, + pub(super) greedy_equal: bool, + pub(super) target_equal: bool, + pub(super) draft_equal: bool, + pub(super) continued_target_equal: bool, + pub(super) continued_draft_equal: bool, + pub(super) full_journal: Journal, +} + +/// The cancellation phase of the proof. +pub(super) struct CancelReport { + pub(super) observation: Option<(usize, usize)>, + pub(super) cancelled: bool, + pub(super) target_unchanged: bool, + pub(super) draft_unchanged: bool, + pub(super) checkpoint_usable: bool, + pub(super) healthy: bool, +} + +/// What the first-layer partial window observed before its publication was refused. +struct FirstLayer { + finite_words: usize, + journal: Journal, + publication_refused: bool, + mtp_refused: bool, +} + +fn count_differences(a: &[A], b: &[B], same: impl Fn(&A, &B) -> bool) -> usize { + if a.len() == b.len() { a.iter().zip(b).filter(|(x, y)| !same(x, y)).count() } else { usize::MAX } +} + +/// The windowed prefill transaction under the experimental retained-GR policy. The transaction borrows only the +/// session; every other owner is reborrowed for this call alone. +#[allow(clippy::too_many_arguments)] +fn prepare_txn<'s, 'driver>( + binding: &ModelBinding, + session: &'s mut QwenSession<'driver>, + output: &OutputStage<'_, '_>, + kar: &mut KarPleCache<'_>, + moe: &mut MoeWeightCache<'driver>, + dense: &DenseWeightCache<'_>, + ids: &[TokenId], + known_next: Option, + boundary: BoundaryPlan, + cancelled: impl FnMut() -> bool, +) -> Result> { + let policy = ChunkMoePolicy::ExperimentalRetainedGr; + QwenForward::prepare_prefill_chunk_with_policy_windowed( + binding, + ids, + known_next, + session, + output, + Some(kar), + moe, + dense, + HOST_BUDGET, + cancelled, + policy, + true, + Some(boundary), + ) +} + +/// The loaded owners and fixed tokens every proof phase works on. +pub(super) struct Proof<'a, 'driver, 'k, 'o, 'p, 'd> { + pub(super) binding: &'a ModelBinding, + pub(super) session: &'a mut QwenSession<'driver>, + pub(super) output: &'a OutputStage<'o, 'p>, + pub(super) kar: &'a mut KarPleCache<'k>, + pub(super) moe: &'a mut MoeWeightCache<'driver>, + pub(super) dense: &'a DenseWeightCache<'d>, + pub(super) vocab: Dimension, + pub(super) bounds: Dimension, + pub(super) ids: Vec, + pub(super) next: TokenId, + pub(super) follow: TokenId, +} + +impl<'a, 'driver, 'k, 'o, 'p, 'd> Proof<'a, 'driver, 'k, 'o, 'p, 'd> { + /// The fixed tokens and the fresh-session check, then the output replay recorder on. + pub(super) fn open( + binding: &'a ModelBinding, + session: &'a mut QwenSession<'driver>, + output: &'a OutputStage<'o, 'p>, + kar: &'a mut KarPleCache<'k>, + moe: &'a mut MoeWeightCache<'driver>, + dense: &'a DenseWeightCache<'d>, + ) -> Result { + let vocab = Dimension::new(248320)?; + let bounds = crate::qwen_forward::contract::position_dimension(); + let ids = tokens(4, vocab)?; + let (next, follow) = (TokenId::new(0, vocab)?, TokenId::new(1, vocab)?); + if !session.test_reset_replay_snapshot(binding)?.has_prefix(0, [-1, -1]) { + return Err(Error::IdentityMismatch); + } + output.test_reset_replay_record(true)?; + Ok(Self { binding, session, output, kar, moe, dense, vocab, bounds, ids, next, follow }) + } +} + +impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { + fn snapshot(&self) -> Result { + self.session.test_reset_replay_snapshot(self.binding) + } + + fn snapshots(&self, draft: &MtpDecoder) -> Result<(ResetReplaySnapshot, MtpChunkNumericSnapshot)> { + Ok((self.snapshot()?, draft.test_chunk_snapshot())) + } + + /// A: unchanged actual Native4 target/draft path FIRST. The new candidate changes only the sealed window + /// size; no retrospective baseline policy. + pub(super) fn baseline(&mut self) -> Result { + let mut draft = MtpDecoder::new(self.binding)?; + let product = self.baseline_prefill(&mut draft)?; + let (logits, greedy, bits) = self.baseline_outputs(&product)?; + let (target, mtp) = self.snapshots(&draft)?; + draft.warm_retained(self.binding, self.session, &product, self.next, self.moe)?; + self.continuation(&mut draft)?; + let (continued_target, continued_mtp) = self.snapshots(&draft)?; + drop(product); + drop(draft); + QwenForward::reset(self.session)?; + Ok(Baseline { logits, greedy, bits, target, mtp, continued_target, continued_mtp }) + } + + fn baseline_prefill(&mut self, draft: &mut MtpDecoder) -> Result { + QwenForward::prefill_chunk_cached_joint( + self.binding, + &self.ids, + None, + self.session, + draft, + self.output, + Some(&mut *self.kar), + self.moe, + self.dense, + HOST_BUDGET, + || false, + )? + .ok_or(Error::IdentityMismatch) + } + + fn baseline_outputs(&self, product: &TargetStepProduct) -> Result<(Box<[u32]>, TokenId, Vec)> { + let logits = self.output.test_reset_replay_take_logits()?; + let greedy = product.predicted(self.session)?; + let stream = product.streams(self.binding, self.ids[3], Position::new(3, self.bounds)?, self.session)?; + let mut bits = Vec::new(); + bits.try_reserve_exact(stream.len()).map_err(|_| Error::InputAllocation)?; + bits.extend(stream.iter().map(|v| v.to_bits())); + Ok((logits, greedy, bits)) + } + + /// The continuation row after the window: one more actual prefill step, then the draft warm. + fn continuation(&mut self, draft: &mut MtpDecoder) -> Result<()> { + let position = Position::new(4, self.bounds)?; + let step = QwenForward::prefill_for_mtp_cached( + self.binding, + self.next, + position, + self.session, + self.output, + Some(&mut *self.kar), + self.moe, + self.dense, + )?; + draft.warm_prefill(self.binding, self.session, &step, self.follow, self.moe)?; + Ok(()) + } + + pub(super) fn candidate(&mut self, base: &Baseline) -> Result { + let mut draft = MtpDecoder::new(self.binding)?; + let (product, full_journal) = self.stage_full_micro(&mut draft)?; + let logits = self.output.test_reset_replay_take_logits()?; + let position = Position::new(3, self.bounds)?; + let stream = product.streams(self.binding, self.ids[3], position, self.session)?; + let logit_differences = count_differences(&base.logits, &logits, |a, b| a == b); + let residual_differences = count_differences(&base.bits, &stream, |a, b| *a == b.to_bits()); + let greedy_equal = base.greedy == product.predicted(self.session)?; + let target_equal = base.target.numeric_eq(&self.snapshot()?); + let draft_equal = draft.test_chunk_eq(&base.mtp); + let (continued_target_equal, continued_draft_equal) = + self.candidate_continuation(base, &mut draft, &product)?; + Ok(CandidateReport { + logit_words: logits.len(), + logit_differences, + residual_words: stream.len(), + residual_differences, + greedy_equal, + target_equal, + draft_equal, + continued_target_equal, + continued_draft_equal, + full_journal, + }) + } + + fn candidate_continuation( + &mut self, + base: &Baseline, + draft: &mut MtpDecoder, + product: &TargetStepProduct, + ) -> Result<(bool, bool)> { + draft.validate_resume(self.binding, self.session, product, &[0, 1, 0, 1])?; + draft.warm_retained(self.binding, self.session, product, self.next, self.moe)?; + self.continuation(draft)?; + let target_equal = base.continued_target.numeric_eq(&self.snapshot()?); + Ok((target_equal, draft.test_chunk_eq(&base.continued_mtp))) + } + + fn stage_full_micro(&mut self, draft: &mut MtpDecoder) -> Result<(TargetStepProduct, Journal)> { + let (binding, output, dense) = (self.binding, self.output, self.dense); + let plan = BoundaryPlan::FullMicro2; + let mut txn = + prepare_txn(binding, self.session, output, self.kar, self.moe, dense, &self.ids, None, plan, || false)?; + let journal = owned_journal(&txn)?; + let ready = draft.stage_prefill_chunk(binding, &mut txn, self.moe, || false)?; + let source = txn.publish_joint(ready)?.into_target_product().ok_or(Error::IdentityMismatch)?; + Ok((source, journal)) + } + + pub(super) fn partials(&mut self) -> Result> { + let mut partials = Vec::new(); + partials.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; + for count in [65, 193, 256] { + partials.push(self.partial(count)?); + } + Ok(partials) + } + + fn partial(&mut self, count: usize) -> Result { + QwenForward::reset(self.session)?; + let fresh = self.snapshot()?; + let actual_ids = tokens(count, self.vocab)?; + let mut draft = MtpDecoder::new(self.binding)?; + let original_draft = draft.test_chunk_snapshot(); + let staged = self.stage_first_layer(&actual_ids, &mut draft)?; + let target_unchanged = fresh.numeric_eq(&self.snapshot()?); + let draft_unchanged = draft.test_chunk_eq(&original_draft); + let FirstLayer { finite_words, journal, publication_refused, mtp_refused } = staged; + Ok(PartialReport { + rows: count, + finite_words, + journal, + publication_refused, + mtp_refused, + target_unchanged, + draft_unchanged, + }) + } + + fn stage_first_layer(&mut self, ids: &[TokenId], draft: &mut MtpDecoder) -> Result { + let (binding, output, dense, next) = (self.binding, self.output, self.dense, Some(self.next)); + let plan = BoundaryPlan::FirstLayer; + let mut txn = prepare_txn(binding, self.session, output, self.kar, self.moe, dense, ids, next, plan, || false)?; + let finite_words = txn.test_partial_words(); + let journal = owned_journal(&txn)?; + let publication_refused = txn.test_publication_preflight_refused(); + let staged = draft.stage_prefill_chunk(binding, &mut txn, self.moe, || false); + let mtp_refused = matches!(staged, Err(Error::IdentityMismatch)); + Ok(FirstLayer { finite_words, journal, publication_refused, mtp_refused }) + } + + /// C: exactly256 real rows, cancellation when the actual fourth-window + /// attention producer reaches globalposition193. Original committed state + /// and a genuine checkpoint remain untouched; no fake draft branch warm. + pub(super) fn cancellation(&mut self) -> Result { + QwenForward::reset(self.session)?; + let checkpoint = self.session.checkpoint()?; + let fresh = self.snapshot()?; + let draft = MtpDecoder::new(self.binding)?; + let original_draft = draft.test_chunk_snapshot(); + let observation = Rc::new(Cell::new(None)); + let cancelled = self.cancelled_prepare(&observation)?; + let target_unchanged = fresh.numeric_eq(&self.snapshot()?); + let draft_unchanged = draft.test_chunk_eq(&original_draft); + self.session.restore_checkpoint(&checkpoint)?; + let checkpoint_usable = fresh.numeric_eq(&self.snapshot()?); + let healthy = self.healthy()?; + let observation = observation.get(); + Ok(CancelReport { observation, cancelled, target_unchanged, draft_unchanged, checkpoint_usable, healthy }) + } + + /// The caches still validate against the MTP context, which must not be poisoned. + fn healthy(&mut self) -> Result { + let context = self.session.mtp_context()?; + self.moe.validate(self.binding, context)?; + self.dense.validate(self.binding)?; + Ok(!context.is_poisoned()) + } + + fn cancelled_prepare(&mut self, observation: &Rc>>) -> Result { + let actual_ids = tokens(256, self.vocab)?; + let cancellation = Rc::new(Cell::new(false)); + let plan = BoundaryPlan::CancelFirstLayerAt193 { + observed: Rc::clone(observation), + cancelled: Rc::clone(&cancellation), + }; + let (binding, output, dense, next) = (self.binding, self.output, self.dense, Some(self.next)); + let (session, kar, moe) = (&mut *self.session, &mut *self.kar, &mut *self.moe); + let prepared = + prepare_txn(binding, session, output, kar, moe, dense, &actual_ids, next, plan, || cancellation.get()); + Ok(matches!(prepared, Err(Error::Unsupported(Stage::Executor)))) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch.rs index 3ce215c0..a5441491 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch.rs @@ -21,6 +21,9 @@ const ALPHA_BETA: usize = 96; const BATCH_RESERVE: usize = 128 * 1024 * 1024; const EAGER_TOKENS: usize = 64; /// Largest dequantized GDN matrix (attn_qkv, 10240 x 2560) in FP16 bytes. +/// The shared exclusively loaned GEMM adapter every batched step receives. +type GemmRef<'a> = &'a dyn GdnGemm; + pub(in crate::qwen_forward) const BATCH_SCRATCH_BYTES: usize = CHANNELS * MIXED * 2; /// BF16 alpha/beta GEMM profile. `HighOnly` is the original default @@ -141,3 +144,5 @@ mod impl_buffers; use impl_buffers::release_pool; #[path = "gdn_prefill_batch/impl_gdnstage.rs"] mod impl_gdnstage; +#[path = "gdn_prefill_batch/step_batch_fns.rs"] +mod step_batch_fns; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnstage.rs index 076e3756..28674fec 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnstage.rs @@ -1,6 +1,9 @@ //! Moved out of the parent module by STRA-338: impl GdnStage. #[allow(unused_imports)] +use super::step_batch_fns::{ + check_gdn_window, gather_gdn_rows, gdn_operands, prepare_or_refuse, run_gdn_program, settle_gdn, window_bytes, +}; use super::*; impl GdnStage { @@ -23,130 +26,20 @@ impl GdnStage { cache: &DenseWeightCache<'ctx>, owner: &mut GdnChunkDevice<'ctx>, resources: &mut GdnBatchResources<'ctx>, - gemm: &dyn GdnGemm, + gemm: GemmRef<'_>, ) -> 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::Gdn); let tokens = micro.len(); - if tokens == 0 || tokens > resources.capacity || owner.is_verification() { - return Err(Error::IdentityMismatch); - } - let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; - if expected != layer { - return Err(Error::IdentityMismatch); - } - let descriptor = binding.ordered_layers().get(layer.get() as usize).ok_or(Error::InvalidLayer)?; - if descriptor.index() != layer.get() || descriptor.kind() != BoundLayerKind::Gdn { - return Err(Error::InvalidLayer); - } - let mut host = Vec::new(); - host.try_reserve_exact(tokens * MIXED).map_err(|_| Error::InputAllocation)?; - let mut identities = Vec::new(); - identities.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; - for local in 0..tokens { - let row = micro.row(local)?; - let input = micro.input(local)?; - if row.identity().layer() != layer || row.identity() != input.identity() { - return Err(Error::IdentityMismatch); - } - validate_values(input.mixed(), MIXED)?; - host.extend_from_slice(input.mixed()); - identities.push(input.identity()); - } + check_gdn_window(binding, layer, tokens, resources.capacity, owner)?; + let (host, identities) = gather_gdn_rows(micro, layer)?; let context = cache.retained_context(binding, current)?; let failed = cache.transport_failure_flag(binding, context)?; - let resident = cache.gdn(binding, layer.get())?; - let weights = resident.weights.clone(); - if weights.epsilon().to_bits() != GDN_BATCH_EPSILON.to_bits() { - // The original prompt path normalizes with its own constant. - return Err(Error::Unsupported(Stage::Gdn)); - } - let aux = cache.gdn_aux(resident)?; - let (qkv_w, qkv_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Qkv)?; - let (z_w, z_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Z)?; - let (out_w, out_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Out)?; - let (alpha_w, alpha_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Alpha)?; - let (beta_w, beta_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Beta)?; - if alpha_kind != GdnMatrixKind::Bf16 || beta_kind != GdnMatrixKind::Bf16 { - return Err(Error::Unsupported(Stage::Gdn)); - } - let formats = [native_format(qkv_kind)?, native_format(z_kind)?, native_format(out_kind)?]; - for (role, columns, rows_) in [ - (GdnMatrixRole::Qkv, MIXED, CHANNELS), - (GdnMatrixRole::Z, MIXED, VALUES), - (GdnMatrixRole::Out, VALUES, MIXED), - (GdnMatrixRole::Alpha, MIXED, VALUE_HEADS), - (GdnMatrixRole::Beta, MIXED, VALUE_HEADS), - ] { - if weights.shape(role) != (columns, rows_) { - return Err(Error::InvalidDimension); - } - } - if let Err(primary) = resources.prepare_buffers(context, tokens) { - if primary == Error::CudaExecution { - failed.set(true); - } - owner.refuse(primary); - return Err(primary); - } - let (state, next_state) = owner.micro_operands(micro, &binding.identity())?; - let history_bytes = f32_bytes(owner.history()?)?; - let mixed_bytes = f32_bytes(&host)?; - let operation = (|| -> Result<(Box<[f32]>, Box<[f32]>)> { - let GdnBatchResources { batch, scratch, buffers, .. } = &mut *resources; - let buffers = buffers.as_mut().ok_or(Error::IdentityMismatch)?; - buffers.mixed.copy_from(&mixed_bytes).map_err(driver_error)?; - buffers.history.copy_from(&history_bytes).map_err(driver_error)?; - let batch = batch.as_mut().ok_or(Error::IdentityMismatch)?; - let scratch = scratch.as_ref().ok_or(Error::IdentityMismatch)?; - let mut prefix = batch.begin(tokens, gemm).map_err(driver_error)?; - let program = (|| -> std::result::Result<(), leleka_cuda_driver::Error> { - prefix.pack_mixed(&buffers.mixed, &buffers.mixed_h, &buffers.mixed_bf, buffers.mixed_bf_lo.as_ref())?; - prefix.project_qkv(formats[0], qkv_w, scratch, &buffers.qkv)?; - prefix.project_z(formats[1], z_w, scratch, &buffers.z)?; - prefix.project_alpha_beta(alpha_w, beta_w, &buffers.ab)?; - prefix.gates(aux[1], aux[2], &buffers.gate, &buffers.beta)?; - prefix.conv(&buffers.history, aux[0], &buffers.next_history, &buffers.h)?; - prefix.l2()?; - prefix.recurrence(state, next_state, &buffers.y)?; - prefix.out_norm(aux[3], &buffers.y16)?; - prefix.project_out(formats[2], out_w, scratch, &buffers.bo)?; - Ok(()) - })(); - // `finish` always drains what was admitted so that an earlier - // numerical refusal outranks a later admission error. - // `finish` drains what was admitted and itself returns the latched - // admission error only when the drain showed no numerical refusal, - // so an earlier non-finite stage outranks a later admission error. - let _ = program; - let completion = prefix.finish().map_err(driver_error)?; - let next_history = completion.into_next_history().map_err(|_| Error::NonFinite)?; - let output = download(&buffers.bo, tokens * MIXED)?; - Ok((next_history, output)) - })(); - if matches!(operation, Err(Error::CudaExecution)) { - failed.set(true); - } - // Clean completion leaves this exact-T bank reusable by the next - // layer/micro. On uncertainty it stays owned until poisoned-context - // cleanup; nothing is freed or reissued ahead of the driver's drain. - let (history, output) = match operation { - Ok(values) => values, - Err(primary) => { - owner.refuse(primary); - return Err(primary); - } - }; - let edges = owner.finish_micro(micro, &binding.identity(), history)?; - let mut ready = Vec::new(); - ready.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; - for ((edge, identity), row_output) in edges.into_iter().zip(identities).zip(output.chunks_exact(MIXED)) { - let mut values = Vec::new(); - values.try_reserve_exact(MIXED).map_err(|_| Error::InputAllocation)?; - values.extend_from_slice(row_output); - ready.push(ChunkReady::from_batch(identity, binding.identity(), values.into_boxed_slice(), edge)); - } - Ok(ready) + let operands = gdn_operands(cache, cache.gdn(binding, layer.get())?)?; + prepare_or_refuse(resources, context, tokens, &failed, owner)?; + let bytes = window_bytes(binding, micro, owner, &host)?; + let operation = run_gdn_program(resources, gemm, tokens, &operands, &bytes); + settle_gdn(operation, &failed, owner, micro, binding, identities) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/step_batch_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/step_batch_fns.rs new file mode 100644 index 00000000..295e0552 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/step_batch_fns.rs @@ -0,0 +1,231 @@ +//! Phases of `GdnStage::step_chunk_batch` (STRA-338 size: extract-method only). + +#[allow(unused_imports)] +use super::*; +use crate::qwen_forward::dense_weight_cache::GdnResident; +use leleka_cuda_driver::GdnBatchPrefix; +use std::cell::Cell; + +/// The layer's resident GDN device operands as the batch program needs them. +pub(super) struct GdnOperands<'a, 'ctx> { + qkv: &'a DeviceBuffer<'ctx>, + z: &'a DeviceBuffer<'ctx>, + out: &'a DeviceBuffer<'ctx>, + alpha: &'a DeviceBuffer<'ctx>, + beta: &'a DeviceBuffer<'ctx>, + aux: [&'a DeviceBuffer<'ctx>; 4], + formats: [GdnNativeFormat; 3], +} + +/// The window size, chunk state, layer and GDN descriptor must be this binding's own. +pub(super) fn check_gdn_window( + binding: &ModelBinding, + layer: LayerId, + tokens: usize, + capacity: usize, + owner: &GdnChunkDevice<'_>, +) -> Result<()> { + if tokens == 0 || tokens > capacity || owner.is_verification() { + return Err(Error::IdentityMismatch); + } + let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; + if expected != layer { + return Err(Error::IdentityMismatch); + } + let descriptor = binding.ordered_layers().get(layer.get() as usize).ok_or(Error::InvalidLayer)?; + if descriptor.index() != layer.get() || descriptor.kind() != BoundLayerKind::Gdn { + return Err(Error::InvalidLayer); + } + Ok(()) +} + +/// Genuine rows only: each row's layer and identity match its input, with finite mixed values. +pub(super) fn gather_gdn_rows(micro: &GdnChunkMicro, layer: LayerId) -> Result<(Vec, Vec)> { + let tokens = micro.len(); + let mut host = Vec::new(); + host.try_reserve_exact(tokens * MIXED).map_err(|_| Error::InputAllocation)?; + let mut identities = Vec::new(); + identities.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; + for local in 0..tokens { + let row = micro.row(local)?; + let input = micro.input(local)?; + if row.identity().layer() != layer || row.identity() != input.identity() { + return Err(Error::IdentityMismatch); + } + validate_values(input.mixed(), MIXED)?; + host.extend_from_slice(input.mixed()); + identities.push(input.identity()); + } + Ok((host, identities)) +} + +/// The original prompt path normalizes with its own constant. +fn check_gdn_epsilon(resident: &GdnResident) -> Result<()> { + if resident.weights.epsilon().to_bits() != GDN_BATCH_EPSILON.to_bits() { + return Err(Error::Unsupported(Stage::Gdn)); + } + Ok(()) +} + +/// Every matrix must have its expected shape. +fn check_gdn_shapes(resident: &GdnResident) -> Result<()> { + for (role, columns, rows_) in [ + (GdnMatrixRole::Qkv, MIXED, CHANNELS), + (GdnMatrixRole::Z, MIXED, VALUES), + (GdnMatrixRole::Out, VALUES, MIXED), + (GdnMatrixRole::Alpha, MIXED, VALUE_HEADS), + (GdnMatrixRole::Beta, MIXED, VALUE_HEADS), + ] { + if resident.weights.shape(role) != (columns, rows_) { + return Err(Error::InvalidDimension); + } + } + Ok(()) +} + +pub(super) fn gdn_operands<'a, 'ctx>( + cache: &'a DenseWeightCache<'ctx>, + resident: &'a GdnResident, +) -> Result> { + check_gdn_epsilon(resident)?; + let aux = cache.gdn_aux(resident)?; + let ([qkv, z, out, alpha, beta], [qkv_kind, z_kind, out_kind]) = gdn_matrices(cache, resident)?; + let formats = [native_format(qkv_kind)?, native_format(z_kind)?, native_format(out_kind)?]; + check_gdn_shapes(resident)?; + Ok(GdnOperands { qkv, z, out, alpha, beta, aux, formats }) +} + +type GdnMatrices<'a, 'ctx> = ([&'a DeviceBuffer<'ctx>; 5], [GdnMatrixKind; 3]); + +/// The five resident matrices (Qkv, Z, Out, Alpha, Beta) and the kinds of the three projections; Alpha and Beta +/// must be BF16. +fn gdn_matrices<'a, 'ctx>( + cache: &'a DenseWeightCache<'ctx>, + resident: &'a GdnResident, +) -> Result> { + let (qkv, qkv_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Qkv)?; + let (z, z_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Z)?; + let (out, out_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Out)?; + let (alpha, alpha_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Alpha)?; + let (beta, beta_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Beta)?; + if alpha_kind != GdnMatrixKind::Bf16 || beta_kind != GdnMatrixKind::Bf16 { + return Err(Error::Unsupported(Stage::Gdn)); + } + Ok(([qkv, z, out, alpha, beta], [qkv_kind, z_kind, out_kind])) +} + +/// Allocate the exact-T bank; a refusal marks the chunk device and, on a CUDA failure, the transport. +pub(super) fn prepare_or_refuse<'ctx>( + resources: &mut GdnBatchResources<'ctx>, + context: &'ctx Context<'ctx>, + tokens: usize, + failed: &Cell, + owner: &mut GdnChunkDevice<'ctx>, +) -> Result<()> { + if let Err(primary) = resources.prepare_buffers(context, tokens) { + if primary == Error::CudaExecution { + failed.set(true); + } + owner.refuse(primary); + return Err(primary); + } + Ok(()) +} + +/// The state operands and host byte images of one window. +pub(super) struct WindowBytes<'a, 'ctx> { + pub(super) state: &'a DeviceBuffer<'ctx>, + pub(super) next_state: &'a DeviceBuffer<'ctx>, + pub(super) mixed: Vec, + pub(super) history: Vec, +} + +/// The state operands and the history/mixed byte images of one window. +pub(super) fn window_bytes<'a, 'ctx>( + binding: &ModelBinding, + micro: &GdnChunkMicro, + owner: &'a GdnChunkDevice<'ctx>, + host: &[f32], +) -> Result> { + let (state, next_state) = owner.micro_operands(micro, &binding.identity())?; + let (history, mixed) = (f32_bytes(owner.history()?)?, f32_bytes(host)?); + Ok(WindowBytes { state, next_state, mixed, history }) +} + +/// Upload, run the closed GDN program and read back the next history and the Out projection. +pub(super) fn run_gdn_program<'ctx>( + resources: &mut GdnBatchResources<'ctx>, + gemm: GemmRef<'_>, + tokens: usize, + ops: &GdnOperands<'_, 'ctx>, + bytes: &WindowBytes<'_, 'ctx>, +) -> Result<(Box<[f32]>, Box<[f32]>)> { + let GdnBatchResources { batch, scratch, buffers, .. } = &mut *resources; + let buffers = buffers.as_mut().ok_or(Error::IdentityMismatch)?; + buffers.mixed.copy_from(&bytes.mixed).map_err(driver_error)?; + buffers.history.copy_from(&bytes.history).map_err(driver_error)?; + let batch = batch.as_mut().ok_or(Error::IdentityMismatch)?; + let scratch = scratch.as_ref().ok_or(Error::IdentityMismatch)?; + let mut prefix = batch.begin(tokens, gemm).map_err(driver_error)?; + let program = launch_program(&mut prefix, buffers, scratch, ops, bytes); + // `finish` drains what was admitted and itself returns the latched admission error only when the drain showed no + // numerical refusal, so an earlier non-finite stage outranks a later admission error. + let _ = program; + let completion = prefix.finish().map_err(driver_error)?; + let next_history = completion.into_next_history().map_err(|_| Error::NonFinite)?; + let output = download(&buffers.bo, tokens * MIXED)?; + Ok((next_history, output)) +} + +fn launch_program<'l, 'ctx>( + prefix: &mut GdnBatchPrefix<'l, 'ctx>, + buffers: &'l Buffers<'ctx>, + scratch: &'l DeviceBuffer<'ctx>, + ops: &'l GdnOperands<'l, 'ctx>, + bytes: &'l WindowBytes<'l, 'ctx>, +) -> std::result::Result<(), leleka_cuda_driver::Error> { + let [qkv_format, z_format, out_format] = ops.formats; + prefix.pack_mixed(&buffers.mixed, &buffers.mixed_h, &buffers.mixed_bf, buffers.mixed_bf_lo.as_ref())?; + prefix.project_qkv(qkv_format, ops.qkv, scratch, &buffers.qkv)?; + prefix.project_z(z_format, ops.z, scratch, &buffers.z)?; + prefix.project_alpha_beta(ops.alpha, ops.beta, &buffers.ab)?; + prefix.gates(ops.aux[1], ops.aux[2], &buffers.gate, &buffers.beta)?; + prefix.conv(&buffers.history, ops.aux[0], &buffers.next_history, &buffers.h)?; + prefix.l2()?; + prefix.recurrence(bytes.state, bytes.next_state, &buffers.y)?; + prefix.out_norm(ops.aux[3], &buffers.y16)?; + prefix.project_out(out_format, ops.out, scratch, &buffers.bo) +} + +/// Clean completion leaves this exact-T bank reusable by the next layer/micro. On uncertainty it stays owned until +/// poisoned-context cleanup; nothing is freed or reissued ahead of the driver's drain. All edges are minted only +/// after the whole batch drained finite and the chunk device adopted the final state. +pub(super) fn settle_gdn<'ctx>( + operation: Result<(Box<[f32]>, Box<[f32]>)>, + failed: &Cell, + owner: &mut GdnChunkDevice<'ctx>, + micro: &GdnChunkMicro, + binding: &ModelBinding, + identities: Vec, +) -> Result> { + if matches!(operation, Err(Error::CudaExecution)) { + failed.set(true); + } + let (history, output) = match operation { + Ok(values) => values, + Err(primary) => { + owner.refuse(primary); + return Err(primary); + } + }; + let edges = owner.finish_micro(micro, &binding.identity(), history)?; + let mut ready = Vec::new(); + ready.try_reserve_exact(identities.len()).map_err(|_| Error::InputAllocation)?; + for ((edge, identity), row_output) in edges.into_iter().zip(identities).zip(output.chunks_exact(MIXED)) { + let mut values = Vec::new(); + values.try_reserve_exact(MIXED).map_err(|_| Error::InputAllocation)?; + values.extend_from_slice(row_output); + ready.push(ChunkReady::from_batch(identity, binding.identity(), values.into_boxed_slice(), edge)); + } + Ok(ready) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs index 359294ee..fad74e6b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs @@ -53,3 +53,5 @@ pub(super) use impl_grmicroinput::save_micro_values; mod impl_grstage; #[path = "gr_batch_chunk/impl_grstage_2.rs"] mod impl_grstage_2; +#[path = "gr_batch_chunk/inject_batch_fns.rs"] +mod inject_batch_fns; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs index 66d45d7a..d13a8e4d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs @@ -1,6 +1,9 @@ //! Moved out of the parent module by STRA-338: impl GrStage. #[allow(unused_imports)] +use super::inject_batch_fns::{device_inject, gather_batch}; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +use super::inject_batch_fns::{finish_queued, queued_inject}; use super::*; impl GrStage { @@ -31,19 +34,10 @@ impl GrStage { if owner.injected { return Err(Error::IdentityMismatch); } - let read = &owner.ready; - txn.validate_binding(&binding.identity())?; - read.validate_origin(&binding.identity(), GrRole::Ffn(read.identity.layer().get()))?; - read.identity.validate(txn.token(), txn.position(), read.identity.layer())?; - if read.identity != block_identity { - return Err(Error::IdentityMismatch); - } - validate_streams(&read.streams)?; - validate_values(&read.inject, 4)?; - validate_values(block, 2560)?; + check_batch_read(binding, &owner.ready, block, block_identity, txn)?; let context = txn.cuda_context()?; if let Some(scratch) = owner.scratch.as_ref() { - if !scratch.binding.matches(&read.binding) { + if !scratch.binding.matches(&owner.ready.binding) { return Err(Error::IdentityMismatch); } scratch.buffer(context)?; @@ -69,135 +63,30 @@ impl GrStage { if !(1..=64).contains(&rows.len()) { return Err(Error::InvalidDimension); } - let role = rows[0].ready.role; - let layer = rows[0].ready.identity.layer(); - let first = rows[0].ready.identity.position().get(); - let mut streams = Vec::new(); - let mut blocks = Vec::new(); - let mut injects = Vec::new(); - streams.try_reserve_exact(rows.len() * 10240).map_err(|_| Error::InputAllocation)?; - blocks.try_reserve_exact(rows.len() * 2560).map_err(|_| Error::InputAllocation)?; - injects.try_reserve_exact(rows.len() * 4).map_err(|_| Error::InputAllocation)?; - for (i, row) in rows.iter().enumerate() { - row.ready.validate_origin(&binding.identity(), role)?; - if row.ready.identity.layer() != layer || row.ready.identity.position().get() != first + i as u64 { - return Err(Error::IdentityMismatch); - } - validate_streams(&row.ready.streams)?; - validate_values(&row.block, 2560)?; - validate_values(&row.ready.inject, 4)?; - streams.extend_from_slice(&row.ready.streams); - blocks.extend_from_slice(&row.block); - injects.extend_from_slice(&row.ready.inject); - } + let operands = gather_batch(binding, &rows)?; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - { - let shape = match rows.len() { - 1 => Some(leleka_cuda_driver::GrBatchInjectShape::T1), - 2 => Some(leleka_cuda_driver::GrBatchInjectShape::T2), - 3 => Some(leleka_cuda_driver::GrBatchInjectShape::T3), - _ => None, - }; - let queued = if let Some(shape) = shape - && let Some(mut workspace) = cache.gr_batch_workspace(binding, context)? - { - let result = - workspace.inject(context, shape, &streams, &blocks, &injects).map_err(|error| match error { - leleka_cuda_driver::Error::InvalidDriverValue("GR batch injection finite input") => { - Error::NonFinite - } - other => driver_error(other), - }); - if workspace.is_failed() || context.is_poisoned() { - failed.set(true); - } - Some(result) - } else { - None - }; - // The exclusive scratch lease ends before host finite validation - // or publication of any original row capability. - if let Some(values) = queued { - let values = values?; - if values.len() != rows.len() * 10240 { - return Err(Error::InvalidDimension); - } - validate_values(&values, rows.len() * 10240)?; - let mut completed = Vec::new(); - completed.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; - for (row, column) in rows.into_iter().zip(values.as_chunks::<10240>().0) { - let mut copied = Vec::new(); - copied.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?; - copied.extend_from_slice(column); - completed.push(InjectedResidual::from_candidates( - row.ready.identity, - row.ready.binding, - row.ready.role, - copied.into_boxed_slice(), - )?); - } - cache.retained_context(binding, context)?; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - cache.test_record_gr_batch_completed(binding, context)?; - return Ok(completed); - } + if let Some(values) = queued_inject(binding, context, cache, &failed, &operands, rows.len())? { + return finish_queued(binding, context, cache, rows, values); } - admit_budget(context, rows.len() * (2 * 40960 + 10240 + 16))?; - let (mut residual, mut output, mut injection, mut candidate) = (None, None, None, None); - let result = (|| { - residual = Some(upload_f32(context, &streams)?); - output = Some(upload_f32(context, &blocks)?); - injection = Some(upload_f32(context, &injects)?); - candidate = Some(context.allocate(rows.len() * 40960).map_err(driver_error)?); - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - cache - .chunk_modules(binding, context)? - .gr(context)? - .inject( - rows.len(), - residual.as_ref().ok_or(Error::CudaExecution)?, - output.as_ref().ok_or(Error::CudaExecution)?, - injection.as_ref().ok_or(Error::CudaExecution)?, - candidate.as_mut().ok_or(Error::CudaExecution)?, - ) - .map_err(driver_error)?; - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - context - .gr_batch_inject_residual_f32( - rows.len(), - residual.as_ref().ok_or(Error::CudaExecution)?, - output.as_ref().ok_or(Error::CudaExecution)?, - injection.as_ref().ok_or(Error::CudaExecution)?, - candidate.as_mut().ok_or(Error::CudaExecution)?, - ) - .map_err(driver_error)?; - let values = download_f32(candidate.as_ref().ok_or(Error::CudaExecution)?, rows.len() * 10240)?; - let mut completed = Vec::new(); - completed.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; - for (row, column) in rows.into_iter().zip(values.as_chunks::<10240>().0) { - let mut copied = Vec::new(); - copied.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?; - copied.extend_from_slice(column); - completed.push(InjectedResidual::from_candidates( - row.ready.identity, - row.ready.binding, - row.ready.role, - copied.into_boxed_slice(), - )?); - } - Ok(completed) - })(); - // Attempt every owned release even after a CUDA or finite refusal. - let mut cleanup = Ok(()); - for buffer in [candidate, injection, output, residual].into_iter().flatten() { - let released = buffer.release().map_err(driver_error); - if cleanup.is_ok() { - cleanup = released; - } - } - if cleanup.is_err() || matches!(result, Err(Error::CudaExecution)) { - failed.set(true); - } - result.and_then(|value| cleanup.map(|()| value)) + device_inject(binding, context, cache, &failed, rows, &operands) } } + +/// The genuine FFN read this transaction owns: binding, origin, position, matching block identity and finite values. +fn check_batch_read( + binding: &ModelBinding, + read: &ResidualReady, + block: &[f32], + block_identity: TokenLayer, + txn: &QwenStepTxn, +) -> Result<()> { + txn.validate_binding(&binding.identity())?; + read.validate_origin(&binding.identity(), GrRole::Ffn(read.identity.layer().get()))?; + read.identity.validate(txn.token(), txn.position(), read.identity.layer())?; + if read.identity != block_identity { + return Err(Error::IdentityMismatch); + } + validate_streams(&read.streams)?; + validate_values(&read.inject, 4)?; + validate_values(block, 2560) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs new file mode 100644 index 00000000..31641df3 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs @@ -0,0 +1,206 @@ +//! Phases of `GrStage::inject_batch` (STRA-338 size: extract-method only). + +#[allow(unused_imports)] +use super::*; + +/// The packed streams, attention blocks and inject scalars of the validated consecutive rows. +pub(super) struct BatchOperands { + pub(super) streams: Vec, + pub(super) blocks: Vec, + pub(super) injects: Vec, +} + +/// Genuine rows only: one origin and layer, strictly consecutive positions, finite values. +pub(super) fn gather_batch(binding: &ModelBinding, rows: &[GrBatchRow]) -> Result { + let role = rows[0].ready.role; + let layer = rows[0].ready.identity.layer(); + let first = rows[0].ready.identity.position().get(); + let mut streams = Vec::new(); + let mut blocks = Vec::new(); + let mut injects = Vec::new(); + streams.try_reserve_exact(rows.len() * 10240).map_err(|_| Error::InputAllocation)?; + blocks.try_reserve_exact(rows.len() * 2560).map_err(|_| Error::InputAllocation)?; + injects.try_reserve_exact(rows.len() * 4).map_err(|_| Error::InputAllocation)?; + for (i, row) in rows.iter().enumerate() { + check_batch_row(binding, role, layer, first + i as u64, row)?; + streams.extend_from_slice(&row.ready.streams); + blocks.extend_from_slice(&row.block); + injects.extend_from_slice(&row.ready.inject); + } + Ok(BatchOperands { streams, blocks, injects }) +} + +fn check_batch_row( + binding: &ModelBinding, + role: GrRole, + layer: LayerId, + position: u64, + row: &GrBatchRow, +) -> Result<()> { + row.ready.validate_origin(&binding.identity(), role)?; + if row.ready.identity.layer() != layer || row.ready.identity.position().get() != position { + return Err(Error::IdentityMismatch); + } + validate_streams(&row.ready.streams)?; + validate_values(&row.block, 2560)?; + validate_values(&row.ready.inject, 4) +} + +/// One injected residual per row from the device columns. +pub(super) fn complete_rows(rows: Vec, values: &[f32]) -> Result> { + let mut completed = Vec::new(); + completed.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; + for (row, column) in rows.into_iter().zip(values.as_chunks::<10240>().0) { + let mut copied = Vec::new(); + copied.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?; + copied.extend_from_slice(column); + completed.push(InjectedResidual::from_candidates( + row.ready.identity, + row.ready.binding, + row.ready.role, + copied.into_boxed_slice(), + )?); + } + Ok(completed) +} + +/// The queued T1/T2/T3 workspace path; `None` when no shape or workspace applies. The exclusive scratch lease ends +/// before the caller does any host finite validation or publication of an original row capability. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(super) fn queued_inject( + binding: &ModelBinding, + context: &Context<'_>, + cache: &DenseWeightCache<'_>, + failed: &Cell, + operands: &BatchOperands, + tokens: usize, +) -> Result>> { + let shape = match tokens { + 1 => leleka_cuda_driver::GrBatchInjectShape::T1, + 2 => leleka_cuda_driver::GrBatchInjectShape::T2, + 3 => leleka_cuda_driver::GrBatchInjectShape::T3, + _ => return Ok(None), + }; + let Some(mut workspace) = cache.gr_batch_workspace(binding, context)? else { + return Ok(None); + }; + let BatchOperands { streams, blocks, injects } = operands; + let result = workspace.inject(context, shape, streams, blocks, injects).map_err(|error| match error { + leleka_cuda_driver::Error::InvalidDriverValue("GR batch injection finite input") => Error::NonFinite, + other => driver_error(other), + }); + if workspace.is_failed() || context.is_poisoned() { + failed.set(true); + } + result.map(Some) +} + +/// Validate the queued columns and publish the original row capabilities. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(super) fn finish_queued( + binding: &ModelBinding, + context: &Context<'_>, + cache: &DenseWeightCache<'_>, + rows: Vec, + values: Box<[f32]>, +) -> Result> { + if values.len() != rows.len() * 10240 { + return Err(Error::InvalidDimension); + } + validate_values(&values, rows.len() * 10240)?; + let completed = complete_rows(rows, &values)?; + cache.retained_context(binding, context)?; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + cache.test_record_gr_batch_completed(binding, context)?; + Ok(completed) +} + +/// The generic device path: upload, inject, download and release every owner whatever the outcome. +pub(super) fn device_inject<'c>( + binding: &ModelBinding, + context: &'c Context<'c>, + cache: &DenseWeightCache<'_>, + failed: &Cell, + rows: Vec, + operands: &BatchOperands, +) -> Result> { + admit_budget(context, rows.len() * (2 * 40960 + 10240 + 16))?; + let (mut residual, mut output, mut injection, mut candidate) = (None, None, None, None); + let mut owners = [&mut residual, &mut output, &mut injection, &mut candidate]; + let result = inject_on_device(binding, context, cache, rows, operands, &mut owners); + // Attempt every owned release even after a CUDA or finite refusal. + let mut cleanup = Ok(()); + for buffer in [candidate, injection, output, residual].into_iter().flatten() { + let released = buffer.release().map_err(driver_error); + if cleanup.is_ok() { + cleanup = released; + } + } + if cleanup.is_err() || matches!(result, Err(Error::CudaExecution)) { + failed.set(true); + } + result.and_then(|value| cleanup.map(|()| value)) +} + +type Owners<'a, 'c> = [&'a mut Option>; 4]; + +fn inject_on_device<'c>( + binding: &ModelBinding, + context: &'c Context<'c>, + cache: &DenseWeightCache<'_>, + rows: Vec, + operands: &BatchOperands, + owners: &mut Owners<'_, 'c>, +) -> Result> { + let [residual, output, injection, candidate] = owners; + **residual = Some(upload_f32(context, &operands.streams)?); + **output = Some(upload_f32(context, &operands.blocks)?); + **injection = Some(upload_f32(context, &operands.injects)?); + **candidate = Some(context.allocate(rows.len() * 40960).map_err(driver_error)?); + launch_gr_inject(binding, context, cache, rows.len(), owners)?; + let candidate = owners[3].as_ref().ok_or(Error::CudaExecution)?; + let values = download_f32(candidate, rows.len() * 10240)?; + complete_rows(rows, &values) +} + +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +fn launch_gr_inject<'c>( + binding: &ModelBinding, + context: &'c Context<'c>, + cache: &DenseWeightCache<'_>, + tokens: usize, + owners: &mut Owners<'_, 'c>, +) -> Result<()> { + let [residual, output, injection, candidate] = owners; + cache + .chunk_modules(binding, context)? + .gr(context)? + .inject( + tokens, + residual.as_ref().ok_or(Error::CudaExecution)?, + output.as_ref().ok_or(Error::CudaExecution)?, + injection.as_ref().ok_or(Error::CudaExecution)?, + candidate.as_mut().ok_or(Error::CudaExecution)?, + ) + .map_err(driver_error) +} + +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] +fn launch_gr_inject<'c>( + _binding: &ModelBinding, + context: &'c Context<'c>, + _cache: &DenseWeightCache<'_>, + tokens: usize, + owners: &mut Owners<'_, 'c>, +) -> Result<()> { + let [residual, output, injection, candidate] = owners; + context + .gr_batch_inject_residual_f32( + tokens, + residual.as_ref().ok_or(Error::CudaExecution)?, + output.as_ref().ok_or(Error::CudaExecution)?, + injection.as_ref().ok_or(Error::CudaExecution)?, + candidate.as_mut().ok_or(Error::CudaExecution)?, + ) + .map_err(driver_error) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs index f22a8635..6f375336 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs @@ -96,6 +96,8 @@ mod project_group_source_consumers_fn; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(unused_imports)] use project_group_source_consumers_fn::project_group_source_consumers; +#[path = "moe_group_chunk/direct_packets_fns.rs"] +mod direct_packets_fns; #[path = "moe_group_chunk/ordered_down_refusal_fn.rs"] mod ordered_down_refusal_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/direct_packets_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/direct_packets_fns.rs new file mode 100644 index 00000000..3441aefb --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/direct_packets_fns.rs @@ -0,0 +1,219 @@ +//! Phases of `execute_direct_packets` (STRA-338 size: extract-method only). + +#[allow(unused_imports)] +use super::ordered_down_refusal_fn::close_packets; +use super::*; + +/// The sealed rows, their origins and shared activations of one direct-packet layer batch. +pub(super) struct PacketRun<'a, 'ctx, 'l, 'd> { + pub(super) context: &'ctx Context<'ctx>, + pub(super) binding: &'a ModelBinding, + pub(super) rows: &'a [ChunkFfnRow], + pub(super) scope: &'a DownScope<'ctx>, + pub(super) origins: &'a [Rc], + pub(super) activations: &'a [TransportBuffer<'ctx>], + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(super) native: Option>, + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + pub(super) marker: std::marker::PhantomData<(&'l (), &'d ())>, +} + +impl<'ctx> PacketRun<'_, 'ctx, '_, '_> { + /// Reserve the packets, run the batch and close every packet whatever the outcome. + pub(super) fn execute( + self, + groups: &[Vec], + cache: &mut MoeWeightCache<'ctx>, + prepared: &[RoutedGateUpQ8<'_>], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, 'ctx>, + ) -> Result> { + let mut packets = Vec::new(); + packets.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?; + let scope = self.scope; + let operation = self.operate(&mut packets, groups, cache, prepared, cancelled, actual); + scope.record(&operation); + let cleanup = close_packets(packets); + operation.and_then(|values| cleanup.map(|()| values)) + } + + /// Initialise the packets, project the groups, then finish natively or row by row. + fn operate( + mut self, + packets: &mut Vec>, + groups: &[Vec], + cache: &mut MoeWeightCache<'ctx>, + prepared: &[RoutedGateUpQ8<'_>], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, 'ctx>, + ) -> Result> { + self.init_packets(packets)?; + self.project_groups(packets, groups, cache, prepared, cancelled, actual)?; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(mut finish) = self.native.take() { + return self.finish_native(packets, cache, &mut finish, cancelled, actual); + } + self.finish_rows(packets, cache, cancelled, actual) + } + + /// One empty packet per authenticated row. + pub(super) fn init_packets(&self, packets: &mut Vec>) -> Result<()> { + for (index, row) in self.rows.iter().enumerate() { + let identity = row.row().route.identity(); + row.row().validate(&self.binding.identity(), identity.token(), identity.position(), identity.layer())?; + packets.push(ActualSlotPacket { + origin: Rc::clone(&self.origins[index]), + packet: super::super::moe_down::ResidentPackedDown::new(self.scope)?, + }); + } + Ok(()) + } + + /// The adaptive producer (when selected) or every non-empty expert group, one at a time. + #[allow(clippy::too_many_arguments)] + pub(super) fn project_groups( + &self, + packets: &mut [ActualSlotPacket<'ctx>], + groups: &[Vec], + cache: &mut MoeWeightCache<'ctx>, + prepared: &[RoutedGateUpQ8<'_>], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, 'ctx>, + ) -> Result<()> { + let adaptive = uses_adaptive(cache); + self.project_adaptive(adaptive, packets, groups, cache, prepared, cancelled, actual)?; + for pairs in groups.iter().filter(|group| !group.is_empty() && !adaptive) { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + self.project_one(pairs, packets, cache, prepared, cancelled, actual)?; + } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + #[cfg_attr( + not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")), + allow(unused_variables) + )] + fn project_adaptive( + &self, + adaptive: bool, + packets: &mut [ActualSlotPacket<'ctx>], + groups: &[Vec], + cache: &mut MoeWeightCache<'ctx>, + prepared: &[RoutedGateUpQ8<'_>], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, 'ctx>, + ) -> Result<()> { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if adaptive { + let (context, binding, rows, scope) = (self.context, self.binding, self.rows, self.scope); + adaptive_packets::project_adaptive_packets( + context, + binding, + rows, + groups, + cache, + prepared, + scope, + self.origins, + packets, + cancelled, + actual, + )?; + } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + fn project_one( + &self, + pairs: &[Pair], + packets: &mut [ActualSlotPacket<'ctx>], + cache: &mut MoeWeightCache<'ctx>, + prepared: &[RoutedGateUpQ8<'_>], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, 'ctx>, + ) -> Result<()> { + let (context, binding, rows, scope, origins) = + (self.context, self.binding, self.rows, self.scope, self.origins); + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + return project_group_source_fenced( + context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, + ); + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + return project_group_direct( + context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, + ); + } + + /// The native prompt finish consumes the completed packets of every row. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(super) fn finish_native( + &self, + packets: &[ActualSlotPacket<'ctx>], + cache: &mut MoeWeightCache<'ctx>, + finish: &mut prompt_finish::NativePromptFinish<'_, 'ctx, '_>, + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, 'ctx>, + ) -> Result> { + let (rows, binding) = (self.rows, self.binding); + let layer = rows[0].row().route.identity().layer(); + let mut refs = Vec::new(); + refs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; + for (index, packet) in packets.iter().enumerate() { + actual.validate_ffn_row(actual.micro_row_index(index)?, layer, &rows[index])?; + packet.validate(&self.origins[index], binding, rows[index].row().route.identity())?; + refs.push(&packet.packet); + } + prompt_finish::finish(self.context, binding, layer, rows, actual, self.scope, &refs, cache, finish, cancelled) + } + + /// Complete each row's packet and run the shared tail, row by row. + pub(super) fn finish_rows( + &self, + packets: &[ActualSlotPacket<'ctx>], + cache: &mut MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, 'ctx>, + ) -> Result> { + let mut outputs = Vec::new(); + outputs.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?; + for (index, row) in self.rows.iter().enumerate() { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + actual.validate_ffn_row(actual.micro_row_index(index)?, row.row().route.identity().layer(), row)?; + let values = self.finish_row(index, row.row(), &packets[index], cache)?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + outputs.push(ExpertReady::from_completed(self.binding.identity(), row.row().route.identity(), values)?); + } + Ok(outputs) + } + + fn finish_row( + &self, + index: usize, + row: &PreparedMoeRow, + packet: &ActualSlotPacket<'ctx>, + cache: &mut MoeWeightCache<'ctx>, + ) -> Result> { + let (context, binding, scope, origin) = (self.context, self.binding, self.scope, &self.origins[index]); + packet.validate(origin, binding, row.route.identity())?; + packet.packet.complete(scope)?; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + packet.packet.with_completed(scope, |packet| direct_gpu::observe_packet(packet))?; + let activation = self.activations[index].buffer()?; + if use_shared_tail(cache) { + return packet.packet.with_completed(scope, |completed| { + finish_shared_queued(context, binding, row, activation, cache, scope, origin, completed) + }); + } + finish_shared_with(context, binding, row, activation, cache, scope, origin, |weights, scaled| { + packet.packet.combine(scope, weights, scaled) + }) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs index 7af2394b..a28085f3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: fn ordered_down_refusal, fn use_direct_packets, fn validate_packet_pairs, fn execute_direct_packets, fn finish_shared, fn use_shared_tail .... #[allow(unused_imports)] +use super::direct_packets_fns::PacketRun; use super::*; pub(super) fn ordered_down_refusal( @@ -19,27 +20,38 @@ pub(super) fn ordered_down_refusal( if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let activation = scope.upload(values)?; - let result = scope.project(*selection, |out| { - launch_cached_projection(context, kind, matrix, activation.buffer()?, out, N, FF) - }); - let close_activation = activation.close(); - match result { - Err(primary) => { - let _ = close_activation; - return Err(primary); - } - Ok(actual) => { - let close_output = actual.close(); - close_activation?; - close_output?; - } - } + replay_selection(context, kind, matrix, values, *selection, scope)?; } // A native failing status with every scalar column valid is an internal // inconsistency, never permission to publish candidate output. Err(Error::CudaExecution) } +/// One column of the ordered replay: upload its hidden values, project, and close both owners. +fn replay_selection( + context: &Context<'_>, + kind: MoeMatrixKind, + matrix: CachedMoeMatrix<'_, '_>, + values: &[f32; FF], + selection: DownSelection, + scope: &DownScope<'_>, +) -> Result<()> { + let activation = scope.upload(values)?; + let result = scope + .project(selection, |out| launch_cached_projection(context, kind, matrix, activation.buffer()?, out, N, FF)); + let close_activation = activation.close(); + match result { + Err(primary) => { + let _ = close_activation; + Err(primary) + } + Ok(actual) => { + let close_output = actual.close(); + close_activation?; + close_output + } + } +} + pub(super) fn use_direct_packets(cache: &MoeWeightCache<'_>) -> bool { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] { @@ -59,25 +71,35 @@ pub(super) fn validate_packet_pairs( origins: &[Rc], packets: &[ActualSlotPacket<'_>], ) -> Result<()> { - if !(1..=64).contains(&pairs.len()) - || packets.len() != rows.len() - || origins.len() != rows.len() - || pairs.windows(2).any(|p| p[0].row >= p[1].row) - { + if !(1..=64).contains(&pairs.len()) || packets.len() != rows.len() || origins.len() != rows.len() { + return Err(Error::IdentityMismatch); + } + if pairs.windows(2).any(|p| p[0].row >= p[1].row) { return Err(Error::IdentityMismatch); } for pair in pairs { - if pair.row >= rows.len() || pair.slot >= K { - return Err(Error::IdentityMismatch); - } - let row = rows[pair.row].row(); - let identity = row.route.identity(); - actual.validate_ffn_row(actual.micro_row_index(pair.row)?, identity.layer(), &rows[pair.row])?; - row.validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?; - packets[pair.row].validate(&origins[pair.row], binding, identity)?; + validate_pair(actual, binding, rows, pair, origins, packets)?; } Ok(()) } + +fn validate_pair( + actual: &QwenChunkTxn<'_, '_>, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + pair: &Pair, + origins: &[Rc], + packets: &[ActualSlotPacket<'_>], +) -> Result<()> { + if pair.row >= rows.len() || pair.slot >= K { + return Err(Error::IdentityMismatch); + } + let row = rows[pair.row].row(); + let identity = row.route.identity(); + actual.validate_ffn_row(actual.micro_row_index(pair.row)?, identity.layer(), &rows[pair.row])?; + row.validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?; + packets[pair.row].validate(&origins[pair.row], binding, identity) +} #[allow(clippy::too_many_arguments)] pub(super) fn execute_direct_packets<'ctx>( context: &'ctx Context<'ctx>, @@ -91,131 +113,27 @@ pub(super) fn execute_direct_packets<'ctx>( origins: &[Rc], cancelled: &mut impl FnMut() -> bool, actual: &QwenChunkTxn<'_, 'ctx>, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mut native: Option< + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< prompt_finish::NativePromptFinish<'_, 'ctx, '_>, >, ) -> Result> { - let mut packets = Vec::new(); - packets.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; - let operation = (|| { - for (index, row) in rows.iter().enumerate() { - let identity = row.row().route.identity(); - row.row().validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?; - packets.push(ActualSlotPacket { - origin: Rc::clone(&origins[index]), - packet: super::super::moe_down::ResidentPackedDown::new(scope)?, - }); - } - let adaptive = uses_adaptive(cache); + let run = PacketRun { + context, + binding, + rows, + scope, + origins, + activations, #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if adaptive { - adaptive_packets::project_adaptive_packets( - context, - binding, - rows, - groups, - cache, - prepared, - scope, - origins, - &mut packets, - cancelled, - actual, - )?; - } - for pairs in groups.iter().filter(|group| !group.is_empty() && !adaptive) { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - project_group_source_fenced( - context, - binding, - rows, - pairs, - cache, - prepared, - scope, - origins, - &mut packets, - cancelled, - actual, - )?; - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - project_group_direct( - context, - binding, - rows, - pairs, - cache, - prepared, - scope, - origins, - &mut packets, - cancelled, - actual, - )?; - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(finish) = native.as_mut() { - let layer = rows[0].row().route.identity().layer(); - let mut refs = Vec::new(); - refs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; - for (index, packet) in packets.iter().enumerate() { - actual.validate_ffn_row(actual.micro_row_index(index)?, layer, &rows[index])?; - packet.validate(&origins[index], binding, rows[index].row().route.identity())?; - refs.push(&packet.packet); - } - return prompt_finish::finish( - context, binding, layer, rows, actual, scope, &refs, cache, finish, cancelled, - ); - } - let mut outputs = Vec::new(); - outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; - for (index, row) in rows.iter().enumerate() { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - actual.validate_ffn_row(actual.micro_row_index(index)?, row.row().route.identity().layer(), row)?; - let row = row.row(); - let actual = &packets[index]; - actual.validate(&origins[index], binding, row.route.identity())?; - actual.packet.complete(scope)?; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - actual.packet.with_completed(scope, |packet| direct_gpu::observe_packet(packet))?; - let values = if use_shared_tail(cache) { - actual.packet.with_completed(scope, |packet| { - finish_shared_queued( - context, - binding, - row, - activations[index].buffer()?, - cache, - scope, - &origins[index], - packet, - ) - })? - } else { - finish_shared_with( - context, - binding, - row, - activations[index].buffer()?, - cache, - scope, - &origins[index], - |weights, scaled| actual.packet.combine(scope, weights, scaled), - )? - }; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - outputs.push(ExpertReady::from_completed(binding.identity(), row.route.identity(), values)?); - } - Ok(outputs) - })(); - scope.record(&operation); + native, + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + marker: std::marker::PhantomData, + }; + run.execute(groups, cache, prepared, cancelled, actual) +} + +/// Close every packet; the first failure is kept and every packet is closed. +pub(super) fn close_packets(packets: Vec>) -> Result<()> { let mut cleanup = Ok(()); for actual in packets { let next = actual.packet.close(); @@ -223,7 +141,7 @@ pub(super) fn execute_direct_packets<'ctx>( cleanup = next; } } - operation.and_then(|values| cleanup.map(|()| values)) + cleanup } #[allow(clippy::too_many_arguments)] pub(super) fn finish_shared<'ctx>( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs index 2bd9323b..cb2dcd07 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs @@ -49,7 +49,7 @@ pub(super) fn project_group_source_consumers<'ctx>( /// Fixed actual group member descriptors retain every original geometry, /// role and same-expert check without another zero-byte fstat per member. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -fn check_source_members(source: &mut MoeRoutedSourceScope<'_, '_>, members: usize) -> Result<()> { +pub(super) fn check_source_members(source: &mut MoeRoutedSourceScope<'_, '_>, members: usize) -> Result<()> { for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { let original = source.descriptor(0, role).map_err(binding_error)?; for member in 0..members { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs index 34db16da..56a40a98 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs @@ -1,6 +1,9 @@ //! Closed original-kernel resident expert pipeline and genuine packet handoff. +use super::project_group_direct_fn::DirectGroup; +use super::project_group_shared_fns::{down_format, gate_up_format, packet_targets}; +use super::project_group_source_consumers_fn::check_source_members; use super::*; -use leleka_cuda_driver::{RoutedResidentRefusal, RoutedResidentWeights}; +use leleka_cuda_driver::{RoutedResidentQueue, RoutedResidentRefusal, RoutedResidentWeights}; #[allow(clippy::too_many_arguments)] pub(super) fn project_group_packets<'ctx>( @@ -24,146 +27,186 @@ pub(super) fn project_group_packets<'ctx>( } let queue_owner = cache.routed_resident_owner(binding, context)?; let output_owner = cache.routed_output_owner(binding, context)?; - let first = pairs[0]; - let weights = &rows[first.row].row().weights; - let selection = MoeExpertSelection::Routed { slot: first.slot }; - let gu = |role| match weights.kind(selection, role).map_err(binding_error)? { - MoeMatrixKind::Iq3Xxs => Ok(RoutedFormat::IQ3_XXS), - MoeMatrixKind::Iq2S => Ok(RoutedFormat::IQ2_S), - MoeMatrixKind::Iq3S => Ok(RoutedFormat::IQ3_S), - MoeMatrixKind::RoutedIq4Xs => Ok(RoutedFormat::IQ4_XS), - _ => Err(Error::Unsupported(Stage::MoeExpert)), - }; - let gu_formats = [gu(MoeMatrixRole::Gate)?, gu(MoeMatrixRole::Up)?]; - let down_kind = weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?; - let down_format = match down_kind { - MoeMatrixKind::RoutedIq4Nl => RoutedFormat::IQ4_NL, - MoeMatrixKind::Q2_0 => RoutedFormat::Q2_0, - _ => return Err(Error::Unsupported(Stage::MoeExpert)), - }; - let mut members = Vec::new(); - let mut refs = Vec::new(); - let mut selections = Vec::new(); - members.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; - refs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; - selections.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; - for pair in pairs { - members.push((&rows[pair.row].row().weights, pair.slot)); - refs.push(prepared.get(pair.row).ok_or(Error::IdentityMismatch)?); - selections.push(DownSelection::Routed(pair.slot)); - } - let operation = output_owner.with_outputs(context, pairs.len(), |[gate, up, hidden, down]| { - binding.with_moe_routed_source(&members, binding_error, |source| { - // Every grouped member must name the same actual whole expert triplet. - for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { - let key = source.descriptor(0, role).map_err(binding_error)?; - for member in 1..pairs.len() { - if source.descriptor(member, role).map_err(binding_error)? != key { - return Err(Error::IdentityMismatch); - } - } - } - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - // Fresh per loan; set only when the real cancelled closure answers true inside the callback. - let cancel_observed = std::cell::Cell::new(false); - let mut observed_cancel = - crate::qwen_forward::moe_weight_cache::observe_cancel(&cancel_observed, cancelled); - let consume = - |raw: [&DeviceBuffer<'_>; 3], - health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, - source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>| { - queue_owner.with_queue(|queue| { - let complete = queue - .compose( - RoutedResidentWeights { - gate: raw[0], - up: raw[1], - down: raw[2], - gu_formats, - down_format, - }, - &refs, - gate, - up, - hidden, - down, - ) - .map_err(driver_error)?; - match complete.numerical_refusal() { - Some(RoutedResidentRefusal::DownQuant) => { - let values = download_f32( - complete.completed_hidden().ok_or(Error::IdentityMismatch)?, - pairs.len() * FF, - )?; - return ordered_down_refusal( - context, - down_kind, - CachedMoeMatrix::Raw(raw[2]), - &values, - &selections, - scope, - &mut observed_cancel, - ); - } - Some(_) => return Err(Error::NonFinite), - None => {} - } - let down_source = complete.completed_down().ok_or(Error::IdentityMismatch)?; - if observed_cancel() { - return Err(Error::Unsupported(Stage::Executor)); - } - validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; - let mut targets = Vec::new(); - targets.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; - let mut next = 0; - for (row, packet) in packets.iter_mut().enumerate() { - if next < pairs.len() && pairs[next].row == row { - targets.push((&mut packet.packet, pairs[next].slot)); - next += 1; - } - } - if next != pairs.len() { - return Err(Error::IdentityMismatch); - } - super::super::moe_down::ResidentPackedDown::copy_group_with(scope, &mut targets, |copies| { - context - .copy_routed_down_columns_to_slots(down_source, pairs.len(), copies) - .map_err(driver_error)?; - if observed_cancel() { - return Err(Error::Unsupported(Stage::Executor)); - } - source.finish().map_err(binding_error)?; - health.validate(binding, context)?; - for pair in pairs { - actual.validate_ffn_row( - actual.micro_row_index(pair.row)?, - rows[pair.row].row().route.identity().layer(), - &rows[pair.row], - )?; - let row = rows[pair.row].row(); - let id = row.route.identity(); - row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; - if !origins[pair.row].binding.matches(&binding.identity()) - || origins[pair.row].identity != id - { - return Err(Error::IdentityMismatch); - } - } - Ok(()) - }) - }) - }; - match ephemeral_slot { - Some(slot) => { - cache.with_ephemeral_triplet_routed_source(binding, source, 0, slot, &cancel_observed, consume) - } - None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume), - } - }) + let run = QueueRun::for_pairs(context, binding, rows, pairs, scope, origins, prepared)?; + let operation = output_owner.with_outputs(context, pairs.len(), |outputs| { + run.in_source(cache, &queue_owner, ephemeral_slot, outputs, cancelled, actual, packets) }); scope.record(&operation); let health = cache.validate(binding, context); operation.and(health) } + +/// One resident-queue group: the shared group identity, its prepared columns and the three kernel formats. +struct QueueRun<'a, 'ctx> { + group: DirectGroup<'a, 'ctx>, + members: Vec<(&'a MoeExpertWeights, usize)>, + refs: Vec<&'a RoutedGateUpQ8<'a>>, + selections: Vec, + gu_formats: [RoutedFormat; 2], + down_kind: MoeMatrixKind, + down_format: RoutedFormat, +} + +impl<'a, 'ctx> QueueRun<'a, 'ctx> { + fn for_pairs( + context: &'ctx Context<'ctx>, + binding: &'a ModelBinding, + rows: &'a [ChunkFfnRow], + pairs: &'a [Pair], + scope: &'a DownScope<'ctx>, + origins: &'a [Rc], + prepared: &'a [RoutedGateUpQ8<'a>], + ) -> Result { + let first = pairs[0]; + let weights = &rows[first.row].row().weights; + let selection = MoeExpertSelection::Routed { slot: first.slot }; + Self::new(DirectGroup { context, binding, rows, pairs, scope, origins, weights, selection }, prepared) + } + + fn new(group: DirectGroup<'a, 'ctx>, prepared: &'a [RoutedGateUpQ8<'a>]) -> Result { + let (weights, selection, pairs) = (group.weights, group.selection, group.pairs); + let gu_formats = [ + gate_up_format(weights, selection, MoeMatrixRole::Gate)?, + gate_up_format(weights, selection, MoeMatrixRole::Up)?, + ]; + let down_kind = weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?; + let down_format = down_format(down_kind)?; + let (mut members, mut refs, mut selections) = (Vec::new(), Vec::new(), Vec::new()); + members.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; + refs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; + selections.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; + for pair in pairs { + members.push((&group.rows[pair.row].row().weights, pair.slot)); + refs.push(prepared.get(pair.row).ok_or(Error::IdentityMismatch)?); + selections.push(DownSelection::Routed(pair.slot)); + } + Ok(Self { group, members, refs, selections, gu_formats, down_kind, down_format }) + } + + /// Every grouped member must name the same actual whole expert triplet; the source stays open for the + /// resident compose and the packet copy. + #[allow(clippy::too_many_arguments)] + fn in_source<'c>( + &self, + cache: &MoeWeightCache<'c>, + queue_owner: &Rc>, + ephemeral_slot: Option, + outputs: [&mut DeviceBuffer<'c>; 4], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, '_>, + packets: &mut [ActualSlotPacket<'ctx>], + ) -> Result<()> { + let binding = self.group.binding; + binding.with_moe_routed_source(&self.members, binding_error, |source| { + check_source_members(source, self.group.pairs.len())?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + self.dispatch(cache, queue_owner, ephemeral_slot, outputs, cancelled, actual, packets, source) + }) + } + + #[allow(clippy::too_many_arguments)] + fn dispatch<'c>( + &self, + cache: &MoeWeightCache<'c>, + queue_owner: &Rc>, + ephemeral_slot: Option, + outputs: [&mut DeviceBuffer<'c>; 4], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, '_>, + packets: &mut [ActualSlotPacket<'ctx>], + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>, + ) -> Result<()> { + // Fresh per loan; set only when the real cancelled closure answers true inside the callback. + let cancel_observed = std::cell::Cell::new(false); + let mut observed_cancel = crate::qwen_forward::moe_weight_cache::observe_cancel(&cancel_observed, cancelled); + let consume = + |raw: [&DeviceBuffer<'_>; 3], + health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>| { + queue_owner.with_queue(|queue| { + self.compose_copy(queue, raw, outputs, &mut observed_cancel, actual, packets, health, source) + }) + }; + let binding = self.group.binding; + match ephemeral_slot { + Some(slot) => { + cache.with_ephemeral_triplet_routed_source(binding, source, 0, slot, &cancel_observed, consume) + } + None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume), + } + } + + /// Compose the resident kernels; a numerical refusal replays in row order, otherwise the Down columns are + /// copied into the packets. + #[allow(clippy::too_many_arguments)] + fn compose_copy<'c>( + &self, + queue: &mut RoutedResidentQueue<'c>, + raw: [&DeviceBuffer<'_>; 3], + outputs: [&mut DeviceBuffer<'c>; 4], + observed_cancel: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, '_>, + packets: &mut [ActualSlotPacket<'ctx>], + health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>, + ) -> Result<()> { + let weights = self.resident_weights(raw); + let [gate, up, hidden, down] = outputs; + let complete = queue.compose(weights, &self.refs, gate, up, hidden, down).map_err(driver_error)?; + match complete.numerical_refusal() { + Some(RoutedResidentRefusal::DownQuant) => { + return self.down_refusal(complete.completed_hidden(), raw[2], observed_cancel); + } + Some(_) => return Err(Error::NonFinite), + None => {} + } + let down_source = complete.completed_down().ok_or(Error::IdentityMismatch)?; + if observed_cancel() { + return Err(Error::Unsupported(Stage::Executor)); + } + self.copy_down(down_source, observed_cancel, actual, packets, health, source) + } + + fn resident_weights<'w, 'b>(&self, raw: [&'w DeviceBuffer<'b>; 3]) -> RoutedResidentWeights<'w, 'b> { + let (gu_formats, down_format) = (self.gu_formats, self.down_format); + RoutedResidentWeights { gate: raw[0], up: raw[1], down: raw[2], gu_formats, down_format } + } + + fn down_refusal( + &self, + hidden: Option<&DeviceBuffer<'_>>, + down: &DeviceBuffer<'_>, + observed_cancel: &mut impl FnMut() -> bool, + ) -> Result<()> { + let values = download_f32(hidden.ok_or(Error::IdentityMismatch)?, self.group.pairs.len() * FF)?; + let matrix = CachedMoeMatrix::Raw(down); + let (context, scope) = (self.group.context, self.group.scope); + ordered_down_refusal(context, self.down_kind, matrix, &values, &self.selections, scope, observed_cancel) + } + + fn copy_down( + &self, + down_source: &DeviceBuffer<'_>, + observed_cancel: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, '_>, + packets: &mut [ActualSlotPacket<'ctx>], + health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>, + ) -> Result<()> { + let group = &self.group; + let (context, binding, pairs) = (group.context, group.binding, group.pairs); + validate_packet_pairs(actual, binding, group.rows, pairs, group.origins, packets)?; + let mut targets = packet_targets(pairs, packets)?; + super::super::moe_down::ResidentPackedDown::copy_group_with(group.scope, &mut targets, |copies| { + context.copy_routed_down_columns_to_slots(down_source, pairs.len(), copies).map_err(driver_error)?; + if observed_cancel() { + return Err(Error::Unsupported(Stage::Executor)); + } + source.finish().map_err(binding_error)?; + health.validate(binding, context)?; + group.validate_completed_rows(actual) + }) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs index 680c5e1d..180f5e8f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs @@ -1,9 +1,16 @@ //! Original prompt MMQ consumers of actual adaptive or completed staging slots. //! Cache policy and staging ownership stay outside the MMQ numerical products. use super::*; +use crate::model_binding::qwen4exp_input::MoeWeightDescriptor; use crate::qwen_forward::moe_weight_cache::original_dual_layout; use leleka_cuda_driver::{MmqWorkspace, OriginalMmqLayer}; +#[path = "moe_mmq_adaptive/gather_fns.rs"] +mod gather_fns; +#[path = "moe_mmq_adaptive/walk_fns.rs"] +mod walk_fns; +use walk_fns::{SlotState, Walk}; + #[allow(clippy::too_many_arguments)] pub(super) fn execute_adaptive_groups<'ctx>( txn: &QwenChunkTxn<'_, 'ctx>, @@ -19,17 +26,7 @@ pub(super) fn execute_adaptive_groups<'ctx>( cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { cache.validate(binding, context)?; - if !cache.has_original_prompt_mmq() - || !cache.uses_strata_adaptive_experts() - || txn.is_mtp_verification()? - || rows.is_empty() - || u32::try_from(rows.len()).map_err(|_| Error::Overflow)? - > workspace.original_expert_capacity().map_err(mmq_error)? - || rows.len() != txn.micro_len()? - || groups.len() != 512 - { - return Err(Error::IdentityMismatch); - } + check_adaptive_request(txn, cache, workspace, rows, groups)?; let ephemeral = cache.ephemeral_routed_owner(binding, context)?; let operation = execute_inner(txn, context, binding, layer, rows, groups, cache, workspace, inputs, packets, cancelled); @@ -42,6 +39,37 @@ pub(super) fn execute_adaptive_groups<'ctx>( operation.and(cleanup) } +/// The adaptive prompt consumer runs only for a full original-prompt chunk with the Strata adaptive owner. +fn check_adaptive_request<'ctx>( + txn: &QwenChunkTxn<'_, 'ctx>, + cache: &MoeWeightCache<'ctx>, + workspace: &MmqWorkspace<'ctx>, + rows: &[ChunkFfnRow], + groups: &[Vec], +) -> Result<()> { + if !cache.has_original_prompt_mmq() || !cache.uses_strata_adaptive_experts() || txn.is_mtp_verification()? { + return Err(Error::IdentityMismatch); + } + check_adaptive_rows(txn, workspace, rows, groups) +} + +fn check_adaptive_rows( + txn: &QwenChunkTxn<'_, '_>, + workspace: &MmqWorkspace<'_>, + rows: &[ChunkFfnRow], + groups: &[Vec], +) -> Result<()> { + if rows.is_empty() + || u32::try_from(rows.len()).map_err(|_| Error::Overflow)? + > workspace.original_expert_capacity().map_err(mmq_error)? + || rows.len() != txn.micro_len()? + || groups.len() != 512 + { + return Err(Error::IdentityMismatch); + } + Ok(()) +} + #[allow(clippy::too_many_arguments)] fn execute_inner<'ctx>( txn: &QwenChunkTxn<'_, 'ctx>, @@ -56,6 +84,22 @@ fn execute_inner<'ctx>( packets: &mut SlotPacks<'_, '_, 'ctx>, cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { + let (counts, sorted_rows) = count_groups(rows, groups)?; + let walk = Walk { txn, context, binding, layer, rows, groups }; + walk.authenticate(packets)?; + let tokens = u32::try_from(rows.len()).map_err(|_| Error::Overflow)?; + let mut source = + workspace.prepare_original_expert_layer(inputs, tokens, &counts, &sorted_rows).map_err(mmq_error)?; + walk.observe_rows(cache)?; + let classified = walk.classify(cache, packets)?; + let (mut wait, mut state) = walk.open_staging(cache, classified.maximum_charge)?; + walk.fill_slots(cache, cancelled, &classified, &mut state)?; + walk.walk(&mut source, cache, packets, cancelled, &mut wait, &classified, &mut state, counts.len())?; + walk.finish(source, cache, &classified, &state) +} + +/// The rows per used expert and the row indices sorted by expert. +fn count_groups(rows: &[ChunkFfnRow], groups: &[Vec]) -> Result<(Vec, Vec)> { let mut counts = Vec::new(); counts.try_reserve_exact(512).map_err(|_| Error::InputAllocation)?; let mut sorted_rows = Vec::new(); @@ -68,246 +112,5 @@ fn execute_inner<'ctx>( sorted_rows.push(u32::try_from(pair.row).map_err(|_| Error::Overflow)?); } } - // Authenticate every actual row/group before the first device command. - // Frequency/event policy still runs at its original point below. - for (index, row) in rows.iter().enumerate() { - txn.validate_ffn_row(txn.micro_row_index(index)?, layer, row)?; - } - for (expert, pairs) in groups.iter().enumerate().filter(|(_, pairs)| !pairs.is_empty()) { - let _ = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; - } - let mut source = workspace - .prepare_original_expert_layer( - inputs, - u32::try_from(rows.len()).map_err(|_| Error::Overflow)?, - &counts, - &sorted_rows, - ) - .map_err(mmq_error)?; - cache.poll_strata_adaptive(binding, false)?; - for (index, row) in rows.iter().enumerate() { - txn.validate_ffn_row(txn.micro_row_index(index)?, layer, row)?; - cache.observe_strata_adaptive_row(binding, &row.row().weights)?; - } - // Fixed metadata, independent of route frequency. No logical residency - // entry is minted: true means the real adaptive owner can loan the triplet. - let mut resident = [false; 512]; - let mut misses = [0usize; 512]; - let mut miss_count = 0; - let mut maximum_charge = 0usize; - for (expert, pairs) in groups.iter().enumerate().filter(|(_, p)| !p.is_empty()) { - let _ = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; - let first = pairs[0]; - let row = rows.get(first.row).ok_or(Error::IdentityMismatch)?; - let mut charge = 0usize; - for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { - let key = binding - .moe_weight_descriptor(&row.row().weights, MoeExpertSelection::Routed { slot: first.slot }, role) - .map_err(binding_error)?; - if key.layer != layer.get() || key.expert != Some(expert as u32) { - return Err(Error::IdentityMismatch); - } - let (_, bytes) = original_dual_layout(key)?.ok_or(Error::InvalidDimension)?; - charge = charge.checked_add(bytes).ok_or(Error::Overflow)?; - } - maximum_charge = maximum_charge.max(charge); - resident[expert] = cache.strata_adaptive_resident( - binding, - &row.row().weights, - MoeExpertSelection::Routed { slot: first.slot }, - )?; - if !resident[expert] { - misses[miss_count] = expert; - miss_count += 1; - } - } - // Genuine padded destinations coexist with all actual staging/resident - // owners. The cache guard adds the unchanged independent 128MiB reserve. - cache.reserve_mmq_transient(binding, context, maximum_charge)?; - let owner = cache.ephemeral_routed_owner(binding, context)?; - let capacity = owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.slot_count(); - if !matches!(capacity, 2 | 8 | 16) { - return Err(Error::IdentityMismatch); - } - let mut slots = [None; 16]; - let mut next = 0usize; - for (slot, directory) in slots[..capacity].iter_mut().enumerate() { - if next == miss_count { - break; - } - let expert = misses[next]; - stage(cache, context, binding, rows, &groups[expert], slot, cancelled)?; - *directory = Some(expert); - next += 1; - } - // Literal prompt order: residents and staged misses share one ID walk. - // The real bank retains gathered bytes until the <=16-expert numerical run. - let mut staged_experts = [0usize; 16]; - let mut staged_count = 0usize; - let used_count = counts.len(); - let mut consumed = 0usize; - for (expert, pairs) in groups.iter().enumerate().filter(|(_, p)| !p.is_empty()) { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let slot = if resident[expert] { - None - } else { - let slot = - slots[..capacity].iter().position(|entry| *entry == Some(expert)).ok_or(Error::IdentityMismatch)?; - owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.wait(slot, binding)?; - Some(slot) - }; - gather_expert(txn, context, binding, layer, rows, expert, pairs, cache, &mut source, packets, slot, cancelled)?; - staged_experts[staged_count] = expert; - staged_count += 1; - consumed += 1; - if staged_count == 16 || consumed == used_count { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - { - let finite = source.run_group().map_err(mmq_error)?; - for (group_index, expert) in staged_experts[..staged_count].iter().copied().enumerate() { - let pairs = &groups[expert]; - let origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; - packets.copy_group( - &origin, - |destinations| { - finite.copy_expert_down_columns_to_slots(group_index, destinations).map_err(mmq_error)?; - // Each genuine source scope was explicitly finished after - // its completed gather. Revalidate current model/context - // before the actual packet owner publishes coverage. - cache.validate(binding, context) - }, - cancelled, - )?; - } - } - source.finish_group().map_err(mmq_error)?; - staged_count = 0; - } - if let Some(slot) = slot { - slots[slot] = None; - if next < miss_count { - let expert = misses[next]; - stage(cache, context, binding, rows, &groups[expert], slot, cancelled)?; - slots[slot] = Some(expert); - next += 1; - } - } - } - if next != miss_count || slots[..capacity].iter().any(Option::is_some) { - return Err(Error::IdentityMismatch); - } - source.finish().map_err(mmq_error)?; - cache.validate(binding, context) -} - -fn stage( - cache: &MoeWeightCache<'_>, - context: &Context<'_>, - binding: &ModelBinding, - rows: &[ChunkFfnRow], - pairs: &[Pair], - slot: usize, - cancelled: &mut impl FnMut() -> bool, -) -> Result<()> { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let first = pairs.first().ok_or(Error::IdentityMismatch)?; - let row = rows.get(first.row).ok_or(Error::IdentityMismatch)?; - let members = [(&row.row().weights, first.slot)]; - let owner = cache.ephemeral_routed_owner(binding, context)?; - binding.with_moe_routed_source(&members, binding_error, |source| { - owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.stage(slot, binding, source, 0) - }) -} - -#[allow(clippy::too_many_arguments)] -fn gather_expert<'ctx>( - txn: &QwenChunkTxn<'_, 'ctx>, - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], - expert: usize, - pairs: &[Pair], - cache: &mut MoeWeightCache<'ctx>, - activation: &mut OriginalMmqLayer<'_, 'ctx>, - packets: &mut SlotPacks<'_, '_, 'ctx>, - ephemeral_slot: Option, - cancelled: &mut impl FnMut() -> bool, -) -> Result<()> { - let origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; - let mut members = Vec::new(); - members.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; - let first = pairs.first().ok_or(Error::IdentityMismatch)?; - let row = rows.get(first.row).ok_or(Error::IdentityMismatch)?; - let descriptor = |role| { - binding - .moe_weight_descriptor(&row.row().weights, MoeExpertSelection::Routed { slot: first.slot }, role) - .map_err(binding_error) - }; - let keys = [descriptor(MoeMatrixRole::Gate)?, descriptor(MoeMatrixRole::Up)?, descriptor(MoeMatrixRole::Down)?]; - let layouts = [ - original_dual_layout(keys[0])?.ok_or(Error::InvalidDimension)?, - original_dual_layout(keys[1])?.ok_or(Error::InvalidDimension)?, - original_dual_layout(keys[2])?.ok_or(Error::InvalidDimension)?, - ]; - let formats = layouts.map(|(format, _)| format); - let charge = - layouts.into_iter().try_fold(0usize, |sum, (_, bytes)| sum.checked_add(bytes).ok_or(Error::Overflow))?; - for pair in pairs { - let row = rows.get(pair.row).ok_or(Error::IdentityMismatch)?; - txn.validate_ffn_row(txn.micro_row_index(pair.row)?, layer, row)?; - members.push((&row.row().weights, pair.slot)); - } - cache.reserve_mmq_transient(binding, context, charge)?; - binding.with_moe_routed_source(&members, binding_error, |source| { - for (role_index, role) in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down].into_iter().enumerate() - { - let key = source.descriptor(0, role).map_err(binding_error)?; - if key != keys[role_index] { - return Err(Error::IdentityMismatch); - } - for member in 1..pairs.len() { - if source.descriptor(member, role).map_err(binding_error)? != key { - return Err(Error::IdentityMismatch); - } - } - } - let cancel_observed = Cell::new(false); - let mut observed_cancel = crate::qwen_forward::moe_weight_cache::observe_cancel(&cancel_observed, cancelled); - let consume = - |raw: [&DeviceBuffer<'ctx>; 3], - health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, - source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>| { - if observed_cancel() { - return Err(Error::Unsupported(Stage::Executor)); - } - activation.stage_expert(formats, raw).map_err(mmq_error)?; - source.finish().map_err(binding_error)?; - health.validate(binding, context)?; - if observed_cancel() { - return Err(Error::Unsupported(Stage::Executor)); - } - for pair in pairs { - let row = rows.get(pair.row).ok_or(Error::IdentityMismatch)?; - txn.validate_ffn_row(txn.micro_row_index(pair.row)?, layer, row)?; - } - // The genuine bytes are now retained in the admitted bank, not a - // synthetic MmqWeights view. Actual staging owner can be reused only - // after this confirmed gather + source/current-row health boundary. - let _ = origin; - Ok(()) - }; - match ephemeral_slot { - Some(slot) => { - cache.with_ephemeral_triplet_routed_source(binding, source, 0, slot, &cancel_observed, consume) - } - None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume), - } - }) + Ok((counts, sorted_rows)) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs new file mode 100644 index 00000000..425b1dcd --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs @@ -0,0 +1,146 @@ +//! Gather of one expert's matrices into the admitted bank (STRA-338 size: extract-method only). + +use super::walk_fns::Walk; +#[allow(unused_imports)] +use super::*; + +impl<'ctx> Walk<'_, '_, 'ctx> { + /// Gather one expert's three matrices into the admitted bank, from the adaptive owner or its staged slot. + #[allow(clippy::too_many_arguments)] + pub(super) fn gather_expert( + &self, + expert: usize, + pairs: &[Pair], + cache: &mut MoeWeightCache<'ctx>, + activation: &mut OriginalMmqLayer<'_, 'ctx>, + packets: &mut SlotPacks<'_, '_, 'ctx>, + ephemeral_slot: Option, + cancelled: &mut impl FnMut() -> bool, + ) -> Result<()> { + let _origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; + let mut members = Vec::new(); + members.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; + let first = pairs.first().ok_or(Error::IdentityMismatch)?; + let row = self.rows.get(first.row).ok_or(Error::IdentityMismatch)?; + let (keys, formats, charge) = gather_layouts(self.binding, row, first)?; + self.fill_members(pairs, &mut members)?; + cache.reserve_mmq_transient(self.binding, self.context, charge)?; + self.binding.with_moe_routed_source(&members, binding_error, |source| { + check_expert_keys(source, &keys, pairs.len())?; + self.gather_source(source, formats, pairs, cache, activation, ephemeral_slot, cancelled) + }) + } + + fn fill_members<'p>(&'p self, pairs: &[Pair], members: &mut Vec<(&'p MoeExpertWeights, usize)>) -> Result<()> { + for pair in pairs { + let row = self.rows.get(pair.row).ok_or(Error::IdentityMismatch)?; + self.txn.validate_ffn_row(self.txn.micro_row_index(pair.row)?, self.layer, row)?; + members.push((&row.row().weights, pair.slot)); + } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + fn gather_source( + &self, + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>, + formats: [leleka_cuda_driver::MmqFormat; 3], + pairs: &[Pair], + cache: &MoeWeightCache<'ctx>, + activation: &mut OriginalMmqLayer<'_, 'ctx>, + ephemeral_slot: Option, + cancelled: &mut impl FnMut() -> bool, + ) -> Result<()> { + let binding = self.binding; + let cancel_observed = Cell::new(false); + let mut observed_cancel = crate::qwen_forward::moe_weight_cache::observe_cancel(&cancel_observed, cancelled); + let consume = + |raw: [&DeviceBuffer<'ctx>; 3], + health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>| { + self.after_gather(activation, formats, raw, health, source, &mut observed_cancel, pairs) + }; + match ephemeral_slot { + Some(slot) => { + cache.with_ephemeral_triplet_routed_source(binding, source, 0, slot, &cancel_observed, consume) + } + None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume), + } + } + + /// The genuine bytes are retained in the admitted bank, not a synthetic MmqWeights view. The actual staging + /// owner can be reused only after this confirmed gather + source/current-row health boundary. + #[allow(clippy::too_many_arguments)] + fn after_gather( + &self, + activation: &mut OriginalMmqLayer<'_, 'ctx>, + formats: [leleka_cuda_driver::MmqFormat; 3], + raw: [&DeviceBuffer<'ctx>; 3], + health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>, + observed_cancel: &mut impl FnMut() -> bool, + pairs: &[Pair], + ) -> Result<()> { + if observed_cancel() { + return Err(Error::Unsupported(Stage::Executor)); + } + activation.stage_expert(formats, raw).map_err(mmq_error)?; + source.finish().map_err(binding_error)?; + health.validate(self.binding, self.context)?; + if observed_cancel() { + return Err(Error::Unsupported(Stage::Executor)); + } + revalidate_rows(self.txn, self.layer, self.rows, pairs) + } +} + +type ExpertLayouts = ([MoeWeightDescriptor; 3], [leleka_cuda_driver::MmqFormat; 3], usize); + +/// The Gate/Up/Down descriptors of one expert, their formats and the summed byte charge. +pub(super) fn gather_layouts(binding: &ModelBinding, row: &ChunkFfnRow, first: &Pair) -> Result { + let selection = MoeExpertSelection::Routed { slot: first.slot }; + let descriptor = |role| binding.moe_weight_descriptor(&row.row().weights, selection, role).map_err(binding_error); + let keys = [descriptor(MoeMatrixRole::Gate)?, descriptor(MoeMatrixRole::Up)?, descriptor(MoeMatrixRole::Down)?]; + let layouts = [layout(keys[0])?, layout(keys[1])?, layout(keys[2])?]; + let formats = layouts.map(|(format, _)| format); + let charge = + layouts.into_iter().try_fold(0usize, |sum, (_, bytes)| sum.checked_add(bytes).ok_or(Error::Overflow))?; + Ok((keys, formats, charge)) +} + +/// Every grouped member must name the expected whole expert triplet. +pub(super) fn check_expert_keys( + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>, + keys: &[MoeWeightDescriptor; 3], + members: usize, +) -> Result<()> { + for (role_index, role) in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down].into_iter().enumerate() { + let key = source.descriptor(0, role).map_err(binding_error)?; + if key != keys[role_index] { + return Err(Error::IdentityMismatch); + } + for member in 1..members { + if source.descriptor(member, role).map_err(binding_error)? != key { + return Err(Error::IdentityMismatch); + } + } + } + Ok(()) +} + +pub(super) fn revalidate_rows( + txn: &QwenChunkTxn<'_, '_>, + layer: LayerId, + rows: &[ChunkFfnRow], + pairs: &[Pair], +) -> Result<()> { + for pair in pairs { + let row = rows.get(pair.row).ok_or(Error::IdentityMismatch)?; + txn.validate_ffn_row(txn.micro_row_index(pair.row)?, layer, row)?; + } + Ok(()) +} + +fn layout(key: MoeWeightDescriptor) -> Result<(leleka_cuda_driver::MmqFormat, usize)> { + original_dual_layout(key)?.ok_or(Error::InvalidDimension) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/walk_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/walk_fns.rs new file mode 100644 index 00000000..49285e52 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/walk_fns.rs @@ -0,0 +1,288 @@ +//! The adaptive prompt layer walk over staged and resident experts (STRA-338 size: extract-method only). + +#[allow(unused_imports)] +use super::*; + +/// Fixed metadata, independent of route frequency: which experts are resident and which miss. +pub(super) struct Classified { + pub(super) resident: [bool; 512], + pub(super) misses: [usize; 512], + pub(super) miss_count: usize, + pub(super) maximum_charge: usize, +} + +/// The occupied ephemeral staging slots and the next miss to stage. +pub(super) struct SlotState { + pub(super) slots: [Option; 16], + pub(super) next: usize, + pub(super) capacity: usize, +} + +/// The experts gathered for the next numerical run. +pub(super) struct Batch { + pub(super) experts: [usize; 16], + pub(super) count: usize, + pub(super) consumed: usize, +} + +/// The sealed layer rows and expert groups one adaptive prompt layer walks. +pub(super) struct Walk<'a, 't, 'ctx> { + pub(super) txn: &'a QwenChunkTxn<'t, 'ctx>, + pub(super) context: &'ctx Context<'ctx>, + pub(super) binding: &'a ModelBinding, + pub(super) layer: LayerId, + pub(super) rows: &'a [ChunkFfnRow], + pub(super) groups: &'a [Vec], +} + +impl<'a, 'ctx> Walk<'a, '_, 'ctx> { + /// Genuine padded destinations coexist with all actual staging/resident owners. The cache guard adds the + /// unchanged independent 128MiB reserve. Returns the slot waiter and the empty slot state. + pub(super) fn open_staging( + &self, + cache: &mut MoeWeightCache<'ctx>, + maximum_charge: usize, + ) -> Result<(impl FnMut(usize) -> Result<()> + 'a, SlotState)> { + cache.reserve_mmq_transient(self.binding, self.context, maximum_charge)?; + let owner = cache.ephemeral_routed_owner(self.binding, self.context)?; + let capacity = owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.slot_count(); + if !matches!(capacity, 2 | 8 | 16) { + return Err(Error::IdentityMismatch); + } + let binding = self.binding; + let wait = move |slot: usize| -> Result<()> { + owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.wait(slot, binding)?; + Ok(()) + }; + Ok((wait, SlotState { slots: [None; 16], next: 0, capacity })) + } + + /// Every miss must have been staged and consumed; then the source scope ends and the model is revalidated. + pub(super) fn finish( + &self, + source: OriginalMmqLayer<'_, 'ctx>, + cache: &MoeWeightCache<'ctx>, + classified: &Classified, + state: &SlotState, + ) -> Result<()> { + if state.next != classified.miss_count || state.slots[..state.capacity].iter().any(Option::is_some) { + return Err(Error::IdentityMismatch); + } + source.finish().map_err(mmq_error)?; + cache.validate(self.binding, self.context) + } + + pub(super) fn used(&self) -> impl Iterator)> { + self.groups.iter().enumerate().filter(|(_, pairs)| !pairs.is_empty()) + } + + /// Authenticate every actual row/group before the first device command. + /// Frequency/event policy still runs at its original point below. + pub(super) fn authenticate(&self, packets: &SlotPacks<'_, '_, 'ctx>) -> Result<()> { + for (index, row) in self.rows.iter().enumerate() { + self.txn.validate_ffn_row(self.txn.micro_row_index(index)?, self.layer, row)?; + } + for (expert, pairs) in self.used() { + let _ = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; + } + Ok(()) + } + + pub(super) fn observe_rows(&self, cache: &mut MoeWeightCache<'ctx>) -> Result<()> { + cache.poll_strata_adaptive(self.binding, false)?; + for (index, row) in self.rows.iter().enumerate() { + self.txn.validate_ffn_row(self.txn.micro_row_index(index)?, self.layer, row)?; + cache.observe_strata_adaptive_row(self.binding, &row.row().weights)?; + } + Ok(()) + } + + /// No logical residency entry is minted: true means the real adaptive owner can loan the triplet. + pub(super) fn classify( + &self, + cache: &MoeWeightCache<'ctx>, + packets: &SlotPacks<'_, '_, 'ctx>, + ) -> Result { + let mut out = Classified { resident: [false; 512], misses: [0; 512], miss_count: 0, maximum_charge: 0 }; + for (expert, pairs) in self.used() { + let _ = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; + let first = pairs[0]; + let row = self.rows.get(first.row).ok_or(Error::IdentityMismatch)?; + out.maximum_charge = out.maximum_charge.max(self.expert_charge(row, &first, expert)?); + let selection = MoeExpertSelection::Routed { slot: first.slot }; + out.resident[expert] = cache.strata_adaptive_resident(self.binding, &row.row().weights, selection)?; + if !out.resident[expert] { + out.misses[out.miss_count] = expert; + out.miss_count += 1; + } + } + Ok(out) + } + + /// The Gate/Up/Down bytes of one expert, after every descriptor names this layer and expert. + pub(super) fn expert_charge(&self, row: &ChunkFfnRow, first: &Pair, expert: usize) -> Result { + let mut charge = 0usize; + for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { + let selection = MoeExpertSelection::Routed { slot: first.slot }; + let key = self.binding.moe_weight_descriptor(&row.row().weights, selection, role).map_err(binding_error)?; + if key.layer != self.layer.get() || key.expert != Some(expert as u32) { + return Err(Error::IdentityMismatch); + } + let (_, bytes) = original_dual_layout(key)?.ok_or(Error::InvalidDimension)?; + charge = charge.checked_add(bytes).ok_or(Error::Overflow)?; + } + Ok(charge) + } + + pub(super) fn stage_miss( + &self, + cache: &MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + expert: usize, + slot: usize, + ) -> Result<()> { + stage(cache, self.context, self.binding, self.rows, &self.groups[expert], slot, cancelled) + } + + /// The first staging wave: one miss per slot. + pub(super) fn fill_slots( + &self, + cache: &MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + classified: &Classified, + state: &mut SlotState, + ) -> Result<()> { + for slot in 0..state.capacity { + if state.next == classified.miss_count { + break; + } + let expert = classified.misses[state.next]; + self.stage_miss(cache, cancelled, expert, slot)?; + state.slots[slot] = Some(expert); + state.next += 1; + } + Ok(()) + } + + /// Literal prompt order: residents and staged misses share one ID walk. The real bank retains gathered bytes + /// until the <=16-expert numerical run. + #[allow(clippy::too_many_arguments)] + pub(super) fn walk( + &self, + source: &mut OriginalMmqLayer<'_, 'ctx>, + cache: &mut MoeWeightCache<'ctx>, + packets: &mut SlotPacks<'_, '_, 'ctx>, + cancelled: &mut impl FnMut() -> bool, + wait: &mut impl FnMut(usize) -> Result<()>, + classified: &Classified, + state: &mut SlotState, + used_count: usize, + ) -> Result<()> { + let mut batch = Batch { experts: [0; 16], count: 0, consumed: 0 }; + for (expert, pairs) in self.used() { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let slot = self.wait_slot(wait, classified, state, expert)?; + self.gather_expert(expert, pairs, cache, source, packets, slot, cancelled)?; + batch.experts[batch.count] = expert; + batch.count += 1; + batch.consumed += 1; + if batch.count == 16 || batch.consumed == used_count { + self.run_batch(source, cache, packets, cancelled, &mut batch)?; + } + self.refill(cache, cancelled, classified, state, slot)?; + } + Ok(()) + } + + /// A resident expert needs no slot; a miss waits for its staged slot. + pub(super) fn wait_slot( + &self, + wait: &mut impl FnMut(usize) -> Result<()>, + classified: &Classified, + state: &SlotState, + expert: usize, + ) -> Result> { + if classified.resident[expert] { + return Ok(None); + } + let slots = &state.slots[..state.capacity]; + let slot = slots.iter().position(|entry| *entry == Some(expert)).ok_or(Error::IdentityMismatch)?; + wait(slot)?; + Ok(Some(slot)) + } + + pub(super) fn run_batch( + &self, + source: &mut OriginalMmqLayer<'_, 'ctx>, + cache: &mut MoeWeightCache<'ctx>, + packets: &mut SlotPacks<'_, '_, 'ctx>, + cancelled: &mut impl FnMut() -> bool, + batch: &mut Batch, + ) -> Result<()> { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + { + let finite = source.run_group().map_err(mmq_error)?; + for (group_index, expert) in batch.experts[..batch.count].iter().copied().enumerate() { + let pairs = &self.groups[expert]; + let origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; + // Each genuine source scope was explicitly finished after its completed gather. Revalidate current + // model/context before the actual packet owner publishes coverage. + let copy = |destinations: &mut [(u32, &mut DeviceBuffer<'ctx>, u32)]| { + finite.copy_expert_down_columns_to_slots(group_index, destinations).map_err(mmq_error)?; + cache.validate(self.binding, self.context) + }; + packets.copy_group(&origin, copy, cancelled)?; + } + } + source.finish_group().map_err(mmq_error)?; + batch.count = 0; + Ok(()) + } + + /// The consumed slot is freed and immediately restaged with the next miss. + pub(super) fn refill( + &self, + cache: &MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + classified: &Classified, + state: &mut SlotState, + slot: Option, + ) -> Result<()> { + let Some(slot) = slot else { + return Ok(()); + }; + state.slots[slot] = None; + if state.next < classified.miss_count { + let expert = classified.misses[state.next]; + self.stage_miss(cache, cancelled, expert, slot)?; + state.slots[slot] = Some(expert); + state.next += 1; + } + Ok(()) + } +} + +fn stage( + cache: &MoeWeightCache<'_>, + context: &Context<'_>, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + pairs: &[Pair], + slot: usize, + cancelled: &mut impl FnMut() -> bool, +) -> Result<()> { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let first = pairs.first().ok_or(Error::IdentityMismatch)?; + let row = rows.get(first.row).ok_or(Error::IdentityMismatch)?; + let members = [(&row.row().weights, first.slot)]; + let owner = cache.ephemeral_routed_owner(binding, context)?; + binding.with_moe_routed_source(&members, binding_error, |source| { + owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.stage(slot, binding, source, 0) + }) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs index f392f400..78c8313f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs @@ -3,9 +3,15 @@ use super::resident_slotpack::SlotPacks; use super::*; use leleka_cuda_driver::MmqWorkspace; +#[path = "moe_mmq_chunk/admission_fns.rs"] +mod admission_fns; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "moe_mmq_adaptive.rs"] mod original_adaptive; +#[path = "moe_mmq_chunk/resident_fns.rs"] +mod resident_fns; +use admission_fns::{mmq_triplets, rows_supported}; +use resident_fns::execute_resident; impl MoeExpertStage { pub(in crate::qwen_forward) fn execute_chunk_mmq<'ctx>( @@ -62,107 +68,110 @@ impl MoeExpertStage { if rows.len() != chunk.micro_len()? || !(1..=64).contains(&rows.len()) { return Err(Error::InvalidDimension); } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let original_prompt = native.is_some() && cache.has_original_prompt_mmq(); - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let original_prompt = false; - let mut supported = original_prompt || rows.len() > 1; - for (index, row) in rows.iter().enumerate() { - chunk.validate_ffn_row(chunk.micro_row_index(index)?, layer, row)?; - for slot in 0..K { - let selection = MoeExpertSelection::Routed { slot }; - let gate = row.row().weights.kind(selection, MoeMatrixRole::Gate).map_err(binding_error)?; - let up = row.row().weights.kind(selection, MoeMatrixRole::Up).map_err(binding_error)?; - let down = row.row().weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?; - supported &= (if original_prompt { - matches!( - gate, - MoeMatrixKind::Iq3Xxs - | MoeMatrixKind::Iq2S - | MoeMatrixKind::Iq3S - | MoeMatrixKind::RoutedIq4Xs - | MoeMatrixKind::RoutedIq4Nl - ) - } else { - matches!(gate, MoeMatrixKind::Iq3Xxs | MoeMatrixKind::Iq2S) - }) && gate == up - && matches!(down, MoeMatrixKind::RoutedIq4Nl | MoeMatrixKind::Q2_0); - } - } - let mut triplets = Vec::new(); - if supported && (original_prompt || cache.requires_iq3_mmq_admission()) { - triplets - .try_reserve_exact(rows.len().checked_mul(K).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; - for row in rows { - for slot in 0..K { - let selection = MoeExpertSelection::Routed { slot }; - let keys = [ - binding - .moe_weight_descriptor(&row.row().weights, selection, MoeMatrixRole::Gate) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(&row.row().weights, selection, MoeMatrixRole::Up) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(&row.row().weights, selection, MoeMatrixRole::Down) - .map_err(binding_error)?, - ]; - if keys.iter().any(|key| key.layer != layer.get()) { - return Err(Error::IdentityMismatch); - } - triplets.push(keys); - } - } - } - let admission = if supported { - cache.admit_mmq_chunk(binding, chunk.context()?, rows.len(), &triplets, original_prompt)? - } else { - None - }; - supported &= admission.is_some(); - if !supported { - // Actual21/23, T1 and GU22 under the IQ3-only policy take native. This is - // an admission decision BEFORE MMQ numerics, not error fallback. + ChunkCall { + binding, + layer, + rows, #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(finish) = native { - return Self::execute_chunk_native_prompt( - binding, - layer, - rows, - chunk, - cache, - cancelled, - finish.products, - finish.dense, - ); - } - let result = Self::execute_chunk(binding, layer, rows, chunk, cache, cancelled); - #[cfg(test)] - if result.is_ok() { - cache.note_test_mmq_dispatch(false, rows.len()); - } - return result; + native, + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + marker: std::marker::PhantomData, } - let admission = admission.ok_or(Error::IdentityMismatch)?; + .run(chunk, cache, cancelled) + } +} + +/// One MMQ layer batch: the rows plus the optional native prompt finish. +pub(super) struct ChunkCall<'a, 'ctx, 'l, 'd> { + pub(super) binding: &'a ModelBinding, + pub(super) layer: LayerId, + pub(super) rows: &'a [ChunkFfnRow], + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(super) native: Option>, + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + pub(super) marker: std::marker::PhantomData<(&'ctx (), &'l (), &'d ())>, +} + +impl<'ctx> ChunkCall<'_, 'ctx, '_, '_> { + /// The original prompt operator is selected only with the native prompt finish and an original-prompt cache. + fn original_prompt(&self, cache: &MoeWeightCache<'ctx>) -> bool { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + return self.native.is_some() && cache.has_original_prompt_mmq(); + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + return false; + } + + fn run( + self, + chunk: &mut QwenChunkTxn<'_, 'ctx>, + cache: &mut MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + ) -> Result> { + match self.admit(chunk, cache)? { + Some(admission) => self.execute_admitted(chunk, cache, cancelled, &admission), + None => self.execute_unsupported(chunk, cache, cancelled), + } + } + + /// The MMQ admission of the batch; `None` when any slot kind or the cache policy is unsupported. + fn admit( + &self, + chunk: &mut QwenChunkTxn<'_, 'ctx>, + cache: &mut MoeWeightCache<'ctx>, + ) -> Result> { + let (binding, layer, rows) = (self.binding, self.layer, self.rows); + let original_prompt = self.original_prompt(cache); + let supported = rows_supported(chunk, layer, rows, original_prompt, original_prompt || rows.len() > 1)?; + if !supported { + return Ok(None); + } + let triplets = if original_prompt || cache.requires_iq3_mmq_admission() { + mmq_triplets(binding, layer, rows)? + } else { + Vec::new() + }; + cache.admit_mmq_chunk(binding, chunk.context()?, rows.len(), &triplets, original_prompt) + } + + /// Actual21/23, T1 and GU22 under the IQ3-only policy take native. This is an admission decision BEFORE MMQ + /// numerics, not error fallback. + fn execute_unsupported( + self, + chunk: &mut QwenChunkTxn<'_, 'ctx>, + cache: &mut MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + ) -> Result> { + let (binding, layer, rows) = (self.binding, self.layer, self.rows); + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(finish) = self.native { + let (products, dense) = (finish.products, finish.dense); + return MoeExpertStage::execute_chunk_native_prompt( + binding, layer, rows, chunk, cache, cancelled, products, dense, + ); + } + let result = MoeExpertStage::execute_chunk(binding, layer, rows, chunk, cache, cancelled); + #[cfg(test)] + if result.is_ok() { + cache.note_test_mmq_dispatch(false, rows.len()); + } + result + } + + fn execute_admitted( + self, + chunk: &mut QwenChunkTxn<'_, 'ctx>, + cache: &mut MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + admission: &crate::qwen_forward::moe_weight_cache::MmqChunkAdmission, + ) -> Result> { + let (binding, layer, rows) = (self.binding, self.layer, self.rows); let context = cache.mmq_context(binding, chunk.context()?)?; let result = chunk.batch_outputs_ffn(layer, rows, |actual, observed| { if !std::ptr::eq(context, observed) { return Err(Error::IdentityMismatch); } - cache.with_mmq_workspace(binding, context, &admission, |cache, workspace| { - execute_resident( - actual, - context, - binding, - layer, - rows, - cache, - workspace, - cancelled, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - native, - ) + cache.with_mmq_workspace(binding, context, admission, |cache, workspace| { + self.resident(actual, context, cache, workspace, cancelled) }) }); #[cfg(test)] @@ -173,6 +182,28 @@ impl MoeExpertStage { } result } + + fn resident( + self, + actual: &QwenChunkTxn<'_, 'ctx>, + context: &'ctx Context<'ctx>, + cache: &mut MoeWeightCache<'ctx>, + workspace: &mut MmqWorkspace<'ctx>, + cancelled: &mut impl FnMut() -> bool, + ) -> Result> { + execute_resident( + actual, + context, + self.binding, + self.layer, + self.rows, + cache, + workspace, + cancelled, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + self.native, + ) + } } fn mmq_error(error: DriverError) -> Error { match error { @@ -180,215 +211,3 @@ fn mmq_error(error: DriverError) -> Error { other => driver_error(other), } } -#[allow(clippy::too_many_arguments)] -fn execute_resident<'ctx>( - txn: &QwenChunkTxn<'_, 'ctx>, - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], - cache: &mut MoeWeightCache<'ctx>, - workspace: &mut MmqWorkspace<'ctx>, - cancelled: &mut impl FnMut() -> bool, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mut native: Option< - super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, - >, -) -> 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::Moe); - cache.validate(binding, context)?; - // Workspace is ALREADY allocated/charged by the explicit cache factory. - // Account all simultaneous slot packets and unchanged shared activations; - // existing cache.room retains the independent 128MiB transient reserve. - let extra = - rows.len().checked_mul(K * N * 4 + N * 4).and_then(|v| v.checked_add(DEVICE_PEAK)).ok_or(Error::Overflow)?; - #[cfg(test)] - let allocated_before = context.allocated_bytes(); - #[cfg(test)] - let first_row = txn.micro_row_index(0)?; - cache.reserve_mmq_transient(binding, context, extra).inspect_err(|_error| { - #[cfg(test)] - eprintln!( - "PUBLIC MMQ allocation stage=reserve-transient layer={} first={} rows={} allocated_before={} allocated_after={} extra={} reserve={} budget={} error={_error:?}", - layer.get(), first_row, rows.len(), allocated_before, - context.allocated_bytes(), extra, - crate::qwen_forward::moe_weight_cache::WORKING_RESERVE, - context.budget_bytes() - ); - })?; - if context - .allocated_bytes() - .checked_add(extra) - .and_then(|v| v.checked_add(crate::qwen_forward::moe_weight_cache::WORKING_RESERVE)) - .is_none_or(|v| v > context.budget_bytes()) - { - #[cfg(test)] - eprintln!( - "PUBLIC MMQ allocation stage=post-reservation-guard layer={} first={} rows={} allocated={} extra={} reserve={} budget={}", - layer.get(), - first_row, - rows.len(), - context.allocated_bytes(), - extra, - crate::qwen_forward::moe_weight_cache::WORKING_RESERVE, - context.budget_bytes() - ); - return Err(Error::InputAllocation); - } - let failed = Rc::new(Cell::new(false)); - let scope = DownScope::new(context, Rc::clone(&failed)); - let result = (|| { - let mut inputs = Vec::new(); - inputs - .try_reserve_exact(rows.len().checked_mul(N).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; - let mut ids = Vec::new(); - ids.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; - for (index, row) in rows.iter().enumerate() { - txn.validate_ffn_row(txn.micro_row_index(index)?, layer, row)?; - inputs.extend_from_slice(row.row().read.ready().mixed()); - ids.push(std::array::from_fn(|slot| row.row().route.experts()[slot].get())); - } - let groups = grouped_pairs(&ids)?; - let mut packets = SlotPacks::new(txn, binding, layer, rows, context, &scope)?; - let mut activations = Vec::new(); - activations.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; - let operation = (|| { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - { - let tokens = u32::try_from(rows.len()).map_err(|_| Error::Overflow)?; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let original_prompt = native.is_some() && cache.has_original_prompt_mmq(); - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let original_prompt = false; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let adaptive_prompt = original_prompt && cache.uses_strata_adaptive_experts(); - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let adaptive_prompt = false; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if adaptive_prompt { - original_adaptive::execute_adaptive_groups( - txn, - context, - binding, - layer, - rows, - &groups, - cache, - workspace, - &inputs, - &mut packets, - cancelled, - )?; - } - if !adaptive_prompt { - let mut source = if original_prompt { - workspace.prepare_original_gate_up_chunk(&inputs, tokens) - } else { - workspace.prepare_gate_up_chunk(&inputs, tokens) - } - .map_err(mmq_error)?; - for (expert, pairs) in - groups.iter().enumerate().filter(|(_, pairs)| !pairs.is_empty() && !adaptive_prompt) - { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; - let first = pairs.first().ok_or(Error::IdentityMismatch)?; - let row = rows.get(first.row).ok_or(Error::IdentityMismatch)?; - let mut indices = Vec::new(); - indices.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; - for pair in pairs { - txn.validate_ffn_row(txn.micro_row_index(pair.row)?, layer, &rows[pair.row])?; - for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { - let source_key = binding - .moe_weight_descriptor( - &row.row().weights, - MoeExpertSelection::Routed { slot: first.slot }, - role, - ) - .map_err(binding_error)?; - let actual_key = binding - .moe_weight_descriptor( - &rows[pair.row].row().weights, - MoeExpertSelection::Routed { slot: pair.slot }, - role, - ) - .map_err(binding_error)?; - if source_key != actual_key { - return Err(Error::IdentityMismatch); - } - } - indices.push(u32::try_from(pair.row).map_err(|_| Error::Overflow)?); - } - let group = source.gather_gate_up(&indices).map_err(mmq_error)?; - cache.with_mmq_triplet( - binding, - &row.row().weights, - MoeExpertSelection::Routed { slot: first.slot }, - original_prompt, - |gate, up, down| { - let hidden = group.gate_up(gate, up).map_err(mmq_error)?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let finite = hidden.down(down).map_err(mmq_error)?; - if finite.tokens() as usize != pairs.len() { - return Err(Error::IdentityMismatch); - } - packets.copy_group( - &origin, - |destinations| finite.copy_down_columns_to_slots(destinations).map_err(mmq_error), - cancelled, - )?; - Ok(()) - }, - )?; - // finite group lease has expired; the same workspace is reused. - } - } - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(finish) = native.as_mut() { - return packets.finish_native_micro(cache, finish, cancelled); - } - let mut outputs = Vec::new(); - outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; - for (index, row) in rows.iter().enumerate() { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - // Shared expert is unchanged native math. Its existing private - // scalar staging is retained, not advertised as device-resident. - activations.push(scope.upload(row.row().read.ready().mixed())?); - outputs.push(packets.finish_row( - index, - activations.last().ok_or(Error::IdentityMismatch)?.buffer()?, - cache, - cancelled, - )?); - } - Ok(outputs) - })(); - scope.record(&operation); - let mut cleanup = packets.close(); - for activation in activations { - let next = activation.close(); - if cleanup.is_ok() { - cleanup = next; - } - } - operation.and_then(|values| cleanup.map(|()| values)) - })(); - // Covers early setup/partial packet allocation failures as well as the - // numerical body. Drop cleanup may set the shared flag while preserving a - // non-transport primary; never lose that uncertain-free cache fence. - if failed.get() || context.is_poisoned() { - cache.note_transport_failure(); - } - result -} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/admission_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/admission_fns.rs new file mode 100644 index 00000000..6631e7ba --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/admission_fns.rs @@ -0,0 +1,74 @@ +//! Support and descriptor admission of one MMQ chunk (STRA-338 size: extract-method only). + +#[allow(unused_imports)] +use super::*; +use crate::model_binding::qwen4exp_input::MoeWeightDescriptor; + +/// Whether every routed slot of every row has an MMQ-capable Gate/Up/Down kind. `supported` is the starting verdict. +pub(super) fn rows_supported( + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + rows: &[ChunkFfnRow], + original_prompt: bool, + mut supported: bool, +) -> Result { + for (index, row) in rows.iter().enumerate() { + chunk.validate_ffn_row(chunk.micro_row_index(index)?, layer, row)?; + for slot in 0..K { + supported &= slot_supported(row, slot, original_prompt)?; + } + } + Ok(supported) +} + +fn slot_supported(row: &ChunkFfnRow, slot: usize, original_prompt: bool) -> Result { + let selection = MoeExpertSelection::Routed { slot }; + let gate = row.row().weights.kind(selection, MoeMatrixRole::Gate).map_err(binding_error)?; + let up = row.row().weights.kind(selection, MoeMatrixRole::Up).map_err(binding_error)?; + let down = row.row().weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?; + let gate_kind = if original_prompt { + matches!( + gate, + MoeMatrixKind::Iq3Xxs + | MoeMatrixKind::Iq2S + | MoeMatrixKind::Iq3S + | MoeMatrixKind::RoutedIq4Xs + | MoeMatrixKind::RoutedIq4Nl + ) + } else { + matches!(gate, MoeMatrixKind::Iq3Xxs | MoeMatrixKind::Iq2S) + }; + Ok(gate_kind && gate == up && matches!(down, MoeMatrixKind::RoutedIq4Nl | MoeMatrixKind::Q2_0)) +} + +/// Every row's ten Gate/Up/Down descriptor triplets, all bound to this layer. +pub(super) fn mmq_triplets( + binding: &ModelBinding, + layer: LayerId, + rows: &[ChunkFfnRow], +) -> Result> { + let mut triplets = Vec::new(); + triplets + .try_reserve_exact(rows.len().checked_mul(K).ok_or(Error::Overflow)?) + .map_err(|_| Error::InputAllocation)?; + for row in rows { + for slot in 0..K { + let keys = slot_keys(binding, row, slot)?; + if keys.iter().any(|key| key.layer != layer.get()) { + return Err(Error::IdentityMismatch); + } + triplets.push(keys); + } + } + Ok(triplets) +} + +fn slot_keys(binding: &ModelBinding, row: &ChunkFfnRow, slot: usize) -> Result<[MoeWeightDescriptor; 3]> { + let selection = MoeExpertSelection::Routed { slot }; + let weights = &row.row().weights; + Ok([ + binding.moe_weight_descriptor(weights, selection, MoeMatrixRole::Gate).map_err(binding_error)?, + binding.moe_weight_descriptor(weights, selection, MoeMatrixRole::Up).map_err(binding_error)?, + binding.moe_weight_descriptor(weights, selection, MoeMatrixRole::Down).map_err(binding_error)?, + ]) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs new file mode 100644 index 00000000..1f7842c4 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs @@ -0,0 +1,372 @@ +//! The resident MMQ chunk execution (STRA-338 size: extract-method only). + +#[allow(unused_imports)] +use super::*; +use leleka_cuda_driver::MmqChunkActivation; + +/// The sealed rows of one resident MMQ layer batch. +struct Resident<'a, 't, 'ctx> { + txn: &'a QwenChunkTxn<'t, 'ctx>, + context: &'ctx Context<'ctx>, + binding: &'a ModelBinding, + layer: LayerId, + rows: &'a [ChunkFfnRow], +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn execute_resident<'ctx>( + txn: &QwenChunkTxn<'_, 'ctx>, + context: &'ctx Context<'ctx>, + binding: &ModelBinding, + layer: LayerId, + rows: &[ChunkFfnRow], + cache: &mut MoeWeightCache<'ctx>, + workspace: &mut MmqWorkspace<'ctx>, + cancelled: &mut impl FnMut() -> bool, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< + super::super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, + >, +) -> 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::Moe); + let resident = Resident { txn, context, binding, layer, rows }; + resident.execute( + cache, + workspace, + cancelled, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native, + ) +} + +fn reserved(count: usize) -> Result> { + let mut items = Vec::new(); + items.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; + Ok(items) +} + +impl<'ctx> Resident<'_, '_, 'ctx> { + fn execute( + &self, + cache: &mut MoeWeightCache<'ctx>, + workspace: &mut MmqWorkspace<'ctx>, + cancelled: &mut impl FnMut() -> bool, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< + super::super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, + >, + ) -> Result> { + self.admit(cache)?; + let failed = Rc::new(Cell::new(false)); + let scope = DownScope::new(self.context, Rc::clone(&failed)); + let result = self.run( + &scope, + cache, + workspace, + cancelled, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native, + ); + // Covers early setup/partial packet allocation failures as well as the + // numerical body. Drop cleanup may set the shared flag while preserving a + // non-transport primary; never lose that uncertain-free cache fence. + if failed.get() || self.context.is_poisoned() { + cache.note_transport_failure(); + } + result + } + + /// Workspace is ALREADY allocated/charged by the explicit cache factory. + /// Account all simultaneous slot packets and unchanged shared activations; + /// existing cache.room retains the independent 128MiB transient reserve. + fn admit(&self, cache: &mut MoeWeightCache<'ctx>) -> Result<()> { + cache.validate(self.binding, self.context)?; + let extra = self + .rows + .len() + .checked_mul(K * N * 4 + N * 4) + .and_then(|v| v.checked_add(DEVICE_PEAK)) + .ok_or(Error::Overflow)?; + self.reserve(cache, extra)?; + let reserve = crate::qwen_forward::moe_weight_cache::WORKING_RESERVE; + if self + .context + .allocated_bytes() + .checked_add(extra) + .and_then(|v| v.checked_add(reserve)) + .is_none_or(|v| v > self.context.budget_bytes()) + { + #[cfg(test)] + self.trace_guard_failure(extra)?; + return Err(Error::InputAllocation); + } + Ok(()) + } + + fn reserve(&self, cache: &mut MoeWeightCache<'ctx>, extra: usize) -> Result<()> { + #[cfg(test)] + let allocated_before = self.context.allocated_bytes(); + #[cfg(test)] + let first_row = self.txn.micro_row_index(0)?; + cache.reserve_mmq_transient(self.binding, self.context, extra).inspect_err(|_error| { + #[cfg(test)] + self.trace_reserve_failure(first_row, allocated_before, extra, _error); + }) + } + + #[cfg(test)] + fn trace_reserve_failure(&self, first_row: usize, allocated_before: usize, extra: usize, _error: &Error) { + eprintln!( + "PUBLIC MMQ allocation stage=reserve-transient layer={} first={} rows={} allocated_before={} allocated_after={} extra={} reserve={} budget={} error={_error:?}", + self.layer.get(), + first_row, + self.rows.len(), + allocated_before, + self.context.allocated_bytes(), + extra, + crate::qwen_forward::moe_weight_cache::WORKING_RESERVE, + self.context.budget_bytes() + ); + } + + #[cfg(test)] + fn trace_guard_failure(&self, extra: usize) -> Result<()> { + eprintln!( + "PUBLIC MMQ allocation stage=post-reservation-guard layer={} first={} rows={} allocated={} extra={} reserve={} budget={}", + self.layer.get(), + self.txn.micro_row_index(0)?, + self.rows.len(), + self.context.allocated_bytes(), + extra, + crate::qwen_forward::moe_weight_cache::WORKING_RESERVE, + self.context.budget_bytes() + ); + Ok(()) + } + + fn run( + &self, + scope: &DownScope<'ctx>, + cache: &mut MoeWeightCache<'ctx>, + workspace: &mut MmqWorkspace<'ctx>, + cancelled: &mut impl FnMut() -> bool, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< + super::super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, + >, + ) -> Result> { + let (inputs, ids) = self.gather_rows()?; + let groups = grouped_pairs(&ids)?; + let mut packets = SlotPacks::new(self.txn, self.binding, self.layer, self.rows, self.context, scope)?; + let mut activations = reserved(self.rows.len())?; + let operation = self.operate( + scope, + cache, + workspace, + cancelled, + &groups, + &inputs, + &mut packets, + &mut activations, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native, + ); + scope.record(&operation); + let cleanup = close_resident(packets, activations); + operation.and_then(|values| cleanup.map(|()| values)) + } + + fn gather_rows(&self) -> Result<(Vec, Vec<[u32; K]>)> { + let mut inputs = reserved(self.rows.len().checked_mul(N).ok_or(Error::Overflow)?)?; + let mut ids = reserved(self.rows.len())?; + for (index, row) in self.rows.iter().enumerate() { + self.txn.validate_ffn_row(self.txn.micro_row_index(index)?, self.layer, row)?; + inputs.extend_from_slice(row.row().read.ready().mixed()); + ids.push(std::array::from_fn(|slot| row.row().route.experts()[slot].get())); + } + Ok((inputs, ids)) + } + + #[allow(clippy::too_many_arguments)] + fn operate( + &self, + scope: &DownScope<'ctx>, + cache: &mut MoeWeightCache<'ctx>, + workspace: &mut MmqWorkspace<'ctx>, + cancelled: &mut impl FnMut() -> bool, + groups: &[Vec], + inputs: &[f32], + packets: &mut SlotPacks<'_, '_, 'ctx>, + activations: &mut Vec>, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mut native: Option< + super::super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, + >, + ) -> Result> { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let original_prompt = native.is_some() && cache.has_original_prompt_mmq(); + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + let original_prompt = false; + self.project_all(cache, workspace, cancelled, original_prompt, groups, inputs, packets)?; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(finish) = native.as_mut() { + return packets.finish_native_micro(cache, finish, cancelled); + } + self.finish_rows(scope, cache, cancelled, packets, activations) + } + + /// Shared expert is unchanged native math. Its existing private scalar staging is retained, not advertised as + /// device-resident. + fn finish_rows( + &self, + scope: &DownScope<'ctx>, + cache: &mut MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + packets: &SlotPacks<'_, '_, 'ctx>, + activations: &mut Vec>, + ) -> Result> { + let mut outputs = reserved(self.rows.len())?; + for (index, row) in self.rows.iter().enumerate() { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + activations.push(scope.upload(row.row().read.ready().mixed())?); + let activation = activations.last().ok_or(Error::IdentityMismatch)?.buffer()?; + outputs.push(packets.finish_row(index, activation, cache, cancelled)?); + } + Ok(outputs) + } + + #[allow(clippy::too_many_arguments)] + fn project_all( + &self, + cache: &mut MoeWeightCache<'ctx>, + workspace: &mut MmqWorkspace<'ctx>, + cancelled: &mut impl FnMut() -> bool, + original_prompt: bool, + groups: &[Vec], + inputs: &[f32], + packets: &mut SlotPacks<'_, '_, 'ctx>, + ) -> Result<()> { + let tokens = u32::try_from(self.rows.len()).map_err(|_| Error::Overflow)?; + if self.project_adaptive(cache, workspace, cancelled, original_prompt, groups, inputs, packets)? { + return Ok(()); + } + let mut source = if original_prompt { + workspace.prepare_original_gate_up_chunk(inputs, tokens) + } else { + workspace.prepare_gate_up_chunk(inputs, tokens) + } + .map_err(mmq_error)?; + for (expert, pairs) in groups.iter().enumerate().filter(|(_, pairs)| !pairs.is_empty()) { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + // finite group lease has expired after each call; the same workspace is reused. + self.project_expert(cache, cancelled, original_prompt, &mut source, expert, pairs, packets)?; + } + Ok(()) + } + + /// The Strata adaptive producer handles the whole layer when selected; `true` means it did. + #[allow(clippy::too_many_arguments)] + fn project_adaptive( + &self, + cache: &mut MoeWeightCache<'ctx>, + workspace: &mut MmqWorkspace<'ctx>, + cancelled: &mut impl FnMut() -> bool, + original_prompt: bool, + groups: &[Vec], + inputs: &[f32], + packets: &mut SlotPacks<'_, '_, 'ctx>, + ) -> Result { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if original_prompt && cache.uses_strata_adaptive_experts() { + let (txn, context, binding, layer, rows) = (self.txn, self.context, self.binding, self.layer, self.rows); + super::original_adaptive::execute_adaptive_groups( + txn, context, binding, layer, rows, groups, cache, workspace, inputs, packets, cancelled, + )?; + return Ok(true); + } + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + let _ = (cache, workspace, cancelled, original_prompt, groups, inputs, packets); + Ok(false) + } + + #[allow(clippy::too_many_arguments)] + fn project_expert( + &self, + cache: &mut MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + original_prompt: bool, + source: &mut MmqChunkActivation<'_, 'ctx>, + expert: usize, + pairs: &[Pair], + packets: &mut SlotPacks<'_, '_, 'ctx>, + ) -> Result<()> { + let origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; + let (first, row) = self.group_head(pairs)?; + let indices = self.group_indices(row, first, pairs)?; + let group = source.gather_gate_up(&indices).map_err(mmq_error)?; + let selection = MoeExpertSelection::Routed { slot: first.slot }; + cache.with_mmq_triplet(self.binding, &row.row().weights, selection, original_prompt, |gate, up, down| { + let hidden = group.gate_up(gate, up).map_err(mmq_error)?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let finite = hidden.down(down).map_err(mmq_error)?; + if finite.tokens() as usize != pairs.len() { + return Err(Error::IdentityMismatch); + } + let copy = |destinations: &mut [(u32, &mut DeviceBuffer<'ctx>, u32)]| { + finite.copy_down_columns_to_slots(destinations).map_err(mmq_error) + }; + packets.copy_group(&origin, copy, cancelled) + }) + } + + /// The first pair of an expert group and its sealed row. + fn group_head<'p>(&self, pairs: &'p [Pair]) -> Result<(&'p Pair, &ChunkFfnRow)> { + let first = pairs.first().ok_or(Error::IdentityMismatch)?; + Ok((first, self.rows.get(first.row).ok_or(Error::IdentityMismatch)?)) + } + + /// The sealed row indices of one expert group, after every pair matches the group's source descriptors. + fn group_indices(&self, row: &ChunkFfnRow, first: &Pair, pairs: &[Pair]) -> Result> { + let mut indices = reserved(pairs.len())?; + for pair in pairs { + self.txn.validate_ffn_row(self.txn.micro_row_index(pair.row)?, self.layer, &self.rows[pair.row])?; + self.check_pair_keys(row, first, pair)?; + indices.push(u32::try_from(pair.row).map_err(|_| Error::Overflow)?); + } + Ok(indices) + } + + fn check_pair_keys(&self, row: &ChunkFfnRow, first: &Pair, pair: &Pair) -> Result<()> { + for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { + let source = MoeExpertSelection::Routed { slot: first.slot }; + let actual = MoeExpertSelection::Routed { slot: pair.slot }; + let source_key = + self.binding.moe_weight_descriptor(&row.row().weights, source, role).map_err(binding_error)?; + let weights = &self.rows[pair.row].row().weights; + let actual_key = self.binding.moe_weight_descriptor(weights, actual, role).map_err(binding_error)?; + if source_key != actual_key { + return Err(Error::IdentityMismatch); + } + } + Ok(()) + } +} + +/// Close the packets, then every shared activation; the first failure is kept and everything is closed. +fn close_resident<'ctx>(packets: SlotPacks<'_, '_, 'ctx>, activations: Vec>) -> Result<()> { + let mut cleanup = packets.close(); + for activation in activations { + let next = activation.close(); + if cleanup.is_ok() { + cleanup = next; + } + } + cleanup +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch.rs index 5b66d1ca..7b725f73 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch.rs @@ -21,6 +21,9 @@ use leleka_cuda_driver::{ MoeRouteBatch, }; +/// The shared exclusively loaned GEMM adapter every batched step receives. +type GemmRef<'a> = &'a dyn GdnGemm; + const MIXED: usize = 2560; const EXPERTS: usize = 512; const SELECTED: usize = 10; @@ -111,6 +114,11 @@ pub(crate) struct MoePrefillStage; #[cfg(test)] mod tests; +#[path = "moe_prefill_batch/route_micro_fns.rs"] +mod route_micro_fns; +use route_micro_fns::{ + MicroInputs, assemble_products, check_combine_window, combine_on_device, route_on_device, validate_micro, +}; #[path = "moe_prefill_batch/impl_moeprefillresources.rs"] mod impl_moeprefillresources; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/device_bytes_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/device_bytes_fn.rs index 1f0360b6..58006bc1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/device_bytes_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/device_bytes_fn.rs @@ -34,53 +34,18 @@ impl<'ctx> Buffers<'ctx> { profile: MoeBf16Profile, combine: bool, ) -> Result { - let images = tokens * MIXED * 2; let lo = profile == MoeBf16Profile::HighPlusLow; - let mut sizes = vec![tokens * MIXED * 4, images, images]; - if lo { - sizes.push(images); - } - sizes.extend([ - tokens * EXPERTS * 4, - tokens * SELECTED * 4, - tokens * SELECTED * 4, - tokens * FF * 4, - tokens * FF * 4, - tokens * FF * 2, - tokens * MIXED * 4, - tokens * 4, - ]); - if combine { - sizes.push(tokens * MIXED * 4); - } - let mut pool = Vec::new(); - pool.try_reserve_exact(sizes.len()).map_err(|_| Error::InputAllocation)?; - for bytes in sizes { - match context.allocate(bytes) { - Ok(buffer) => pool.push(buffer), - Err(error) => { - let _ = release_pool(pool); - return Err(driver_error(error)); - } - } - } + let pool = allocate_pool(context, buffer_sizes(tokens, lo, combine))?; + Self::from_pool(pool, lo, combine) + } + + fn from_pool(pool: Vec>, lo: bool, combine: bool) -> Result { let mut pool = pool.into_iter(); - let mut take = || pool.next().ok_or(Error::IdentityMismatch); - Ok(Self { - mixed: take()?, - mixed_h: take()?, - mixed_bf: take()?, - mixed_bf_lo: if lo { Some(take()?) } else { None }, - logits: take()?, - ids: take()?, - weights: take()?, - sgate: take()?, - sup: take()?, - sh_h: take()?, - shared: take()?, - sg: take()?, - bo: if combine { Some(take()?) } else { None }, - }) + let [mixed, mixed_h, mixed_bf] = take3(&mut pool)?; + let mixed_bf_lo = take_optional(&mut pool, lo)?; + let [logits, ids, weights, sgate, sup, sh_h, shared, sg] = take8(&mut pool)?; + let bo = take_optional(&mut pool, combine)?; + Ok(Self { mixed, mixed_h, mixed_bf, mixed_bf_lo, logits, ids, weights, sgate, sup, sh_h, shared, sg, bo }) } /// Release the internal owners and hand `shared`, `sg`, `bo` and (when `keep_weights`) the route weights out. pub(super) fn into_outputs( @@ -122,3 +87,69 @@ pub(super) fn release_pool(pool: Vec>) -> Result<()> { } failure.map_or(Ok(()), Err) } + +/// The byte size of every per-call buffer, in allocation order. +fn buffer_sizes(tokens: usize, lo: bool, combine: bool) -> Vec { + let images = tokens * MIXED * 2; + let mut sizes = vec![tokens * MIXED * 4, images, images]; + if lo { + sizes.push(images); + } + sizes.extend([ + tokens * EXPERTS * 4, + tokens * SELECTED * 4, + tokens * SELECTED * 4, + tokens * FF * 4, + tokens * FF * 4, + tokens * FF * 2, + tokens * MIXED * 4, + tokens * 4, + ]); + if combine { + sizes.push(tokens * MIXED * 4); + } + sizes +} + +fn allocate_pool<'ctx>(context: &'ctx Context<'ctx>, sizes: Vec) -> Result>> { + let mut pool = Vec::new(); + pool.try_reserve_exact(sizes.len()).map_err(|_| Error::InputAllocation)?; + for bytes in sizes { + match context.allocate(bytes) { + Ok(buffer) => pool.push(buffer), + Err(error) => { + let _ = release_pool(pool); + return Err(driver_error(error)); + } + } + } + Ok(pool) +} + +fn take_one<'ctx>(pool: &mut impl Iterator>) -> Result> { + pool.next().ok_or(Error::IdentityMismatch) +} + +fn take_optional<'ctx>( + pool: &mut impl Iterator>, + present: bool, +) -> Result>> { + if present { Ok(Some(take_one(pool)?)) } else { Ok(None) } +} + +fn take3<'ctx>(pool: &mut impl Iterator>) -> Result<[DeviceBuffer<'ctx>; 3]> { + Ok([take_one(pool)?, take_one(pool)?, take_one(pool)?]) +} + +fn take8<'ctx>(pool: &mut impl Iterator>) -> Result<[DeviceBuffer<'ctx>; 8]> { + Ok([ + take_one(pool)?, + take_one(pool)?, + take_one(pool)?, + take_one(pool)?, + take_one(pool)?, + take_one(pool)?, + take_one(pool)?, + take_one(pool)?, + ]) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillstage.rs index 4425a10a..be03bec2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillstage.rs @@ -27,143 +27,23 @@ impl MoePrefillStage { weights: SharedWeights<'_, 'ctx>, combine: Option>, resources: &mut MoePrefillResources<'ctx>, - gemm: &dyn GdnGemm, + gemm: GemmRef<'_>, ) -> Result> { resources.validate_context(current)?; - let tokens = reads.len(); - if tokens == 0 || tokens > MOE_BATCH_MAX_TOKENS { - return Err(Error::IdentityMismatch); - } - let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; - if expected != layer { - return Err(Error::IdentityMismatch); - } - if binding.expert_count() != EXPERTS as u32 || binding.expert_used_count() != SELECTED as u32 { - return Err(Error::InvalidDimension); - } - // The layer's router weights must be this binding's own (as in `route_from_ffn`). - let route_weights = binding.moe_route_weights(layer.get()).map_err(|_| Error::IdentityMismatch)?; - if !route_weights.matches(&binding.identity(), layer.get()) { - return Err(Error::IdentityMismatch); - } - // Genuine reads only: origin, layer, and strictly consecutive positions. - let mut host = Vec::new(); - host.try_reserve_exact(tokens * MIXED).map_err(|_| Error::InputAllocation)?; - let mut identities: Vec = Vec::new(); - identities.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; - for read in reads { - read.validate_origin(&binding.identity(), GrRole::Ffn(layer.get()))?; - let identity = read.identity(); - if identity.layer() != layer { - return Err(Error::IdentityMismatch); - } - if let Some(previous) = identities.last().copied() - && previous.position().get().checked_add(1) != Some(identity.position().get()) - { - return Err(Error::IdentityMismatch); - } - let values = read.mixed(); - if values.len() != MIXED { - return Err(Error::InvalidDimension); - } - if values.iter().any(|v| !v.is_finite()) { - return Err(Error::NonFinite); - } - host.extend_from_slice(values); - identities.push(identity); - } - // The shared expert's real descriptors, sizes and formats. - validate_descriptors(weights.keys)?; - // `validate_descriptors` makes all four keys agree; they must also be THIS layer's, before any CUDA write. - if weights.keys.iter().any(|key| key.layer != layer.get()) { - return Err(Error::IdentityMismatch); - } - for (buffer, key) in weights.buffers.iter().zip(weights.keys) { - if buffer.len() != key.bytes { - return Err(Error::IdentityMismatch); - } - } - let gate_format = gate_up_format(weights.keys[0])?; - let up_format = gate_up_format(weights.keys[1])?; - let down = down_format(weights.keys[2])?; - if router.len() != EXPERTS * MIXED * 2 { - return Err(Error::InvalidDimension); - } + let plan = validate_micro(binding, layer, reads, router, &weights, combine.as_ref())?; let profile = resources.profile; - let with_combine = combine.is_some(); - if let Some(input) = &combine - && (input.slot.len() != tokens * SELECTED || input.dm.len() != tokens * SELECTED * MIXED * 4) - { - return Err(Error::InvalidDimension); - } - admit(current, device_bytes(tokens, profile, with_combine)?)?; - let mixed_bytes = f32_bytes(&host)?; - let mut buffers = Buffers::new(current, tokens, profile, with_combine)?; - - let operation = (|| -> Result { - buffers.mixed.copy_from(&mixed_bytes).map_err(driver_error)?; - let MoePrefillResources { batch, scratch, .. } = &mut *resources; - let batch = batch.as_mut().ok_or(Error::IdentityMismatch)?; - let scratch = scratch.as_ref().ok_or(Error::IdentityMismatch)?; - let mut prefix = batch.begin(tokens, gemm).map_err(driver_error)?; - let program = (|| -> std::result::Result<(), leleka_cuda_driver::Error> { - prefix.pack_mixed(&buffers.mixed, &buffers.mixed_h, &buffers.mixed_bf, buffers.mixed_bf_lo.as_ref())?; - prefix.route(router, &buffers.logits, &buffers.ids, &buffers.weights)?; - prefix.shared_gate(gate_format, weights.buffers[0], scratch, &buffers.sgate)?; - prefix.shared_up(up_format, weights.buffers[1], scratch, &buffers.sup)?; - prefix.swiglu(&buffers.sh_h)?; - prefix.shared_down(down, weights.buffers[2], scratch, &buffers.shared)?; - prefix.shared_scalar(weights.buffers[3], &buffers.sg)?; - if let (Some(input), Some(bo)) = (&combine, buffers.bo.as_ref()) { - prefix.combine(input.dm, input.slot, bo)?; - } - Ok(()) - })(); - // `finish` drains what was admitted and itself returns the latched admission error only when the - // drain showed no numerical refusal, so an earlier non-finite stage outranks a later admission error. - let _ = program; - let completion = prefix.finish().map_err(driver_error)?; - completion.into_route().map_err(|_| Error::NonFinite) - })(); - let route = match operation { - Ok(route) => route, - Err(primary) => { - let _ = buffers.release(); - return Err(primary); - } + admit(current, device_bytes(plan.tokens, profile, plan.with_combine)?)?; + let mixed_bytes = f32_bytes(&plan.host)?; + let buffers = Buffers::new(current, plan.tokens, profile, plan.with_combine)?; + let inputs = MicroInputs { + router, + weights: &weights, + combine: combine.as_ref(), + formats: plan.formats, + tokens: plan.tokens, }; - let mut rows = Vec::new(); - rows.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; - let assembled = (|| -> Result<()> { - if route.ids.len() != tokens * SELECTED || route.weights.len() != tokens * SELECTED { - return Err(Error::InvalidDimension); - } - for (index, identity) in identities.into_iter().enumerate() { - let ids: [i32; SELECTED] = std::array::from_fn(|k| route.ids[index * SELECTED + k]); - let row_weights: [f32; SELECTED] = std::array::from_fn(|k| route.weights[index * SELECTED + k]); - validate_route_row(&ids, &row_weights)?; - rows.push(RouteRow { - binding: binding.identity(), - origin: GrRole::Ffn(layer.get()), - identity, - ids, - weights: row_weights, - _sealed: (), - }); - } - Ok(()) - })(); - if let Err(primary) = assembled { - let _ = buffers.release(); - return Err(primary); - } - let ((shared, sg, bo, route_weights), internal) = buffers.into_outputs(!with_combine); - let products = MoeMicroProducts { rows, shared: Some(shared), sg: Some(sg), bo, route_weights }; - if let Err(error) = internal { - drop(products); - return Err(error); - } - Ok(products) + let (buffers, route) = route_on_device(buffers, resources, gemm, &inputs, &mixed_bytes)?; + assemble_products(binding, layer, buffers, &route, plan) } /// The separate Original `moe_combine` of a window whose `route_shared_micro` ran with `combine = None`. Runs @@ -184,46 +64,14 @@ impl MoePrefillStage { products: &mut MoeMicroProducts<'ctx>, combine: CombineInput<'_, 'ctx>, resources: &mut MoePrefillResources<'ctx>, - gemm: &dyn GdnGemm, + gemm: GemmRef<'_>, ) -> Result<()> { resources.validate_context(current)?; - let tokens = expected.len(); - if tokens == 0 || tokens > MOE_BATCH_MAX_TOKENS { - return Err(Error::IdentityMismatch); - } - let checked = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; - if checked != layer { - return Err(Error::IdentityMismatch); - } - if binding.expert_count() != EXPERTS as u32 || binding.expert_used_count() != SELECTED as u32 { - return Err(Error::InvalidDimension); - } - // The window's own origin: actual binding, FFN role of this layer, exactly the caller's rows. - products.validate_window(&binding.identity(), layer, expected)?; - if products.bo.is_some() || products.route_weights.is_none() { - return Err(Error::IdentityMismatch); - } - if combine.slot.len() != tokens * SELECTED || combine.dm.len() != tokens * SELECTED * MIXED * 4 { - return Err(Error::InvalidDimension); - } + let tokens = check_combine_window(binding, layer, expected, products, &combine)?; let bytes = tokens * MIXED * 4; admit(current, bytes)?; let bo = current.allocate(bytes).map_err(driver_error)?; - let operation = (|| -> Result<()> { - let batch = resources.batch.as_mut().ok_or(Error::IdentityMismatch)?; - let route_weights = products.route_weights.as_ref().ok_or(Error::IdentityMismatch)?; - let shared = products.shared.as_ref().ok_or(Error::IdentityMismatch)?; - let sg = products.sg.as_ref().ok_or(Error::IdentityMismatch)?; - let mut prefix = batch.begin_combine(tokens, gemm).map_err(driver_error)?; - // As in `route_shared_micro`: `finish` alone decides, so an admission error here is reported only when - // the drain showed no numerical refusal. - let _ = prefix.combine_from(route_weights, shared, sg, combine.dm, combine.slot, &bo); - let completion = prefix.finish().map_err(driver_error)?; - if completion.numerical_refusal().is_some() { - return Err(Error::NonFinite); - } - Ok(()) - })(); + let operation = combine_on_device(resources, products, tokens, gemm, &combine, &bo); if let Err(primary) = operation { let _ = bo.release(); return Err(primary); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/route_micro_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/route_micro_fns.rs new file mode 100644 index 00000000..269d36bc --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/route_micro_fns.rs @@ -0,0 +1,285 @@ +//! Validation and device phases of `MoePrefillStage::route_shared_micro` (STRA-338 size: extract-method only). + +#[allow(unused_imports)] +use super::*; +use leleka_cuda_driver::MoeBatchPrefix; + +/// The validated host side of one window: the packed mixed rows, their identities and the shared formats. +pub(super) struct MicroPlan { + pub(super) tokens: usize, + pub(super) host: Vec, + pub(super) identities: Vec, + pub(super) formats: [GdnNativeFormat; 3], + pub(super) with_combine: bool, +} + +/// The device-side operands of the route program. +pub(super) struct MicroInputs<'a, 'ctx> { + pub(super) router: &'a DeviceBuffer<'a>, + pub(super) weights: &'a SharedWeights<'a, 'ctx>, + pub(super) combine: Option<&'a CombineInput<'a, 'ctx>>, + pub(super) formats: [GdnNativeFormat; 3], + pub(super) tokens: usize, +} + +/// Validate everything before the first device allocation. +pub(super) fn validate_micro<'ctx>( + binding: &ModelBinding, + layer: LayerId, + reads: &[&ResidualReady], + router: &DeviceBuffer<'_>, + weights: &SharedWeights<'_, 'ctx>, + combine: Option<&CombineInput<'_, 'ctx>>, +) -> Result { + let tokens = reads.len(); + check_window(binding, layer, tokens)?; + let (host, identities) = gather_reads(binding, layer, reads)?; + let formats = check_shared(weights, layer)?; + if router.len() != EXPERTS * MIXED * 2 { + return Err(Error::InvalidDimension); + } + if let Some(input) = combine + && (input.slot.len() != tokens * SELECTED || input.dm.len() != tokens * SELECTED * MIXED * 4) + { + return Err(Error::InvalidDimension); + } + Ok(MicroPlan { tokens, host, identities, formats, with_combine: combine.is_some() }) +} + +/// The window size, layer and expert counts must be this binding's own. +fn check_window(binding: &ModelBinding, layer: LayerId, tokens: usize) -> Result<()> { + check_window_size(binding, layer, tokens)?; + // The layer's router weights must be this binding's own (as in `route_from_ffn`). + let route_weights = binding.moe_route_weights(layer.get()).map_err(|_| Error::IdentityMismatch)?; + if !route_weights.matches(&binding.identity(), layer.get()) { + return Err(Error::IdentityMismatch); + } + Ok(()) +} + +/// Genuine reads only: origin, layer, and strictly consecutive positions. +fn gather_reads( + binding: &ModelBinding, + layer: LayerId, + reads: &[&ResidualReady], +) -> Result<(Vec, Vec)> { + let tokens = reads.len(); + let mut host = Vec::new(); + host.try_reserve_exact(tokens * MIXED).map_err(|_| Error::InputAllocation)?; + let mut identities: Vec = Vec::new(); + identities.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; + for read in reads { + let identity = read_identity(binding, layer, read, identities.last().copied())?; + host.extend_from_slice(read.mixed()); + identities.push(identity); + } + Ok((host, identities)) +} + +fn read_identity( + binding: &ModelBinding, + layer: LayerId, + read: &ResidualReady, + previous: Option, +) -> Result { + read.validate_origin(&binding.identity(), GrRole::Ffn(layer.get()))?; + let identity = read.identity(); + if identity.layer() != layer { + return Err(Error::IdentityMismatch); + } + if let Some(previous) = previous + && previous.position().get().checked_add(1) != Some(identity.position().get()) + { + return Err(Error::IdentityMismatch); + } + let values = read.mixed(); + if values.len() != MIXED { + return Err(Error::InvalidDimension); + } + if values.iter().any(|v| !v.is_finite()) { + return Err(Error::NonFinite); + } + Ok(identity) +} + +/// The shared expert's real descriptors, sizes and formats. `validate_descriptors` makes all four keys agree; they +/// must also be THIS layer's, before any CUDA write. +fn check_shared(weights: &SharedWeights<'_, '_>, layer: LayerId) -> Result<[GdnNativeFormat; 3]> { + validate_descriptors(weights.keys)?; + if weights.keys.iter().any(|key| key.layer != layer.get()) { + return Err(Error::IdentityMismatch); + } + for (buffer, key) in weights.buffers.iter().zip(weights.keys) { + if buffer.len() != key.bytes { + return Err(Error::IdentityMismatch); + } + } + Ok([gate_up_format(weights.keys[0])?, gate_up_format(weights.keys[1])?, down_format(weights.keys[2])?]) +} + +/// Upload the mixed rows and run the closed route program; `finish` drains what was admitted and itself returns the +/// latched admission error only when the drain showed no numerical refusal, so an earlier non-finite stage outranks a +/// later admission error. +pub(super) fn route_on_device<'ctx>( + mut buffers: Buffers<'ctx>, + resources: &mut MoePrefillResources<'ctx>, + gemm: GemmRef<'_>, + inputs: &MicroInputs<'_, 'ctx>, + mixed_bytes: &[u8], +) -> Result<(Buffers<'ctx>, MoeRouteBatch)> { + match launch_route(&mut buffers, resources, gemm, inputs, mixed_bytes) { + Ok(route) => Ok((buffers, route)), + Err(primary) => { + let _ = buffers.release(); + Err(primary) + } + } +} + +fn launch_route<'ctx>( + buffers: &mut Buffers<'ctx>, + resources: &mut MoePrefillResources<'ctx>, + gemm: GemmRef<'_>, + inputs: &MicroInputs<'_, 'ctx>, + mixed_bytes: &[u8], +) -> Result { + buffers.mixed.copy_from(mixed_bytes).map_err(driver_error)?; + let MoePrefillResources { batch, scratch, .. } = &mut *resources; + let batch = batch.as_mut().ok_or(Error::IdentityMismatch)?; + let scratch = scratch.as_ref().ok_or(Error::IdentityMismatch)?; + let mut prefix = batch.begin(inputs.tokens, gemm).map_err(driver_error)?; + let program = launch_program(&mut prefix, buffers, scratch, inputs); + let _ = program; + let completion = prefix.finish().map_err(driver_error)?; + completion.into_route().map_err(|_| Error::NonFinite) +} + +fn launch_program<'l, 'ctx>( + prefix: &mut MoeBatchPrefix<'l, 'ctx>, + b: &'l Buffers<'ctx>, + scratch: &'l DeviceBuffer<'ctx>, + inputs: &'l MicroInputs<'l, 'ctx>, +) -> std::result::Result<(), leleka_cuda_driver::Error> { + let (weights, [gate_format, up_format, down]) = (inputs.weights, inputs.formats); + prefix.pack_mixed(&b.mixed, &b.mixed_h, &b.mixed_bf, b.mixed_bf_lo.as_ref())?; + prefix.route(inputs.router, &b.logits, &b.ids, &b.weights)?; + prefix.shared_gate(gate_format, weights.buffers[0], scratch, &b.sgate)?; + prefix.shared_up(up_format, weights.buffers[1], scratch, &b.sup)?; + prefix.swiglu(&b.sh_h)?; + prefix.shared_down(down, weights.buffers[2], scratch, &b.shared)?; + prefix.shared_scalar(weights.buffers[3], &b.sg)?; + if let (Some(input), Some(bo)) = (inputs.combine, b.bo.as_ref()) { + prefix.combine(input.dm, input.slot, bo)?; + } + Ok(()) +} + +/// One validated `RouteRow` per window row, in order. +pub(super) fn assemble_rows( + binding: &ModelBinding, + layer: LayerId, + route: &MoeRouteBatch, + identities: Vec, + rows: &mut Vec, +) -> Result<()> { + if route.ids.len() != identities.len() * SELECTED || route.weights.len() != identities.len() * SELECTED { + return Err(Error::InvalidDimension); + } + for (index, identity) in identities.into_iter().enumerate() { + let ids: [i32; SELECTED] = std::array::from_fn(|k| route.ids[index * SELECTED + k]); + let row_weights: [f32; SELECTED] = std::array::from_fn(|k| route.weights[index * SELECTED + k]); + validate_route_row(&ids, &row_weights)?; + rows.push(RouteRow { + binding: binding.identity(), + origin: GrRole::Ffn(layer.get()), + identity, + ids, + weights: row_weights, + _sealed: (), + }); + } + Ok(()) +} + +/// Assemble the validated rows and hand the buffers' outputs to the products; the buffers are released on failure. +pub(super) fn assemble_products<'ctx>( + binding: &ModelBinding, + layer: LayerId, + mut buffers: Buffers<'ctx>, + route: &MoeRouteBatch, + plan: MicroPlan, +) -> Result> { + let mut rows = Vec::new(); + rows.try_reserve_exact(plan.tokens).map_err(|_| Error::InputAllocation)?; + if let Err(primary) = assemble_rows(binding, layer, route, plan.identities, &mut rows) { + let _ = buffers.release(); + return Err(primary); + } + let ((shared, sg, bo, route_weights), internal) = buffers.into_outputs(!plan.with_combine); + let products = MoeMicroProducts { rows, shared: Some(shared), sg: Some(sg), bo, route_weights }; + if let Err(error) = internal { + drop(products); + return Err(error); + } + Ok(products) +} + +/// The combine window: size, layer, expert counts, the products' own origin and the operand shapes. Returns the +/// token count. +pub(super) fn check_combine_window<'ctx>( + binding: &ModelBinding, + layer: LayerId, + expected: &[TokenLayer], + products: &MoeMicroProducts<'ctx>, + combine: &CombineInput<'_, 'ctx>, +) -> Result { + let tokens = expected.len(); + check_window_size(binding, layer, tokens)?; + // The window's own origin: actual binding, FFN role of this layer, exactly the caller's rows. + products.validate_window(&binding.identity(), layer, expected)?; + if products.bo.is_some() || products.route_weights.is_none() { + return Err(Error::IdentityMismatch); + } + if combine.slot.len() != tokens * SELECTED || combine.dm.len() != tokens * SELECTED * MIXED * 4 { + return Err(Error::InvalidDimension); + } + Ok(tokens) +} + +/// The window size, layer and expert counts. +fn check_window_size(binding: &ModelBinding, layer: LayerId, tokens: usize) -> Result<()> { + if tokens == 0 || tokens > MOE_BATCH_MAX_TOKENS { + return Err(Error::IdentityMismatch); + } + let checked = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; + if checked != layer { + return Err(Error::IdentityMismatch); + } + if binding.expert_count() != EXPERTS as u32 || binding.expert_used_count() != SELECTED as u32 { + return Err(Error::InvalidDimension); + } + Ok(()) +} + +/// Run the closed Original-combine program over the window's own drained products. As in `route_shared_micro`, +/// `finish` alone decides, so an admission error here is reported only when the drain showed no numerical refusal. +pub(super) fn combine_on_device<'ctx>( + resources: &mut MoePrefillResources<'ctx>, + products: &MoeMicroProducts<'ctx>, + tokens: usize, + gemm: GemmRef<'_>, + combine: &CombineInput<'_, 'ctx>, + bo: &DeviceBuffer<'ctx>, +) -> Result<()> { + let batch = resources.batch.as_mut().ok_or(Error::IdentityMismatch)?; + let route_weights = products.route_weights.as_ref().ok_or(Error::IdentityMismatch)?; + let shared = products.shared.as_ref().ok_or(Error::IdentityMismatch)?; + let sg = products.sg.as_ref().ok_or(Error::IdentityMismatch)?; + let mut prefix = batch.begin_combine(tokens, gemm).map_err(driver_error)?; + let _ = prefix.combine_from(route_weights, shared, sg, combine.dm, combine.slot, bo); + let completion = prefix.finish().map_err(driver_error)?; + if completion.numerical_refusal().is_some() { + return Err(Error::NonFinite); + } + Ok(()) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs index 3ed90030..e3d830c9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs @@ -3,6 +3,17 @@ #[allow(unused_imports)] use super::*; +const TRIPLET_ROLES: [MoeMatrixRole; 3] = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + +/// The Gate/Up/Down identity of one requested triplet and how much of it is missing from the cache. +struct TripletPlan { + keys: [MoeWeightDescriptor; 3], + formats: [MmqFormat; 3], + charges: [usize; 3], + missing: usize, + extra: usize, +} + impl<'ctx> MoeWeightCache<'ctx> { // Only the explicit integer candidate uses the closed three-weight fill. // Every requested owner stays resident while missing roles are admitted. @@ -15,154 +26,234 @@ impl<'ctx> MoeWeightCache<'ctx> { execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result, ) -> Result { self.validate(binding, self.context)?; - let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + let plan = self.triplet_plan(binding, weights, selection, original_prompt)?; + let next_age = self.triplet_admit(&plan)?; + self.triplet_fill(binding, weights, selection, original_prompt, &plan, next_age)?; + self.triplet_note_hits(&plan); + self.validate(binding, self.context)?; + let [gate, up, down] = self.triplet_owners(&plan.keys)?; + execute(gate, up, down) + } + + fn triplet_fill( + &mut self, + binding: &ModelBinding, + weights: &MoeExpertWeights, + selection: MoeExpertSelection, + original_prompt: bool, + plan: &TripletPlan, + next_age: u64, + ) -> Result<()> { + match plan.missing { + 3 => self.triplet_full_miss(binding, weights, selection, original_prompt, plan, next_age), + 0 => self.triplet_hit(plan, next_age), + _ => self.triplet_partial(binding, weights, selection, plan), + } + } + + fn triplet_owners(&self, keys: &[MoeWeightDescriptor; 3]) -> Result<[&MmqWeights<'ctx>; 3]> { + Ok([self.mmq_owner(&keys[0])?, self.mmq_owner(&keys[1])?, self.mmq_owner(&keys[2])?]) + } + + /// Profile requests, then room and main slots for whatever is missing; returns the age after the triplet. + fn triplet_admit(&mut self, plan: &TripletPlan) -> Result { + if plan.missing == 0 || plan.missing == 3 { + for key in plan.keys { + self.note_profile_request(key, plan.missing == 0); + } + } + let next_age = self.age.checked_add(3).ok_or(Error::Overflow)?; + if plan.missing != 0 { + self.room_protected(plan.extra, &plan.keys)?; + self.reserve_main(plan.missing)?; + } + Ok(next_age) + } + + fn triplet_note_hits(&mut self, plan: &TripletPlan) { + if plan.missing == 0 { + for key in plan.keys { + self.note_permanent_hit(key); + } + } + #[cfg(test)] + self.note_triplet_witness(plan.missing); + } + + fn triplet_plan( + &self, + binding: &ModelBinding, + weights: &MoeExpertWeights, + selection: MoeExpertSelection, + original_prompt: bool, + ) -> Result { + let roles = TRIPLET_ROLES; let keys = [ binding.moe_weight_descriptor(weights, selection, roles[0]).map_err(binding_error)?, binding.moe_weight_descriptor(weights, selection, roles[1]).map_err(binding_error)?, binding.moe_weight_descriptor(weights, selection, roles[2]).map_err(binding_error)?, ]; - let layouts = [ - self.weight_layout(keys[0])?.ok_or(Error::InvalidDimension)?, - self.weight_layout(keys[1])?.ok_or(Error::InvalidDimension)?, - self.weight_layout(keys[2])?.ok_or(Error::InvalidDimension)?, - ]; + let layouts = [self.layout_of(keys[0])?, self.layout_of(keys[1])?, self.layout_of(keys[2])?]; let formats = layouts.map(|(format, _)| format); let charges = layouts.map(|(_, charge)| charge); - let mut missing = 0usize; - let mut extra = 0usize; - for (key, charged) in keys.iter().zip(charges) { - if !self.main.contains_key(key) { - missing += 1; - extra = extra.checked_add(charged).ok_or(Error::Overflow)?; - } else { - let owner = self.mmq_owner(key)?; - if owner.allocated_bytes() != charged { - return Err(Error::IdentityMismatch); - } - } - } - if !(if original_prompt { original_mmq_triplet(&keys)? } else { integer_iq3_triplet(&keys)? }) { + let (missing, extra) = self.triplet_missing(&keys, charges)?; + self.check_triplet(&keys, original_prompt)?; + Ok(TripletPlan { keys, formats, charges, missing, extra }) + } + + fn layout_of(&self, key: MoeWeightDescriptor) -> Result<(MmqFormat, usize)> { + self.weight_layout(key)?.ok_or(Error::InvalidDimension) + } + + fn check_triplet(&self, keys: &[MoeWeightDescriptor; 3], original_prompt: bool) -> Result<()> { + if !(if original_prompt { original_mmq_triplet(keys)? } else { integer_iq3_triplet(keys)? }) { return Err(Error::InvalidDimension); } if keys.iter().any(|key| self.is_pinned(*key) && !self.main.contains_key(key)) { return Err(Error::IdentityMismatch); } - if missing == 0 || missing == 3 { - for key in keys { - self.note_profile_request(key, missing == 0); - } - } - let next_age = self.age.checked_add(3).ok_or(Error::Overflow)?; - if missing != 0 { - self.room_protected(extra, &keys)?; - self.reserve_main(missing)?; - } - if missing == 3 { - let update = - self.prepare_lru_updates(&[(keys[0], self.age + 1), (keys[1], self.age + 2), (keys[2], next_age)])?; - // Read actual bound spans before any upload. The driver owns its - // padded staging until all attempted copies have completed. - let mut raw: [Box<[u8]>; 3] = std::array::from_fn(|_| Box::default()); - let mut read_bytes = 0usize; - for (index, (role, key)) in roles.into_iter().zip(&keys).enumerate() { - let block = binding.moe_expert_block(weights, selection, role, 0, key.rows).map_err(binding_error)?; - if block.bytes().len() != key.bytes { - return Err(Error::InvalidDimension); - } - raw[index] = block.into_bytes(); - read_bytes = read_bytes.checked_add(key.bytes).ok_or(Error::Overflow)?; - } - let main_bytes = self.main_bytes.checked_add(extra).ok_or(Error::Overflow)?; - let context = self.context; - let uploaded = if original_prompt { - context.mmq_original_weight_triplet(formats, [&raw[0], &raw[1], &raw[2]]) - } else { - context.mmq_weight_triplet(formats, [&raw[0], &raw[1], &raw[2]]) - }; - let owners = match uploaded { - Ok(owners) => owners, - Err(error) => { - if context.is_poisoned() { - self.failed.set(true); - } - return Err(driver_error(error)); - } - }; - if owners.iter().zip(&charges).any(|(owner, &charge)| owner.allocated_bytes() != charge) { - for owner in owners.into_iter().rev() { - if owner.close().is_err() { - self.failed.set(true); - } - } + Ok(()) + } + + /// How many of the three owners are absent and the bytes they would add; resident owners must match their charge. + fn triplet_missing(&self, keys: &[MoeWeightDescriptor; 3], charges: [usize; 3]) -> Result<(usize, usize)> { + let (mut missing, mut extra) = (0usize, 0usize); + for (key, charged) in keys.iter().zip(charges) { + if !self.main.contains_key(key) { + missing += 1; + extra = extra.checked_add(charged).ok_or(Error::Overflow)?; + } else if self.mmq_owner(key)?.allocated_bytes() != charged { return Err(Error::IdentityMismatch); } - if let Err(primary) = self.commit_lru_updates(update, 3) { - for owner in owners.into_iter().rev() { - if owner.close().is_err() { - self.failed.set(true); - } - } - return Err(primary); - } - // No fallible allocation/validation follows the first insertion. - // Publish the complete triplet only after driver completion. - for (index, owner) in owners.into_iter().enumerate() { - self.main.insert( - keys[index], - Entry { - weight: EncodedWeight::Dual(formats[index], owner), - charged_bytes: charges[index], - age: self.age + index as u64 + 1, - }, - ); - } - self.main_bytes = main_bytes; - self.age = next_age; - self.counters.misses = self.counters.misses.saturating_add(3); - self.counters.read_bytes = self.counters.read_bytes.saturating_add(read_bytes as u64); - self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(extra as u64); - for (key, charge) in keys.into_iter().zip(charges) { - self.note_permanent_fill(key, key.bytes, charge); - } - } else if missing != 0 { - // Admission is not a reservation against other GPU actors. Every - // later physical-room query protects all requested roles again. - for (role, key) in roles.into_iter().zip(&keys) { - let _ = self.main_entry_protected(*key, &keys, || { - let block = - binding.moe_expert_block(weights, selection, role, 0, key.rows).map_err(binding_error)?; - Ok(block.into_bytes()) - })?; - } + } + Ok((missing, extra)) + } + + fn triplet_ages(&self, plan: &TripletPlan, next_age: u64) -> [(MoeWeightDescriptor, u64); 3] { + [(plan.keys[0], self.age + 1), (plan.keys[1], self.age + 2), (plan.keys[2], next_age)] + } + + fn triplet_full_miss( + &mut self, + binding: &ModelBinding, + weights: &MoeExpertWeights, + selection: MoeExpertSelection, + original_prompt: bool, + plan: &TripletPlan, + next_age: u64, + ) -> Result<()> { + let update = self.prepare_lru_updates(&self.triplet_ages(plan, next_age))?; + // Read actual bound spans before any upload. The driver owns its + // padded staging until all attempted copies have completed. + let (raw, read_bytes) = read_triplet(binding, weights, selection, &plan.keys)?; + let main_bytes = self.main_bytes.checked_add(plan.extra).ok_or(Error::Overflow)?; + let owners = self.upload_triplet(original_prompt, plan, &raw)?; + if owners.iter().zip(&plan.charges).any(|(owner, &charge)| owner.allocated_bytes() != charge) { + self.close_triplet_owners(owners); + return Err(Error::IdentityMismatch); + } + if let Err(primary) = self.commit_lru_updates(update, 3) { + self.close_triplet_owners(owners); + return Err(primary); + } + self.publish_triplet(plan, owners, main_bytes, next_age, read_bytes); + Ok(()) + } + + fn upload_triplet( + &mut self, + original_prompt: bool, + plan: &TripletPlan, + raw: &[Box<[u8]>; 3], + ) -> Result<[MmqWeights<'ctx>; 3]> { + let context = self.context; + let inputs: [&[u8]; 3] = [&raw[0], &raw[1], &raw[2]]; + let uploaded = if original_prompt { + context.mmq_original_weight_triplet(plan.formats, inputs) } else { - // A complete resident hit allocates/uploads nothing, so it needs - // no physical-memory query or new admission reservation. - let update = - self.prepare_lru_updates(&[(keys[0], self.age + 1), (keys[1], self.age + 2), (keys[2], next_age)])?; - self.commit_lru_updates(update, 3)?; - for (index, key) in keys.iter().enumerate() { - let entry = self.main.get_mut(key).ok_or(Error::IdentityMismatch)?; - entry.age = self.age + index as u64 + 1; + context.mmq_weight_triplet(plan.formats, inputs) + }; + uploaded.map_err(|error| { + if context.is_poisoned() { + self.failed.set(true); } - self.age = next_age; - self.counters.hits = self.counters.hits.saturating_add(3); - } - if missing == 0 { - for key in keys { - self.note_permanent_hit(key); + driver_error(error) + }) + } + + fn close_triplet_owners(&mut self, owners: [MmqWeights<'ctx>; 3]) { + for owner in owners.into_iter().rev() { + if owner.close().is_err() { + self.failed.set(true); } } - #[cfg(test)] - { - let (full, mixed, hit) = self.mmq_triplet_witness.get(); - self.mmq_triplet_witness.set(match missing { - 3 => (full.saturating_add(1), mixed, hit), - 0 => (full, mixed, hit.saturating_add(1)), - _ => (full, mixed.saturating_add(1), hit), - }); + } + + /// No fallible allocation/validation follows the first insertion. + /// Publish the complete triplet only after driver completion. + fn publish_triplet( + &mut self, + plan: &TripletPlan, + owners: [MmqWeights<'ctx>; 3], + main_bytes: usize, + next_age: u64, + read_bytes: usize, + ) { + for (index, owner) in owners.into_iter().enumerate() { + let weight = EncodedWeight::Dual(plan.formats[index], owner); + let age = self.age + index as u64 + 1; + self.main.insert(plan.keys[index], Entry { weight, charged_bytes: plan.charges[index], age }); } - self.validate(binding, self.context)?; - execute(self.mmq_owner(&keys[0])?, self.mmq_owner(&keys[1])?, self.mmq_owner(&keys[2])?) + self.main_bytes = main_bytes; + self.age = next_age; + self.counters.misses = self.counters.misses.saturating_add(3); + self.counters.read_bytes = self.counters.read_bytes.saturating_add(read_bytes as u64); + self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(plan.extra as u64); + for (key, charge) in plan.keys.into_iter().zip(plan.charges) { + self.note_permanent_fill(key, key.bytes, charge); + } + } + + /// Admission is not a reservation against other GPU actors. Every later physical-room query protects all + /// requested roles again. + fn triplet_partial( + &mut self, + binding: &ModelBinding, + weights: &MoeExpertWeights, + selection: MoeExpertSelection, + plan: &TripletPlan, + ) -> Result<()> { + for (role, key) in TRIPLET_ROLES.into_iter().zip(&plan.keys) { + let _ = self.main_entry_protected(*key, &plan.keys, || { + let block = binding.moe_expert_block(weights, selection, role, 0, key.rows).map_err(binding_error)?; + Ok(block.into_bytes()) + })?; + } + Ok(()) + } + + /// A complete resident hit allocates/uploads nothing, so it needs no physical-memory query or new admission + /// reservation. + fn triplet_hit(&mut self, plan: &TripletPlan, next_age: u64) -> Result<()> { + let update = self.prepare_lru_updates(&self.triplet_ages(plan, next_age))?; + self.commit_lru_updates(update, 3)?; + for (index, key) in plan.keys.iter().enumerate() { + let entry = self.main.get_mut(key).ok_or(Error::IdentityMismatch)?; + entry.age = self.age + index as u64 + 1; + } + self.age = next_age; + self.counters.hits = self.counters.hits.saturating_add(3); + Ok(()) + } + + #[cfg(test)] + fn note_triplet_witness(&self, missing: usize) { + let (full, mixed, hit) = self.mmq_triplet_witness.get(); + self.mmq_triplet_witness.set(match missing { + 3 => (full.saturating_add(1), mixed, hit), + 0 => (full, mixed, hit.saturating_add(1)), + _ => (full, mixed.saturating_add(1), hit), + }); } #[cfg(test)] @@ -198,3 +289,23 @@ impl<'ctx> MoeWeightCache<'ctx> { } } } + +/// The raw encoded bytes of the three requested matrices and their total size. +fn read_triplet( + binding: &ModelBinding, + weights: &MoeExpertWeights, + selection: MoeExpertSelection, + keys: &[MoeWeightDescriptor; 3], +) -> Result<([Box<[u8]>; 3], usize)> { + let mut raw: [Box<[u8]>; 3] = std::array::from_fn(|_| Box::default()); + let mut read_bytes = 0usize; + for (index, (role, key)) in TRIPLET_ROLES.into_iter().zip(keys).enumerate() { + let block = binding.moe_expert_block(weights, selection, role, 0, key.rows).map_err(binding_error)?; + if block.bytes().len() != key.bytes { + return Err(Error::InvalidDimension); + } + raw[index] = block.into_bytes(); + read_bytes = read_bytes.checked_add(key.bytes).ok_or(Error::Overflow)?; + } + Ok((raw, read_bytes)) +} diff --git a/limits-baseline.json b/limits-baseline.json index 944cff96..d3305c74 100644 --- a/limits-baseline.json +++ b/limits-baseline.json @@ -9,7 +9,7 @@ "census": { "prod": { "leleka-backend-api": { - "width": 16, + "width": 18, "complexity": 2, "fn_lines": 3 }, @@ -28,10 +28,10 @@ "width": 6 }, "leleka-cuda-driver": { - "fn_lines": 639, - "width": 819, - "complexity": 623, - "nesting": 25 + "fn_lines": 586, + "width": 815, + "complexity": 574, + "nesting": 23 }, "leleka-deploy": { "fn_lines": 101, @@ -44,10 +44,10 @@ "complexity": 8 }, "leleka-engine-qwen35-cuda": { - "fn_lines": 541, - "width": 570, - "complexity": 550, - "nesting": 14 + "fn_lines": 517, + "width": 569, + "complexity": 526, + "nesting": 10 }, "leleka-experimental-ref": { "fn_lines": 15,