From f021ce73cb614790d03ee4c2dea640c9e62dd6ff Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 13:48:40 +0100 Subject: [PATCH] STRA-338 size: cuda-driver mmq_original_ring Ring::new split into construction phases in ring_init (213 -> 19 lines) --- .../src/mmq_original_ring/impl_ring.rs | 3 + .../impl_ring/impl_ring_2.rs | 198 +---------- .../mmq_original_ring/impl_ring/ring_init.rs | 312 ++++++++++++++++++ 3 files changed, 320 insertions(+), 193 deletions(-) create mode 100644 crates/cuda-driver/src/mmq_original_ring/impl_ring/ring_init.rs diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring.rs index db1f0144..462576d7 100644 --- a/crates/cuda-driver/src/mmq_original_ring/impl_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring.rs @@ -9,3 +9,6 @@ mod impl_ring_2; mod impl_ring_2_2; #[path = "impl_ring/impl_ring_3.rs"] mod impl_ring_3; +#[path = "impl_ring/ring_init.rs"] +mod ring_init; +use ring_init::RingPlan; diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs index c40b1dff..397fdb62 100644 --- a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs @@ -14,205 +14,17 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { spans: &'read [[ResidentExpertBankSpan; 3]], groups: usize, ) -> Result { - if !read.context_matches(context) - || !bank.cache_context_matches(context) - || layer >= 48 - || spans.is_empty() - || spans.len() > 512 - || groups != spans.len().div_ceil(16) - || formats[0] != formats[1] - || !FORMATS[..5].contains(&formats[0]) - || !FORMATS[5..].contains(&formats[2]) - { - return Err(Error::InvalidProjectionShape); - } - let gu = formats[0].layout(1)?.raw_weight; - let down = formats[2].layout(1)?.raw_weight; - let blob = gu.checked_mul(2).and_then(|n| n.checked_add(down)).ok_or(Error::InvalidSize)?; + Self::validate_new(context, read, &bank, (layer, groups, spans.len()), &formats)?; + let (gu, down, blob) = Self::blob_geometry(&formats)?; let admitted: &dyn RingArena = read; let count = admitted.stage_slots()?; schedule.validate_context(context)?; if schedule.ring_slots() != count { return Err(Error::InvalidProjectionShape); } - let mut owner = Self { - context, - read, - bank: Some(bank), - schedule, - slots: Vec::new(), - sources: Vec::new(), - commands: Vec::new(), - status: None, - flags: Vec::new(), - stage_next: 0, - staging: false, - streamed: false, - layer: layer as u8, - stage_done: 0, - submitted: false, - drained: false, - closed: false, - }; - let result = (|| { - owner.slots.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; - owner.sources.try_reserve_exact(spans.len()).map_err(|_| Error::HostAllocation)?; - owner.commands.try_reserve_exact(COMMAND_CAP).map_err(|_| Error::HostAllocation)?; - owner.flags.try_reserve_exact(groups * 16).map_err(|_| Error::HostAllocation)?; - owner.flags.resize(groups * 16, 0); - // Includes actual fixed ABI storage conservatively (<=512B each), - // plus actual vector capacities; no second unbounded launch list. - if owner - .metadata_bytes()? - .checked_add(owner.schedule.metadata_bytes()?) - .and_then(|n| n.checked_add(owner.schedule.host_metadata_outside)) - .is_none_or(|n| n > 16 * 1024 * 1024) - { - return Err(Error::BudgetExceeded); - } - for index in 0..count { - let (h, n) = admitted.stage_span(index)?; - if n < blob { - return Err(Error::InvalidSize); - } - h.validate_projection_extent(n, 256)?; - for slot in &owner.slots { - if h.overlaps(n, slot.span, slot.bytes) { - return Err(Error::OutputAliasesInput); - } - } - for role in 0..TMP { - let (a, n) = GroupArena::span(read, role)?; - if h.overlaps(blob, a, n) { - return Err(Error::OutputAliasesInput); - } - } - owner.slots.push(Slot { span: h, bytes: n, live: false, gathered: false }); - } - let bank = owner.bank.as_ref().ok_or(Error::ContextPoisoned)?; - for (i, spans) in spans.iter().enumerate() { - if !bank.eligible(spans) - || !matches!(spans[0].role(),TensorRole::Layer{layer:l,..} if usize::from(l)==layer) - || i > 0 && spans[0].expert() <= owner.sources[i - 1].spans[0].expert() - { - return Err(Error::InvalidProjectionShape); - } - for (role, span) in spans.iter().enumerate() { - let actual = bank.cache_source(span)?; - if span.raw_kind() != kind(formats[role]) || actual.len() != if role < 2 { gu } else { down } { - return Err(Error::InvalidProjectionShape); - } - } - let resident = admitted - .cache_span(layer, spans[0].expert() as usize)? - .map(|(h, n)| { - if n < blob { - return Err(Error::InvalidSize); - } - Ok([ - h.checked_subspan(n, 0, gu)?, - h.checked_subspan(n, gu, gu)?, - h.checked_subspan(n, gu * 2, down)?, - ]) - }) - .transpose()?; - owner.sources.push(Source { spans, resident, slot: None, job: None, entry: None, dest: None }); - } - // With an active chunk stream for this layer, every non-resident expert is the stream's entry. - if let Some(stream) = owner.schedule.stream.as_ref() { - if stream.next_layer_is(layer as u8) { - for source in &mut owner.sources { - if source.resident.is_some() { - continue; - } - let entry = - stream.entry(layer as u8, source.spans[0].expert()).ok_or(Error::InvalidProjectionShape)?; - // the stream copies exactly the bytes this span names - if !stream.entry_matches( - entry, - [ - bank.cache_source(&source.spans[0])?, - bank.cache_source(&source.spans[1])?, - bank.cache_source(&source.spans[2])?, - ], - ) { - return Err(Error::InvalidProjectionShape); - } - source.entry = Some(entry); - } - owner.streamed = true; - } else { - return Err(Error::InvalidProjectionShape); - } - } - // Experts not page-locked (a pageable bank) are copied by the host stager's helpers into page-locked - // buffers, in launch order, ahead of their DMAs. - let mut jobs = Vec::new(); - for source in &mut owner.sources { - if source.resident.is_none() && source.entry.is_none() && bank.host_staged(source.spans) { - let mut pieces = [(0usize, 0usize, 0u32); 3]; - for (role, span) in source.spans.iter().enumerate() { - let bytes = bank.cache_source(span)?; - pieces[role] = (bytes.as_ptr() as usize, bytes.len(), span.raw_kind()); - } - source.job = Some(jobs.len()); - jobs.push(Job { pieces, priority: 0 }); - } - } - if !jobs.is_empty() { - let priority = host_stage::layer_priority(layer, jobs.len().saturating_mul(blob)); - for job in &mut jobs { - job.priority = priority; - } - } - let charge = groups * 16; - let required = charge.checked_add(128 * 1024 * 1024).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); - } - owner.status = match owner.schedule.status_pool.take() { - Some((bytes, buffer)) if bytes >= charge => Some(buffer), - Some((_, other)) => { - other.release()?; - Some(context.allocate(charge.max(512))?) - } - None => Some(context.allocate(charge.max(512))?), - }; - // The old input quantization/metadata upload used default stream. - // Admit that dependency once before starting nonblocking producers. - context.synchronize()?; - if !jobs.is_empty() { - let pageable = owner.bank.as_ref().ok_or(Error::ContextPoisoned)?.pageable(); - let schedule = &mut *owner.schedule; - if schedule.host.as_ref().is_some_and(|h| h.buffer_bytes() < blob) { - // a larger blob than the buffers: every earlier DMA from them was drained with its layer - let mut old = schedule.host.take().ok_or(Error::ContextPoisoned)?; - old.close()?; - for event in schedule.host_events.drain(..) { - event.close()?; - } - } - if schedule.host.is_none() { - let guard = context.enter()?; - let created = HostStage::new(blob, pageable); - let pop = guard.finish(); - let host = match (created, pop) { - (Ok(host), Ok(())) => host, - (Err(e), _) | (Ok(_), Err(e)) => return Err(e), - }; - for _ in 0..host.ring() { - schedule.host_events.push(context.original_gpu_event(OriginalEventKind::Completion)?); - } - schedule.host = Some(host); - } - schedule.host.as_mut().ok_or(Error::ContextPoisoned)?.start(jobs)?; - owner.staging = true; - } - Ok(()) - })(); - if let Err(primary) = result { + let mut owner = Self::empty(context, read, bank, schedule, layer); + let plan = RingPlan { layer, groups, formats, gu, down, blob, count }; + if let Err(primary) = owner.init(spans, &plan) { return combine(Err(primary), owner.close_inner()); } Ok(owner) diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring/ring_init.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring/ring_init.rs new file mode 100644 index 00000000..a0fcc5ad --- /dev/null +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring/ring_init.rs @@ -0,0 +1,312 @@ +//! Construction phases of `Ring::new`, split out by STRA-338 (size). Every phase keeps the original statement +//! order and error handling; `Ring::init` runs them in the order the former closure ran them. + +#[allow(unused_imports)] +use super::*; + +/// Layer-wide numbers every construction phase needs. +pub(super) struct RingPlan { + pub(super) layer: usize, + pub(super) groups: usize, + pub(super) formats: [MmqFormat; 3], + /// raw bytes of one gate or up matrix + pub(super) gu: usize, + /// raw bytes of one down matrix + pub(super) down: usize, + /// bytes of one expert blob (gate + up + down) + pub(super) blob: usize, + /// number of stage slots of the arena + pub(super) count: usize, +} + +impl<'read, 'ctx> Ring<'read, 'ctx> { + /// Rejects a read, bank, layer, span list or format set the literal ring cannot serve. + pub(super) fn validate_new( + context: &'ctx Context<'ctx>, + read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, + bank: &crate::MappedExpertBank<'ctx>, + (layer, groups, nspans): (usize, usize, usize), + formats: &[MmqFormat; 3], + ) -> Result<()> { + if !read.context_matches(context) + || !bank.cache_context_matches(context) + || layer >= 48 + || nspans == 0 + || nspans > 512 + || groups != nspans.div_ceil(16) + || formats[0] != formats[1] + || !FORMATS[..5].contains(&formats[0]) + || !FORMATS[5..].contains(&formats[2]) + { + return Err(Error::InvalidProjectionShape); + } + Ok(()) + } + + /// `(gate/up bytes, down bytes, blob bytes)` of one expert. + pub(super) fn blob_geometry(formats: &[MmqFormat; 3]) -> Result<(usize, usize, usize)> { + let gu = formats[0].layout(1)?.raw_weight; + let down = formats[2].layout(1)?.raw_weight; + let blob = gu.checked_mul(2).and_then(|n| n.checked_add(down)).ok_or(Error::InvalidSize)?; + Ok((gu, down, blob)) + } + + /// An owner with no slots, sources or commands yet. + pub(super) fn empty( + context: &'ctx Context<'ctx>, + read: &'read dyn RingArena, + bank: Rc>, + schedule: &'read mut OriginalMmqCopySchedule<'ctx>, + layer: usize, + ) -> Self { + Self { + context, + read, + bank: Some(bank), + schedule, + slots: Vec::new(), + sources: Vec::new(), + commands: Vec::new(), + status: None, + flags: Vec::new(), + stage_next: 0, + staging: false, + streamed: false, + layer: layer as u8, + stage_done: 0, + submitted: false, + drained: false, + closed: false, + } + } + + /// Everything the former construction closure did after the owner existed; on error the caller closes the owner. + pub(super) fn init(&mut self, spans: &'read [[ResidentExpertBankSpan; 3]], plan: &RingPlan) -> Result<()> { + self.reserve_buffers(spans.len(), plan)?; + self.check_metadata_budget()?; + self.admit_slots(plan)?; + self.admit_sources(spans, plan)?; + self.attach_stream(plan)?; + let jobs = self.plan_host_jobs(plan)?; + self.admit_status(plan)?; + // The old input quantization/metadata upload used default stream. + // Admit that dependency once before starting nonblocking producers. + self.context.synchronize()?; + if !jobs.is_empty() { + self.start_host_stage(jobs, plan)?; + } + Ok(()) + } + + fn reserve_buffers(&mut self, nspans: usize, plan: &RingPlan) -> Result<()> { + self.slots.try_reserve_exact(plan.count).map_err(|_| Error::HostAllocation)?; + self.sources.try_reserve_exact(nspans).map_err(|_| Error::HostAllocation)?; + self.commands.try_reserve_exact(COMMAND_CAP).map_err(|_| Error::HostAllocation)?; + self.flags.try_reserve_exact(plan.groups * 16).map_err(|_| Error::HostAllocation)?; + self.flags.resize(plan.groups * 16, 0); + Ok(()) + } + + fn check_metadata_budget(&self) -> Result<()> { + // Includes actual fixed ABI storage conservatively (<=512B each), + // plus actual vector capacities; no second unbounded launch list. + if self + .metadata_bytes()? + .checked_add(self.schedule.metadata_bytes()?) + .and_then(|n| n.checked_add(self.schedule.host_metadata_outside)) + .is_none_or(|n| n > 16 * 1024 * 1024) + { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + + /// Every stage slot must hold a blob, be GPU-addressable, and overlap neither another slot nor a temporary role. + fn admit_slots(&mut self, plan: &RingPlan) -> Result<()> { + let read = self.read; + for index in 0..plan.count { + let (h, n) = read.stage_span(index)?; + if n < plan.blob { + return Err(Error::InvalidSize); + } + h.validate_projection_extent(n, 256)?; + for slot in &self.slots { + if h.overlaps(n, slot.span, slot.bytes) { + return Err(Error::OutputAliasesInput); + } + } + for role in 0..TMP { + let (a, n) = GroupArena::span(read, role)?; + if h.overlaps(plan.blob, a, n) { + return Err(Error::OutputAliasesInput); + } + } + self.slots.push(Slot { span: h, bytes: n, live: false, gathered: false }); + } + Ok(()) + } + + fn admit_sources(&mut self, spans: &'read [[ResidentExpertBankSpan; 3]], plan: &RingPlan) -> Result<()> { + let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?; + for (i, spans) in spans.iter().enumerate() { + let ordered = i == 0 || spans[0].expert() > self.sources[i - 1].spans[0].expert(); + Self::check_source_spans(bank, spans, ordered, plan)?; + let resident = self.resident_blob(spans[0].expert() as usize, plan)?; + self.sources.push(Source { spans, resident, slot: None, job: None, entry: None, dest: None }); + } + Ok(()) + } + + fn check_source_spans( + bank: &crate::MappedExpertBank<'ctx>, + spans: &[ResidentExpertBankSpan; 3], + ordered: bool, + plan: &RingPlan, + ) -> Result<()> { + if !bank.eligible(spans) + || !matches!(spans[0].role(),TensorRole::Layer{layer:l,..} if usize::from(l)==plan.layer) + || !ordered + { + return Err(Error::InvalidProjectionShape); + } + for (role, span) in spans.iter().enumerate() { + let actual = bank.cache_source(span)?; + if span.raw_kind() != kind(plan.formats[role]) || actual.len() != if role < 2 { plan.gu } else { plan.down } + { + return Err(Error::InvalidProjectionShape); + } + } + Ok(()) + } + + /// The gate, up and down spans of an expert that already sits in the arena cache. + fn resident_blob(&self, expert: usize, plan: &RingPlan) -> Result> { + self.read + .cache_span(plan.layer, expert)? + .map(|(h, n)| { + if n < plan.blob { + return Err(Error::InvalidSize); + } + Ok([ + h.checked_subspan(n, 0, plan.gu)?, + h.checked_subspan(n, plan.gu, plan.gu)?, + h.checked_subspan(n, plan.gu * 2, plan.down)?, + ]) + }) + .transpose() + } + + /// With an active chunk stream for this layer, every non-resident expert is the stream's entry. + fn attach_stream(&mut self, plan: &RingPlan) -> Result<()> { + let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?; + if let Some(stream) = self.schedule.stream.as_ref() { + if !stream.next_layer_is(plan.layer as u8) { + return Err(Error::InvalidProjectionShape); + } + for source in &mut self.sources { + if source.resident.is_some() { + continue; + } + let entry = + stream.entry(plan.layer as u8, source.spans[0].expert()).ok_or(Error::InvalidProjectionShape)?; + // the stream copies exactly the bytes this span names + let sources = [ + bank.cache_source(&source.spans[0])?, + bank.cache_source(&source.spans[1])?, + bank.cache_source(&source.spans[2])?, + ]; + if !stream.entry_matches(entry, sources) { + return Err(Error::InvalidProjectionShape); + } + source.entry = Some(entry); + } + self.streamed = true; + } + Ok(()) + } + + /// Experts not page-locked (a pageable bank) are copied by the host stager's helpers into page-locked + /// buffers, in launch order, ahead of their DMAs. + fn plan_host_jobs(&mut self, plan: &RingPlan) -> Result> { + let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?; + let mut jobs = Vec::new(); + for source in &mut self.sources { + if source.resident.is_none() && source.entry.is_none() && bank.host_staged(source.spans) { + let mut pieces = [(0usize, 0usize, 0u32); 3]; + for (role, span) in source.spans.iter().enumerate() { + let bytes = bank.cache_source(span)?; + pieces[role] = (bytes.as_ptr() as usize, bytes.len(), span.raw_kind()); + } + source.job = Some(jobs.len()); + jobs.push(Job { pieces, priority: 0 }); + } + } + if !jobs.is_empty() { + let priority = host_stage::layer_priority(plan.layer, jobs.len().saturating_mul(plan.blob)); + for job in &mut jobs { + job.priority = priority; + } + } + Ok(jobs) + } + + /// Checks the device budget for the status words and takes (or allocates) their buffer. + fn admit_status(&mut self, plan: &RingPlan) -> Result<()> { + let context = self.context; + let charge = plan.groups * 16; + let required = charge.checked_add(128 * 1024 * 1024).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); + } + self.status = match self.schedule.status_pool.take() { + Some((bytes, buffer)) if bytes >= charge => Some(buffer), + Some((_, other)) => { + other.release()?; + Some(context.allocate(charge.max(512))?) + } + None => Some(context.allocate(charge.max(512))?), + }; + Ok(()) + } + + fn start_host_stage(&mut self, jobs: Vec, plan: &RingPlan) -> Result<()> { + let pageable = self.bank.as_ref().ok_or(Error::ContextPoisoned)?.pageable(); + Self::ensure_host_stage(self.context, &mut *self.schedule, plan.blob, pageable)?; + self.schedule.host.as_mut().ok_or(Error::ContextPoisoned)?.start(jobs)?; + self.staging = true; + Ok(()) + } + + /// Replaces a host stage whose buffers are smaller than `blob` and creates one when none exists. + fn ensure_host_stage( + context: &'ctx Context<'ctx>, + schedule: &mut OriginalMmqCopySchedule<'ctx>, + blob: usize, + pageable: bool, + ) -> Result<()> { + if schedule.host.as_ref().is_some_and(|h| h.buffer_bytes() < blob) { + // a larger blob than the buffers: every earlier DMA from them was drained with its layer + let mut old = schedule.host.take().ok_or(Error::ContextPoisoned)?; + old.close()?; + for event in schedule.host_events.drain(..) { + event.close()?; + } + } + if schedule.host.is_none() { + let guard = context.enter()?; + let created = HostStage::new(blob, pageable); + let pop = guard.finish(); + let host = match (created, pop) { + (Ok(host), Ok(())) => host, + (Err(e), _) | (Ok(_), Err(e)) => return Err(e), + }; + for _ in 0..host.ring() { + schedule.host_events.push(context.original_gpu_event(OriginalEventKind::Completion)?); + } + schedule.host = Some(host); + } + Ok(()) + } +}