Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
268 lines
9.4 KiB
Rust
268 lines
9.4 KiB
Rust
//! First real chunk primitive: one launch over independent GR token columns.
|
|
//! Numerical experiment only; no production asset admission or session commit.
|
|
use super::*;
|
|
fn batch_layout(operation: Operation, tokens: usize) -> Result<qwen_ffi::Layout> {
|
|
if !(1..=64).contains(&tokens)
|
|
|| !matches!(
|
|
operation,
|
|
Operation::Norm
|
|
| Operation::LayerGate
|
|
| Operation::FinalGate
|
|
| Operation::InjectResidual
|
|
)
|
|
{
|
|
return Err(Error::InvalidQwenShape);
|
|
}
|
|
let mut layout = operation.layout();
|
|
for i in 0..layout.count {
|
|
if operation == Operation::Norm && i == 1 {
|
|
continue;
|
|
}
|
|
layout.bytes[i] = layout.bytes[i]
|
|
.checked_mul(tokens)
|
|
.ok_or(Error::InvalidQwenShape)?;
|
|
}
|
|
if operation != Operation::Norm {
|
|
layout.columns = layout
|
|
.columns
|
|
.checked_mul(tokens as u32)
|
|
.ok_or(Error::InvalidQwenShape)?;
|
|
}
|
|
layout.grid_y = tokens as u32;
|
|
Ok(layout)
|
|
}
|
|
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
|
|
mod installed {
|
|
use super::*;
|
|
fn slot(operation: Operation) -> Result<usize> {
|
|
match operation {
|
|
Operation::LayerGate => Ok(0),
|
|
Operation::FinalGate => Ok(1),
|
|
Operation::InjectResidual => Ok(2),
|
|
Operation::Norm => Ok(3),
|
|
_ => Err(Error::InvalidQwenShape),
|
|
}
|
|
}
|
|
pub struct GrBatchPreview<'ctx> {
|
|
context: &'ctx Context<'ctx>,
|
|
module: Option<ffi::ModuleHandle>,
|
|
functions: [ffi::FunctionHandle; 4],
|
|
launch_attempts: std::cell::Cell<usize>,
|
|
}
|
|
impl<'ctx> GrBatchPreview<'ctx> {
|
|
pub fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
|
|
if context.poisoned() {
|
|
return Err(Error::ContextPoisoned);
|
|
}
|
|
let guard = context.enter()?;
|
|
let module = match context.driver.api.load_gr_batch_preview_module() {
|
|
Ok(v) => v,
|
|
Err(e) => return combine(Err(e), guard.finish()),
|
|
};
|
|
let result = (|| {
|
|
Ok([
|
|
context
|
|
.driver
|
|
.api
|
|
.qwen_function(module, Operation::LayerGate)?,
|
|
context
|
|
.driver
|
|
.api
|
|
.qwen_function(module, Operation::FinalGate)?,
|
|
context
|
|
.driver
|
|
.api
|
|
.qwen_function(module, Operation::InjectResidual)?,
|
|
context.driver.api.qwen_function(module, Operation::Norm)?,
|
|
])
|
|
})();
|
|
let functions = match result {
|
|
Ok(v) => v,
|
|
Err(e) => {
|
|
let cleanup = context.driver.api.unload(module);
|
|
if cleanup.is_err() {
|
|
context.poison();
|
|
context.retain_driver();
|
|
}
|
|
return combine(combine(Err(e), cleanup), guard.finish());
|
|
}
|
|
};
|
|
if let Err(e) = guard.finish() {
|
|
context.poison();
|
|
context.retain_driver();
|
|
return Err(e);
|
|
}
|
|
Ok(Self {
|
|
context,
|
|
module: Some(module),
|
|
functions,
|
|
launch_attempts: std::cell::Cell::new(0),
|
|
})
|
|
}
|
|
pub fn inject(
|
|
&self,
|
|
tokens: usize,
|
|
residual: &DeviceBuffer<'_>,
|
|
output: &DeviceBuffer<'_>,
|
|
inject: &DeviceBuffer<'_>,
|
|
candidate: &mut DeviceBuffer<'_>,
|
|
) -> Result<()> {
|
|
self.run(
|
|
Operation::InjectResidual,
|
|
tokens,
|
|
&[residual, output, inject, candidate],
|
|
)
|
|
}
|
|
pub(super) fn run(
|
|
&self,
|
|
operation: Operation,
|
|
tokens: usize,
|
|
buffers: &[&DeviceBuffer<'_>],
|
|
) -> Result<()> {
|
|
self.run_with_epsilon(operation, tokens, buffers, 0.)
|
|
}
|
|
pub(super) fn run_with_epsilon(
|
|
&self,
|
|
operation: Operation,
|
|
tokens: usize,
|
|
buffers: &[&DeviceBuffer<'_>],
|
|
epsilon: f32,
|
|
) -> Result<()> {
|
|
if !epsilon.is_finite() || epsilon < 0. {
|
|
return Err(Error::InvalidQwenShape);
|
|
}
|
|
let context = self.context;
|
|
if context.poisoned() || self.module.is_none() {
|
|
return Err(Error::ContextPoisoned);
|
|
}
|
|
let layout = batch_layout(operation, tokens)?;
|
|
if buffers.len() != layout.count {
|
|
return Err(Error::InvalidQwenShape);
|
|
}
|
|
let first = buffers[0].handle.ok_or(Error::ContextPoisoned)?;
|
|
let mut handles = [first; 9];
|
|
let mut bytes = [0; 9];
|
|
for (i, b) in buffers.iter().enumerate() {
|
|
if !std::ptr::eq(context, b.context) {
|
|
return Err(Error::ContextMismatch);
|
|
}
|
|
handles[i] = b.handle.ok_or(Error::ContextPoisoned)?;
|
|
bytes[i] = b.bytes;
|
|
}
|
|
ranges_layout(operation, layout, handles, bytes, false)?;
|
|
if context.allocated_bytes() > context.budget_bytes() {
|
|
return Err(Error::BudgetExceeded);
|
|
}
|
|
let kernel = self.functions[slot(operation)?];
|
|
let mut arguments = Arguments::with_layout(operation, layout, handles, epsilon);
|
|
let guard = context.enter()?;
|
|
let launch = context
|
|
.driver
|
|
.api
|
|
.launch_qwen(kernel, operation, &mut arguments);
|
|
self.launch_attempts.set(self.launch_attempts.get() + 1);
|
|
let sync = context.driver.api.synchronize();
|
|
if sync.is_err() {
|
|
context.poison();
|
|
context.retain_driver();
|
|
}
|
|
let pop = guard.finish();
|
|
if sync.is_err() || pop.is_err() {
|
|
std::mem::forget(arguments);
|
|
}
|
|
combine(combine(launch, sync), pop)
|
|
}
|
|
pub fn close(mut self) -> Result<()> {
|
|
self.unload()
|
|
}
|
|
fn unload(&mut self) -> Result<()> {
|
|
let Some(module) = self.module.take() else {
|
|
return Ok(());
|
|
};
|
|
if self.context.poisoned() {
|
|
self.context.retain_driver();
|
|
return Err(Error::ContextPoisoned);
|
|
}
|
|
let guard = match self.context.enter() {
|
|
Ok(v) => v,
|
|
Err(e) => {
|
|
self.context.poison();
|
|
self.context.retain_driver();
|
|
return Err(e);
|
|
}
|
|
};
|
|
let cleanup = self.context.driver.api.unload(module);
|
|
if cleanup.is_err() {
|
|
self.context.poison();
|
|
self.context.retain_driver();
|
|
}
|
|
combine(cleanup, guard.finish())
|
|
}
|
|
}
|
|
impl Drop for GrBatchPreview<'_> {
|
|
fn drop(&mut self) {
|
|
let _ = self.unload();
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Context<'_> {
|
|
pub fn gr_batch_inject_residual_f32(
|
|
&self,
|
|
tokens: usize,
|
|
residual: &DeviceBuffer<'_>,
|
|
output: &DeviceBuffer<'_>,
|
|
inject: &DeviceBuffer<'_>,
|
|
candidate: &mut DeviceBuffer<'_>,
|
|
) -> Result<()> {
|
|
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
|
|
{
|
|
let dispatcher = installed::GrBatchPreview::new(self)?;
|
|
let result = dispatcher.run(
|
|
Operation::InjectResidual,
|
|
tokens,
|
|
&[residual, output, inject, candidate],
|
|
);
|
|
let cleanup = dispatcher.close();
|
|
combine(result, cleanup)
|
|
}
|
|
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver")))]
|
|
{
|
|
let _ = (tokens, residual, output, inject, candidate);
|
|
Err(Error::UnsupportedPlatform)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Private ignored derivative proof entry; shared gamma, per-token R/output.
|
|
impl Context<'_> {
|
|
pub fn gr_batch_norm_f32(
|
|
&self,
|
|
tokens: usize,
|
|
residual: &DeviceBuffer<'_>,
|
|
gamma: &DeviceBuffer<'_>,
|
|
epsilon: f32,
|
|
output: &mut DeviceBuffer<'_>,
|
|
) -> Result<()> {
|
|
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
|
|
{
|
|
let dispatcher = installed::GrBatchPreview::new(self)?;
|
|
let result = dispatcher.run_with_epsilon(
|
|
Operation::Norm,
|
|
tokens,
|
|
&[residual, gamma, output],
|
|
epsilon,
|
|
);
|
|
combine(result, dispatcher.close())
|
|
}
|
|
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver")))]
|
|
{
|
|
let _ = (tokens, residual, gamma, epsilon, output);
|
|
Err(Error::UnsupportedPlatform)
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
|
|
pub use installed::GrBatchPreview as GrBatchModule;
|