STRA-338 size: engine GrStage::inject_batch: operands/queued/device phases (145 -> <=30)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 16:37:24 +01:00
parent f24dab2d49
commit f244afd2ac
3 changed files with 236 additions and 139 deletions
@@ -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;
@@ -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)
}
@@ -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<f32>,
pub(super) blocks: Vec<f32>,
pub(super) injects: Vec<f32>,
}
/// Genuine rows only: one origin and layer, strictly consecutive positions, finite values.
pub(super) fn gather_batch(binding: &ModelBinding, rows: &[GrBatchRow]) -> Result<BatchOperands> {
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<GrBatchRow>, values: &[f32]) -> Result<Vec<InjectedResidual>> {
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<bool>,
operands: &BatchOperands,
tokens: usize,
) -> Result<Option<Box<[f32]>>> {
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<GrBatchRow>,
values: Box<[f32]>,
) -> Result<Vec<InjectedResidual>> {
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<bool>,
rows: Vec<GrBatchRow>,
operands: &BatchOperands,
) -> Result<Vec<InjectedResidual>> {
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<DeviceBuffer<'c>>; 4];
fn inject_on_device<'c>(
binding: &ModelBinding,
context: &'c Context<'c>,
cache: &DenseWeightCache<'_>,
rows: Vec<GrBatchRow>,
operands: &BatchOperands,
owners: &mut Owners<'_, 'c>,
) -> Result<Vec<InjectedResidual>> {
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)
}