Retain PLE weights and reuse projection scratch on the GPU

This commit is contained in:
Pavlo Ratushnyi
2026-10-10 05:21:51 +02:00
parent 58dbd1799c
commit 3b865b8426
5 changed files with 495 additions and 172 deletions
@@ -1,4 +1,5 @@
//! Retained layer-one PLE weights. Matrices are read in at most 64 whole rows.
//! Retained layer-one PLE weights. Closed matrices may be read once in full;
//! compute still uses the original exact 64-row operations.
use super::{
BindingIdentity, InputBindingError as E, InputResult, LayerRole, ModelBinding,
Qwen4ExpArtifact, TensorRole,
@@ -134,15 +135,13 @@ impl ModelBinding {
let norm_conv = norm(&mut a, LayerRole::PleNormConv)?;
let mut conv = Vec::new();
conv.try_reserve_exact(HC * 4).map_err(|_| E::Allocation)?;
for row in 0..HC {
let bytes = read(&mut a, role(LayerRole::PleConv1d), row as u64, 8)?;
for bits in bytes.as_chunks::<2>().0 {
let h = u16::from_le_bytes(*bits);
if !leleka_quant_core::f16_bits_to_f32(h).is_finite() {
return Err(E::NonFinite);
}
conv.push(h);
let bytes = read_rows(&mut a, role(LayerRole::PleConv1d), 0, HC, HC * 8)?;
for bits in bytes.as_chunks::<2>().0 {
let h = u16::from_le_bytes(*bits);
if !leleka_quant_core::f16_bits_to_f32(h).is_finite() {
return Err(E::NonFinite);
}
conv.push(h);
}
Ok(PleWeights {
binding: self.identity(),
@@ -164,6 +163,30 @@ impl ModelBinding {
}
let (r, rows) = matrix(r);
range(first, count, rows)?;
self.ple_matrix_span(weights, r, first, count, rows)
}
pub(crate) fn ple_matrix_full(
&self,
weights: &PleWeights,
r: PleMatrixRole,
) -> InputResult<PleWeightBlock> {
if !weights.matches(&self.identity()) {
return Err(E::Geometry);
}
let (r, rows) = matrix(r);
self.ple_matrix_span(weights, r, 0, rows, rows)
}
fn ple_matrix_span(
&self,
weights: &PleWeights,
r: TensorRole,
first: usize,
count: usize,
rows: usize,
) -> InputResult<PleWeightBlock> {
if !weights.matches(&self.identity()) {
return Err(E::Geometry);
}
let mut a = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?;
let d = a.tensor(r).map_err(|_| E::Geometry)?;
descriptor(
@@ -174,24 +197,64 @@ impl ModelBinding {
&[N as u64, rows as u64],
N * rows * 2,
)?;
let mut values = Vec::new();
values
.try_reserve_exact(N * 2 * count)
.map_err(|_| E::Allocation)?;
for row in first..first + count {
let bytes = read(&mut a, r, row as u64, N * 2)?;
for bits in bytes.as_chunks::<2>().0 {
if !f32::from_bits(u32::from(u16::from_le_bytes(*bits)) << 16).is_finite() {
return Err(E::NonFinite);
}
let values = read_rows(&mut a, r, first, count, N * 2 * count)?;
for bits in values.as_chunks::<2>().0 {
if !f32::from_bits(u32::from(u16::from_le_bytes(*bits)) << 16).is_finite() {
return Err(E::NonFinite);
}
values.extend_from_slice(&bytes);
}
Ok(PleWeightBlock {
bytes: values.into_boxed_slice(),
rows: count,
})
}
pub(crate) fn validate_ple_sources(&self) -> InputResult<()> {
let mut a = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?;
let mut checked = [false; 2];
for r in [
LayerRole::PleKey,
LayerRole::PleValue,
LayerRole::PleNormKey,
LayerRole::PleNormQuery,
LayerRole::PleNormConv,
LayerRole::PleConv1d,
] {
let r = role(r);
let shard = usize::from(a.tensor(r).map_err(|_| E::Geometry)?.shard());
let done = checked.get_mut(shard).ok_or(E::Geometry)?;
if !*done {
a.validate_tensor_source(r).map_err(|_| E::Read)?;
*done = true;
}
}
Ok(())
}
}
fn read_rows(
a: &mut Qwen4ExpArtifact,
r: TensorRole,
first: usize,
count: usize,
limit: usize,
) -> InputResult<Vec<u8>> {
let mut bytes = Vec::new();
bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?;
a.stream_rows(r, first as u64, count as u64, |chunk| {
if bytes
.len()
.checked_add(chunk.len())
.is_none_or(|end| end > limit)
{
return Err(std::io::ErrorKind::InvalidData.into());
}
bytes.extend_from_slice(chunk);
Ok(())
})
.map_err(|_| E::Read)?;
if bytes.len() != limit {
return Err(E::Read);
}
Ok(bytes)
}
fn read(a: &mut Qwen4ExpArtifact, r: TensorRole, row: u64, limit: usize) -> InputResult<Vec<u8>> {
let mut bytes = Vec::new();
@@ -3,7 +3,7 @@ use super::contract::{Error, Result};
use super::qsa_index::{binding_error, driver_error};
use crate::model_binding::qwen4exp_input::{
BindingIdentity, BoundLayerKind, GdnMatrixKind, GdnMatrixRole, GdnWeights, GrRole, GrWeights,
ModelBinding, QsaMatrixKind, QsaMatrixRole, QsaWeights,
ModelBinding, PleMatrixRole, PleWeights, QsaMatrixKind, QsaMatrixRole, QsaWeights,
};
use leleka_cuda_driver::{Context, DeviceBuffer};
use std::{cell::Cell, rc::Rc};
@@ -32,6 +32,12 @@ pub(super) struct GrResident {
pub weights: Rc<GrWeights>,
buffers: [Option<usize>; 4],
}
pub(super) struct PleResident {
owner: Rc<()>,
pub weights: Rc<PleWeights>,
tiles: [Vec<usize>; 2],
aux: [usize; 4],
}
pub(crate) struct DenseWeightCache<'ctx> {
binding: BindingIdentity,
owner: Rc<()>,
@@ -41,6 +47,7 @@ pub(crate) struct DenseWeightCache<'ctx> {
qsa: Vec<Option<QsaResident>>,
gr: Vec<GrResident>,
router: Vec<usize>,
ple: Option<PleResident>,
counters: Cell<DenseCacheCounters>,
}
impl<'ctx> DenseWeightCache<'ctx> {
@@ -58,120 +65,133 @@ impl<'ctx> DenseWeightCache<'ctx> {
qsa: Vec::new(),
gr: Vec::new(),
router: Vec::new(),
ple: None,
counters: Cell::new(DenseCacheCounters::default()),
};
result
.gdn
.try_reserve_exact(n)
.map_err(|_| Error::InputAllocation)?;
result
.qsa
.try_reserve_exact(n)
.map_err(|_| Error::InputAllocation)?;
result
.gr
.try_reserve_exact(n * 2 + 1)
.map_err(|_| Error::InputAllocation)?;
result
.router
.try_reserve_exact(n)
.map_err(|_| Error::InputAllocation)?;
for layer in binding.ordered_layers() {
let id = layer.index();
let gdn = if layer.kind() == BoundLayerKind::Gdn {
let weights = Rc::new(binding.gdn_weights(id).map_err(binding_error)?);
let mut matrices = [(0, GdnMatrixKind::Bf16); 5];
for (i, role) in [
GdnMatrixRole::Qkv,
GdnMatrixRole::Z,
GdnMatrixRole::Alpha,
GdnMatrixRole::Beta,
GdnMatrixRole::Out,
]
.into_iter()
.enumerate()
{
let block = binding
.gdn_matrix_block(&weights, role, 0, weights.shape(role).1)
.map_err(binding_error)?;
matrices[i] = (
result.add(
block.bytes(),
weights.source_bytes(role).map_err(binding_error)?,
)?,
block.kind(),
);
let loaded = (|| -> Result<()> {
result
.gdn
.try_reserve_exact(n)
.map_err(|_| Error::InputAllocation)?;
result
.qsa
.try_reserve_exact(n)
.map_err(|_| Error::InputAllocation)?;
result
.gr
.try_reserve_exact(n * 2 + 1)
.map_err(|_| Error::InputAllocation)?;
result
.router
.try_reserve_exact(n)
.map_err(|_| Error::InputAllocation)?;
for layer in binding.ordered_layers() {
let id = layer.index();
let gdn = if layer.kind() == BoundLayerKind::Gdn {
let weights = Rc::new(binding.gdn_weights(id).map_err(binding_error)?);
let mut matrices = [(0, GdnMatrixKind::Bf16); 5];
for (i, role) in [
GdnMatrixRole::Qkv,
GdnMatrixRole::Z,
GdnMatrixRole::Alpha,
GdnMatrixRole::Beta,
GdnMatrixRole::Out,
]
.into_iter()
.enumerate()
{
let block = binding
.gdn_matrix_block(&weights, role, 0, weights.shape(role).1)
.map_err(binding_error)?;
matrices[i] = (
result.add(
block.bytes(),
weights.source_bytes(role).map_err(binding_error)?,
)?,
block.kind(),
);
}
let aux = [
result.add_f32(weights.conv())?,
result.add_f32(weights.dt())?,
result.add_f32(weights.a())?,
result.add_f32(weights.norm())?,
];
Some(GdnResident {
owner: result.owner.clone(),
weights,
matrices,
aux,
})
} else {
None
};
let qsa = if layer.kind() == BoundLayerKind::Qsa {
let weights = Rc::new(binding.qsa_weights(id).map_err(binding_error)?);
let mut matrices = [(0, QsaMatrixKind::Bf16); 6];
for (i, role) in [
QsaMatrixRole::Q,
QsaMatrixRole::K,
QsaMatrixRole::V,
QsaMatrixRole::IndexQ,
QsaMatrixRole::IndexK,
QsaMatrixRole::Out,
]
.into_iter()
.enumerate()
{
let block = binding
.qsa_matrix_block(&weights, role, 0, weights.shape(role).1)
.map_err(binding_error)?;
matrices[i] = (
result.add(
block.bytes(),
weights.source_bytes(role).map_err(binding_error)?,
)?,
block.kind(),
);
}
let norms = [
result.add_f32(weights.q_norm())?,
result.add_f32(weights.k_norm())?,
result.add_f32(weights.index_q_norm())?,
result.add_f32(weights.index_k_norm())?,
];
Some(QsaResident {
owner: result.owner.clone(),
weights,
matrices,
norms,
})
} else {
None
};
result.gdn.push(gdn);
result.qsa.push(qsa);
for role in [GrRole::Attention(id), GrRole::Ffn(id)] {
result.add_gr(binding, role)?;
}
let aux = [
result.add_f32(weights.conv())?,
result.add_f32(weights.dt())?,
result.add_f32(weights.a())?,
result.add_f32(weights.norm())?,
];
Some(GdnResident {
owner: result.owner.clone(),
weights,
matrices,
aux,
})
} else {
None
};
let qsa = if layer.kind() == BoundLayerKind::Qsa {
let weights = Rc::new(binding.qsa_weights(id).map_err(binding_error)?);
let mut matrices = [(0, QsaMatrixKind::Bf16); 6];
for (i, role) in [
QsaMatrixRole::Q,
QsaMatrixRole::K,
QsaMatrixRole::V,
QsaMatrixRole::IndexQ,
QsaMatrixRole::IndexK,
QsaMatrixRole::Out,
]
.into_iter()
.enumerate()
{
let block = binding
.qsa_matrix_block(&weights, role, 0, weights.shape(role).1)
.map_err(binding_error)?;
matrices[i] = (
result.add(
block.bytes(),
weights.source_bytes(role).map_err(binding_error)?,
)?,
block.kind(),
);
}
let norms = [
result.add_f32(weights.q_norm())?,
result.add_f32(weights.k_norm())?,
result.add_f32(weights.index_q_norm())?,
result.add_f32(weights.index_k_norm())?,
];
Some(QsaResident {
owner: result.owner.clone(),
weights,
matrices,
norms,
})
} else {
None
};
result.gdn.push(gdn);
result.qsa.push(qsa);
for role in [GrRole::Attention(id), GrRole::Ffn(id)] {
result.add_gr(binding, role)?;
let weights = binding.moe_route_weights(id).map_err(binding_error)?;
let block = binding
.moe_route_matrix_block(&weights, 0, 512)
.map_err(binding_error)?;
let index = result.add(block.bytes(), block.bytes().len())?;
result.router.push(index);
}
result.add_gr(binding, GrRole::Final)?;
result.add_ple(binding)?;
result.validate(binding)?;
Ok(())
})();
match loaded {
Ok(()) => Ok(result),
Err(primary) => {
// A failed eager load publishes no cache. Explicitly attempt
// every owned release, preserving the original load refusal.
let _ = result.close();
Err(primary)
}
let weights = binding.moe_route_weights(id).map_err(binding_error)?;
let block = binding
.moe_route_matrix_block(&weights, 0, 512)
.map_err(binding_error)?;
let index = result.add(block.bytes(), block.bytes().len())?;
result.router.push(index);
}
result.add_gr(binding, GrRole::Final)?;
result.validate(binding)?;
Ok(result)
}
fn add(&mut self, bytes: &[u8], source_bytes: usize) -> Result<usize> {
if self
@@ -187,7 +207,11 @@ impl<'ctx> DenseWeightCache<'ctx> {
.try_reserve(1)
.map_err(|_| Error::InputAllocation)?;
let mut b = self.context.allocate(bytes.len()).map_err(driver_error)?;
b.copy_from(bytes).map_err(driver_error)?;
if let Err(error) = b.copy_from(bytes) {
let primary = driver_error(error);
let _ = b.release();
return Err(primary);
}
let index = self.buffers.len();
self.buffers.push(b);
let mut c = self.counters.get();
@@ -248,9 +272,59 @@ impl<'ctx> DenseWeightCache<'ctx> {
});
Ok(())
}
fn add_ple(&mut self, binding: &ModelBinding) -> Result<()> {
let weights = Rc::new(binding.ple_weights().map_err(binding_error)?);
let mut tiles = [Vec::new(), Vec::new()];
// One closed contiguous read per matrix. Keep the exact original
// 64-row compute geometry and specialized Value arithmetic unchanged.
for (i, role) in [PleMatrixRole::Key, PleMatrixRole::Value]
.into_iter()
.enumerate()
{
let matrix = binding
.ple_matrix_full(&weights, role)
.map_err(binding_error)?;
let rows = match role {
PleMatrixRole::Key => 10240,
PleMatrixRole::Value => 2560,
};
if matrix.rows() != rows || matrix.bytes().len() != rows * 2560 * 2 {
return Err(Error::InvalidDimension);
}
tiles[i]
.try_reserve_exact(rows / 64)
.map_err(|_| Error::InputAllocation)?;
for tile in matrix.bytes().as_chunks::<{ 64 * 2560 * 2 }>().0 {
tiles[i].push(self.add(tile, tile.len())?);
}
}
let mut conv = Vec::new();
conv.try_reserve_exact(weights.conv().len() * 2)
.map_err(|_| Error::InputAllocation)?;
for v in weights.conv() {
if !leleka_quant_core::f16_bits_to_f32(*v).is_finite() {
return Err(Error::NonFinite);
}
conv.extend_from_slice(&v.to_le_bytes());
}
let aux = [
self.add_f32(weights.norm_key())?,
self.add_f32(weights.norm_query())?,
self.add_f32(weights.norm_conv())?,
self.add(&conv, conv.len())?,
];
self.ple = Some(PleResident {
owner: self.owner.clone(),
weights,
tiles,
aux,
});
Ok(())
}
pub(super) fn validate(&self, binding: &ModelBinding) -> Result<()> {
self.check(binding)?;
binding.validate_dense_sources().map_err(binding_error)
binding.validate_dense_sources().map_err(binding_error)?;
binding.validate_ple_sources().map_err(binding_error)
}
fn check(&self, binding: &ModelBinding) -> Result<()> {
if self.binding.matches(&binding.identity()) {
@@ -301,6 +375,52 @@ impl<'ctx> DenseWeightCache<'ctx> {
fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> {
self.buffers.get(index).ok_or(Error::IdentityMismatch)
}
pub(super) fn ple(
&self,
binding: &ModelBinding,
context: &Context<'_>,
) -> Result<&PleResident> {
self.check(binding)?;
if !std::ptr::eq(self.context, context) {
return Err(Error::IdentityMismatch);
}
binding.validate_ple_sources().map_err(binding_error)?;
let entry = self.ple.as_ref().ok_or(Error::IdentityMismatch)?;
if !Rc::ptr_eq(&self.owner, &entry.owner) || !entry.weights.matches(&binding.identity()) {
return Err(Error::IdentityMismatch);
}
self.hit()?;
Ok(entry)
}
pub(super) fn ple_tile(
&self,
entry: &PleResident,
role: PleMatrixRole,
first: usize,
) -> Result<&DeviceBuffer<'ctx>> {
if !Rc::ptr_eq(&self.owner, &entry.owner) || !first.is_multiple_of(64) {
return Err(Error::IdentityMismatch);
}
let i = match role {
PleMatrixRole::Key => 0,
PleMatrixRole::Value => 1,
};
let index = *entry.tiles[i]
.get(first / 64)
.ok_or(Error::InvalidDimension)?;
self.buffer(index)
}
pub(super) fn ple_aux(&self, entry: &PleResident) -> Result<[&DeviceBuffer<'ctx>; 4]> {
if !Rc::ptr_eq(&self.owner, &entry.owner) {
return Err(Error::IdentityMismatch);
}
Ok([
self.buffer(entry.aux[0])?,
self.buffer(entry.aux[1])?,
self.buffer(entry.aux[2])?,
self.buffer(entry.aux[3])?,
])
}
pub(super) fn gdn_matrix(
&self,
entry: &GdnResident,
@@ -684,7 +684,7 @@ fn read_layer_attention(
ForwardPhase::Ple,
layer.get(),
txn.position(),
InputStage::apply_ple(binding, previous, &prior, txn),
InputStage::apply_ple_cached(binding, previous, &prior, txn, cache),
)?;
ple.validate_origin(&binding.identity())?;
ple.identity()
+110 -39
View File
@@ -1,6 +1,7 @@
#![allow(dead_code)]
use super::contract::{Dimension, Error, Position, Result, Stage, TokenId};
use super::dense_weight_cache::{DenseWeightCache, PleResident};
use super::session::QwenStepTxn;
use crate::model_binding::qwen4exp_input::{
BindingIdentity, EMBEDDING_VALUES, InputBindingError, ModelBinding, PLE_ROW_VALUES, VOCABULARY,
@@ -472,6 +473,15 @@ impl InputStage {
residual: &InjectedResidual,
prior: &PlePrior,
txn: &mut QwenStepTxn,
) -> Result<PleReady> {
Self::apply_ple_cached(binding, residual, prior, txn, None)
}
pub(super) fn apply_ple_cached(
binding: &ModelBinding,
residual: &InjectedResidual,
prior: &PlePrior,
txn: &mut QwenStepTxn,
cache: Option<&DenseWeightCache<'_>>,
) -> Result<PleReady> {
txn.validate_binding(&binding.identity())?;
residual.validate_origin(&binding.identity(), GrRole::Ffn(0))?;
@@ -488,7 +498,11 @@ impl InputStage {
ple_values(&prior.0.history, PLE_HISTORY)?;
let context = txn.cuda_context()?;
ple_budget(context)?;
let weights = binding.ple_weights().map_err(binding_error)?;
let resident = cache.map(|c| c.ple(binding, context)).transpose()?;
let weights = match resident {
Some(entry) => entry.weights.clone(),
None => Rc::new(binding.ple_weights().map_err(binding_error)?),
};
if !weights.matches(&binding.identity()) {
return Err(Error::IdentityMismatch);
}
@@ -499,6 +513,7 @@ impl InputStage {
input.ple_embedding(),
residual.streams(),
&prior.0.history,
cache.zip(resident),
)?;
let layer1 = LayerId::new(1, Dimension::new(u64::from(binding.layer_count()))?)?;
let identity = TokenLayer::new(txn.token(), txn.position(), layer1);
@@ -522,19 +537,67 @@ fn ple_cuda(
embedding: &[f32],
streams: &[f32],
history: &[f32],
resident: Option<(&DenseWeightCache<'_>, &PleResident)>,
) -> Result<PleCandidate> {
let emb = ple_upload_f32(context, embedding)?;
let key_values = ple_project(context, binding, weights, PleMatrixRole::Key, &emb)?;
let value_values = ple_project(context, binding, weights, PleMatrixRole::Value, &emb)?;
let key_values = ple_project(
context,
binding,
weights,
PleMatrixRole::Key,
&emb,
resident,
)?;
let value_values = ple_project(
context,
binding,
weights,
PleMatrixRole::Value,
&emb,
resident,
)?;
emb.release().map_err(ple_driver_error)?;
let raw_key = ple_upload_f32(context, &key_values)?;
let value = ple_upload_f32(context, &value_values)?;
let residual = ple_upload_f32(context, streams)?;
let prior = ple_upload_f32(context, history)?;
let norm_key = ple_upload_f32(context, weights.norm_key())?;
let norm_query = ple_upload_f32(context, weights.norm_query())?;
let norm_conv = ple_upload_f32(context, weights.norm_conv())?;
let conv_weights = ple_upload_u16(context, weights.conv())?;
let aux = resident.map(|(c, r)| c.ple_aux(r)).transpose()?;
let norm_key_owned = if aux.is_none() {
Some(ple_upload_f32(context, weights.norm_key())?)
} else {
None
};
let norm_query_owned = if aux.is_none() {
Some(ple_upload_f32(context, weights.norm_query())?)
} else {
None
};
let norm_conv_owned = if aux.is_none() {
Some(ple_upload_f32(context, weights.norm_conv())?)
} else {
None
};
let conv_owned = if aux.is_none() {
Some(ple_upload_u16(context, weights.conv())?)
} else {
None
};
let norm_key = aux
.map(|v| v[0])
.or(norm_key_owned.as_ref())
.ok_or(Error::IdentityMismatch)?;
let norm_query = aux
.map(|v| v[1])
.or(norm_query_owned.as_ref())
.ok_or(Error::IdentityMismatch)?;
let norm_conv = aux
.map(|v| v[2])
.or(norm_conv_owned.as_ref())
.ok_or(Error::IdentityMismatch)?;
let conv_weights = aux
.map(|v| v[3])
.or(conv_owned.as_ref())
.ok_or(Error::IdentityMismatch)?;
let mut key = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?;
let mut query = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?;
let mut gate = context.allocate(16).map_err(ple_driver_error)?;
@@ -546,11 +609,11 @@ fn ple_cuda(
.allocate(PLE_HISTORY * 4)
.map_err(ple_driver_error)?;
context
.ple_grouped_norm_f32(&raw_key, &norm_key, &mut key)
.ple_grouped_norm_f32(&raw_key, norm_key, &mut key)
.map_err(ple_driver_error)?;
let _ = ple_download(&key, PLE_HC)?;
context
.ple_grouped_norm_f32(&residual, &norm_query, &mut query)
.ple_grouped_norm_f32(&residual, norm_query, &mut query)
.map_err(ple_driver_error)?;
let _ = ple_download(&query, PLE_HC)?;
context
@@ -562,11 +625,11 @@ fn ple_cuda(
.map_err(ple_driver_error)?;
let _ = ple_download(&gated, PLE_HC)?;
context
.ple_grouped_norm_f32(&gated, &norm_conv, &mut normalized)
.ple_grouped_norm_f32(&gated, norm_conv, &mut normalized)
.map_err(ple_driver_error)?;
let _ = ple_download(&normalized, PLE_HC)?;
context
.ple_conv_history_f32(&prior, &normalized, &conv_weights, &mut conv, &mut next)
.ple_conv_history_f32(&prior, &normalized, conv_weights, &mut conv, &mut next)
.map_err(ple_driver_error)?;
let _ = ple_download(&conv, PLE_HC)?;
let next_values = ple_download(&next, PLE_HISTORY)?;
@@ -576,25 +639,21 @@ fn ple_cuda(
let result_values = ple_download(&result, PLE_HC)?;
// No candidate can escape until fallible owned resource release succeeds.
for buffer in [
next,
result,
conv,
normalized,
gated,
gate,
query,
key,
conv_weights,
norm_conv,
norm_query,
norm_key,
prior,
residual,
value,
raw_key,
next, result, conv, normalized, gated, gate, query, key, prior, residual, value, raw_key,
] {
buffer.release().map_err(ple_driver_error)?;
}
for buffer in [
conv_owned,
norm_conv_owned,
norm_query_owned,
norm_key_owned,
]
.into_iter()
.flatten()
{
buffer.release().map_err(ple_driver_error)?;
}
Ok(PleCandidate {
streams: result_values,
history: next_values,
@@ -606,6 +665,7 @@ fn ple_project(
weights: &PleWeights,
role: PleMatrixRole,
embedding: &DeviceBuffer<'_>,
resident: Option<(&DenseWeightCache<'_>, &PleResident)>,
) -> Result<Box<[f32]>> {
let rows = if role == PleMatrixRole::Key {
PLE_HC
@@ -616,19 +676,28 @@ fn ple_project(
values
.try_reserve_exact(rows)
.map_err(|_| Error::InputAllocation)?;
// Every admitted tile overwrites all 64 outputs. Reuse one scratch buffer
// per projection instead of allocating and freeing it for every tile.
let mut output = context.allocate(64 * 4).map_err(ple_driver_error)?;
for first in (0..rows).step_by(64) {
let block = binding
.ple_matrix_block(weights, role, first, 64)
.map_err(binding_error)?;
if block.rows() != 64 || block.bytes().len() != 64 * 2560 * 2 {
return Err(Error::InvalidDimension);
}
let matrix = ple_upload(context, block.bytes())?;
let mut output = context.allocate(64 * 4).map_err(ple_driver_error)?;
let owned;
let matrix = if let Some((cache, entry)) = resident {
owned = None;
cache.ple_tile(entry, role, first)?
} else {
let block = binding
.ple_matrix_block(weights, role, first, 64)
.map_err(binding_error)?;
if block.rows() != 64 || block.bytes().len() != 64 * 2560 * 2 {
return Err(Error::InvalidDimension);
}
owned = Some(ple_upload(context, block.bytes())?);
owned.as_ref().ok_or(Error::IdentityMismatch)?
};
if role == PleMatrixRole::Key {
context
.bf16_f32(
&matrix,
matrix,
embedding,
&mut output,
Bf16ProjectionShape {
@@ -639,14 +708,16 @@ fn ple_project(
.map_err(ple_driver_error)?;
} else {
context
.ple_value_bf16_f32(embedding, &matrix, &mut output)
.ple_value_bf16_f32(embedding, matrix, &mut output)
.map_err(ple_driver_error)?;
}
let decoded = ple_download(&output, 64)?;
values.extend_from_slice(&decoded);
output.release().map_err(ple_driver_error)?;
matrix.release().map_err(ple_driver_error)?;
if let Some(matrix) = owned {
matrix.release().map_err(ple_driver_error)?;
}
}
output.release().map_err(ple_driver_error)?;
Ok(values.into_boxed_slice())
}
fn ple_budget(context: &Context<'_>) -> Result<()> {
+69
View File
@@ -1291,6 +1291,18 @@ fn plan_stream_rows(
TensorRole::Layer {
role: L::SsmConv1d, ..
} => (4, 10240, false),
TensorRole::Layer {
layer: 1,
role: L::PleKey,
} if tensor.kind == 30 => (2560, 10240, false),
TensorRole::Layer {
layer: 1,
role: L::PleValue,
} if tensor.kind == 30 => (2560, 2560, false),
TensorRole::Layer {
layer: 1,
role: L::PleConv1d,
} if tensor.kind == 1 => (4, 10240, false),
TensorRole::Layer {
role: L::SsmOut | L::AttnOutput,
..
@@ -1497,6 +1509,63 @@ mod whole_moe_matrix_sdet {
mod whole_dense_matrix_transport_tests {
use super::*;
#[test]
fn closed_ple_spans_keep_exact_tile_offsets_and_original_formats() {
for (role, kind, columns, rows) in [
(LayerRole::PleKey, 30, 2560_u64, 10240_u64),
(LayerRole::PleValue, 30, 2560, 2560),
(LayerRole::PleConv1d, 1, 4, 10240),
] {
let bytes = columns * rows * 2;
let tensor = ResolvedTensor {
shard: 0,
tensor_number: 0,
name: "closed.ple.test".into(),
kind,
dimensions: vec![columns, rows],
absolute_start: 4096,
byte_length: bytes,
file_size: 4096 + bytes,
};
let closed = TensorRole::Layer { layer: 1, role };
assert_eq!(
plan_stream_rows(&tensor, closed, 0, rows, None).unwrap(),
(0, bytes)
);
for first in (0..rows).step_by(64) {
assert_eq!(
plan_rows(&tensor, first, 64, None).unwrap(),
(first * columns * 2, 64 * columns * 2)
);
}
for (first, count, expert) in [
(1, rows, None),
(0, rows - 1, None),
(0, rows + 1, None),
(0, rows, Some(0)),
(u64::MAX, rows, None),
] {
assert!(plan_stream_rows(&tensor, closed, first, count, expert).is_err());
}
assert!(
plan_stream_rows(&tensor, TensorRole::Layer { layer: 0, role }, 0, rows, None)
.is_err()
);
let mut wrong = tensor.clone();
wrong.kind = if kind == 30 { 1 } else { 30 };
assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err());
wrong = tensor.clone();
wrong.dimensions[0] += 1;
assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err());
wrong = tensor.clone();
wrong.byte_length -= 1;
assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err());
wrong = tensor.clone();
wrong.file_size -= 1;
assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err());
}
}
#[test]
fn closed_dense_spans_preserve_legacy_offsets_and_refuse_partial_matrices() {
use LayerRole as L;