Files
leleka/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs
T

223 lines
9.8 KiB
Rust

//! Original methods FIRST; synthetic finite inputs are not a model certificate.
use super::*;
use crate::Driver;
type Products = [Vec<u8>; 4];
fn check(ok: bool) -> Result<()> {
if ok { Ok(()) } else { Err(Error::InvalidDriverValue("GR batch workspace proof")) }
}
fn bytes(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
fn inputs(tokens: usize, pattern: usize) -> [Vec<f32>; 3] {
let streams = (0..10240 * tokens)
.map(|i| match pattern {
0 => (i as i32 % 83 - 41) as f32 * 0.03125,
1 => (i as i32 % 107 - 53) as f32 * -0.0625,
_ => {
if i % 2 == 0 {
-0.0
} else {
0.0
}
}
})
.collect();
let blocks = (0..2560 * tokens)
.map(|i| match pattern {
0 => (i as i32 % 31 - 15) as f32 * 0.015625,
1 => (i as i32 % 53 - 26) as f32 * -0.125,
_ => {
if i % 2 == 0 {
0.0
} else {
-0.0
}
}
})
.collect();
let injects = (0..4 * tokens)
.map(|i| match pattern {
0 => (i % 7) as f32 * 0.25,
1 => (i as i32 % 13 - 6) as f32 * -0.0625,
_ => {
if i % 2 == 0 {
-0.0
} else {
0.0
}
}
})
.collect();
[streams, blocks, injects]
}
// All actual old owners are explicitly closed even on a comparison refusal.
fn original(context: &Context<'_>, shape: GrBatchInjectShape, source: &[Vec<f32>; 3]) -> Result<Products> {
let mut buffers: [Option<DeviceBuffer<'_>>; 4] = std::array::from_fn(|_| None);
let result = (|| {
for (i, size) in ROW_BYTES.into_iter().enumerate() {
buffers[i] = Some(context.allocate(size * shape.tokens())?);
}
for (buffer, source) in buffers.iter_mut().zip(source).take(3) {
buffer.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&bytes(source))?;
}
let (sources, output) = buffers.split_at_mut(3);
context.gr_batch_inject_residual_f32(
shape.tokens(),
sources[0].as_ref().ok_or(Error::ContextPoisoned)?,
sources[1].as_ref().ok_or(Error::ContextPoisoned)?,
sources[2].as_ref().ok_or(Error::ContextPoisoned)?,
output[0].as_mut().ok_or(Error::ContextPoisoned)?,
)?;
let mut products: Products = std::array::from_fn(|_| Vec::new());
for (i, buffer) in buffers.iter().enumerate() {
products[i] =
buffer.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(ROW_BYTES[i] * shape.tokens())?;
}
Ok(products)
})();
let mut cleanup = Ok(());
for buffer in buffers.into_iter().flatten() {
cleanup = combine(cleanup, buffer.release());
}
combine(result, cleanup)
}
fn products(workspace: &GrBatchInjectWorkspace<'_>, shape: GrBatchInjectShape) -> Result<Products> {
let mut result = std::array::from_fn(|_| Vec::new());
for (i, buffer) in workspace.buffers[shape.bank()].iter().enumerate() {
result[i] = buffer.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(ROW_BYTES[i] * shape.tokens())?;
}
Ok(result)
}
fn original_first(
context: &Context<'_>,
workspace: &mut GrBatchInjectWorkspace<'_>,
shape: GrBatchInjectShape,
source: &[Vec<f32>; 3],
) -> Result<usize> {
let expected = original(context, shape, source)?;
let charged = context.allocated_bytes();
let actual = workspace.inject(context, shape, &source[0], &source[1], &source[2])?;
check(context.allocated_bytes() == charged && !workspace.is_failed())?;
let observed = products(workspace, shape)?;
for i in 0..4 {
check(observed[i] == expected[i])?;
}
for i in 0..3 {
check(observed[i] == bytes(&source[i]))?;
}
check(bytes(&actual) == expected[3])?;
Ok(expected.iter().map(|p| p.len() / 4).sum())
}
fn refuses_without_change(
context: &Context<'_>,
workspace: &mut GrBatchInjectWorkspace<'_>,
shape: GrBatchInjectShape,
source: &[Vec<f32>; 3],
expected: Error,
) -> Result<()> {
let previous = products(workspace, shape)?;
let charged = context.allocated_bytes();
let refusal = workspace.inject(context, shape, &source[0], &source[1], &source[2]);
check(refusal.err() == Some(expected))?;
check(products(workspace, shape)? == previous && context.allocated_bytes() == charged && !workspace.is_failed())
}
#[test]
#[ignore]
fn original_first_t1_t2_t3_gr_batch_injection_overwrite_refusal_and_cleanup() {
assert_eq!(std::env::var("LELEKA_STRA172_RUN_GR_BATCH_INJECT_WORKSPACE").as_deref(), Ok("yes"));
let driver = Driver::load().expect("real CUDA driver required");
let device = driver.device(0).expect("real GPU required");
let context = device.create_context(512 * 1024 * 1024).expect("owned Context");
let foreign = device.create_context(512 * 1024 * 1024).expect("foreign Context");
let budget = device.create_context(GR_BATCH_INJECT_WORKSPACE_BYTES + RESERVE - 1).expect("budget Context");
let result = (|| -> Result<(usize, usize)> {
// Scope the borrowed Result/owner before the budget Context is moved.
let refused = match budget.gr_batch_inject_workspace() {
Ok(owner) => combine(Err(Error::InvalidDriverValue("missing eager budget refusal")), owner.close()),
Err(error) => check(error == Error::BudgetExceeded),
};
refused?;
check(budget.allocated_bytes() == 0)?;
let mut workspace = context.gr_batch_inject_workspace()?;
let operation = (|| -> Result<(usize, usize)> {
check(workspace.allocated_bytes() == GR_BATCH_INJECT_WORKSPACE_BYTES)?;
let mut words = 0;
let mut guards = 1;
for shape in [GrBatchInjectShape::T1, GrBatchInjectShape::T2, GrBatchInjectShape::T3] {
for pattern in [0, 1, 2, 0] {
words += original_first(&context, &mut workspace, shape, &inputs(shape.tokens(), pattern))?;
}
// All three roles and both short/long lengths refuse before writes.
for role in 0..3 {
let mut wrong = inputs(shape.tokens(), 1);
wrong[role].pop();
refuses_without_change(&context, &mut workspace, shape, &wrong, Error::InvalidQwenShape)?;
guards += 1;
wrong[role].push(0.);
wrong[role].push(0.);
refuses_without_change(&context, &mut workspace, shape, &wrong, Error::InvalidQwenShape)?;
guards += 1;
for invalid in [f32::NAN, f32::INFINITY] {
let mut late = inputs(shape.tokens(), 1);
*late[role].last_mut().ok_or(Error::InvalidQwenShape)? = invalid;
refuses_without_change(
&context,
&mut workspace,
shape,
&late,
Error::InvalidDriverValue("GR batch injection finite input"),
)?;
guards += 1;
words += original_first(&context, &mut workspace, shape, &inputs(shape.tokens(), 0))?;
}
}
let previous = products(&workspace, shape)?;
let source = inputs(shape.tokens(), 0);
check(
workspace.inject(&foreign, shape, &source[0], &source[1], &source[2]).err()
== Some(Error::ContextMismatch),
)?;
check(products(&workspace, shape)? == previous && !workspace.is_failed())?;
guards += 1;
// Completed numeric overflow is raw output, not transport poison.
let overflow = [
vec![f32::MAX; shape.tokens() * 10240],
vec![f32::MAX; shape.tokens() * 2560],
vec![f32::MAX; shape.tokens() * 4],
];
words += original_first(&context, &mut workspace, shape, &overflow)?;
check(
products(&workspace, shape)?[3]
.as_chunks::<4>()
.0
.iter()
.any(|b| !f32::from_le_bytes(*b).is_finite()),
)?;
words += original_first(&context, &mut workspace, shape, &inputs(shape.tokens(), 1))?;
}
// Switching one bank cannot overwrite a completed other whole bank.
let t1 = products(&workspace, GrBatchInjectShape::T1)?;
let t2 = products(&workspace, GrBatchInjectShape::T2)?;
words += original_first(&context, &mut workspace, GrBatchInjectShape::T3, &inputs(3, 2))?;
check(
products(&workspace, GrBatchInjectShape::T1)? == t1
&& products(&workspace, GrBatchInjectShape::T2)? == t2,
)?;
guards += 1;
Ok((words, guards))
})();
combine(operation, workspace.close())
})();
let allocated = [context.allocated_bytes(), foreign.allocated_bytes(), budget.allocated_bytes()];
// Every actual Context is closed before result/numerical assertions.
let result = combine(combine(combine(result, context.close()), foreign.close()), budget.close());
let (words, guards) = result.expect("original-first workspace proof and exhaustive teardown");
assert_eq!(allocated, [0; 3]);
println!(
"GR_BATCH_INJECT_WORKSPACE PASS exact_words={words} guards={guards} allocated0=true original_first=true raw_overflow=true"
);
}