STRA-338 params h04: gdn family (gates, recur, projections, step phases, chunk rows, mirror, chain, prompt device) takes grouped operands

This commit is contained in:
Pavlo Ratushnyi
2026-11-08 01:21:30 +01:00
parent 4b04c24981
commit f2aa4093d0
40 changed files with 633 additions and 490 deletions
@@ -218,6 +218,8 @@ mod four_borrow_gpu;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gdn_prompt_device.rs"]
mod prompt_device;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in crate::qwen_forward) use prompt_device::{PromptLayer, PromptProgram, PromptSource};
mod impl_gdnready;
mod impl_gdnstage;
@@ -236,11 +238,14 @@ use project_fn::dispatch_projection;
#[allow(unused_imports)]
use project_fn::normalize_qk;
#[allow(unused_imports)]
use project_fn::project;
#[allow(unused_imports)]
use project_fn::project_retained;
#[allow(unused_imports)]
use project_fn::{ProjectionOperands, project};
mod gates_fn;
#[allow(unused_imports)]
use gates_fn::{GateHostOperands, OutNormScale};
mod step_operands;
#[allow(unused_imports)]
use gates_fn::all_finite;
#[allow(unused_imports)]
use gates_fn::allocate;
@@ -268,6 +273,13 @@ use gates_fn::upload;
use gates_fn::validate_values;
#[allow(unused_imports)]
use gates_fn::zeros;
#[allow(unused_imports)]
use step_operands::MirrorStep;
#[allow(unused_imports)]
pub(in crate::qwen_forward) use step_operands::{
DeviceChunkRow, GdnLayerInput, GdnMatrixLayout, LeaseClaim, LeasedProjection, MirrorAuthority, ProjectedQkvSource,
ReadoutClaim, RecurrenceOperands,
};
mod driver_error_fn;
#[allow(unused_imports)]
pub(super) use driver_error_fn::driver_error;
@@ -18,15 +18,20 @@ struct GateOutputs<'a> {
gate_values: Box<[f32]>,
sigmoid_values: Box<[f32]>,
}
/// The four host vectors the gate kernels read: the raw alpha and beta of the current token and the layer's dt and a.
#[derive(Clone, Copy)]
pub(super) struct GateHostOperands<'h> {
pub(super) alpha: &'h [f32],
pub(super) beta: &'h [f32],
pub(super) dt: &'h [f32],
pub(super) a: &'h [f32],
}
pub(super) fn gates(
context: &Context<'_>,
alpha: &[f32],
beta: &[f32],
dt: &[f32],
a: &[f32],
host: GateHostOperands<'_>,
resident: Option<[&DeviceBuffer<'_>; 2]>,
) -> Result<CandidatePair> {
let GateUploads { alpha, beta, dt_owned, a_owned } = upload_gate_inputs(context, alpha, beta, dt, a, resident)?;
let GateUploads { alpha, beta, dt_owned, a_owned } = upload_gate_inputs(context, host, resident)?;
let dt = resident.map(|v| v[0]).or(dt_owned.as_ref()).ok_or(Error::IdentityMismatch)?;
let a = resident.map(|v| v[1]).or(a_owned.as_ref()).ok_or(Error::IdentityMismatch)?;
let GateOutputs { gate, sigmoid, gate_values, sigmoid_values } = run_gate_kernels(context, &alpha, &beta, dt, a)?;
@@ -37,19 +42,16 @@ pub(super) fn gates(
}
fn upload_gate_inputs<'a>(
context: &'a Context<'_>,
alpha: &[f32],
beta: &[f32],
dt: &[f32],
a: &[f32],
host: GateHostOperands<'_>,
resident: Option<[&DeviceBuffer<'_>; 2]>,
) -> Result<GateUploads<'a>> {
for values in [alpha, beta, dt, a] {
for values in [host.alpha, host.beta, host.dt, host.a] {
validate_values(values, 48)?;
}
let alpha = upload(context, alpha)?;
let beta = upload(context, beta)?;
let dt_owned = if resident.is_none() { Some(upload(context, dt)?) } else { None };
let a_owned = if resident.is_none() { Some(upload(context, a)?) } else { None };
let alpha = upload(context, host.alpha)?;
let beta = upload(context, host.beta)?;
let dt_owned = if resident.is_none() { Some(upload(context, host.dt)?) } else { None };
let a_owned = if resident.is_none() { Some(upload(context, host.a)?) } else { None };
Ok(GateUploads { alpha, beta, dt_owned, a_owned })
}
fn run_gate_kernels<'a>(
@@ -107,16 +109,9 @@ impl RecurHost<'_> {
Ok([state, q, k, v, gate, beta])
}
}
#[allow(clippy::too_many_arguments)] // Source-defined immutable state and six operands.
pub(super) fn recur(
context: &Context<'_>,
state: &[f32],
q: &[f32],
k: &[f32],
v: &[f32],
gate: &[f32],
beta: &[f32],
) -> Result<CandidatePair> {
// Source-defined immutable state and the five operands of one recurrence step.
pub(super) fn recur(context: &Context<'_>, state: &[f32], operands: RecurrenceOperands<'_>) -> Result<CandidatePair> {
let RecurrenceOperands { q, k, v, gate, beta } = operands;
let host = RecurHost { state, q, k, v, gate, beta };
host.validate()?;
let [state, q, k, v, gate, beta] = host.upload_all(context)?;
@@ -128,14 +123,21 @@ pub(super) fn recur(
release([state, q, k, v, gate, beta, next, output])?;
Ok((next_values, output_values))
}
/// The learned scale of the GDN output norm for one call: its host values, the resident device copy when one is lent,
/// and the norm epsilon.
#[derive(Clone, Copy)]
pub(super) struct OutNormScale<'a, 'ctx> {
pub(super) gamma: &'a [f32],
pub(super) resident: Option<&'a DeviceBuffer<'ctx>>,
pub(super) epsilon: f32,
}
pub(super) fn out_norm(
context: &Context<'_>,
input: &[f32],
z: &[f32],
gamma: &[f32],
epsilon: f32,
resident: Option<&DeviceBuffer<'_>>,
scale: OutNormScale<'_, '_>,
) -> Result<Box<[f32]>> {
let OutNormScale { gamma, resident, epsilon } = scale;
let (input, z) = upload_out_norm_inputs(context, input, z, gamma)?;
let owned = upload_unless_resident(context, resident, gamma)?;
let gamma = resident.or(owned.as_ref()).ok_or(Error::IdentityMismatch)?;
@@ -18,12 +18,16 @@ impl GdnStage {
row: super::super::session::chunk::GdnChunkRow,
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, 'ctx>>,
) -> Result<chunk_producer::ChunkReady> {
let layer_input = GdnLayerInput { binding, layer, input };
let device_row = DeviceChunkRow { owner, row };
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if cache.has_native_qsa() {
let program = cache.native_gdn_fused(binding, txn.cuda_context()?)?;
return Self::step_chunk_fused(binding, layer, input, txn, cache, owner, row, program, projection);
let source = ProjectedQkvSource { txn: &*txn, projection };
return Self::step_chunk_fused(layer_input, device_row, cache, program, source);
}
Self::step_chunk(binding, layer, input, txn, cache, owner, row, projection)
let source = ProjectedQkvSource { txn: &*txn, projection };
Self::step_chunk(layer_input, device_row, cache, source)
}
pub(in super::super) fn step(
binding: &ModelBinding,
@@ -33,7 +37,7 @@ impl GdnStage {
txn: &mut QwenStepTxn,
cache: Option<&DenseWeightCache<'_>>,
) -> Result<GdnReady> {
Self::step_impl(binding, layer, input, prior, txn, cache, None)
Self::step_impl(GdnLayerInput { binding, layer, input }, prior, txn, cache, None)
}
pub(in super::super) fn step_projected(
binding: &ModelBinding,
@@ -44,22 +48,22 @@ impl GdnStage {
cache: &DenseWeightCache<'_>,
projection: &mut super::super::q6_attention_columns::ProjectionRow<'_, '_>,
) -> Result<GdnReady> {
Self::step_impl(binding, layer, input, prior, txn, Some(cache), Some(projection))
Self::step_impl(GdnLayerInput { binding, layer, input }, prior, txn, Some(cache), Some(projection))
}
pub(super) fn step_impl(
binding: &ModelBinding,
layer: LayerId,
input: &ResidualReady,
layer_input: GdnLayerInput<'_>,
prior: &GdnPrior,
txn: &mut QwenStepTxn,
cache: Option<&DenseWeightCache<'_>>,
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
) -> Result<GdnReady> {
let GdnLayerInput { binding, layer, input } = layer_input;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(cache) = cache.filter(|cache| cache.has_native_qsa()) {
let owner = cache.native_gdn_fused(binding, txn.cuda_context()?)?;
let mut fused = owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
return Self::step_fused(binding, layer, input, prior, txn, cache, &mut fused, projection);
let source = ProjectedQkvSource { txn: &*txn, projection };
return Self::step_fused(layer_input, prior, cache, &mut fused, source);
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let _owner_wall_scope =
@@ -68,7 +72,7 @@ impl GdnStage {
let context = txn.cuda_context()?;
preflight_budget(context.budget_bytes(), context.allocated_bytes())?;
if let Some(cache) = cache {
return step_cached(binding, layer, input, prior, context, cache, txn, projection);
return step_cached(layer_input, prior, cache, ProjectedQkvSource { txn: &*txn, projection });
}
if projection.is_some() {
return Err(Error::IdentityMismatch);
@@ -108,13 +112,19 @@ impl GdnStage {
prior: &GdnPrior,
context: &Context<'_>,
) -> Result<(Box<[f32]>, CandidatePair)> {
let qkv = project(context, binding, weights, GdnMatrixRole::Qkv, mixed, None, None)?;
let qkv =
project(context, ProjectionOperands::without_cache(binding, weights, GdnMatrixRole::Qkv, mixed), None)?;
let (history, h) = convolve(context, prior.history(), &qkv, weights.conv(), None)?;
let qk = normalize_qk(context, &h, weights.epsilon())?;
let alpha = project(context, binding, weights, GdnMatrixRole::Alpha, mixed, None, None)?;
let beta_raw = project(context, binding, weights, GdnMatrixRole::Beta, mixed, None, None)?;
let (gate, beta) = gates(context, &alpha, &beta_raw, weights.dt(), weights.a(), None)?;
let pair = recur(context, prior.values(), &qk[..2048], &qk[2048..4096], &h[4096..], &gate, &beta)?;
let alpha =
project(context, ProjectionOperands::without_cache(binding, weights, GdnMatrixRole::Alpha, mixed), None)?;
let beta_raw =
project(context, ProjectionOperands::without_cache(binding, weights, GdnMatrixRole::Beta, mixed), None)?;
let gate_host = GateHostOperands { alpha: &alpha, beta: &beta_raw, dt: weights.dt(), a: weights.a() };
let (gate, beta) = gates(context, gate_host, None)?;
let operands =
RecurrenceOperands { q: &qk[..2048], k: &qk[2048..4096], v: &h[4096..], gate: &gate, beta: &beta };
let pair = recur(context, prior.values(), operands)?;
Ok((history, pair))
}
fn step_uncached(
@@ -127,9 +137,11 @@ impl GdnStage {
let weights = std::rc::Rc::new(binding.gdn_weights(layer.get()).map_err(binding_error)?);
let mixed = input.mixed();
let (history, (state, readout)) = Self::uncached_recurrence(binding, &weights, mixed, prior, context)?;
let z = project(context, binding, &weights, GdnMatrixRole::Z, mixed, None, None)?;
let normalized = out_norm(context, &readout, &z, weights.norm(), weights.epsilon(), None)?;
let output = project(context, binding, &weights, GdnMatrixRole::Out, &normalized, None, None)?;
let z = project(context, ProjectionOperands::without_cache(binding, &weights, GdnMatrixRole::Z, mixed), None)?;
let scale = OutNormScale { gamma: weights.norm(), resident: None, epsilon: weights.epsilon() };
let normalized = out_norm(context, &readout, &z, scale)?;
let out_operands = ProjectionOperands::without_cache(binding, &weights, GdnMatrixRole::Out, &normalized);
let output = project(context, out_operands, None)?;
validate_values(&output, 2560)?;
let pending = GdnPending::new(prior, input.identity(), state, history)?;
Ok(GdnReady { identity: input.identity(), binding: binding.identity(), output, pending: Some(pending) })
@@ -7,28 +7,34 @@ use super::*;
pub(super) fn project(
context: &Context<'_>,
binding: &ModelBinding,
weights: &GdnWeights,
role: GdnMatrixRole,
activation: &[f32],
cache: Option<&DenseWeightCache<'_>>,
operands: ProjectionOperands<'_, '_>,
source: Option<&GdnInputLease<'_, '_, '_>>,
) -> Result<Box<[f32]>> {
let (c, _) = weights.shape(role);
validate_values(activation, c)?;
let operands = ProjectionOperands { binding, weights, role, activation, cache };
let (c, _) = operands.weights.shape(operands.role);
validate_values(operands.activation, c)?;
if let Some(source) = source {
return project_leased(context, &operands, source);
}
project_uploaded(context, &operands)
}
/// What one GDN projection reads besides the context and the optional input lease.
struct ProjectionOperands<'a, 'c> {
binding: &'a ModelBinding,
weights: &'a GdnWeights,
role: GdnMatrixRole,
activation: &'a [f32],
cache: Option<&'a DenseWeightCache<'c>>,
pub(super) struct ProjectionOperands<'a, 'c> {
pub(super) binding: &'a ModelBinding,
pub(super) weights: &'a GdnWeights,
pub(super) role: GdnMatrixRole,
pub(super) activation: &'a [f32],
pub(super) cache: Option<&'a DenseWeightCache<'c>>,
}
impl<'a> ProjectionOperands<'a, '_> {
/// The operands of a projection that uploads its own matrix block because no resident cache is present.
pub(super) fn without_cache(
binding: &'a ModelBinding,
weights: &'a GdnWeights,
role: GdnMatrixRole,
activation: &'a [f32],
) -> Self {
Self { binding, weights, role, activation, cache: None }
}
}
fn project_leased(
context: &Context<'_>,
@@ -37,14 +43,15 @@ fn project_leased(
) -> Result<Box<[f32]>> {
let ProjectionOperands { binding, weights, role, activation, cache } = *operands;
let (c, r) = weights.shape(role);
source.buffer(&binding.identity(), context, weights.layer(), role, activation)?;
let claim = LeaseClaim { binding: &binding.identity(), context, layer: weights.layer(), source: activation };
source.buffer(&claim, role)?;
let cache = cache.ok_or(Error::IdentityMismatch)?;
let entry = cache.gdn(binding, weights.layer())?;
if !std::ptr::eq(entry.weights.as_ref(), weights) {
return Err(Error::IdentityMismatch);
}
let (matrix, kind) = cache.gdn_matrix(entry, role)?;
project_retained(context, matrix, kind, c, r, source)
project_retained(context, matrix, GdnMatrixLayout { kind, columns: c, rows: r }, source)
}
fn project_uploaded(context: &Context<'_>, operands: &ProjectionOperands<'_, '_>) -> Result<Box<[f32]>> {
let ProjectionOperands { binding, weights, role, activation, cache } = *operands;
@@ -60,7 +67,8 @@ fn project_uploaded(context: &Context<'_>, operands: &ProjectionOperands<'_, '_>
(owned.as_ref().ok_or(Error::IdentityMismatch)?, kind)
};
let mut output = allocate(context, r)?;
dispatch_projection(context, matrix, &a, &mut output, kind, c, r).map_err(driver_error)?;
dispatch_projection(context, matrix, &a, &mut output, GdnMatrixLayout { kind, columns: c, rows: r })
.map_err(driver_error)?;
release_projection(output, owned, a, r)
}
fn upload_matrix_block<'a>(
@@ -95,10 +103,9 @@ pub(super) fn dispatch_projection(
matrix: &DeviceBuffer<'_>,
a: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
kind: GdnMatrixKind,
c: usize,
r: usize,
layout: GdnMatrixLayout,
) -> std::result::Result<(), DriverError> {
let GdnMatrixLayout { kind, columns: c, rows: r } = layout;
match kind {
GdnMatrixKind::Bf16 => context.bf16_f32(matrix, a, output, Bf16ProjectionShape { rows: r, columns: c }),
GdnMatrixKind::Q5K => context.q5_k_q8_1(matrix, a, output, Q5KProjectionShape { rows: r, columns: c }),
@@ -141,16 +148,15 @@ fn allocate_for_lease<'a>(
pub(super) fn project_retained(
context: &Context<'_>,
matrix: &DeviceBuffer<'_>,
kind: GdnMatrixKind,
columns: usize,
rows: usize,
layout: GdnMatrixLayout,
source: &GdnInputLease<'_, '_, '_>,
) -> Result<Box<[f32]>> {
let GdnMatrixLayout { columns, rows, .. } = layout;
// The actual device input comes only from the lease, never an unrelated buffer.
let activation = source.activation(context, columns)?;
let mut output = allocate_for_lease(context, rows, source)?;
let operation = (|| {
dispatch_projection(context, matrix, activation, &mut output, kind, columns, rows).map_err(driver_error)?;
dispatch_projection(context, matrix, activation, &mut output, layout).map_err(driver_error)?;
download(&output, rows)
})();
let cleanup = output.release().map_err(driver_error);
@@ -5,17 +5,15 @@ use super::*;
use crate::qwen_forward::dense_weight_cache::GdnResident;
use std::{cell::Cell, rc::Rc};
#[allow(clippy::too_many_arguments)]
pub(super) fn step_cached<'ctx>(
binding: &ModelBinding,
layer: LayerId,
input: &ResidualReady,
layer_input: GdnLayerInput<'_>,
prior: &GdnPrior,
current_context: &Context<'_>,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
source: ProjectedQkvSource<'_, '_, '_, '_>,
) -> Result<GdnReady> {
let GdnLayerInput { binding, layer, input } = layer_input;
let ProjectedQkvSource { txn, projection } = source;
let current_context = txn.cuda_context()?;
let context = cache.retained_context(binding, current_context)?;
let failed = cache.transport_failure_flag(binding, context)?;
let resident = cache.gdn(binding, layer.get())?;
@@ -24,16 +22,15 @@ pub(super) fn step_cached<'ctx>(
let mut mirror = cache.gdn_mirror(binding, layer.get(), context)?;
let input_lease = cache.gdn_input(binding, layer.get(), context, input.mixed())?;
let mut chain = open_chain(binding, input, context, cache, &failed)?;
let step =
CachedGdn { binding, input, prior, context, cache, weights: &weights, resident, aux, lease: &input_lease };
let mut mirror_next = None;
let operation = step.run(&mut chain, &mut mirror, &mut mirror_next, txn, layer, projection);
let step = CachedGdn { layer_input, prior, context, cache, weights: &weights, resident, aux, lease: &input_lease };
let mut mirror_step = MirrorStep { mirror: &mut mirror, prior, candidate: None };
let operation = step.run(&mut chain, &mut mirror_step, txn, projection);
if matches!(operation, Err(Error::CudaExecution)) {
failed.set(true);
}
let cleanup = chain.finish();
drop(input_lease);
settle_cached(operation, cleanup, &mut mirror, mirror_next, binding, input)
settle_cached(operation, cleanup, mirror_step, layer_input)
}
fn open_chain<'ctx>(
@@ -55,11 +52,11 @@ fn open_chain<'ctx>(
fn settle_cached<'ctx>(
operation: Result<CandidatePair>,
cleanup: Result<()>,
mirror: &mut GdnStateMirror<'ctx>,
mut mirror_next: Option<mirror::MirrorNext<'ctx>>,
binding: &ModelBinding,
input: &ResidualReady,
step: MirrorStep<'_, 'ctx>,
layer_input: GdnLayerInput<'_>,
) -> Result<GdnReady> {
let MirrorStep { mirror, candidate: mut mirror_next, .. } = step;
let GdnLayerInput { binding, input, .. } = layer_input;
let result = operation.and_then(|values| cleanup.map(|()| values));
let (history, output) = match result {
Ok(values) => values,
@@ -84,8 +81,7 @@ struct RecurrenceInputs {
/// Everything one cached GDN step reads besides the chain, the mirror and the transaction.
struct CachedGdn<'a, 's, 'src, 'ctx> {
binding: &'a ModelBinding,
input: &'a ResidualReady,
layer_input: GdnLayerInput<'a>,
prior: &'a GdnPrior,
context: &'ctx Context<'ctx>,
cache: &'a DenseWeightCache<'ctx>,
@@ -97,21 +93,25 @@ struct CachedGdn<'a, 's, 'src, 'ctx> {
impl<'ctx> CachedGdn<'_, '_, '_, 'ctx> {
fn project(&self, chain: &mut chain::Chain<'ctx>, role: GdnMatrixRole) -> Result<chain::Product> {
let activation = self.input.mixed();
project_chain_input(chain, self.context, self.binding, self.weights, role, self.lease, activation, self.cache)
let operands = LeasedProjection {
binding: self.layer_input.binding,
weights: self.weights,
activation: self.layer_input.input.mixed(),
lease: self.lease,
cache: self.cache,
};
project_chain_input(chain, self.context, &operands, role)
}
fn run(
&self,
chain: &mut chain::Chain<'ctx>,
mirror: &mut GdnStateMirror<'ctx>,
mirror_next: &mut Option<mirror::MirrorNext<'ctx>>,
step: &mut MirrorStep<'_, 'ctx>,
txn: &QwenStepTxn<'_, '_>,
layer: LayerId,
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
) -> Result<CandidatePair> {
let (history, products) = self.leading_products(chain, txn, layer, projection)?;
let (readout, next) = self.recurrence(chain, mirror, txn, products)?;
*mirror_next = Some(next);
let (history, products) = self.leading_products(chain, txn, projection)?;
let (readout, next) = self.recurrence(chain, &mut *step.mirror, txn, products)?;
step.candidate = Some(next);
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
four_borrow_gpu::observe_readout(readout.test_values()?)?;
let output = self.finish(chain, readout)?;
@@ -122,13 +122,12 @@ impl<'ctx> CachedGdn<'_, '_, '_, 'ctx> {
&self,
chain: &mut chain::Chain<'ctx>,
txn: &QwenStepTxn<'_, '_>,
layer: LayerId,
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
) -> Result<(Box<[f32]>, RecurrenceInputs)> {
let qkv = if let Some(projection) = projection {
// Closed actual producer import; extra H2D remains explicit.
// Raw upload still rejects every computed output role.
chain.import_projected_qkv(projection, self.binding, self.cache, txn, layer, self.input)?
chain.import_projected_qkv(projection, self.layer_input, self.cache, txn)?
} else {
self.project(chain, GdnMatrixRole::Qkv)?
};
@@ -147,7 +146,7 @@ impl<'ctx> CachedGdn<'_, '_, '_, 'ctx> {
txn: &QwenStepTxn<'_, '_>,
inputs: RecurrenceInputs,
) -> Result<(mirror::MirrorReadout<'ctx>, mirror::MirrorNext<'ctx>)> {
let four_borrow = self.cache.gdn_four_borrow(self.binding, self.context)?;
let four_borrow = self.cache.gdn_four_borrow(self.layer_input.binding, self.context)?;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let four_borrow = four_borrow_gpu::policy(four_borrow)?;
if four_borrow {
@@ -165,7 +164,7 @@ impl<'ctx> CachedGdn<'_, '_, '_, 'ctx> {
) -> Result<(mirror::MirrorReadout<'ctx>, mirror::MirrorNext<'ctx>)> {
let products = [&inputs.qk, &inputs.h, &inputs.gate, &inputs.beta];
let borrowed = chain.borrow_scalar_recurrence(self.prior, txn, products)?;
let recurrence = mirror.compute_borrowed(self.prior, self.input.identity(), txn, borrowed);
let recurrence = mirror.compute_borrowed(self.prior, self.layer_input.input.identity(), txn, borrowed);
// Attempt all retained-source frees even on recurrence refusal.
// Keep primary failure and the shared sticky cleanup fence.
let cleanup = chain.release_chunk_sources();
@@ -188,7 +187,7 @@ impl<'ctx> CachedGdn<'_, '_, '_, 'ctx> {
chain.drain()?;
mirror.compute_retained(
self.prior,
self.input.identity(),
self.layer_input.input.identity(),
chain.scope_key(),
[&qk[..2048], &qk[2048..4096], &h[4096..], &gate, &beta],
)
@@ -225,21 +224,19 @@ fn checked_gdn_matrix<'c, 'ctx>(
}
cache.gdn_matrix(resident, role)
}
#[allow(clippy::too_many_arguments)] // Explicit closed provider and current input-lease checks.
pub(super) fn project_chain_input<'ctx>(
chain: &mut chain::Chain<'ctx>,
context: &Context<'_>,
binding: &ModelBinding,
weights: &GdnWeights,
operands: &LeasedProjection<'_, '_, '_, 'ctx>,
role: GdnMatrixRole,
source: &GdnInputLease<'_, '_, 'ctx>,
activation: &[f32],
cache: &DenseWeightCache<'ctx>,
) -> Result<chain::Product> {
// Explicit closed provider and current input-lease checks.
let LeasedProjection { binding, weights, activation, lease: source, cache } = *operands;
let output_role = chain_output_role(role)?;
let (columns, rows) = weights.shape(role);
validate_values(activation, columns)?;
let activation = source.buffer(&binding.identity(), context, weights.layer(), role, activation)?;
let claim = LeaseClaim { binding: &binding.identity(), context, layer: weights.layer(), source: activation };
let activation = source.buffer(&claim, role)?;
let (matrix, kind) = checked_gdn_matrix(cache, binding, weights, role)?;
let product = chain.project(matrix, kind, activation, output_role)?;
validate_values(product.values(), rows)?;
@@ -0,0 +1,94 @@
//! The groups of values a GDN layer step passes between its phases (STRA-338: one parameter group per meaning
//! instead of long argument lists). All of them are plain stack values or borrows; none allocates.
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::q6_attention_columns::ProjectionRow;
use std::{cell::Cell, rc::Rc};
/// The GDN layer one step runs and the residual it consumes: the model binding, which layer, and that layer's input.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct GdnLayerInput<'a> {
pub(in crate::qwen_forward) binding: &'a ModelBinding,
pub(in crate::qwen_forward) layer: LayerId,
pub(in crate::qwen_forward) input: &'a ResidualReady,
}
/// The five per-token host operands of the gated delta-rule recurrence: query, key, value, gate and beta.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct RecurrenceOperands<'h> {
pub(in crate::qwen_forward) q: &'h [f32],
pub(in crate::qwen_forward) k: &'h [f32],
pub(in crate::qwen_forward) v: &'h [f32],
pub(in crate::qwen_forward) gate: &'h [f32],
pub(in crate::qwen_forward) beta: &'h [f32],
}
/// The step transaction and, when the attention producer already projected the QKV columns of this row, the row it
/// projected: the two things an imported QKV needs besides the layer input.
pub(in crate::qwen_forward) struct ProjectedQkvSource<'a, 'driver, 'row, 'rowctx> {
pub(in crate::qwen_forward) txn: &'a QwenStepTxn<'a, 'driver>,
pub(in crate::qwen_forward) projection: Option<&'a mut ProjectionRow<'row, 'rowctx>>,
}
/// One layer's state mirror seen from a single step: the prior state the step reads and the candidate state it has
/// computed into the mirror but not yet published or discarded.
pub(super) struct MirrorStep<'a, 'ctx> {
pub(super) mirror: &'a mut GdnStateMirror<'ctx>,
pub(super) prior: &'a GdnPrior,
pub(super) candidate: Option<mirror::MirrorNext<'ctx>>,
}
/// A chunk row together with the chunk device that owns its recurrent state.
pub(in crate::qwen_forward) struct DeviceChunkRow<'a, 'ctx> {
pub(in crate::qwen_forward) owner: &'a mut chunk_device::GdnChunkDevice<'ctx>,
pub(in crate::qwen_forward) row: crate::qwen_forward::session::chunk::GdnChunkRow,
}
/// The stored format and shape of one resident GDN weight matrix, as a projection kernel is dispatched on it.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct GdnMatrixLayout {
pub(in crate::qwen_forward) kind: GdnMatrixKind,
pub(in crate::qwen_forward) columns: usize,
pub(in crate::qwen_forward) rows: usize,
}
/// What a GDN projection through the device input lease reads: the layer's binding and weights, the activation the
/// lease was filled from, the lease itself and the cache that owns the resident matrices.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct LeasedProjection<'a, 'slot, 'src, 'ctx> {
pub(in crate::qwen_forward) binding: &'a ModelBinding,
pub(in crate::qwen_forward) weights: &'a GdnWeights,
pub(in crate::qwen_forward) activation: &'a [f32],
pub(in crate::qwen_forward) lease: &'a GdnInputLease<'slot, 'src, 'ctx>,
pub(in crate::qwen_forward) cache: &'a DenseWeightCache<'ctx>,
}
/// Who asks the device input lease for its buffer: the lease is lent only to the binding, context, layer and source
/// activation it was filled for.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct LeaseClaim<'a, 'ctx> {
pub(in crate::qwen_forward) binding: &'a BindingIdentity,
pub(in crate::qwen_forward) context: &'a Context<'ctx>,
pub(in crate::qwen_forward) layer: u32,
pub(in crate::qwen_forward) source: &'a [f32],
}
/// The mirror that consumes a borrowed recurrence: the borrow is accepted only when its chain was built for exactly
/// this context, model binding and failure latch.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct MirrorAuthority<'a, 'ctx> {
pub(in crate::qwen_forward) context: &'a Context<'ctx>,
pub(in crate::qwen_forward) binding: &'a BindingIdentity,
pub(in crate::qwen_forward) failed: &'a Rc<Cell<bool>>,
}
/// What a consumer must prove before it may take a recurrence readout: the context and failure latch the readout
/// was produced under, the prior state it continues, and the token layer and chain scope it belongs to.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct ReadoutClaim<'a, 'ctx> {
pub(in crate::qwen_forward) context: &'a Context<'ctx>,
pub(in crate::qwen_forward) failed: &'a Rc<Cell<bool>>,
pub(in crate::qwen_forward) prior: &'a GdnPrior,
pub(in crate::qwen_forward) identity: TokenLayer,
pub(in crate::qwen_forward) scope: &'a Rc<()>,
}
@@ -1,7 +1,8 @@
//! Step-local actual CUDA products; canonical finite host readbacks stay intact.
use super::{
BindingIdentity, CHANNELS, Context, DeviceBuffer, Error, GdnMatrixKind, HISTORY_ELEMENTS, Result, TokenLayer,
VALUES, allocate, dispatch_projection, download, driver_error, validate_values,
BindingIdentity, CHANNELS, Context, DeviceBuffer, Error, GdnLayerInput, GdnMatrixKind, GdnMatrixLayout,
HISTORY_ELEMENTS, MirrorAuthority, ReadoutClaim, Result, TokenLayer, VALUES, allocate, dispatch_projection,
download, driver_error, validate_values,
};
use leleka_cuda_driver::GdnRowQueue;
use std::{
@@ -160,13 +160,12 @@ impl<'chain, 'ctx> RecurrenceBorrow<'chain, 'ctx> {
impl<'chain, 'ctx> ScalarRecurrenceBorrow<'chain, 'ctx> {
fn validate_borrow(
&self,
context: &Context<'_>,
binding: &BindingIdentity,
failed: &Rc<Cell<bool>>,
authority: MirrorAuthority<'_, '_>,
prior: &super::super::GdnPrior,
identity: TokenLayer,
txn: &super::super::QwenStepTxn<'_, '_>,
) -> Result<()> {
let MirrorAuthority { context, binding, failed } = authority;
txn.validate_binding(binding)?;
txn.validate_input(identity.token(), identity.position())?;
txn.validate_gdn_prior(prior, identity.layer())?;
@@ -182,14 +181,12 @@ impl<'chain, 'ctx> ScalarRecurrenceBorrow<'chain, 'ctx> {
}
pub(in super::super) fn into_parts(
self,
context: &Context<'_>,
binding: &BindingIdentity,
failed: &Rc<Cell<bool>>,
authority: MirrorAuthority<'_, '_>,
prior: &super::super::GdnPrior,
identity: TokenLayer,
txn: &super::super::QwenStepTxn<'_, '_>,
) -> Result<RecurrenceParts<'chain, 'ctx>> {
self.validate_borrow(context, binding, failed, prior, identity, txn)?;
self.validate_borrow(authority, prior, identity, txn)?;
let [qk, h, gate, beta] = self.products;
Ok((
self.scope,
@@ -192,7 +192,8 @@ impl<'ctx> Chain<'ctx> {
let product = self.reserve_device(role)?;
let operation = {
let output = self.buffers.get_mut(product.slot).and_then(Option::as_mut).ok_or(Error::IdentityMismatch)?;
dispatch_projection(self.context, matrix, source, output, kind, 2560, role.count()).map_err(driver_error)
let layout = GdnMatrixLayout { kind, columns: 2560, rows: role.count() };
dispatch_projection(self.context, matrix, source, output, layout).map_err(driver_error)
};
if let Err(primary) = operation {
self.note(primary);
@@ -212,9 +213,7 @@ impl<'ctx> Chain<'ctx> {
matrix,
chain.device_buffer(normalized, Role::Normalized)?,
&mut out[0],
kind,
VALUES,
2560,
GdnMatrixLayout { kind, columns: VALUES, rows: 2560 },
)
.map_err(driver_error)?;
Ok([download(&out[0], 2560)?])
@@ -260,16 +260,14 @@ impl<'ctx> Chain<'ctx> {
}
// Only this importer can admit computed QKV: the real sealed producer
// must pass all original branch/source/provider/one-use checks first.
#[allow(clippy::too_many_arguments)]
pub(in super::super::super) fn import_projected_qkv(
&mut self,
projection: &mut super::super::super::super::q6_attention_columns::ProjectionRow<'_, '_>,
binding: &super::super::super::ModelBinding,
layer_input: GdnLayerInput<'_>,
cache: &super::super::super::DenseWeightCache<'_>,
txn: &super::super::super::QwenStepTxn<'_, '_>,
layer: super::super::super::LayerId,
input: &super::super::super::ResidualReady,
) -> Result<Product> {
let GdnLayerInput { binding, layer, input } = layer_input;
self.validate(txn.cuda_context()?, &binding.identity(), input.identity())?;
let values = projection.take(
binding,
@@ -112,8 +112,8 @@ impl<'ctx> Chain<'ctx> {
_ => return Err(Error::IdentityMismatch),
};
let [product] = self.produce([role], |chain, out| {
dispatch_projection(chain.context, matrix, source, &mut out[0], kind, columns, role.count())
.map_err(driver_error)?;
let layout = GdnMatrixLayout { kind, columns, rows: role.count() };
dispatch_projection(chain.context, matrix, source, &mut out[0], layout).map_err(driver_error)?;
Ok([download(&out[0], role.count())?])
})?;
Ok(product)
@@ -130,9 +130,7 @@ impl<'ctx> Chain<'ctx> {
matrix,
chain.buffer(normalized, Role::Normalized)?,
&mut out[0],
kind,
VALUES,
2560,
GdnMatrixLayout { kind, columns: VALUES, rows: 2560 },
)
.map_err(driver_error)?;
Ok([download(&out[0], 2560)?])
@@ -232,7 +230,14 @@ impl<'ctx> Chain<'ctx> {
return Err(Error::IdentityMismatch);
}
self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?;
let (buffer, values) = readout.into_parts(self.context, &self.failed, prior, self.identity, &self.epoch)?;
let claim = ReadoutClaim {
context: self.context,
failed: &self.failed,
prior,
identity: self.identity,
scope: &self.epoch,
};
let (buffer, values) = readout.into_parts(claim)?;
Ok(self.track(Role::Readout, buffer, values))
}
}
@@ -31,6 +31,14 @@ pub(in crate::qwen_forward::gdn) struct FusedRow {
pub(in crate::qwen_forward::gdn) normalized: DeviceProduct,
}
/// The device state a fused row reads and updates: the bit-exact resident mirror of the prior state on a key hit, and
/// the candidate state buffer, updated in place.
#[derive(Clone, Copy)]
struct FusedState<'a, 'ctx> {
resident: Option<&'a DeviceBuffer<'ctx>>,
next_state: &'a DeviceBuffer<'ctx>,
}
/// The five chain slots one fused row writes.
struct FusedSlots {
next: DeviceOperand,
@@ -71,7 +79,7 @@ impl<'ctx> Chain<'ctx> {
// drain. The candidate history slot is seeded with the canonical prior (the Original updates it in place).
let slots = self.reserve_fused_slots(Self::reserve_device)?;
self.seed_fused_history(&slots.next, inputs.prior_history)?;
let drained = self.drain_fused_row(program, resident, next_state, &inputs, &slots);
let drained = self.drain_fused_row(program, FusedState { resident, next_state }, &inputs, &slots);
let completion = self.note_err(drained)?;
// A completed numerical refusal is the same NonFinite as the decomposed chain's full readback validation;
// neither the candidate state nor the history is returned.
@@ -141,14 +149,13 @@ impl<'ctx> Chain<'ctx> {
fn drain_fused_row(
&self,
program: &mut GdnFusedT1<'ctx>,
resident: Option<&DeviceBuffer<'ctx>>,
next_state: &DeviceBuffer<'ctx>,
state: FusedState<'_, 'ctx>,
inputs: &FusedInputs<'_, 'ctx>,
slots: &FusedSlots,
) -> Result<GdnFusedCompletion> {
let bufs = self.fused_buffers(inputs, slots)?;
let mut prefix = program.begin().map_err(driver_error)?;
let admitted = Self::admit_fused(&mut prefix, resident, next_state, inputs, &bufs)
let admitted = Self::admit_fused(&mut prefix, state.resident, state.next_state, inputs, &bufs)
.and_then(|()| prefix.fetch_candidate().map_err(driver_error));
// The driver's methods latch admission errors; drain every real
// admitted command so earlier numerics remain primary.
@@ -207,7 +214,8 @@ impl<'ctx> Chain<'ctx> {
// drain. The candidate history slot is seeded with the canonical prior (the Original updates it in place).
let slots = self.reserve_fused_slots(Self::reserve_fused_verified)?;
self.seed_fused_history(&slots.next, inputs.prior_history)?;
let drained = self.drain_fused_verification_row(program, resident, next_state, &inputs, &slots);
let state = FusedState { resident, next_state };
let drained = self.drain_fused_verification_row(program, state, &inputs, &slots);
let completion = self.note_err(drained)?;
if completion.is_some() {
return Err(Error::NonFinite);
@@ -219,14 +227,13 @@ impl<'ctx> Chain<'ctx> {
fn drain_fused_verification_row(
&self,
program: &mut GdnFusedT1<'ctx>,
resident: Option<&DeviceBuffer<'ctx>>,
next_state: &DeviceBuffer<'ctx>,
state: FusedState<'_, 'ctx>,
inputs: &FusedInputs<'_, 'ctx>,
slots: &FusedSlots,
) -> Result<Option<GdnFusedStage>> {
let bufs = self.fused_buffers(inputs, slots)?;
let mut prefix = program.begin().map_err(driver_error)?;
let admitted = Self::admit_fused(&mut prefix, resident, next_state, inputs, &bufs);
let admitted = Self::admit_fused(&mut prefix, state.resident, state.next_state, inputs, &bufs);
let _ = admitted;
prefix.finish_device().map_err(driver_error)
}
@@ -2,7 +2,8 @@
#![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::super::mirror::{MirrorNext, MirrorReadout};
use super::super::{
GdnOwner, GdnPrior, GdnStateMirror, convolve, gates, normalize_qk, out_norm, recur, release, upload,
GateHostOperands, GdnOwner, GdnPrior, GdnStateMirror, OutNormScale, RecurrenceOperands, convolve, gates,
normalize_qk, out_norm, recur, release, upload,
};
use super::*;
use crate::qwen_forward::contract::{Dimension, LayerId, Position, TokenId};
@@ -163,8 +164,13 @@ impl<'c> Case<'c> {
let (alpha, expected_alpha) = pair_projection(&mut self.chain, &self.source, &self.input, Role::Alpha, 1);
let (beta_raw, expected_beta_raw) =
pair_projection(&mut self.chain, &self.source, &self.input, Role::BetaRaw, 2);
let expected_gates =
gates(ctx, &expected_alpha, &expected_beta_raw, &self.params.dt, &self.params.a, None).unwrap();
let gate_host = GateHostOperands {
alpha: &expected_alpha,
beta: &expected_beta_raw,
dt: &self.params.dt,
a: &self.params.a,
};
let expected_gates = gates(ctx, gate_host, None).unwrap();
let (gate, beta) = self.chain.gates(&alpha, &beta_raw, &self.params.dt_buffer, &self.params.a_buffer).unwrap();
exact(gate.values(), &expected_gates.0);
exact(beta.values(), &expected_gates.1);
@@ -192,16 +198,14 @@ impl<'c> Case<'c> {
}
fn recurrence_oracle(&self, fw: &Forward) -> (Box<[f32]>, Box<[f32]>) {
recur(
self.ctx,
self.prior.values(),
&fw.expected_qk[..2048],
&fw.expected_qk[2048..4096],
&fw.expected_conv.1[4096..],
&fw.expected_gates.0,
&fw.expected_gates.1,
)
.unwrap()
let operands = RecurrenceOperands {
q: &fw.expected_qk[..2048],
k: &fw.expected_qk[2048..4096],
v: &fw.expected_conv.1[4096..],
gate: &fw.expected_gates.0,
beta: &fw.expected_gates.1,
};
recur(self.ctx, self.prior.values(), operands).unwrap()
}
// The retained recurrence candidate for `scope`, from the actual recurrence kernel.
@@ -241,8 +245,8 @@ impl<'c> Case<'c> {
fn normalized(&mut self, readout: &Product, expected_recur: &(Box<[f32]>, Box<[f32]>)) -> (Product, Box<[f32]>) {
let (z, expected_z) = pair_projection(&mut self.chain, &self.source, &self.input, Role::Z, 3);
let expected_normalized =
out_norm(self.ctx, &expected_recur.1, &expected_z, &self.params.gamma, 1e-6, None).unwrap();
let scale = OutNormScale { gamma: &self.params.gamma, resident: None, epsilon: 1e-6 };
let expected_normalized = out_norm(self.ctx, &expected_recur.1, &expected_z, scale).unwrap();
let normalized = self.chain.out_norm(readout, &z, &self.params.gamma_buffer, 1e-6).unwrap();
exact(normalized.values(), &expected_normalized);
(normalized, expected_normalized)
@@ -12,6 +12,12 @@ pub(in crate::qwen_forward) struct ChunkEdge {
verified: Option<Rc<super::verification::VerifiedRow>>,
}
/// The device buffer a recurrence step wrote its readout to, with the finite values read back from it.
struct ReadoutDownload<'ctx> {
buffer: Option<DeviceBuffer<'ctx>>,
values: Box<[f32]>,
}
pub(super) struct ChunkReadout<'ctx> {
context: &'ctx Context<'ctx>,
failed: Rc<Cell<bool>>,
@@ -65,10 +65,10 @@ impl<'ctx> GdnChunkDevice<'ctx> {
&self,
row: &GdnChunkRow,
scope: Rc<()>,
buffer: Option<DeviceBuffer<'ctx>>,
values: Box<[f32]>,
download: ReadoutDownload<'ctx>,
verification: Option<Rc<std::cell::RefCell<super::super::super::verification::Workspace<'ctx>>>>,
) -> ChunkReadout<'ctx> {
let ReadoutDownload { buffer, values } = download;
ChunkReadout {
context: self.context,
failed: self.failed.clone(),
@@ -97,7 +97,7 @@ impl<'ctx> GdnChunkDevice<'ctx> {
match result {
Ok(values) => {
self.inflight = true;
Ok(self.minted_readout(row, scope, output.take(), values, None))
Ok(self.minted_readout(row, scope, ReadoutDownload { buffer: output.take(), values }, None))
}
Err(primary) => {
self.note(primary);
@@ -169,7 +169,8 @@ impl<'ctx> GdnChunkDevice<'ctx> {
Ok(values) => {
self.inflight = true;
let verification = self.verification.as_ref().map(|(workspace, _)| workspace.clone());
Ok(self.minted_readout(row, scope, output.take(), values, verification))
let download = ReadoutDownload { buffer: output.take(), values };
Ok(self.minted_readout(row, scope, download, verification))
}
Err(primary) => {
self.note(primary);
@@ -217,12 +218,15 @@ impl<'ctx> GdnChunkDevice<'ctx> {
products: [&DeviceBuffer<'ctx>; 4],
output: &mut Option<DeviceBuffer<'ctx>>,
) -> Result<Box<[f32]>> {
let buffers = super::super::super::verification::VerifiedRowBuffers {
state: Self::step_source(&self.initial, self.cursor, &self.state)?,
products,
next: self.next.as_mut().ok_or(Error::IdentityMismatch)?,
readout: output.as_mut().ok_or(Error::IdentityMismatch)?,
};
super::super::super::verification::compute_row(
self.context,
Self::step_source(&self.initial, self.cursor, &self.state)?,
products,
self.next.as_mut().ok_or(Error::IdentityMismatch)?,
output.as_mut().ok_or(Error::IdentityMismatch)?,
buffers,
self.guard.as_mut().ok_or(Error::IdentityMismatch)?,
)
}
@@ -8,31 +8,28 @@ use leleka_cuda_driver::GdnFusedT1;
use std::{cell::RefCell, rc::Rc};
impl GdnStage {
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn step_chunk_fused<'ctx>(
binding: &ModelBinding,
layer: LayerId,
input: &ResidualReady,
txn: &mut QwenStepTxn,
layer_input: GdnLayerInput<'_>,
mut device_row: DeviceChunkRow<'_, 'ctx>,
cache: &DenseWeightCache<'ctx>,
owner: &mut chunk_device::GdnChunkDevice<'ctx>,
row: GdnChunkRow,
program: Rc<RefCell<GdnFusedT1<'ctx>>>,
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
source: ProjectedQkvSource<'_, '_, '_, '_>,
) -> Result<ChunkReady> {
#[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);
check_fused_step(binding, layer, input, txn, &row)?;
let current = txn.cuda_context()?;
let GdnLayerInput { binding, layer, input } = layer_input;
check_fused_step(binding, layer, input, source.txn, &device_row.row)?;
let current = source.txn.cuda_context()?;
preflight_budget(current.budget_bytes(), current.allocated_bytes())?;
let context = prepare_fused_owner(binding, cache, current, owner, &row, &program)?;
let context = prepare_fused_owner(binding, cache, current, &mut device_row, &program)?;
let env = open_fused_env(binding, layer, input, cache, context)?;
let mut chain = env.new_chain()?;
if let Some(pool) = owner.verification_pool(&row)? {
if let Some(pool) = device_row.owner.verification_pool(&device_row.row)? {
chain.set_verification_pool(pool)?;
}
let operation = env.fused_row(&mut chain, owner, &row, &program, txn, projection);
let operation = env.fused_row(&mut chain, &mut device_row, &program, source);
let DeviceChunkRow { owner, row } = device_row;
settle_row(env, chain, operation, owner, row)
}
}
@@ -53,14 +50,13 @@ fn prepare_fused_owner<'ctx>(
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
current: &Context<'_>,
owner: &mut chunk_device::GdnChunkDevice<'ctx>,
row: &GdnChunkRow,
device_row: &mut DeviceChunkRow<'_, 'ctx>,
program: &Rc<RefCell<GdnFusedT1<'ctx>>>,
) -> Result<&'ctx Context<'ctx>> {
let context = cache.retained_context(binding, current)?;
owner.validate_row(row, &binding.identity(), context)?;
if owner.is_verification() {
owner.bind_native_fused(row, program.clone())?;
device_row.owner.validate_row(&device_row.row, &binding.identity(), context)?;
if device_row.owner.is_verification() {
device_row.owner.bind_native_fused(&device_row.row, program.clone())?;
}
Ok(context)
}
@@ -90,21 +86,20 @@ impl<'a, 'ctx> RowEnv<'a, 'ctx> {
fn fused_row(
&self,
chain: &mut chain::Chain<'ctx>,
owner: &mut chunk_device::GdnChunkDevice<'ctx>,
row: &GdnChunkRow,
device_row: &mut DeviceChunkRow<'_, 'ctx>,
program: &Rc<RefCell<GdnFusedT1<'ctx>>>,
txn: &QwenStepTxn<'_, '_>,
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
source: ProjectedQkvSource<'_, '_, '_, '_>,
) -> Result<CandidatePair> {
let ProjectedQkvSource { txn, projection } = source;
let operands = self.fused_operands(chain, txn, projection)?;
let (next_history, normalized) = self.fused_drain(chain, owner, row, program, &operands)?;
let (next_history, normalized) = self.fused_drain(chain, device_row, program, &operands)?;
let (matrix, kind) = self.cache.gdn_matrix(self.resident, GdnMatrixRole::Out)?;
let output = chain.project_out_device(matrix, kind, &normalized)?.into_values();
validate_values(&output, 2560)?;
// Repeat actual row/current transaction before marking its real
// completed candidate in-flight. No host values mint row authority.
self.recheck_fused_step(txn)?;
owner.complete_native_fused_step(row)?;
device_row.owner.complete_native_fused_step(&device_row.row)?;
Ok((next_history.into_values(), output))
}
fn recheck_fused_step(&self, txn: &QwenStepTxn<'_, '_>) -> Result<()> {
@@ -129,19 +124,13 @@ impl<'a, 'ctx> RowEnv<'a, 'ctx> {
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
) -> Result<FusedOperands<'_, 'ctx>> {
let qkv = if let Some(projection) = projection {
chain.import_projected_qkv(projection, self.binding, self.cache, txn, self.layer, self.input)?
chain.import_projected_qkv(projection, self.layer_input(), self.cache, txn)?
} else {
self.project(chain, GdnMatrixRole::Qkv)?
};
let w_alpha = self.bf16_matrix(GdnMatrixRole::Alpha)?;
let w_beta = self.bf16_matrix(GdnMatrixRole::Beta)?;
let mixed = self.input_lease.buffer(
&self.binding.identity(),
self.context,
self.layer.get(),
GdnMatrixRole::Z,
self.input.mixed(),
)?;
let mixed = self.leased_activation(GdnMatrixRole::Z)?;
let (z_matrix, z_kind) = self.cache.gdn_matrix(self.resident, GdnMatrixRole::Z)?;
let z = chain.project_device(z_matrix, z_kind, mixed, chain::Role::Z)?;
Ok(FusedOperands { qkv, z, w_alpha, w_beta, mixed })
@@ -149,11 +138,11 @@ impl<'a, 'ctx> RowEnv<'a, 'ctx> {
fn fused_drain(
&self,
chain: &mut chain::Chain<'ctx>,
owner: &chunk_device::GdnChunkDevice<'ctx>,
row: &GdnChunkRow,
device_row: &DeviceChunkRow<'_, 'ctx>,
program: &Rc<RefCell<GdnFusedT1<'ctx>>>,
operands: &FusedOperands<'_, 'ctx>,
) -> Result<(chain::Product, chain::DeviceProduct)> {
let (owner, row) = (&*device_row.owner, &device_row.row);
let (state, next) = owner.native_fused_operands(row)?;
let mut program = program.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
program.validate_context(self.context).map_err(driver_error)?;
@@ -2,7 +2,7 @@
//! Tagged cfg(test) rows below deliberately do not attest production all48 seals.
use super::super::super::contract::{Dimension, LayerId};
use super::super::super::session::chunk::TestGdnComponentRows;
use super::super::{convolve, recur};
use super::super::{RecurrenceOperands, convolve, recur};
use super::*;
use leleka_cuda_driver::Driver;
@@ -16,6 +16,15 @@ struct Fixture {
rival: TestGdnComponentRows,
}
// One row whose recurrence just ran: its position in the chunk, the row and chain scope, and the readout still to be
// compared with the reference.
struct ComputedRow<'a, 'c> {
index: usize,
row: &'a GdnChunkRow,
scope: &'a Rc<()>,
readout: ChunkReadout<'c>,
}
impl Fixture {
fn new(context: &Context<'_>) -> Result<Self> {
let binding = BindingIdentity::test_identity(); // Tag only; never a fake pinned ModelBinding.
@@ -80,7 +89,8 @@ impl Fixture {
let row = self.rows.row(index)?;
let scope = Rc::new(());
let readout = owner.compute(&row, scope.clone(), [&p.q, &p.k, &h[4096..], &p.gate, &p.beta])?;
self.check_readout(context, owner, (index, &row, &scope), readout, counts)?;
let computed = ComputedRow { index, row: &row, scope: &scope, readout };
self.check_readout(context, owner, computed, counts)?;
Ok((row, history))
}
@@ -89,10 +99,10 @@ impl Fixture {
&self,
context: &'c Context<'c>,
owner: &mut GdnChunkDevice<'c>,
(index, row, scope): (usize, &GdnChunkRow, &Rc<()>),
readout: ChunkReadout<'c>,
computed: ComputedRow<'_, 'c>,
counts: &mut Counts,
) -> Result<()> {
let ComputedRow { index, row, scope, readout } = computed;
require(owner.cursor == index && owner.inflight)?;
require(
owner.validate_row(&self.rows.row(index)?, &self.binding, context).err() == Some(Error::IdentityMismatch),
@@ -4,6 +4,12 @@
#[allow(unused_imports)]
use super::*;
impl Operands {
// The five recurrence operands of this row, with the value operand taken from the convolution output.
fn recurrence<'a>(&'a self, v: &'a [f32]) -> RecurrenceOperands<'a> {
RecurrenceOperands { q: &self.q, k: &self.k, v, gate: &self.gate, beta: &self.beta }
}
}
pub(super) fn operands(row: usize) -> Operands {
Operands {
q: (0..2048).map(|i| ((i + row * 3) % 17) as f32 / 128.0 - 0.0625).collect(),
@@ -44,7 +50,7 @@ pub(super) fn reference(context: &Context<'_>, prior: &GdnPrior) -> Result<Refer
// Actual unchanged convolution and recurrence FIRST for every row.
let (next_history, h) = convolve(context, &history, &convolution_input(row), &weights, None)?;
let p = operands(row);
let (next, readout) = recur(context, &state, &p.q, &p.k, &h[4096..], &p.gate, &p.beta)?;
let (next, readout) = recur(context, &state, p.recurrence(&h[4096..]))?;
state = next;
history = next_history;
readouts.push(readout);
@@ -66,24 +66,21 @@ pub(super) fn check_input_origin(
txn.validate_input(input.identity().token(), input.identity().position())
}
impl GdnStage {
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn step_chunk<'ctx>(
binding: &ModelBinding,
layer: LayerId,
input: &ResidualReady,
txn: &mut QwenStepTxn,
layer_input: GdnLayerInput<'_>,
device_row: DeviceChunkRow<'_, 'ctx>,
cache: &DenseWeightCache<'ctx>,
owner: &mut chunk_device::GdnChunkDevice<'ctx>,
row: GdnChunkRow,
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, 'ctx>>,
source: ProjectedQkvSource<'_, '_, '_, 'ctx>,
) -> Result<ChunkReady> {
#[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 GdnLayerInput { binding, layer, input } = layer_input;
let txn = source.txn;
txn.validate_binding(&binding.identity())?;
check_gdn_layer(binding, layer, input, false)?;
check_input_origin(binding, layer, input, txn)?;
if row.identity() != input.identity() {
if device_row.row.identity() != input.identity() {
return Err(Error::IdentityMismatch);
}
validate_values(input.mixed(), 2560)?;
@@ -91,10 +88,10 @@ impl GdnStage {
preflight_budget(context.budget_bytes(), context.allocated_bytes())?;
// Explicit opt-in only: the closed one-drain queue never replaces the
// scalar chain for verification rows or without the retained QK slot.
if owner.row_queue_enabled() && cache.has_gdn_qk_workspace() {
return step_chain_queued(binding, layer, input, owner, row, context, cache, txn, projection);
if device_row.owner.row_queue_enabled() && cache.has_gdn_qk_workspace() {
return step_chain_queued(layer_input, device_row, cache, source);
}
step_chain(binding, layer, input, owner, row, context, cache, txn, projection)
step_chain(layer_input, device_row, cache, source)
}
}
// Everything one chunk row resolves from the cache before its chain runs.
@@ -112,14 +109,13 @@ pub(super) struct RowEnv<'a, 'ctx> {
}
impl<'a, 'ctx> RowEnv<'a, 'ctx> {
fn open(
binding: &'a ModelBinding,
layer: LayerId,
input: &'a ResidualReady,
layer_input: GdnLayerInput<'a>,
cache: &'a DenseWeightCache<'ctx>,
current_context: &Context<'_>,
owner: &chunk_device::GdnChunkDevice<'ctx>,
row: &GdnChunkRow,
) -> Result<Self> {
let GdnLayerInput { binding, layer, input } = layer_input;
let context = cache.retained_context(binding, current_context)?;
let failed = cache.transport_failure_flag(binding, context)?;
let resident = cache.gdn(binding, layer.get())?;
@@ -136,29 +132,35 @@ impl<'a, 'ctx> RowEnv<'a, 'ctx> {
chain.validate(self.context, &self.binding.identity(), self.input.identity())?;
Ok(chain)
}
/// The layer and residual this row steps, as the group the chain importers and checks take.
pub(super) fn layer_input(&self) -> GdnLayerInput<'a> {
GdnLayerInput { binding: self.binding, layer: self.layer, input: self.input }
}
fn leased_projection(&self) -> LeasedProjection<'_, 'a, 'a, 'ctx> {
LeasedProjection {
binding: self.binding,
weights: &self.weights,
activation: self.input.mixed(),
lease: &self.input_lease,
cache: self.cache,
}
}
/// The device copy of this row's activation held by the input lease, for the projection `role`.
pub(super) fn leased_activation(&self, role: GdnMatrixRole) -> Result<&DeviceBuffer<'ctx>> {
let binding = self.binding.identity();
let claim = LeaseClaim {
binding: &binding,
context: self.context,
layer: self.layer.get(),
source: self.input.mixed(),
};
self.input_lease.buffer(&claim, role)
}
pub(super) fn project(&self, chain: &mut chain::Chain<'ctx>, role: GdnMatrixRole) -> Result<chain::Product> {
project_chain_input(
chain,
self.context,
self.binding,
&self.weights,
role,
&self.input_lease,
self.input.mixed(),
self.cache,
)
project_chain_input(chain, self.context, &self.leased_projection(), role)
}
fn project_device(&self, chain: &mut chain::Chain<'ctx>, role: GdnMatrixRole) -> Result<chain::DeviceOperand> {
project_device_input(
chain,
self.context,
self.binding,
&self.weights,
role,
&self.input_lease,
self.input.mixed(),
self.cache,
)
project_device_input(chain, self.context, &self.leased_projection(), role)
}
}
// The common tail of every chunk row: latch a CUDA refusal, close the chain, release the input lease, and either
@@ -189,17 +191,14 @@ pub(super) fn settle_row<'ctx>(
}
// Device-only projection: the same pre-checks and library call as
// `project_chain_input`, but no host readback; the finite scan is queued.
#[allow(clippy::too_many_arguments)] // Explicit closed provider and current input-lease checks.
fn project_device_input<'ctx>(
chain: &mut chain::Chain<'ctx>,
context: &Context<'_>,
binding: &ModelBinding,
weights: &GdnWeights,
operands: &LeasedProjection<'_, '_, '_, 'ctx>,
role: GdnMatrixRole,
source: &GdnInputLease<'_, '_, 'ctx>,
activation: &[f32],
cache: &DenseWeightCache<'ctx>,
) -> Result<chain::DeviceOperand> {
// Explicit closed provider and current input-lease checks.
let LeasedProjection { binding, weights, activation, lease: source, cache } = *operands;
let output_role = match role {
GdnMatrixRole::Alpha => chain::Role::Alpha,
GdnMatrixRole::Beta => chain::Role::BetaRaw,
@@ -208,7 +207,8 @@ fn project_device_input<'ctx>(
};
let (columns, _rows) = weights.shape(role);
validate_values(activation, columns)?;
let activation = source.buffer(&binding.identity(), context, weights.layer(), role, activation)?;
let claim = LeaseClaim { binding: &binding.identity(), context, layer: weights.layer(), source: activation };
let activation = source.buffer(&claim, role)?;
let resident = cache.gdn(binding, weights.layer())?;
if !std::ptr::eq(resident.weights.as_ref(), weights) {
return Err(Error::IdentityMismatch);
@@ -6,24 +6,21 @@ use super::*;
// beta and Z are projected first (they depend only on the current input) and
// stay on device; QKV keeps the scalar chain's import. Anything refused, at any
// point, leaves the row refused exactly as the scalar chain would.
#[allow(clippy::too_many_arguments)]
pub(super) fn step_chain_queued<'ctx>(
binding: &ModelBinding,
layer: LayerId,
input: &ResidualReady,
owner: &mut chunk_device::GdnChunkDevice<'ctx>,
row: super::super::super::session::chunk::GdnChunkRow,
current_context: &Context<'_>,
layer_input: GdnLayerInput<'_>,
mut device_row: DeviceChunkRow<'_, 'ctx>,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
projection: Option<&mut super::super::super::q6_attention_columns::ProjectionRow<'_, 'ctx>>,
source: ProjectedQkvSource<'_, '_, '_, 'ctx>,
) -> Result<ChunkReady> {
let env = RowEnv::open(binding, layer, input, cache, current_context, owner, &row)?;
let GdnLayerInput { binding, input, .. } = layer_input;
let current_context = source.txn.cuda_context()?;
let env = RowEnv::open(layer_input, cache, current_context, &*device_row.owner, &device_row.row)?;
let mut chain = env.new_chain()?;
chain.set_qk_workspace(cache.gdn_qk_workspace(binding, env.context, input.identity())?)?;
let mut queue = owner.take_row_queue()?;
let operation = env.queued_row(&mut chain, owner, &mut queue, &row, txn, projection);
owner.put_row_queue(queue);
let mut queue = device_row.owner.take_row_queue()?;
let operation = env.queued_row(&mut chain, &mut device_row, &mut queue, source);
device_row.owner.put_row_queue(queue);
let DeviceChunkRow { owner, row } = device_row;
settle_row(env, chain, operation, owner, row)
}
// Retained device rows (opt-in `project_retained`) never touch the host; host
@@ -55,17 +52,16 @@ impl<'a, 'ctx> RowEnv<'a, 'ctx> {
fn queued_row(
&self,
chain: &mut chain::Chain<'ctx>,
owner: &mut chunk_device::GdnChunkDevice<'ctx>,
device_row: &mut DeviceChunkRow<'_, 'ctx>,
queue: &mut GdnRowQueue<'ctx>,
row: &GdnChunkRow,
txn: &QwenStepTxn<'_, '_>,
projection: Option<&mut super::super::super::q6_attention_columns::ProjectionRow<'_, 'ctx>>,
source: ProjectedQkvSource<'_, '_, '_, 'ctx>,
) -> Result<CandidatePair> {
let operands = self.queued_operands(chain, owner, txn, projection)?;
let queued = self.queued_drain(chain, owner, queue, row, &operands)?;
let ProjectedQkvSource { txn, projection } = source;
let operands = self.queued_operands(chain, &*device_row.owner, txn, projection)?;
let queued = self.queued_drain(chain, device_row, queue, &operands)?;
// The recurrence completed inside the clean drain; only now does the
// row own an in-flight step that `finish_row` may seal.
owner.complete_queued_step(row)?;
device_row.owner.complete_queued_step(&device_row.row)?;
let output = self.queued_output(chain, &queued.normalized)?;
Ok((queued.next_history.into_values(), output))
}
@@ -98,26 +94,20 @@ impl<'a, 'ctx> RowEnv<'a, 'ctx> {
self.input,
super::super::super::q6_attention_columns::Role::GdnQkv,
)?),
Some(projection) => QueuedQkv::Host(chain.import_projected_qkv(
projection,
self.binding,
self.cache,
txn,
self.layer,
self.input,
)?),
Some(projection) => {
QueuedQkv::Host(chain.import_projected_qkv(projection, self.layer_input(), self.cache, txn)?)
}
None => QueuedQkv::Host(self.project(chain, GdnMatrixRole::Qkv)?),
})
}
fn queued_drain(
&self,
chain: &mut chain::Chain<'ctx>,
owner: &chunk_device::GdnChunkDevice<'ctx>,
device_row: &DeviceChunkRow<'_, 'ctx>,
queue: &mut GdnRowQueue<'ctx>,
row: &GdnChunkRow,
operands: &QueuedOperands<'ctx>,
) -> Result<chain::QueuedRow> {
let (state, next_state) = owner.queue_operands(row)?;
let (state, next_state) = device_row.owner.queue_operands(&device_row.row)?;
let qkv = operands.qkv.as_input()?;
chain.run_row_queue(
queue,
@@ -1,44 +1,41 @@
//! The scalar (decomposed) chunk row of the GDN producer: one chain, host readbacks between the stages.
use super::*;
#[allow(clippy::too_many_arguments)]
pub(super) fn step_chain<'ctx>(
binding: &ModelBinding,
layer: LayerId,
input: &ResidualReady,
owner: &mut chunk_device::GdnChunkDevice<'ctx>,
row: super::super::super::session::chunk::GdnChunkRow,
current_context: &Context<'_>,
layer_input: GdnLayerInput<'_>,
mut device_row: DeviceChunkRow<'_, 'ctx>,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
projection: Option<&mut super::super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
source: ProjectedQkvSource<'_, '_, '_, '_>,
) -> Result<ChunkReady> {
let env = RowEnv::open(binding, layer, input, cache, current_context, owner, &row)?;
let GdnLayerInput { binding, input, .. } = layer_input;
let current_context = source.txn.cuda_context()?;
let env = RowEnv::open(layer_input, cache, current_context, &*device_row.owner, &device_row.row)?;
let mut chain = env.new_chain()?;
if let Some(pool) = owner.verification_pool(&row)? {
if let Some(pool) = device_row.owner.verification_pool(&device_row.row)? {
chain.set_verification_pool(pool)?;
} else if cache.has_gdn_qk_workspace() {
chain.set_qk_workspace(cache.gdn_qk_workspace(binding, env.context, input.identity())?)?;
}
let operation = env.scalar_row(&mut chain, owner, &row, txn, projection);
let operation = env.scalar_row(&mut chain, &mut device_row, source);
let DeviceChunkRow { owner, row } = device_row;
settle_row(env, chain, operation, owner, row)
}
impl<'a, 'ctx> RowEnv<'a, 'ctx> {
fn scalar_row(
&self,
chain: &mut chain::Chain<'ctx>,
owner: &mut chunk_device::GdnChunkDevice<'ctx>,
row: &GdnChunkRow,
txn: &QwenStepTxn<'_, '_>,
projection: Option<&mut super::super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
device_row: &mut DeviceChunkRow<'_, 'ctx>,
source: ProjectedQkvSource<'_, '_, '_, '_>,
) -> Result<CandidatePair> {
let (next_history, h, qk) = self.scalar_convolution(chain, owner, txn, projection)?;
let ProjectedQkvSource { txn, projection } = source;
let (next_history, h, qk) = self.scalar_convolution(chain, &*device_row.owner, txn, projection)?;
let (gate, beta) = self.scalar_gates(chain)?;
let history = next_history.into_values();
// Keep the genuine completed producers and every original full finite
// host witness. This consuming borrow cannot outlive/reuse its chain,
// row or epoch; it replaces only five redundant recurrence H2D copies.
let readout = self.scalar_recurrence(chain, owner, row, [&qk, &h, &gate, &beta])?;
let readout =
self.scalar_recurrence(chain, &mut *device_row.owner, &device_row.row, [&qk, &h, &gate, &beta])?;
let output = self.scalar_output(chain, &readout)?;
Ok((history, output))
}
@@ -52,7 +49,7 @@ impl<'a, 'ctx> RowEnv<'a, 'ctx> {
let qkv = if let Some(projection) = projection {
// Closed actual producer import; extra H2D remains explicit.
// Raw upload still rejects every computed output role.
chain.import_projected_qkv(projection, self.binding, self.cache, txn, self.layer, self.input)?
chain.import_projected_qkv(projection, self.layer_input(), self.cache, txn)?
} else {
self.project(chain, GdnMatrixRole::Qkv)?
};
@@ -138,13 +138,13 @@ fn compare(a: &Arm, b: &Arm) -> Result<(usize, usize)> {
Ok((differences, words))
}
// The loaded caches and the session every arm of the proof runs against.
struct Harness<'a, 'ctx, 'k> {
binding: &'a ModelBinding,
context: &'a Rc<Context<'ctx>>,
session: &'a mut QwenSession<'ctx>,
kar: &'a mut KarPleCache<'k>,
moe: &'a mut MoeWeightCache<'ctx>,
dense: &'a DenseWeightCache<'ctx>,
pub(crate) struct Harness<'a, 'ctx, 'k> {
pub(crate) binding: &'a ModelBinding,
pub(crate) context: &'a Rc<Context<'ctx>>,
pub(crate) session: &'a mut QwenSession<'ctx>,
pub(crate) kar: &'a mut KarPleCache<'k>,
pub(crate) moe: &'a mut MoeWeightCache<'ctx>,
pub(crate) dense: &'a DenseWeightCache<'ctx>,
}
fn arm(
@@ -293,16 +293,8 @@ fn gdn_row(
impl QwenForward {
/// Callable after ONE genuine binding admission/eager cache load. It does
/// not rehash/load the archive or construct a source witness.
pub(crate) fn test_gdn_four_borrow_on_loaded<'ctx>(
binding: &ModelBinding,
context: &Rc<Context<'ctx>>,
session: &mut QwenSession<'ctx>,
kar: &mut KarPleCache<'_>,
moe: &mut MoeWeightCache<'ctx>,
dense: &DenseWeightCache<'ctx>,
) -> Result<FourBorrowReport> {
let (initial, allocated) = loaded_baseline(binding, context, session, moe, dense)?;
let mut h = Harness { binding, context, session, kar, moe, dense };
pub(crate) fn test_gdn_four_borrow_on_loaded(mut h: Harness<'_, '_, '_>) -> Result<FourBorrowReport> {
let (initial, allocated) = loaded_baseline(h.binding, h.context, &mut *h.session, &mut *h.moe, h.dense)?;
let pair = reference_pair(&mut h, &initial)?;
let (cancelled, cancelled_unchanged) = cancelled_arm(&mut h, &initial)?;
let (reset_recovered, compared, recovery_foreign_refused) =
@@ -313,7 +305,7 @@ impl QwenForward {
foreign_refused: pair.foreign_refused(recovery_foreign_refused),
cancelled,
original_unchanged: pair.unchanged && cancelled_unchanged,
allocated_unchanged: allocated == context.allocated_bytes(),
allocated_unchanged: allocated == h.context.allocated_bytes(),
reset_recovered,
})
}
@@ -11,7 +11,6 @@
//! clean complete drain). Nothing about the prompt/chunk path changes.
use super::chain::{FusedInputs, Role};
use super::chunk_producer::RowEnv;
use super::mirror::MirrorNext;
use super::*;
use leleka_cuda_driver::GdnFusedT1;
@@ -19,20 +18,18 @@ impl GdnStage {
/// The selected T1 target step on the fused Original path. `fused` is the model-lifetime closed program owner
/// (create and charge it with the other batched owners; `GDN_FUSED_T1_PERSISTENT_BYTES`). Requires the retained
/// cache (the fused path has no cacheless form) and the BF16 alpha/beta matrices the Original kernel reads raw.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn step_fused<'ctx>(
binding: &ModelBinding,
layer: LayerId,
input: &ResidualReady,
layer_input: GdnLayerInput<'_>,
prior: &GdnPrior,
txn: &mut QwenStepTxn,
cache: &DenseWeightCache<'ctx>,
fused: &mut GdnFusedT1<'ctx>,
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
source: ProjectedQkvSource<'_, '_, '_, '_>,
) -> Result<GdnReady> {
#[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 GdnLayerInput { binding, layer, input } = layer_input;
let txn = source.txn;
Self::check_fused_layer(binding, layer, input, txn)?;
input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?;
txn.validate_input(input.identity().token(), input.identity().position())?;
@@ -40,7 +37,7 @@ impl GdnStage {
validate_values(input.mixed(), 2560)?;
let context = txn.cuda_context()?;
preflight_budget(context.budget_bytes(), context.allocated_bytes())?;
step_cached_fused(binding, layer, input, prior, context, cache, txn, projection, fused)
step_cached_fused(layer_input, prior, cache, source, fused)
}
// The transaction is bound to the model, and the layer is the input's own GDN layer of that binding.
@@ -63,18 +60,16 @@ impl GdnStage {
}
}
#[allow(clippy::too_many_arguments)]
fn step_cached_fused<'ctx>(
binding: &ModelBinding,
layer: LayerId,
input: &ResidualReady,
layer_input: GdnLayerInput<'_>,
prior: &GdnPrior,
current_context: &Context<'_>,
cache: &DenseWeightCache<'ctx>,
txn: &QwenStepTxn<'_, '_>,
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
source: ProjectedQkvSource<'_, '_, '_, '_>,
fused: &mut GdnFusedT1<'ctx>,
) -> Result<GdnReady> {
let GdnLayerInput { binding, layer, input } = layer_input;
let ProjectedQkvSource { txn, projection } = source;
let current_context = txn.cuda_context()?;
let context = cache.retained_context(binding, current_context)?;
let failed = cache.transport_failure_flag(binding, context)?;
let resident = cache.gdn(binding, layer.get())?;
@@ -84,9 +79,9 @@ fn step_cached_fused<'ctx>(
let input_lease = cache.gdn_input(binding, layer.get(), context, input.mixed())?;
let env = RowEnv { binding, layer, input, cache, context, resident, weights, aux, input_lease, failed };
let mut chain = env.new_chain()?;
let mut mirror_next = None;
let operation = env.cached_fused_row(&mut chain, &mut mirror, prior, (txn, projection), (fused, &mut mirror_next));
settle_cached_fused(env, chain, &mut mirror, mirror_next, operation)
let mut step = MirrorStep { mirror: &mut mirror, prior, candidate: None };
let operation = env.cached_fused_row(&mut chain, &mut step, ProjectedQkvSource { txn, projection }, fused);
settle_cached_fused(env, chain, step, operation)
}
// The common tail: latch a CUDA refusal, close the chain, release the input lease, then publish the candidate or
@@ -94,10 +89,10 @@ fn step_cached_fused<'ctx>(
fn settle_cached_fused<'ctx>(
env: RowEnv<'_, 'ctx>,
chain: chain::Chain<'ctx>,
mirror: &mut GdnStateMirror<'ctx>,
mut mirror_next: Option<MirrorNext<'ctx>>,
step: MirrorStep<'_, 'ctx>,
operation: Result<(Box<[f32]>, Box<[f32]>)>,
) -> Result<GdnReady> {
let MirrorStep { mirror, candidate: mut mirror_next, .. } = step;
if matches!(operation, Err(Error::CudaExecution)) {
env.failed.set(true);
}
@@ -130,19 +125,17 @@ impl<'a, 'ctx> RowEnv<'a, 'ctx> {
fn cached_fused_row(
&self,
chain: &mut chain::Chain<'ctx>,
mirror: &mut GdnStateMirror<'ctx>,
prior: &GdnPrior,
(txn, projection): (
&QwenStepTxn<'_, '_>,
Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
),
(fused, mirror_next): (&mut GdnFusedT1<'ctx>, &mut Option<MirrorNext<'ctx>>),
step: &mut MirrorStep<'_, 'ctx>,
source: ProjectedQkvSource<'_, '_, '_, '_>,
fused: &mut GdnFusedT1<'ctx>,
) -> Result<(Box<[f32]>, Box<[f32]>)> {
let ProjectedQkvSource { txn, projection } = source;
let ops = self.cached_operands(chain, txn, projection)?;
let (row, next) = mirror.with_fused_candidate(prior, |resident_state, next_state| {
let prior = step.prior;
let (row, next) = step.mirror.with_fused_candidate(prior, |resident_state, next_state| {
chain.run_fused_row(fused, resident_state, next_state, self.cached_inputs(prior, &ops))
})?;
*mirror_next = Some(next);
step.candidate = Some(next);
let (matrix, kind) = self.cache.gdn_matrix(self.resident, GdnMatrixRole::Out)?;
let output = chain.project_out_device(matrix, kind, &row.normalized)?.into_values();
validate_values(&output, 2560)?;
@@ -157,18 +150,12 @@ impl<'a, 'ctx> RowEnv<'a, 'ctx> {
let (w_alpha, w_beta) = self.fused_matrices()?;
let qkv = if let Some(projection) = projection {
// Closed actual producer import; the host-validated QKV product is unchanged.
chain.import_projected_qkv(projection, self.binding, self.cache, txn, self.layer, self.input)?
chain.import_projected_qkv(projection, self.layer_input(), self.cache, txn)?
} else {
self.project(chain, GdnMatrixRole::Qkv)?
};
// The same device activation serves Z (a GEMV) and the fused alpha/beta kernel (`mixed`).
let mixed = self.input_lease.buffer(
&self.binding.identity(),
self.context,
self.layer.get(),
GdnMatrixRole::Z,
self.input.mixed(),
)?;
let mixed = self.leased_activation(GdnMatrixRole::Z)?;
let (z_matrix, z_kind) = self.cache.gdn_matrix(self.resident, GdnMatrixRole::Z)?;
// Z stays on device; the closed program scans it before any consumer reads it.
let z = chain.project_device(z_matrix, z_kind, mixed, Role::Z)?;
@@ -1,6 +1,6 @@
//! One actor-owned activation slot; every layer lease copies its immutable source.
use super::{
BindingIdentity, Context, DeviceBuffer, Error, GdnMatrixRole, Result, driver_error, preflight_budget,
BindingIdentity, Context, DeviceBuffer, Error, GdnMatrixRole, LeaseClaim, Result, driver_error, preflight_budget,
validate_values,
};
use std::{
@@ -109,14 +109,8 @@ impl<'ctx> GdnInputLease<'_, '_, 'ctx> {
}
Ok(&self.slot.buffer)
}
pub(super) fn buffer(
&self,
binding: &BindingIdentity,
context: &Context<'_>,
layer: u32,
role: GdnMatrixRole,
source: &[f32],
) -> Result<&DeviceBuffer<'ctx>> {
pub(super) fn buffer(&self, claim: &LeaseClaim<'_, '_>, role: GdnMatrixRole) -> Result<&DeviceBuffer<'ctx>> {
let LeaseClaim { binding, context, layer, source } = *claim;
if self.slot.failed.get() {
return Err(Error::CudaExecution);
}
@@ -69,16 +69,17 @@ fn projection_pair<'c>(
let matrix = bytes_upload(context, &bytes);
let fresh = upload(context, input).unwrap();
let mut output = allocate(context, rows).unwrap();
dispatch_projection(context, &matrix, &fresh, &mut output, GdnMatrixKind::Bf16, 2560, rows).unwrap();
let layout = GdnMatrixLayout { kind: GdnMatrixKind::Bf16, columns: 2560, rows };
dispatch_projection(context, &matrix, &fresh, &mut output, layout).unwrap();
let expected = download(&output, rows).unwrap();
output.release().unwrap();
fresh.release().unwrap();
let charged = context.allocated_bytes();
let admitted = lease.buffer(binding, context, 0, role, input).unwrap();
let admitted = lease.buffer(&LeaseClaim { binding, context, layer: 0, source: input }, role).unwrap();
let mut retained_input = vec![0; INPUT_BYTES];
admitted.copy_to(&mut retained_input).unwrap();
assert_eq!(retained_input, input.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
let actual = project_retained(context, &matrix, GdnMatrixKind::Bf16, 2560, rows, lease).unwrap();
let actual = project_retained(context, &matrix, layout, lease).unwrap();
exact(&actual, &expected);
assert_eq!(context.allocated_bytes(), charged);
let mut unchanged = vec![0; bytes.len()];
@@ -131,7 +132,8 @@ fn buffer_refusals<'c>(
(binding, context, 0, GdnMatrixRole::Qkv, copy.as_slice(), Error::IdentityMismatch),
(binding, context, 0, GdnMatrixRole::Out, input, Error::InvalidDimension),
] {
assert_eq!(lease.buffer(candidate_binding, candidate_context, layer, role, source).err(), Some(expected));
let claim = LeaseClaim { binding: candidate_binding, context: candidate_context, layer, source };
assert_eq!(lease.buffer(&claim, role).err(), Some(expected));
}
assert_eq!(lease.activation(context, 6144).err(), Some(Error::InvalidDimension));
}
@@ -144,16 +146,14 @@ fn projection_refusals<'c>(context: &'c Context<'c>, lease: &GdnInputLease<'_, '
bytes[end - 2..].copy_from_slice(&0x7fc1u16.to_le_bytes());
let matrix = bytes_upload(context, &bytes);
let charged = context.allocated_bytes();
assert_eq!(project_retained(context, &matrix, GdnMatrixKind::Bf16, 2560, 48, lease).err(), Some(Error::NonFinite));
let layout = GdnMatrixLayout { kind: GdnMatrixKind::Bf16, columns: 2560, rows: 48 };
assert_eq!(project_retained(context, &matrix, layout, lease).err(), Some(Error::NonFinite));
assert_eq!(context.allocated_bytes(), charged);
assert!(!failed.get());
matrix.release().unwrap();
let matrix = bytes_upload(context, &[0; 2]);
let charged = context.allocated_bytes();
assert_eq!(
project_retained(context, &matrix, GdnMatrixKind::Bf16, 2560, 48, lease).err(),
Some(Error::InvalidDimension)
);
assert_eq!(project_retained(context, &matrix, layout, lease).err(), Some(Error::InvalidDimension));
assert_eq!(context.allocated_bytes(), charged);
matrix.release().unwrap();
}
@@ -166,7 +166,7 @@ fn sticky_policy<'c>(
input: &[f32],
) {
let lease = GdnInputScratch::lease(scratch.borrow_mut(), binding, context, 1, input).unwrap();
assert!(lease.buffer(binding, context, 1, GdnMatrixRole::Z, input).is_ok());
assert!(lease.buffer(&LeaseClaim { binding, context, layer: 1, source: input }, GdnMatrixRole::Z).is_ok());
lease.poison(); // Exercise explicit sticky policy, not an injected CUDA fault.
assert_eq!(lease.activation(context, 2560).err(), Some(Error::CudaExecution));
drop(lease);
@@ -2,7 +2,8 @@
#[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,
check_gdn_window, gather_gdn_rows, gdn_operands, latch_cuda_failure, prepare_or_refuse, run_gdn_program,
settle_gdn, window_bytes,
};
use super::*;
@@ -40,6 +41,7 @@ impl GdnStage {
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)
latch_cuda_failure(&operation, &failed);
settle_gdn(operation, owner, micro, binding, identities)
}
}
@@ -197,20 +197,23 @@ fn launch_program<'l, 'ctx>(
prefix.project_out(out_format, ops.out, scratch, &buffers.bo)
}
/// Latches the actor-wide failure flag when CUDA execution refused the batched program.
pub(super) fn latch_cuda_failure(operation: &Result<(Box<[f32]>, Box<[f32]>)>, failed: &Cell<bool>) {
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. 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<bool>,
owner: &mut GdnChunkDevice<'ctx>,
micro: &GdnChunkMicro,
binding: &ModelBinding,
identities: Vec<TokenLayer>,
) -> Result<Vec<ChunkReady>> {
if matches!(operation, Err(Error::CudaExecution)) {
failed.set(true);
}
let (history, output) = match operation {
Ok(values) => values,
Err(primary) => {
@@ -25,25 +25,41 @@ fn format(kind: GdnMatrixKind) -> Result<GdnNativeFormat> {
GdnMatrixKind::Bf16 => return Err(Error::Unsupported(Stage::Gdn)),
})
}
/// The GDN layer a prompt block is produced for: the model binding, the retained dense cache and the device context
/// lent for this call.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct PromptLayer<'a, 'current, 'ctx> {
pub(in crate::qwen_forward) binding: &'a ModelBinding,
pub(in crate::qwen_forward) layer: LayerId,
pub(in crate::qwen_forward) cache: &'a DenseWeightCache<'ctx>,
pub(in crate::qwen_forward) current: &'a Context<'current>,
}
/// The chunk rows of a prompt block together with the device GR read their inputs come from.
pub(in crate::qwen_forward) struct PromptSource<'arena, 'loan, 'ctx> {
pub(in crate::qwen_forward) rows: Vec<GdnChunkRow>,
pub(in crate::qwen_forward) read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
}
/// The closed prompt producer with the batch workspace it runs in.
pub(in crate::qwen_forward) struct PromptProgram<'a, 'ctx> {
pub(in crate::qwen_forward) producer: &'a mut OriginalGdnPromptDevice<'ctx>,
pub(in crate::qwen_forward) workspace: &'a mut NativeBatchWorkspace<'ctx>,
}
impl GdnStage {
/// Root first authenticates every actual PromptDeviceRead transaction/role
/// and current chronological chunk phase. The genuine chunk rows below
/// remain bound to the untouched chunk start and current owner cursor.
/// Returned edges carry only true completed end-state causality, not
/// fabricated intermediate recurrent state or host readout arrays.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn produce_prompt_device<'arena, 'loan, 'ctx>(
binding: &ModelBinding,
layer: LayerId,
cache: &DenseWeightCache<'ctx>,
current: &Context<'_>,
prompt: PromptLayer<'_, '_, 'ctx>,
owner: &mut GdnChunkDevice<'ctx>,
rows: Vec<GdnChunkRow>,
read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
producer: &mut OriginalGdnPromptDevice<'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
source: PromptSource<'arena, 'loan, 'ctx>,
program: PromptProgram<'_, 'ctx>,
) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, Vec<ChunkEdge>)> {
let context = Self::admit_prompt(binding, layer, cache, current, owner, (&rows, &read))?;
let PromptLayer { binding, layer, cache, current } = prompt;
let PromptSource { rows, read } = source;
let PromptProgram { producer, workspace } = program;
let context = Self::admit_prompt(prompt, owner, (&rows, &read))?;
let failed = cache.transport_failure_flag(binding, context)?;
let resident = cache.gdn(binding, layer.get())?;
check_prompt_weights(&resident.weights)?;
@@ -61,13 +77,11 @@ impl GdnStage {
Ok((block, edges))
}
fn admit_prompt<'arena, 'loan, 'ctx>(
binding: &ModelBinding,
layer: LayerId,
cache: &DenseWeightCache<'ctx>,
current: &Context<'_>,
prompt: PromptLayer<'_, '_, 'ctx>,
owner: &GdnChunkDevice<'ctx>,
(rows, read): (&[GdnChunkRow], &OriginalDeviceGrRead<'arena, 'loan, 'ctx>),
) -> Result<&'ctx Context<'ctx>> {
let PromptLayer { binding, layer, cache, current } = prompt;
let context = cache.retained_context(binding, current)?;
cache.validate(binding)?;
if owner.is_verification() || rows.is_empty() || rows.len() != read.rows() || !read.context_matches(context) {
@@ -3,7 +3,10 @@
//! original projections) FIRST. Synthetic Context and tag identity only: this
//! is not a Binding, Session, row or model certificate.
#![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::super::{STATE_ELEMENTS, convolve, gates, normalize_qk, out_norm, recur, release, upload};
use super::super::{
GateHostOperands, OutNormScale, RecurrenceOperands, STATE_ELEMENTS, convolve, gates, normalize_qk, out_norm, recur,
release, upload,
};
use super::*;
use crate::qwen_forward::contract::{Dimension, LayerId, Position, TokenId};
use leleka_cuda_driver::{Bf16ProjectionShape, Driver};
@@ -171,12 +174,19 @@ impl<'ctx> Rig<'ctx> {
let z = original_projection(ctx, &weights.z, input, VALUES);
let conv = convolve(ctx, &data.history, &qkv, &weights.conv_host, None).unwrap();
let qk = normalize_qk(ctx, &conv.1, 1e-6).unwrap();
let gate_beta = gates(ctx, &alpha, &beta_raw, &self.host.dt, &self.host.a, None).unwrap();
let step =
recur(ctx, &data.state_values, &qk[..2048], &qk[2048..4096], &conv.1[4096..], &gate_beta.0, &gate_beta.1)
.unwrap();
let gate_host = GateHostOperands { alpha: &alpha, beta: &beta_raw, dt: &self.host.dt, a: &self.host.a };
let gate_beta = gates(ctx, gate_host, None).unwrap();
let operands = RecurrenceOperands {
q: &qk[..2048],
k: &qk[2048..4096],
v: &conv.1[4096..],
gate: &gate_beta.0,
beta: &gate_beta.1,
};
let step = recur(ctx, &data.state_values, operands).unwrap();
let readout = step.1.clone();
let normalized = out_norm(ctx, &readout, &z, &self.host.gamma, 1e-6, None).unwrap();
let scale = OutNormScale { gamma: &self.host.gamma, resident: None, epsilon: 1e-6 };
let normalized = out_norm(ctx, &readout, &z, scale).unwrap();
let out = original_projection(ctx, &weights.out, &normalized, 2560);
(conv.0, step.0, normalized, out)
}
@@ -1,7 +1,8 @@
//! One latest device recurrence per layer; immutable host state remains canonical.
use super::{
BindingIdentity, Context, DeviceBuffer, Error, GdnPending, GdnPrior, GdnStateKey, Result, STATE_ELEMENTS,
TokenLayer, VALUES, allocate, download, driver_error, preflight_budget, validate_values,
BindingIdentity, Context, DeviceBuffer, Error, GdnPending, GdnPrior, GdnStateKey, MirrorAuthority, ReadoutClaim,
RecurrenceOperands, Result, STATE_ELEMENTS, TokenLayer, VALUES, allocate, download, driver_error, preflight_budget,
validate_values,
};
use std::{cell::Cell, rc::Rc};
// In-place fused T1 candidate (STRA-169): needs the private resident buffer, key and candidate constructor.
@@ -34,6 +35,29 @@ pub(super) struct MirrorNext<'ctx> {
values: Box<[f32]>,
}
/// The device buffers one mirror step owns until it settles: transient uploads, the candidate state and the readout.
pub(super) struct StepBuffers<'ctx> {
temporary: Vec<DeviceBuffer<'ctx>>,
next: Option<DeviceBuffer<'ctx>>,
output: Option<DeviceBuffer<'ctx>>,
}
impl StepBuffers<'_> {
/// Empty buffers with room for `temporary_count` transient uploads, reserved up front.
fn with_capacity(temporary_count: usize) -> Result<Self> {
let mut temporary = Vec::new();
temporary.try_reserve_exact(temporary_count).map_err(|_| Error::InputAllocation)?;
Ok(Self { temporary, next: None, output: None })
}
}
/// What a published candidate becomes: the token layer it was computed for and the state and history values the
/// pending state is minted from.
struct PendingContents {
identity: TokenLayer,
values: Box<[f32]>,
history: Box<[f32]>,
}
/// Only the recurrence producer can pair this buffer with its finite readback.
pub(super) struct MirrorReadout<'ctx> {
context: &'ctx Context<'ctx>,
@@ -44,13 +44,9 @@ impl<'ctx> GdnStateMirror<'ctx> {
pub(in super::super::super) fn compute(
&mut self,
prior: &GdnPrior,
q: &[f32],
k: &[f32],
v: &[f32],
gate: &[f32],
beta: &[f32],
operands: RecurrenceOperands<'_>,
) -> Result<(Box<[f32]>, MirrorNext<'ctx>)> {
let (readout, next) = self.compute_inner(prior, q, k, v, gate, beta)?;
let (readout, next) = self.compute_inner(prior, operands)?;
match readout.into_host() {
Ok(values) => Ok((values, next)),
Err(primary) => {
@@ -70,7 +66,8 @@ impl<'ctx> GdnStateMirror<'ctx> {
if identity.layer() != prior.layer() || identity.position().get() != prior.next_position() {
return Err(Error::IdentityMismatch);
}
let (mut readout, next) = self.compute_inner(prior, inputs[0], inputs[1], inputs[2], inputs[3], inputs[4])?;
let [q, k, v, gate, beta] = inputs;
let (mut readout, next) = self.compute_inner(prior, RecurrenceOperands { q, k, v, gate, beta })?;
readout.identity = Some(identity);
readout.scope = Some(scope);
Ok((readout, next))
@@ -79,12 +76,9 @@ impl<'ctx> GdnStateMirror<'ctx> {
pub(in super::super) fn compute_inner(
&mut self,
prior: &GdnPrior,
q: &[f32],
k: &[f32],
v: &[f32],
gate: &[f32],
beta: &[f32],
operands: RecurrenceOperands<'_>,
) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> {
let RecurrenceOperands { q, k, v, gate, beta } = operands;
self.admit_prior(prior)?;
for (values, count) in
[(prior.values(), STATE_ELEMENTS), (q, 2048), (k, 2048), (v, VALUES), (gate, 48), (beta, 48)]
@@ -92,12 +86,9 @@ impl<'ctx> GdnStateMirror<'ctx> {
validate_values(values, count)?;
}
let hit = self.admit_resident(prior)?;
let mut temporary = Vec::new();
temporary.try_reserve_exact(7).map_err(|_| Error::InputAllocation)?;
let mut next = None;
let mut output = None;
let operation = self.step_uploaded(prior, hit, [q, k, v, gate, beta], &mut temporary, (&mut next, &mut output));
self.settle_step(prior, (None, None), operation, temporary, next, output)
let mut buffers = StepBuffers::with_capacity(7)?;
let operation = self.step_uploaded(prior, hit, [q, k, v, gate, beta], &mut buffers);
self.settle_step(prior, (None, None), operation, buffers)
}
// The failed flag and the prior's mirror admission, checked before anything else.
pub(in super::super) fn admit_prior(&self, prior: &GdnPrior) -> Result<()> {
@@ -161,9 +152,9 @@ impl<'ctx> GdnStateMirror<'ctx> {
prior: &GdnPrior,
hit: bool,
inputs: [&[f32]; 5],
temporary: &mut Vec<DeviceBuffer<'ctx>>,
(next, output): (&mut Option<DeviceBuffer<'ctx>>, &mut Option<DeviceBuffer<'ctx>>),
buffers: &mut StepBuffers<'ctx>,
) -> Result<super::super::super::CandidatePair> {
let StepBuffers { temporary, next, output } = buffers;
let first = self.upload_step_inputs(prior, hit, inputs, temporary)?;
*next = Some(allocate(self.context, STATE_ELEMENTS)?);
*output = Some(allocate(self.context, VALUES)?);
@@ -197,10 +188,9 @@ impl<'ctx> GdnStateMirror<'ctx> {
prior: &GdnPrior,
(identity, scope): (Option<TokenLayer>, Option<Rc<()>>),
operation: Result<super::super::super::CandidatePair>,
temporary: Vec<DeviceBuffer<'ctx>>,
mut next: Option<DeviceBuffer<'ctx>>,
mut output: Option<DeviceBuffer<'ctx>>,
buffers: StepBuffers<'ctx>,
) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> {
let StepBuffers { temporary, mut next, mut output } = buffers;
let cleanup = self.release_temporaries(temporary);
match operation.and_then(|values| cleanup.map_or(Ok(values), Err)) {
Ok((state, readout)) => Ok((
@@ -11,16 +11,14 @@ impl<'ctx> GdnStateMirror<'ctx> {
txn: &super::super::super::QwenStepTxn<'_, '_>,
inputs: super::super::super::chain::ScalarRecurrenceBorrow<'_, 'ctx>,
) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> {
let (scope, products) = inputs.into_parts(self.context, &self.binding, &self.failed, prior, identity, txn)?;
let authority = MirrorAuthority { context: self.context, binding: &self.binding, failed: &self.failed };
let (scope, products) = inputs.into_parts(authority, prior, identity, txn)?;
self.admit_prior(prior)?;
validate_values(prior.values(), STATE_ELEMENTS)?;
let hit = self.admit_resident(prior)?;
let mut temporary = Vec::new();
temporary.try_reserve_exact(1).map_err(|_| Error::InputAllocation)?;
let mut next = None;
let mut output = None;
let operation = self.step_products(prior, hit, products, &mut temporary, (&mut next, &mut output));
self.settle_step(prior, (Some(identity), Some(scope)), operation, temporary, next, output)
let mut buffers = StepBuffers::with_capacity(1)?;
let operation = self.step_products(prior, hit, products, &mut buffers);
self.settle_step(prior, (Some(identity), Some(scope)), operation, buffers)
}
fn step_products(
@@ -28,9 +26,9 @@ impl<'ctx> GdnStateMirror<'ctx> {
prior: &GdnPrior,
hit: bool,
[qk, h, gate, beta]: [&DeviceBuffer<'ctx>; 4],
temporary: &mut Vec<DeviceBuffer<'ctx>>,
(next, output): (&mut Option<DeviceBuffer<'ctx>>, &mut Option<DeviceBuffer<'ctx>>),
buffers: &mut StepBuffers<'ctx>,
) -> Result<super::super::super::CandidatePair> {
let StepBuffers { temporary, next, output } = buffers;
self.upload_prior_on_miss(prior, hit, temporary)?;
*next = Some(allocate(self.context, STATE_ELEMENTS)?);
*output = Some(allocate(self.context, VALUES)?);
@@ -56,7 +54,8 @@ impl<'ctx> GdnStateMirror<'ctx> {
history: Box<[f32]>,
) -> Result<GdnPending> {
let MirrorNext { context, source, buffer, values } = next;
let admitted = self.admit_publish(context, &buffer, &source, identity, (values, history));
let contents = PendingContents { identity, values, history };
let admitted = self.admit_publish(context, &buffer, &source, contents);
let (key, pending) = match admitted {
Ok(value) => value,
Err(primary) => {
@@ -73,9 +72,9 @@ impl<'ctx> GdnStateMirror<'ctx> {
context: &Context<'_>,
buffer: &DeviceBuffer<'ctx>,
source: &GdnPrior,
identity: TokenLayer,
(values, history): (Box<[f32]>, Box<[f32]>),
contents: PendingContents,
) -> Result<(GdnStateKey, GdnPending)> {
let PendingContents { identity, values, history } = contents;
if self.failed.get() {
return Err(Error::CudaExecution);
}
@@ -11,16 +11,12 @@ impl<'ctx> MirrorReadout<'ctx> {
pub(in super::super) fn into_parts(
mut self,
context: &Context<'_>,
failed: &Rc<Cell<bool>>,
prior: &GdnPrior,
identity: TokenLayer,
scope: &Rc<()>,
claim: ReadoutClaim<'_, '_>,
) -> Result<(DeviceBuffer<'ctx>, Box<[f32]>)> {
if self.failed.get() {
return Err(Error::CudaExecution);
}
if !self.same_owner(context, failed, prior, (identity, scope)) {
if !self.same_owner(claim) {
return Err(Error::IdentityMismatch);
}
if self.buffer.as_ref().is_none_or(|b| b.len() != VALUES * 4) {
@@ -29,13 +25,8 @@ impl<'ctx> MirrorReadout<'ctx> {
validate_values(self.values.as_deref().ok_or(Error::IdentityMismatch)?, VALUES)?;
Ok((self.buffer.take().ok_or(Error::IdentityMismatch)?, self.values.take().ok_or(Error::IdentityMismatch)?))
}
fn same_owner(
&self,
context: &Context<'_>,
failed: &Rc<Cell<bool>>,
prior: &GdnPrior,
(identity, scope): (TokenLayer, &Rc<()>),
) -> bool {
fn same_owner(&self, claim: ReadoutClaim<'_, '_>) -> bool {
let ReadoutClaim { context, failed, prior, identity, scope } = claim;
std::ptr::eq(self.context, context)
&& Rc::ptr_eq(&self.failed, failed)
&& self.source.same_state(prior)
@@ -1,6 +1,6 @@
//! New device mirror against the actual uncached recurrence, not a model oracle.
#![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::super::{GdnOwner, HISTORY_ELEMENTS, recur};
use super::super::{GdnOwner, HISTORY_ELEMENTS, RecurrenceOperands, recur};
use super::*;
use crate::qwen_forward::contract::{Dimension, LayerId, Position, TokenId, TokenLayer};
use leleka_cuda_driver::Driver;
@@ -13,6 +13,13 @@ struct Inputs {
beta: [f32; 48],
}
impl Inputs {
// The five recurrence operands of this fixture, borrowed.
fn operands(&self) -> RecurrenceOperands<'_> {
RecurrenceOperands { q: &self.q, k: &self.k, v: &self.v, gate: &self.gate, beta: &self.beta }
}
}
fn inputs(seed: usize) -> Inputs {
Inputs {
q: (0..2048).map(|i| ((i + seed * 3) % 17) as f32 / 128. - 0.0625).collect(),
@@ -49,11 +56,11 @@ fn pair<'ctx>(
let initial = context.allocated_bytes();
// Existing uncached CUDA producer is the reference. Its original input
// upload/release, arithmetic and finite readbacks remain unchanged.
let (expected_state, expected_readout) =
recur(context, prior.values(), &inputs.q, &inputs.k, &inputs.v, &inputs.gate, &inputs.beta).unwrap();
let operands = inputs.operands();
let (expected_state, expected_readout) = recur(context, prior.values(), operands).unwrap();
assert_eq!(context.allocated_bytes(), initial);
let source_bits: Vec<u32> = prior.values().iter().map(|v| v.to_bits()).collect();
let (readout, next) = mirror.compute(prior, &inputs.q, &inputs.k, &inputs.v, &inputs.gate, &inputs.beta).unwrap();
let (readout, next) = mirror.compute(prior, operands).unwrap();
exact(&next.values, &expected_state);
exact(&readout, &expected_readout);
assert_eq!(context.allocated_bytes(), initial + MIRROR_BYTES);
@@ -151,19 +158,17 @@ impl<'c> Run<'c> {
let initial = self.context.allocated_bytes();
let mut malformed = ordinary.q.clone();
malformed[2047] = f32::from_bits(0x7fc00001);
assert_eq!(
self.mirror.compute(reset, &malformed, &ordinary.k, &ordinary.v, &ordinary.gate, &ordinary.beta).err(),
Some(Error::NonFinite)
);
let malformed_operands = RecurrenceOperands { q: &malformed, ..ordinary.operands() };
assert_eq!(self.mirror.compute(reset, malformed_operands).err(), Some(Error::NonFinite));
assert_eq!(self.context.allocated_bytes(), initial);
assert_eq!((self.mirror.hits, self.mirror.misses), (3, 3));
let wrong_layer =
GdnPrior::zero(self.binding.clone(), &self.owner, LayerId::new(1, Dimension::new(48).unwrap()).unwrap())
.unwrap();
let (q, k, v, gate, beta) = (&ordinary.q, &ordinary.k, &ordinary.v, &ordinary.gate, &ordinary.beta);
assert_eq!(self.mirror.compute(&wrong_layer, q, k, v, gate, beta).err(), Some(Error::IdentityMismatch));
let operands = ordinary.operands();
assert_eq!(self.mirror.compute(&wrong_layer, operands).err(), Some(Error::IdentityMismatch));
let wrong_binding = GdnPrior::zero(BindingIdentity::test_identity(), &self.owner, self.layer).unwrap();
assert_eq!(self.mirror.compute(&wrong_binding, q, k, v, gate, beta).err(), Some(Error::IdentityMismatch));
assert_eq!(self.mirror.compute(&wrong_binding, operands).err(), Some(Error::IdentityMismatch));
assert_eq!(self.context.allocated_bytes(), initial);
assert!(!self.failed.get());
initial
@@ -178,12 +183,7 @@ impl<'c> Run<'c> {
let mut overflow = inputs(6);
overflow.v.fill(f32::MAX);
overflow.beta.fill(f32::MAX);
assert_eq!(
self.mirror
.compute(accepted_restored, &overflow.q, &overflow.k, &overflow.v, &overflow.gate, &overflow.beta)
.err(),
Some(Error::NonFinite)
);
assert_eq!(self.mirror.compute(accepted_restored, overflow.operands()).err(), Some(Error::NonFinite));
assert_eq!(self.context.allocated_bytes(), initial);
assert!(self.mirror.key.as_ref().is_some_and(|key| key.matches(accepted_restored)));
let mut after = vec![0; MIRROR_BYTES];
@@ -198,8 +198,7 @@ impl<'c> Run<'c> {
fn discard_lifecycle(&mut self, accepted_restored: &GdnPrior, initial: usize, preserved: &[u8]) {
let mut after = vec![0; MIRROR_BYTES];
let valid = inputs(7);
let (readout, next) =
self.mirror.compute(accepted_restored, &valid.q, &valid.k, &valid.v, &valid.gate, &valid.beta).unwrap();
let (readout, next) = self.mirror.compute(accepted_restored, valid.operands()).unwrap();
assert!(readout.iter().chain(next.values.iter()).all(|v| v.is_finite()));
assert_eq!(self.context.allocated_bytes(), initial + MIRROR_BYTES);
self.mirror.discard(next).unwrap();
@@ -46,6 +46,15 @@ pub(in crate::qwen_forward) struct Workspace<'ctx> {
native_fused: Option<(u64, Rc<RefCell<leleka_cuda_driver::GdnFusedT1<'ctx>>>)>,
}
/// The device buffers one verified row's recurrence step touches: the prior state and the four producer products it
/// reads, the candidate state and the readout it writes.
pub(in crate::qwen_forward) struct VerifiedRowBuffers<'a, 'ctx> {
pub(in crate::qwen_forward) state: &'a DeviceBuffer<'ctx>,
pub(in crate::qwen_forward) products: [&'a DeviceBuffer<'ctx>; 4],
pub(in crate::qwen_forward) next: &'a mut DeviceBuffer<'ctx>,
pub(in crate::qwen_forward) readout: &'a mut DeviceBuffer<'ctx>,
}
pub(super) struct ReplaySeal {
lease: Rc<ActiveLease>,
last: Rc<VerifiedRow>,
@@ -5,14 +5,12 @@ use super::*;
pub(in super::super::super) fn compute_row(
context: &Context<'_>,
state: &DeviceBuffer<'_>,
operands: [&DeviceBuffer<'_>; 4],
next: &mut DeviceBuffer<'_>,
readout: &mut DeviceBuffer<'_>,
buffers: VerifiedRowBuffers<'_, '_>,
guard: &mut GdnStateFiniteGuard<'_>,
) -> Result<Box<[f32]>> {
let VerifiedRowBuffers { state, products, next, readout } = buffers;
context
.gdn_step_from_products_f32(state, operands[0], operands[1], operands[2], operands[3], next, readout)
.gdn_step_from_products_f32(state, products[0], products[1], products[2], products[3], next, readout)
.map_err(driver_error)?;
if !guard.check_next_state(next).map_err(driver_error)? {
return Err(Error::NonFinite);
@@ -104,19 +104,18 @@ impl<'ctx> Workspace<'ctx> {
}
fn replay_composed(&mut self, slot: usize, input: usize, out: &mut DeviceBuffer<'ctx>) -> Result<()> {
let operands = &self.operands[slot];
let _ = compute_row(
self.context,
self.states[input].as_ref().ok_or(Error::IdentityMismatch)?,
[
let buffers = VerifiedRowBuffers {
state: self.states[input].as_ref().ok_or(Error::IdentityMismatch)?,
products: [
operands[0].as_ref().ok_or(Error::IdentityMismatch)?,
operands[1].as_ref().ok_or(Error::IdentityMismatch)?,
operands[2].as_ref().ok_or(Error::IdentityMismatch)?,
operands[3].as_ref().ok_or(Error::IdentityMismatch)?,
],
out,
self.readout.as_mut().ok_or(Error::IdentityMismatch)?,
self.guard.as_mut().ok_or(Error::IdentityMismatch)?,
)?;
next: out,
readout: self.readout.as_mut().ok_or(Error::IdentityMismatch)?,
};
let _ = compute_row(self.context, buffers, self.guard.as_mut().ok_or(Error::IdentityMismatch)?)?;
Ok(())
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -57,14 +57,13 @@ impl<'ctx> Numerical<'ctx> {
}
.ok_or(Error::IdentityMismatch)?;
let row = self.operands.get(index).ok_or(Error::IdentityMismatch)?;
compute_row(
context,
let buffers = VerifiedRowBuffers {
state,
operand_refs(row)?,
products: operand_refs(row)?,
next,
self.readout.as_mut().ok_or(Error::IdentityMismatch)?,
self.guard.as_mut().ok_or(Error::IdentityMismatch)?,
)
readout: self.readout.as_mut().ok_or(Error::IdentityMismatch)?,
};
compute_row(context, buffers, self.guard.as_mut().ok_or(Error::IdentityMismatch)?)
}
fn close(&mut self) -> Result<()> {
let mut primary = None;
@@ -4,8 +4,8 @@
#[allow(unused_imports)]
use super::*;
use super::super::super::gdn::GdnPrior;
use super::super::super::gdn::chunk_device::{ChunkEdge, GdnChunkDevice};
use super::super::super::gdn::{GdnPrior, PromptLayer, PromptProgram, PromptSource};
use super::super::super::qsa_index::prompt_device::resident_device::{
ResidentQsaCompleted, ResidentQsaLayer, ResidentQsaPrior, ResidentQsaSelection,
};
@@ -69,16 +69,13 @@ impl<'ctx> GdnLayer<'ctx> {
) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, Vec<ChunkEdge>)> {
let context = self.context;
let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
let prompt = PromptLayer { binding, layer: self.layer, cache: dense, current: context };
let program = PromptProgram { producer: gdn, workspace: &mut workspace };
super::super::super::gdn::GdnStage::produce_prompt_device(
binding,
self.layer,
dense,
context,
prompt,
&mut self.owner,
rows,
read,
gdn,
&mut workspace,
PromptSource { rows, read },
program,
)
}
pub(super) fn leave(