Merge branch 'claude/size2-en2' into claude/hexagonal-integ

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 23:25:58 +01:00
49 changed files with 3819 additions and 2868 deletions
@@ -161,6 +161,15 @@ fn verify(file: &mut File, bytes: u64, pin: &str) -> InputResult<()> {
buffer.try_reserve_exact(SCRATCH).map_err(|_| InputBindingError::Allocation)?;
buffer.resize(SCRATCH, 0);
file.seek(SeekFrom::Start(0)).map_err(|_| InputBindingError::Read)?;
let actual = hash_exact(file, bytes, &mut buffer)?;
let expected = decode_pin(pin)?;
if actual != expected {
return Err(InputBindingError::Metadata);
}
file.seek(SeekFrom::Start(0)).map_err(|_| InputBindingError::Read)?;
Ok(())
}
fn hash_exact(file: &mut File, bytes: u64, buffer: &mut [u8]) -> InputResult<[u8; 32]> {
let mut hasher = Sha256::new();
let mut remaining = bytes;
while remaining != 0 {
@@ -172,7 +181,9 @@ fn verify(file: &mut File, bytes: u64, pin: &str) -> InputResult<()> {
if file.read(&mut buffer[..1]).map_err(|_| InputBindingError::Read)? != 0 {
return Err(InputBindingError::Range);
}
let actual: [u8; 32] = hasher.finalize().into();
Ok(hasher.finalize().into())
}
fn decode_pin(pin: &str) -> InputResult<[u8; 32]> {
let mut expected = [0u8; 32];
if pin.len() != 64 {
return Err(InputBindingError::Metadata);
@@ -180,11 +191,7 @@ fn verify(file: &mut File, bytes: u64, pin: &str) -> InputResult<()> {
for (i, byte) in expected.iter_mut().enumerate() {
*byte = u8::from_str_radix(&pin[i * 2..i * 2 + 2], 16).map_err(|_| InputBindingError::Metadata)?;
}
if actual != expected {
return Err(InputBindingError::Metadata);
}
file.seek(SeekFrom::Start(0)).map_err(|_| InputBindingError::Read)?;
Ok(())
Ok(expected)
}
#[cfg(test)]
@@ -77,6 +77,13 @@ impl MtpWeights {
let mut data = Vec::new();
data.try_reserve_exact(size).map_err(|_| InputBindingError::Allocation)?;
data.resize(size, 0);
self.read_expert_chunks(&mut data)?;
check_expert_scales(&data)?;
self.validate_sources(binding)?;
Ok(data)
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn read_expert_chunks(&self, data: &mut [u8]) -> InputResult<()> {
// Immutable same-FD owner was fully SHA-verified before MtpWeights.
// Bounded reads, no pathname reopen or weight representation changes.
#[cfg(target_os = "linux")]
@@ -93,15 +100,7 @@ impl MtpWeights {
.map_err(|_| InputBindingError::Read)?;
}
}
for blob in data.as_chunks::<{ EXPERT_BLOB as usize }>().0 {
// These are all original used weight scales; the Q8 activation
// half header (which may legitimately overflow) is not this bank.
if blob[1_228_800..].as_chunks::<2>().0.iter().any(|v| u16::from_le_bytes(*v) & 0x7c00 == 0x7c00) {
return Err(InputBindingError::NonFinite);
}
}
self.validate_sources(binding)?;
Ok(data)
Ok(())
}
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
pub(crate) fn expert_bank(&self, _binding: &ModelBinding) -> InputResult<Vec<u8>> {
@@ -149,3 +148,14 @@ impl MtpWeights {
pub(super) fn validate_identity(expected: &BindingIdentity, actual: &BindingIdentity) -> InputResult<()> {
if expected.matches(actual) { Ok(()) } else { Err(InputBindingError::Metadata) }
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn check_expert_scales(data: &[u8]) -> InputResult<()> {
for blob in data.as_chunks::<{ EXPERT_BLOB as usize }>().0 {
// These are all original used weight scales; the Q8 activation
// half header (which may legitimately overflow) is not this bank.
if blob[1_228_800..].as_chunks::<2>().0.iter().any(|v| u16::from_le_bytes(*v) & 0x7c00 == 0x7c00) {
return Err(InputBindingError::NonFinite);
}
}
Ok(())
}
@@ -36,62 +36,94 @@ pub(crate) fn rt_dense_name(role: MtpRole) -> Option<&'static str> {
pub(crate) fn rt_dense_shape(role: MtpRole) -> Option<(MtpKind, usize, usize)> {
DESCRIPTORS.iter().find(|d| d.role == role).and_then(|d| d.dense).map(|d| (d.kind, d.rows, d.columns))
}
struct IndexLine<'a> {
name: &'a str,
kind: &'a str,
rows: u64,
columns: u64,
offset: u64,
bytes: u64,
}
fn parse_index_line(line: &str) -> InputResult<IndexLine<'_>> {
let mut fields = line.split_ascii_whitespace();
let name = fields.next().ok_or(InputBindingError::Metadata)?;
let kind = fields.next().ok_or(InputBindingError::Metadata)?;
let mut number = || -> InputResult<u64> {
let s = fields.next().ok_or(InputBindingError::Metadata)?;
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
return Err(InputBindingError::Metadata);
}
s.parse().map_err(|_| InputBindingError::Range)
};
let rows = number()?;
let columns = number()?;
let offset = number()?;
let bytes = number()?;
if fields.next().is_some() {
return Err(InputBindingError::Metadata);
}
Ok(IndexLine { name, kind, rows, columns, offset, bytes })
}
fn index_kind_name(kind: MtpKind) -> InputResult<&'static str> {
match kind {
MtpKind::Q8_0 => Ok("q8_0"),
MtpKind::Bf16 => Ok("bf16"),
MtpKind::F32 => Ok("f32"),
MtpKind::Q2_0 => Err(InputBindingError::Metadata),
}
}
fn dense_line_matches(line: &IndexLine<'_>, dense: &Dense, expected_kind: &str) -> bool {
line.kind == expected_kind
&& line.rows == dense.rows as u64
&& line.columns == dense.columns as u64
&& line.offset == dense.offset
&& line.bytes == dense.bytes
}
struct IndexScan {
seen: [bool; 31],
spans: [(u64, u64); 29],
count: usize,
}
impl IndexScan {
fn accept(&mut self, line: &IndexLine<'_>) -> InputResult<()> {
let index = DESCRIPTORS.iter().position(|d| d.name == line.name).ok_or(InputBindingError::Metadata)?;
let dense = DESCRIPTORS[index].dense.ok_or(InputBindingError::Metadata)?;
let expected_kind = index_kind_name(dense.kind)?;
let end = line.offset.checked_add(line.bytes).ok_or(InputBindingError::Range)?;
if self.seen[index] || !dense_line_matches(line, &dense, expected_kind) || !self.fits(line.offset, end) {
return Err(InputBindingError::Metadata);
}
self.spans[self.count] = (line.offset, end);
self.count += 1;
self.seen[index] = true;
Ok(())
}
fn fits(&self, offset: u64, end: u64) -> bool {
offset % 256 == 0
&& end <= DENSE_BYTES
&& self.count != self.spans.len()
&& !self.spans[..self.count].iter().any(|&(a, b)| offset < b && a < end)
}
}
impl MtpIndex {
pub(super) fn inspect(bytes: &[u8]) -> InputResult<Self> {
if bytes.is_empty() || bytes.len() > INDEX_LIMIT || !bytes.is_ascii() {
return Err(InputBindingError::Metadata);
}
let text = std::str::from_utf8(bytes).map_err(|_| InputBindingError::Metadata)?;
let mut seen = [false; 31];
let mut spans = [(0u64, 0u64); 29];
let mut count = 0;
let mut scan = IndexScan { seen: [false; 31], spans: [(0u64, 0u64); 29], count: 0 };
for line in text.lines() {
let mut fields = line.split_ascii_whitespace();
let name = fields.next().ok_or(InputBindingError::Metadata)?;
let kind = fields.next().ok_or(InputBindingError::Metadata)?;
let mut number = || -> InputResult<u64> {
let s = fields.next().ok_or(InputBindingError::Metadata)?;
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
return Err(InputBindingError::Metadata);
}
s.parse().map_err(|_| InputBindingError::Range)
};
let rows = number()?;
let columns = number()?;
let offset = number()?;
let bytes = number()?;
if fields.next().is_some() {
return Err(InputBindingError::Metadata);
}
let index = DESCRIPTORS.iter().position(|d| d.name == name).ok_or(InputBindingError::Metadata)?;
let dense = DESCRIPTORS[index].dense.ok_or(InputBindingError::Metadata)?;
let expected_kind = match dense.kind {
MtpKind::Q8_0 => "q8_0",
MtpKind::Bf16 => "bf16",
MtpKind::F32 => "f32",
MtpKind::Q2_0 => return Err(InputBindingError::Metadata),
};
let end = offset.checked_add(bytes).ok_or(InputBindingError::Range)?;
if seen[index]
|| kind != expected_kind
|| rows != dense.rows as u64
|| columns != dense.columns as u64
|| offset != dense.offset
|| bytes != dense.bytes
|| offset % 256 != 0
|| end > DENSE_BYTES
|| count == spans.len()
|| spans[..count].iter().any(|&(a, b)| offset < b && a < end)
{
return Err(InputBindingError::Metadata);
}
spans[count] = (offset, end);
count += 1;
seen[index] = true;
scan.accept(&parse_index_line(line)?)?;
}
if count != 29
|| DESCRIPTORS.iter().enumerate().any(|(i, d)| d.dense.is_some() != seen[i])
|| spans.iter().map(|s| s.1).max() != Some(DENSE_BYTES)
if scan.count != 29
|| DESCRIPTORS.iter().enumerate().any(|(i, d)| d.dense.is_some() != scan.seen[i])
|| scan.spans.iter().map(|s| s.1).max() != Some(DENSE_BYTES)
{
return Err(InputBindingError::Metadata);
}
@@ -22,28 +22,38 @@ pub(super) fn read_expert_rows(
let mut out = allocate(bytes)?;
let base = u64::from(expert).checked_mul(EXPERT_BLOB).ok_or(InputBindingError::Range)?;
for r in 0..count {
let row = first + r;
let (packed_row, code_base, scale_base) = match matrix {
MtpExpertMatrix::Gate => (row * 2, 0, 1_228_800),
MtpExpertMatrix::Up => (row * 2 + 1, 0, 1_228_800),
MtpExpertMatrix::Down => (row, 819_200, 1_331_200),
};
let block_start = packed_row.checked_mul(blocks).ok_or(InputBindingError::Range)?;
let code_offset = base
.checked_add(code_base)
.and_then(|x| x.checked_add((block_start * 16) as u64))
.ok_or(InputBindingError::Range)?;
let scale_offset = base
.checked_add(scale_base)
.and_then(|x| x.checked_add((block_start * 2) as u64))
.ok_or(InputBindingError::Range)?;
let codes = read_exact_range(experts, code_offset, blocks * 16)?;
let scales = read_exact_range(experts, scale_offset, blocks * 2)?;
let (codes, scales) = read_expert_row(experts, matrix, first + r, blocks, base)?;
interleave_q2(&codes, &scales, &mut out[r * blocks * 18..(r + 1) * blocks * 18])?;
}
Ok(MtpRows { kind: MtpKind::Q2_0, rows: count, columns, bytes: out })
}
fn read_expert_row(
experts: &File,
matrix: MtpExpertMatrix,
row: usize,
blocks: usize,
base: u64,
) -> InputResult<(Vec<u8>, Vec<u8>)> {
let (packed_row, code_base, scale_base) = match matrix {
MtpExpertMatrix::Gate => (row * 2, 0, 1_228_800),
MtpExpertMatrix::Up => (row * 2 + 1, 0, 1_228_800),
MtpExpertMatrix::Down => (row, 819_200, 1_331_200),
};
let block_start = packed_row.checked_mul(blocks).ok_or(InputBindingError::Range)?;
let code_offset = base
.checked_add(code_base)
.and_then(|x| x.checked_add((block_start * 16) as u64))
.ok_or(InputBindingError::Range)?;
let scale_offset = base
.checked_add(scale_base)
.and_then(|x| x.checked_add((block_start * 2) as u64))
.ok_or(InputBindingError::Range)?;
let codes = read_exact_range(experts, code_offset, blocks * 16)?;
let scales = read_exact_range(experts, scale_offset, blocks * 2)?;
Ok((codes, scales))
}
pub(super) fn row_range(rows: usize, row_bytes: usize, first: usize, count: usize) -> InputResult<(u64, usize)> {
if count == 0 || count > MAX_ROWS || first.checked_add(count).is_none_or(|end| end > rows) {
return Err(InputBindingError::Range);
@@ -37,48 +37,64 @@ impl ModelBinding {
});
let mut artifact = self.artifact.try_borrow_mut().map_err(|_| InputBindingError::Busy)?;
let tensor = artifact.tensor(key).map_err(|_| InputBindingError::Geometry)?;
let shape = tensor.dimensions();
if shape.len() != 2
|| shape[0] == 0
|| shape[1] == 0
|| shape[0] > i32::MAX as u64
|| shape[1] > i32::MAX as u64
|| shape[0] % 256 != 0
{
return Err(InputBindingError::Geometry);
}
let n = shape[0] as usize;
let vocab = shape[1] as usize;
let (n, vocab) = native_dims(tensor.dimensions())?;
let kind = tensor.kind();
let supported = match role {
NativeOutputRole::Head => leleka_cuda_driver::native_head_supported(kind),
NativeOutputRole::Embedding => leleka_cuda_driver::native_embed_supported(kind),
};
if !supported {
return Err(InputBindingError::UnsupportedKind);
}
let row = leleka_cuda_driver::native_head_row_bytes(kind, n).map_err(|_| InputBindingError::Geometry)?;
let size = row.checked_mul(vocab).ok_or(InputBindingError::Geometry)?;
let size = native_size(&role, kind, n, vocab)?;
if tensor.byte_length() != size as u64 {
return Err(InputBindingError::Geometry);
}
artifact.validate_tensor_source(key).map_err(|_| InputBindingError::Read)?;
let mut bytes = Vec::new();
bytes.try_reserve_exact(size).map_err(|_| InputBindingError::Allocation)?;
// One genuine whole-tensor stream, bounded chunks; no per-vocabulary-row source syscalls.
artifact
.stream_rows(key, 0, vocab as u64, |part| {
if bytes.len().checked_add(part.len()).is_none_or(|end| end > size) {
return Err(std::io::Error::from(std::io::ErrorKind::InvalidData));
}
bytes.extend_from_slice(part);
Ok(())
})
.map_err(|_| InputBindingError::Read)?;
artifact.validate_tensor_source(key).map_err(|_| InputBindingError::Read)?;
if bytes.len() != size {
return Err(InputBindingError::Read);
}
let bytes = stream_whole_tensor(&mut artifact, key, vocab, size)?;
Ok(NativeOutputBlock { binding: self.identity(), kind, n, vocab, bytes: bytes.into_boxed_slice() })
}
}
fn native_dims(shape: &[u64]) -> InputResult<(usize, usize)> {
if shape.len() != 2
|| shape[0] == 0
|| shape[1] == 0
|| shape[0] > i32::MAX as u64
|| shape[1] > i32::MAX as u64
|| shape[0] % 256 != 0
{
return Err(InputBindingError::Geometry);
}
Ok((shape[0] as usize, shape[1] as usize))
}
fn native_size(role: &NativeOutputRole, kind: u32, n: usize, vocab: usize) -> InputResult<usize> {
let supported = match role {
NativeOutputRole::Head => leleka_cuda_driver::native_head_supported(kind),
NativeOutputRole::Embedding => leleka_cuda_driver::native_embed_supported(kind),
};
if !supported {
return Err(InputBindingError::UnsupportedKind);
}
let row = leleka_cuda_driver::native_head_row_bytes(kind, n).map_err(|_| InputBindingError::Geometry)?;
row.checked_mul(vocab).ok_or(InputBindingError::Geometry)
}
fn stream_whole_tensor(
artifact: &mut super::Qwen4ExpArtifact,
key: TensorRole,
vocab: usize,
size: usize,
) -> InputResult<Vec<u8>> {
artifact.validate_tensor_source(key).map_err(|_| InputBindingError::Read)?;
let mut bytes = Vec::new();
bytes.try_reserve_exact(size).map_err(|_| InputBindingError::Allocation)?;
// One genuine whole-tensor stream, bounded chunks; no per-vocabulary-row source syscalls.
artifact
.stream_rows(key, 0, vocab as u64, |part| {
if bytes.len().checked_add(part.len()).is_none_or(|end| end > size) {
return Err(std::io::Error::from(std::io::ErrorKind::InvalidData));
}
bytes.extend_from_slice(part);
Ok(())
})
.map_err(|_| InputBindingError::Read)?;
artifact.validate_tensor_source(key).map_err(|_| InputBindingError::Read)?;
if bytes.len() != size {
return Err(InputBindingError::Read);
}
Ok(bytes)
}
@@ -91,39 +91,8 @@ impl ModelBinding {
)?;
}
let row_blocks =
OUTPUT_COLUMNS.checked_div(256).filter(|&blocks| blocks != 0).ok_or(InputBindingError::Geometry)?;
let row_bytes = row_blocks.checked_mul(210).ok_or(InputBindingError::Geometry)?;
if row_bytes != OUTPUT_ROW_BYTES
|| row_bytes.checked_mul(OUTPUT_ROWS).filter(|&total| total == OUTPUT_WEIGHT_BYTES).is_none()
{
return Err(InputBindingError::Geometry);
}
let mut bytes = Vec::new();
bytes.try_reserve_exact(OUTPUT_WEIGHT_BYTES).map_err(|_| InputBindingError::Allocation)?;
for row in 0..OUTPUT_ROWS {
let row_start = bytes.len();
artifact
.stream_row(TensorRole::Global(GlobalRole::Output), row as u64, |chunk| {
let next = bytes
.len()
.checked_add(chunk.len())
.ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?;
if next > OUTPUT_WEIGHT_BYTES || next - row_start > row_bytes {
return Err(io::Error::from(io::ErrorKind::InvalidData));
}
bytes.extend_from_slice(chunk);
Ok(())
})
.map_err(|_| InputBindingError::Read)?;
if bytes.len() - row_start != row_bytes {
return Err(InputBindingError::Read);
}
}
if bytes.len() != OUTPUT_WEIGHT_BYTES {
return Err(InputBindingError::Read);
}
check_output_row_geometry()?;
let bytes = stream_output_rows(&mut artifact)?;
Ok(OutputWeights {
binding: self.identity(),
@@ -135,6 +104,45 @@ impl ModelBinding {
}
}
fn check_output_row_geometry() -> InputResult<()> {
let row_blocks =
OUTPUT_COLUMNS.checked_div(256).filter(|&blocks| blocks != 0).ok_or(InputBindingError::Geometry)?;
let row_bytes = row_blocks.checked_mul(210).ok_or(InputBindingError::Geometry)?;
if row_bytes != OUTPUT_ROW_BYTES
|| row_bytes.checked_mul(OUTPUT_ROWS).filter(|&total| total == OUTPUT_WEIGHT_BYTES).is_none()
{
return Err(InputBindingError::Geometry);
}
Ok(())
}
fn stream_output_rows(artifact: &mut super::Qwen4ExpArtifact) -> InputResult<Vec<u8>> {
let row_bytes = OUTPUT_ROW_BYTES;
let mut bytes = Vec::new();
bytes.try_reserve_exact(OUTPUT_WEIGHT_BYTES).map_err(|_| InputBindingError::Allocation)?;
for row in 0..OUTPUT_ROWS {
let row_start = bytes.len();
artifact
.stream_row(TensorRole::Global(GlobalRole::Output), row as u64, |chunk| {
let next =
bytes.len().checked_add(chunk.len()).ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?;
if next > OUTPUT_WEIGHT_BYTES || next - row_start > row_bytes {
return Err(io::Error::from(io::ErrorKind::InvalidData));
}
bytes.extend_from_slice(chunk);
Ok(())
})
.map_err(|_| InputBindingError::Read)?;
if bytes.len() - row_start != row_bytes {
return Err(InputBindingError::Read);
}
}
if bytes.len() != OUTPUT_WEIGHT_BYTES {
return Err(InputBindingError::Read);
}
Ok(bytes)
}
#[cfg(test)]
mod tests {
use super::{InputBindingError, validate_descriptor};
@@ -78,44 +78,52 @@ fn range(first: usize, count: usize, rows: usize) -> InputResult<()> {
}
Ok(())
}
fn admit_ple(a: &mut Qwen4ExpArtifact) -> InputResult<()> {
let t = a.topology();
if t.ple_layers() != [1]
|| t.hc_count() != 4
|| t.embedding_length() != N as u32
|| t.ple_conv_kernel() != 4
|| t.ple_ngram_size() != 3
{
return Err(E::Metadata);
}
// Admit every descriptor before allocation or reading any payload.
for r in [PleMatrixRole::Key, PleMatrixRole::Value] {
let (r, rows) = matrix(r);
let d = a.tensor(r).map_err(|_| E::Geometry)?;
descriptor(d.kind(), d.dimensions(), d.byte_length(), 30, &[N as u64, rows as u64], N * rows * 2)?;
}
for r in [LayerRole::PleNormKey, LayerRole::PleNormQuery, LayerRole::PleNormConv] {
let d = a.tensor(role(r)).map_err(|_| E::Geometry)?;
descriptor(d.kind(), d.dimensions(), d.byte_length(), 0, &[HC as u64], HC * 4)?;
}
let d = a.tensor(role(LayerRole::PleConv1d)).map_err(|_| E::Geometry)?;
descriptor(d.kind(), d.dimensions(), d.byte_length(), 1, &[4, HC as u64], HC * 4 * 2)?;
Ok(())
}
fn read_conv(a: &mut Qwen4ExpArtifact) -> InputResult<Box<[u16]>> {
let mut conv = Vec::new();
conv.try_reserve_exact(HC * 4).map_err(|_| E::Allocation)?;
let bytes = read_rows(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(conv.into_boxed_slice())
}
impl ModelBinding {
pub(crate) fn ple_weights(&self) -> InputResult<PleWeights> {
let mut a = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?;
let t = a.topology();
if t.ple_layers() != [1]
|| t.hc_count() != 4
|| t.embedding_length() != N as u32
|| t.ple_conv_kernel() != 4
|| t.ple_ngram_size() != 3
{
return Err(E::Metadata);
}
// Admit every descriptor before allocation or reading any payload.
for r in [PleMatrixRole::Key, PleMatrixRole::Value] {
let (r, rows) = matrix(r);
let d = a.tensor(r).map_err(|_| E::Geometry)?;
descriptor(d.kind(), d.dimensions(), d.byte_length(), 30, &[N as u64, rows as u64], N * rows * 2)?;
}
for r in [LayerRole::PleNormKey, LayerRole::PleNormQuery, LayerRole::PleNormConv] {
let d = a.tensor(role(r)).map_err(|_| E::Geometry)?;
descriptor(d.kind(), d.dimensions(), d.byte_length(), 0, &[HC as u64], HC * 4)?;
}
let d = a.tensor(role(LayerRole::PleConv1d)).map_err(|_| E::Geometry)?;
descriptor(d.kind(), d.dimensions(), d.byte_length(), 1, &[4, HC as u64], HC * 4 * 2)?;
admit_ple(&mut a)?;
let norm_key = norm(&mut a, LayerRole::PleNormKey)?;
let norm_query = norm(&mut a, LayerRole::PleNormQuery)?;
let norm_conv = norm(&mut a, LayerRole::PleNormConv)?;
let mut conv = Vec::new();
conv.try_reserve_exact(HC * 4).map_err(|_| E::Allocation)?;
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(), norm_key, norm_query, norm_conv, conv: conv.into_boxed_slice() })
let conv = read_conv(&mut a)?;
Ok(PleWeights { binding: self.identity(), norm_key, norm_query, norm_conv, conv })
}
pub(crate) fn ple_matrix_block(
&self,
@@ -28,41 +28,43 @@ pub(super) struct PlePolicy {
pub direct: bool,
}
fn policy_number(
get: &impl Fn(&str) -> Option<String>,
key: &str,
default: u64,
min: u64,
max: u64,
) -> InputResult<u64> {
match get(key) {
None => Ok(default),
Some(text) => {
let value = text.trim().parse::<u64>().map_err(|_| InputBindingError::Metadata)?;
if (min..=max).contains(&value) { Ok(value) } else { Err(InputBindingError::Metadata) }
}
}
}
fn policy_flag(get: &impl Fn(&str) -> Option<String>, key: &str, default: bool) -> InputResult<bool> {
match get(key).as_deref().map(str::trim) {
None => Ok(default),
Some("1") => Ok(true),
Some("0") => Ok(false),
Some(_) => Err(InputBindingError::Metadata),
}
}
impl PlePolicy {
pub(super) fn from_values(get: impl Fn(&str) -> Option<String>) -> InputResult<Self> {
fn number(
get: &impl Fn(&str) -> Option<String>,
key: &str,
default: u64,
min: u64,
max: u64,
) -> InputResult<u64> {
match get(key) {
None => Ok(default),
Some(text) => {
let value = text.trim().parse::<u64>().map_err(|_| InputBindingError::Metadata)?;
if (min..=max).contains(&value) { Ok(value) } else { Err(InputBindingError::Metadata) }
}
}
}
let flag = |key: &str, default: bool| -> InputResult<bool> {
match get(key).as_deref().map(str::trim) {
None => Ok(default),
Some("1") => Ok(true),
Some("0") => Ok(false),
Some(_) => Err(InputBindingError::Metadata),
}
};
let inline = flag("LELEKA_PLE_SYNC_SUBMIT", false)?;
let keepalive_ms = number(&get, "LELEKA_SSD_KEEPALIVE_MS", 100, 0, 10_000)?;
let inline = policy_flag(&get, "LELEKA_PLE_SYNC_SUBMIT", false)?;
let keepalive_ms = policy_number(&get, "LELEKA_SSD_KEEPALIVE_MS", 100, 0, 10_000)?;
Ok(Self {
enabled: flag("LELEKA_PLE_READER", true)?,
cache_rows: number(&get, "LELEKA_PLE_ROW_CACHE", 1 << 20, 0, PLE_ROWS)?,
max_inflight: number(&get, "LELEKA_PLE_INFLIGHT", 64, 1, 1024)? as usize,
enabled: policy_flag(&get, "LELEKA_PLE_READER", true)?,
cache_rows: policy_number(&get, "LELEKA_PLE_ROW_CACHE", 1 << 20, 0, PLE_ROWS)?,
max_inflight: policy_number(&get, "LELEKA_PLE_INFLIGHT", 64, 1, 1024)? as usize,
inline,
keepalive: if inline { Duration::ZERO } else { Duration::from_millis(keepalive_ms) },
keepalive_window: Duration::from_secs(number(&get, "LELEKA_SSD_KEEPALIVE_WINDOW_S", 60, 1, 86_400)?),
direct: flag("LELEKA_PLE_DIRECT", cfg!(target_os = "linux"))?,
keepalive_window: Duration::from_secs(policy_number(&get, "LELEKA_SSD_KEEPALIVE_WINDOW_S", 60, 1, 86_400)?),
direct: policy_flag(&get, "LELEKA_PLE_DIRECT", cfg!(target_os = "linux"))?,
})
}
@@ -130,6 +130,103 @@ fn descriptor(
}
Ok(())
}
fn finish_qsa_block(
m: Matrix,
role: QsaMatrixRole,
count: usize,
row: usize,
bytes: Vec<u8>,
) -> InputResult<QsaWeightBlock> {
for packed in bytes.chunks_exact(row) {
let _finite = super::decode::row(m.kind, packed, m.columns)?;
}
Ok(QsaWeightBlock { kind: kind(m.kind, role)?, columns: m.columns, rows: count, bytes: bytes.into_boxed_slice() })
}
fn check_qsa_topology(a: &Qwen4ExpArtifact) -> InputResult<()> {
let t = a.topology();
if (
t.block_count(),
t.embedding_length(),
t.attention_head_count(),
t.attention_head_count_kv(),
t.attention_key_length(),
t.attention_value_length(),
t.rope_dimension_count(),
t.indexer_head_count(),
t.indexer_key_length(),
t.indexer_top_k(),
t.context_length(),
) != (48, 2560, 24, 2, 256, 256, 64, 4, 128, 2048, 262144)
|| t.rope_frequency_base() != 10_000_000.0
|| !t.rms_epsilon().is_finite()
|| (t.rms_epsilon() - 1.0e-6).abs() > 1.0e-12
{
return Err(E::Metadata);
}
Ok(())
}
fn qsa_role(layer: u8, role: LayerRole) -> TensorRole {
TensorRole::Layer { layer, role }
}
fn admit_qsa_matrices(a: &mut Qwen4ExpArtifact, layer8: u8) -> InputResult<[Matrix; 6]> {
let definitions = [
(QsaMatrixRole::Q, LayerRole::AttnQ, 2560, 12288),
(QsaMatrixRole::K, LayerRole::AttnK, 2560, 512),
(QsaMatrixRole::V, LayerRole::AttnV, 2560, 512),
(QsaMatrixRole::IndexQ, LayerRole::IndexerQProj, 2560, 512),
(QsaMatrixRole::IndexK, LayerRole::IndexerKProj, 2560, 128),
(QsaMatrixRole::Out, LayerRole::AttnOutput, 6144, 2560),
];
let mut matrices = [Matrix { role: qsa_role(layer8, LayerRole::AttnQ), kind: 0, columns: 0, rows: 0 }; 6];
for (r, l, c, n) in definitions {
let tensor = a.tensor(qsa_role(layer8, l)).map_err(|_| E::Geometry)?;
descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), r, c, n)?;
matrices[index(r)] = Matrix { role: qsa_role(layer8, l), kind: tensor.kind(), columns: c, rows: n };
}
Ok(matrices)
}
fn read_qsa_norms(a: &mut Qwen4ExpArtifact, layer8: u8) -> InputResult<[Box<[f32]>; 4]> {
let norms = [
(LayerRole::AttnQNorm, 256),
(LayerRole::AttnKNorm, 256),
(LayerRole::IndexerQNorm, 128),
(LayerRole::IndexerKNorm, 128),
];
for (r, n) in norms {
let tensor = a.tensor(qsa_role(layer8, r)).map_err(|_| E::Geometry)?;
if tensor.kind() != 0 || tensor.dimensions() != [n as u64] || tensor.byte_length() != n as u64 * 4 {
return Err(E::Geometry);
}
}
let q = read_norm(a, qsa_role(layer8, norms[0].0), 256)?;
let k = read_norm(a, qsa_role(layer8, norms[1].0), 256)?;
let iq = read_norm(a, qsa_role(layer8, norms[2].0), 128)?;
let ik = read_norm(a, qsa_role(layer8, norms[3].0), 128)?;
Ok([q, k, iq, ik])
}
fn stream_qsa_rows(
a: &mut Qwen4ExpArtifact,
m: Matrix,
first: usize,
count: usize,
row: usize,
) -> InputResult<Vec<u8>> {
let limit = row.checked_mul(count).ok_or(E::Geometry)?;
let mut bytes = Vec::new();
bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?;
a.stream_rows(m.role, first as u64, count as u64, |chunk| {
if bytes.len().checked_add(chunk.len()).is_none_or(|n| n > 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)
}
impl ModelBinding {
pub(crate) fn qsa_weights(&self, layer: u32) -> InputResult<QsaWeights> {
let bound = self.ordered_layers().get(layer as usize).ok_or(E::Range)?;
@@ -137,59 +234,11 @@ impl ModelBinding {
return Err(E::Geometry);
}
let mut a = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?;
let t = a.topology();
if (
t.block_count(),
t.embedding_length(),
t.attention_head_count(),
t.attention_head_count_kv(),
t.attention_key_length(),
t.attention_value_length(),
t.rope_dimension_count(),
t.indexer_head_count(),
t.indexer_key_length(),
t.indexer_top_k(),
t.context_length(),
) != (48, 2560, 24, 2, 256, 256, 64, 4, 128, 2048, 262144)
|| t.rope_frequency_base() != 10_000_000.0
|| !t.rms_epsilon().is_finite()
|| (t.rms_epsilon() - 1.0e-6).abs() > 1.0e-12
{
return Err(E::Metadata);
}
check_qsa_topology(&a)?;
let layer8 = u8::try_from(layer).map_err(|_| E::Range)?;
let role = |role| TensorRole::Layer { layer: layer8, role };
let definitions = [
(QsaMatrixRole::Q, LayerRole::AttnQ, 2560, 12288),
(QsaMatrixRole::K, LayerRole::AttnK, 2560, 512),
(QsaMatrixRole::V, LayerRole::AttnV, 2560, 512),
(QsaMatrixRole::IndexQ, LayerRole::IndexerQProj, 2560, 512),
(QsaMatrixRole::IndexK, LayerRole::IndexerKProj, 2560, 128),
(QsaMatrixRole::Out, LayerRole::AttnOutput, 6144, 2560),
];
let mut matrices = [Matrix { role: role(LayerRole::AttnQ), kind: 0, columns: 0, rows: 0 }; 6];
for (r, l, c, n) in definitions {
let tensor = a.tensor(role(l)).map_err(|_| E::Geometry)?;
descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), r, c, n)?;
matrices[index(r)] = Matrix { role: role(l), kind: tensor.kind(), columns: c, rows: n };
}
let norms = [
(LayerRole::AttnQNorm, 256),
(LayerRole::AttnKNorm, 256),
(LayerRole::IndexerQNorm, 128),
(LayerRole::IndexerKNorm, 128),
];
for (r, n) in norms {
let tensor = a.tensor(role(r)).map_err(|_| E::Geometry)?;
if tensor.kind() != 0 || tensor.dimensions() != [n as u64] || tensor.byte_length() != n as u64 * 4 {
return Err(E::Geometry);
}
}
let q = read_norm(&mut a, role(norms[0].0), 256)?;
let k = read_norm(&mut a, role(norms[1].0), 256)?;
let iq = read_norm(&mut a, role(norms[2].0), 128)?;
let ik = read_norm(&mut a, role(norms[3].0), 128)?;
Ok(QsaWeights { binding: self.identity(), layer, matrices, norms: [q, k, iq, ik] })
let matrices = admit_qsa_matrices(&mut a, layer8)?;
let norms = read_qsa_norms(&mut a, layer8)?;
Ok(QsaWeights { binding: self.identity(), layer, matrices, norms })
}
pub(crate) fn qsa_matrix_block(
&self,
@@ -212,29 +261,8 @@ impl ModelBinding {
}
descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), role, m.columns, m.rows)?;
let row = super::decode::row_bytes(m.kind, m.columns)?;
let limit = row.checked_mul(count).ok_or(E::Geometry)?;
let mut bytes = Vec::new();
bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?;
a.stream_rows(m.role, first as u64, count as u64, |chunk| {
if bytes.len().checked_add(chunk.len()).is_none_or(|n| n > 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);
}
for packed in bytes.chunks_exact(row) {
let _finite = super::decode::row(m.kind, packed, m.columns)?;
}
Ok(QsaWeightBlock {
kind: kind(m.kind, role)?,
columns: m.columns,
rows: count,
bytes: bytes.into_boxed_slice(),
})
let bytes = stream_qsa_rows(&mut a, m, first, count, row)?;
finish_qsa_block(m, role, count, row, bytes)
}
}
fn block_range(first: usize, count: usize, rows: usize) -> InputResult<()> {
@@ -33,23 +33,38 @@ pub(super) fn admit_pool(binding: &ModelBinding, metadata: usize) -> Result<()>
}
Ok(())
}
fn memory_available() -> Result<u64> {
let mut text = String::new();
fn read_meminfo() -> Result<String> {
#[cfg(not(target_os = "windows"))]
File::open("/proc/meminfo")
.map_err(|_| Error::InputAllocation)?
.take(65537)
.read_to_string(&mut text)
.map_err(|_| Error::InputAllocation)?;
{
let mut text = String::new();
File::open("/proc/meminfo")
.map_err(|_| Error::InputAllocation)?
.take(65537)
.read_to_string(&mut text)
.map_err(|_| Error::InputAllocation)?;
Ok(text)
}
// Windows: the same text, rendered from GlobalMemoryStatusEx by leleka-memory.
#[cfg(target_os = "windows")]
{
use leleka_memory::ProcSource;
text = leleka_memory::RealProc.read("/proc/meminfo").map_err(|_| Error::InputAllocation)?;
leleka_memory::RealProc.read("/proc/meminfo").map_err(|_| Error::InputAllocation)
}
}
fn memory_available() -> Result<u64> {
let text = read_meminfo()?;
if text.len() > 65536 {
return Err(Error::InputAllocation);
}
let (available, total) = meminfo_fields(&text)?;
let available = available.ok_or(Error::InputAllocation)?;
let total = total.ok_or(Error::InputAllocation)?;
if total == 0 || available > total {
return Err(Error::InputAllocation);
}
Ok(available)
}
fn meminfo_fields(text: &str) -> Result<(Option<u64>, Option<u64>)> {
let mut available = None;
let mut total = None;
for line in text.lines() {
@@ -69,10 +84,5 @@ fn memory_available() -> Result<u64> {
}
*destination = Some(value.checked_mul(1024).ok_or(Error::Overflow)?);
}
let available = available.ok_or(Error::InputAllocation)?;
let total = total.ok_or(Error::InputAllocation)?;
if total == 0 || available > total {
return Err(Error::InputAllocation);
}
Ok(available)
Ok((available, total))
}
@@ -3,6 +3,8 @@
#[allow(unused_imports)]
use super::*;
type CompletedLoan<'ctx> = ([MoeWeightDescriptor; 3], Buffers<'ctx>, Option<MappedExpertCopyScratch<'ctx>>);
impl Drop for EphemeralRoutedOwner<'_> {
fn drop(&mut self) {
let _ = self.release_all();
@@ -67,11 +69,7 @@ impl<'ctx> MappedStage<'ctx> {
maximum: [usize; 3],
shape: MappedStageShape,
) -> Result<Self> {
for (bytes, ceiling) in maximum.into_iter().zip(CLOSED_MAXIMUM) {
if bytes == 0 || bytes > ceiling || !bytes.is_multiple_of(256) {
return Err(Error::InvalidDimension);
}
}
EphemeralRoutedOwner::validate_maximum(maximum)?;
let count = shape.slots();
let extra = maximum
.into_iter()
@@ -83,27 +81,28 @@ impl<'ctx> MappedStage<'ctx> {
let bank = Rc::new(context.mapped_expert_bank(lease, members).map_err(driver_error)?);
let mut owner = Self { binding: binding.identity(), context, maximum, bank: Some(bank), slots: Vec::new() };
owner.slots.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?;
let operation = (|| {
for _ in 0..count {
let mut buffers = std::array::from_fn(|_| None);
for (buffer, bytes) in buffers.iter_mut().zip(maximum) {
*buffer = Some(context.allocate(bytes).map_err(driver_error)?);
}
let scratch = context.mapped_expert_copy_scratch().map_err(driver_error)?;
owner.slots.push(MappedSlot::Idle { buffers, scratch: Some(scratch) });
}
EphemeralRoutedOwner::room(context, 0)?;
if owner.metadata_bytes() > HOST_LIMIT {
return Err(Error::InputAllocation);
}
Ok(())
})();
if let Err(primary) = operation {
if let Err(primary) = owner.fill_slots(count) {
let _ = owner.release_all();
return Err(primary);
}
Ok(owner)
}
fn fill_slots(&mut self, count: usize) -> Result<()> {
let (context, maximum) = (self.context, self.maximum);
for _ in 0..count {
let mut buffers = std::array::from_fn(|_| None);
for (buffer, bytes) in buffers.iter_mut().zip(maximum) {
*buffer = Some(context.allocate(bytes).map_err(driver_error)?);
}
let scratch = context.mapped_expert_copy_scratch().map_err(driver_error)?;
self.slots.push(MappedSlot::Idle { buffers, scratch: Some(scratch) });
}
EphemeralRoutedOwner::room(context, 0)?;
if self.metadata_bytes() > HOST_LIMIT {
return Err(Error::InputAllocation);
}
Ok(())
}
pub(super) fn metadata_bytes(&self) -> usize {
std::mem::size_of::<Self>()
+ self.slots.capacity() * std::mem::size_of::<MappedSlot<'ctx>>()
@@ -160,45 +159,67 @@ impl<'ctx> MappedStage<'ctx> {
return Err(Error::InputAllocation);
}
// Same exact Gate then Up then Down full encoded finite precedence.
let spans = [
source.mapped_span(member, ROLES[0]).map_err(binding_error)?,
source.mapped_span(member, ROLES[1]).map_err(binding_error)?,
source.mapped_span(member, ROLES[2]).map_err(binding_error)?,
];
let spans = Self::mapped_spans(source, member)?;
let bank = self.bank.as_ref().ok_or(Error::IdentityMismatch)?;
if !bank.eligible(&spans) {
return Err(Error::IdentityMismatch);
}
source.finish().map_err(binding_error)?;
let prior = std::mem::replace(&mut self.slots[slot], MappedSlot::InUse);
let MappedSlot::Idle { mut buffers, mut scratch } = prior else {
return Err(Error::IdentityMismatch);
};
for (buffer, key) in buffers.iter_mut().zip(&keys) {
let (whole, scratch) = Self::prepare_whole(self.context, &mut self.slots[slot], &keys)?;
let copy = bank.copy_triplet(spans, whole, scratch).map_err(driver_error)?;
self.slots[slot] = MappedSlot::Pending { keys, copy };
Ok(())
}
fn mapped_spans(
source: &MoeRoutedSourceScope<'_, '_>,
member: usize,
) -> Result<[leleka_model_format::qwen4exp::ResidentExpertBankSpan; 3]> {
Ok([
source.mapped_span(member, ROLES[0]).map_err(binding_error)?,
source.mapped_span(member, ROLES[1]).map_err(binding_error)?,
source.mapped_span(member, ROLES[2]).map_err(binding_error)?,
])
}
fn reshape_buffers(
context: &'ctx Context<'ctx>,
buffers: &mut Buffers<'ctx>,
keys: &[MoeWeightDescriptor; 3],
) -> Result<()> {
for (buffer, key) in buffers.iter_mut().zip(keys) {
if buffer.as_ref().is_some_and(|b| b.len() != key.bytes) {
buffer.take().ok_or(Error::IdentityMismatch)?.release().map_err(driver_error)?;
}
}
let extra = buffers
.iter()
.zip(&keys)
.zip(keys)
.filter(|(b, _)| b.is_none())
.try_fold(0usize, |n, (_, key)| n.checked_add(key.bytes).ok_or(Error::Overflow))?;
EphemeralRoutedOwner::room(self.context, extra)?;
for (buffer, key) in buffers.iter_mut().zip(&keys) {
EphemeralRoutedOwner::room(context, extra)?;
for (buffer, key) in buffers.iter_mut().zip(keys) {
if buffer.is_none() {
*buffer = Some(self.context.allocate(key.bytes).map_err(driver_error)?);
*buffer = Some(context.allocate(key.bytes).map_err(driver_error)?);
}
}
Ok(())
}
/// Takes the Idle slot, resizes its whole buffers to the keys and hands them out for the copy.
fn prepare_whole(
context: &'ctx Context<'ctx>,
slot: &mut MappedSlot<'ctx>,
keys: &[MoeWeightDescriptor; 3],
) -> Result<([DeviceBuffer<'ctx>; 3], MappedExpertCopyScratch<'ctx>)> {
let prior = std::mem::replace(slot, MappedSlot::InUse);
let MappedSlot::Idle { mut buffers, mut scratch } = prior else {
return Err(Error::IdentityMismatch);
};
Self::reshape_buffers(context, &mut buffers, keys)?;
let whole = [
buffers[0].take().ok_or(Error::IdentityMismatch)?,
buffers[1].take().ok_or(Error::IdentityMismatch)?,
buffers[2].take().ok_or(Error::IdentityMismatch)?,
];
let copy =
bank.copy_triplet(spans, whole, scratch.take().ok_or(Error::IdentityMismatch)?).map_err(driver_error)?;
self.slots[slot] = MappedSlot::Pending { keys, copy };
Ok(())
Ok((whole, scratch.take().ok_or(Error::IdentityMismatch)?))
}
pub(super) fn wait(&mut self, slot: usize, binding: &ModelBinding) -> Result<()> {
self.validate(binding, slot)?;
@@ -216,6 +237,19 @@ impl<'ctx> MappedStage<'ctx> {
self.slots[slot] = MappedSlot::Completed { keys, buffers: whole.map(Some), scratch: Some(scratch) };
Ok(())
}
fn loan_completed(&mut self, slot: usize, fresh: &[MoeWeightDescriptor; 3]) -> Result<CompletedLoan<'ctx>> {
let MappedSlot::Completed { keys, .. } = &self.slots[slot] else {
return Err(Error::IdentityMismatch);
};
if keys != fresh {
return Err(Error::IdentityMismatch);
}
let prior = std::mem::replace(&mut self.slots[slot], MappedSlot::InUse);
let MappedSlot::Completed { keys, buffers, scratch } = prior else {
return Err(Error::IdentityMismatch);
};
Ok((keys, buffers, scratch))
}
pub(super) fn with_triplet<'source, 'group, T>(
&mut self,
slot: usize,
@@ -230,28 +264,14 @@ impl<'ctx> MappedStage<'ctx> {
) -> Result<T> {
self.validate(binding, slot)?;
let fresh = EphemeralRoutedOwner::keys(binding, source, member)?;
let MappedSlot::Completed { keys, .. } = &self.slots[slot] else {
return Err(Error::IdentityMismatch);
};
if *keys != fresh {
return Err(Error::IdentityMismatch);
}
let prior = std::mem::replace(&mut self.slots[slot], MappedSlot::InUse);
let MappedSlot::Completed { keys, buffers, scratch } = prior else {
return Err(Error::IdentityMismatch);
};
let (keys, buffers, scratch) = self.loan_completed(slot, &fresh)?;
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
consume(
[
buffers[0].as_ref().ok_or(Error::IdentityMismatch)?,
buffers[1].as_ref().ok_or(Error::IdentityMismatch)?,
buffers[2].as_ref().ok_or(Error::IdentityMismatch)?,
],
keys,
source,
)
consume(EphemeralRoutedOwner::borrow_triplet(&buffers)?, keys, source)
}));
self.slots[slot] = MappedSlot::Idle { buffers, scratch };
self.settle_loan(result)
}
fn settle_loan<T>(&mut self, result: std::thread::Result<Result<T>>) -> Result<T> {
match result {
Ok(value) => {
let value = value?;
@@ -12,11 +12,7 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
context: &'ctx Context<'ctx>,
maximum: [usize; 3],
) -> Result<Self> {
for (bytes, ceiling) in maximum.into_iter().zip(CLOSED_MAXIMUM) {
if bytes == 0 || bytes > ceiling || !bytes.is_multiple_of(256) {
return Err(Error::InvalidDimension);
}
}
Self::validate_maximum(maximum)?;
let total = maximum
.into_iter()
.try_fold(0usize, |n, b| n.checked_add(b).ok_or(Error::Overflow))?
@@ -33,22 +29,31 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
#[cfg(test)]
completed_loans: 0,
};
let allocation = (|| -> Result<()> {
for slot in &mut owner.slots {
let Slot::Idle { buffers, .. } = slot else {
return Err(Error::IdentityMismatch);
};
for (destination, &bytes) in buffers.iter_mut().zip(&maximum) {
*destination = Some(context.allocate(bytes).map_err(driver_error)?);
}
}
Self::room(context, 0)
})();
match allocation {
match owner.allocate_idle() {
Ok(()) => Ok(owner),
Err(primary) => owner.fail(primary),
}
}
pub(in super::super) fn validate_maximum(maximum: [usize; 3]) -> Result<()> {
for (bytes, ceiling) in maximum.into_iter().zip(CLOSED_MAXIMUM) {
if bytes == 0 || bytes > ceiling || !bytes.is_multiple_of(256) {
return Err(Error::InvalidDimension);
}
}
Ok(())
}
fn allocate_idle(&mut self) -> Result<()> {
let (context, maximum) = (self.context, self.maximum);
for slot in &mut self.slots {
let Slot::Idle { buffers, .. } = slot else {
return Err(Error::IdentityMismatch);
};
for (destination, &bytes) in buffers.iter_mut().zip(&maximum) {
*destination = Some(context.allocate(bytes).map_err(driver_error)?);
}
}
Self::room(context, 0)
}
pub(in super::super) fn room(context: &Context<'_>, extra: usize) -> Result<()> {
let needed = extra.checked_add(RESERVE).ok_or(Error::Overflow)?;
@@ -3,6 +3,13 @@
#[allow(unused_imports)]
use super::*;
/// Host payloads taken out of the source blocks, with the pair vector reserved for the copy.
struct DetachedPayloads<'ctx> {
pairs: Vec<(DeviceBuffer<'ctx>, Vec<u8>)>,
bytes: [Option<Vec<u8>>; 3],
host_bytes: usize,
}
impl<'ctx> EphemeralRoutedOwner<'ctx> {
pub(in super::super) fn stage_inner(
&mut self,
@@ -13,6 +20,23 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
) -> Result<()> {
self.validate_slot(binding, slot)?;
let keys = Self::keys(binding, source, member)?;
let pair_metadata = self.admit_stage(slot, &keys)?;
self.install_idle_buffers(slot, &keys)?;
let mut blocks = self.read_stage_blocks(source, member, &keys, pair_metadata)?;
let detached = Self::detach_payloads(&mut blocks)?;
if self.host_bytes()?.checked_add(detached.host_bytes).ok_or(Error::Overflow)? > HOST_LIMIT {
return Err(Error::InputAllocation);
}
self.enqueue_stage(slot, keys, detached)
}
fn fixed_preparation() -> usize {
std::mem::size_of::<[Option<MoeExpertBlock>; 3]>()
+ std::mem::size_of::<[Option<Vec<u8>>; 3]>()
+ std::mem::size_of::<Vec<(DeviceBuffer<'ctx>, Vec<u8>)>>()
+ std::mem::size_of::<[MoeWeightDescriptor; 3]>()
}
/// Key extents, slot state and the host peak; returns the pair metadata bytes.
fn admit_stage(&self, slot: usize, keys: &[MoeWeightDescriptor; 3]) -> Result<usize> {
for (key, &maximum) in keys.iter().zip(&self.maximum) {
if key.bytes > maximum {
return Err(Error::InputAllocation);
@@ -24,13 +48,9 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
let raw = keys.iter().try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?;
// The complete current role Boxes, any transient read/copy and all old
// pending Vec capacities coexist. No assumption that payload==capacity.
let fixed_preparation = std::mem::size_of::<[Option<MoeExpertBlock>; 3]>()
+ std::mem::size_of::<[Option<Vec<u8>>; 3]>()
+ std::mem::size_of::<Vec<(DeviceBuffer<'ctx>, Vec<u8>)>>()
+ std::mem::size_of::<[MoeWeightDescriptor; 3]>();
let pair_metadata = 3usize
.checked_mul(std::mem::size_of::<(DeviceBuffer<'ctx>, Vec<u8>)>())
.and_then(|n| n.checked_add(fixed_preparation))
.and_then(|n| n.checked_add(Self::fixed_preparation()))
.ok_or(Error::Overflow)?;
let peak = self
.host_bytes()?
@@ -40,26 +60,39 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
if peak > HOST_LIMIT {
return Err(Error::InputAllocation);
}
Ok(pair_metadata)
}
/// Reuses exact-size whole owners, allocates the rest and reinstalls them as Idle.
fn install_idle_buffers(&mut self, slot: usize, keys: &[MoeWeightDescriptor; 3]) -> Result<()> {
let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse);
let Slot::Idle { layer: _, mut buffers } = previous else {
return Err(Error::IdentityMismatch);
};
let exact = buffers.iter().zip(&keys).all(|(b, k)| b.as_ref().is_some_and(|b| b.len() == k.bytes));
let exact = buffers.iter().zip(keys).all(|(b, k)| b.as_ref().is_some_and(|b| b.len() == k.bytes));
if !exact {
close_buffers(&mut buffers)?;
}
// Exact-size whole owners may be reused after complete overwrite even across layers; never pass padded views.
let extra = buffers.iter().zip(&keys).try_fold(0usize, |n, (buffer, key)| {
let extra = buffers.iter().zip(keys).try_fold(0usize, |n, (buffer, key)| {
n.checked_add(if buffer.is_none() { key.bytes } else { 0 }).ok_or(Error::Overflow)
})?;
Self::room(self.context, extra)?;
for (buffer, key) in buffers.iter_mut().zip(&keys) {
for (buffer, key) in buffers.iter_mut().zip(keys) {
if buffer.is_none() {
*buffer = Some(self.context.allocate(key.bytes).map_err(driver_error)?);
}
}
// Install actual owners so any subsequent refusal drains both slots.
self.slots[slot] = Slot::Idle { layer: Some(keys[0].layer), buffers };
Ok(())
}
fn read_stage_blocks(
&self,
source: &mut MoeRoutedSourceScope<'_, '_>,
member: usize,
keys: &[MoeWeightDescriptor; 3],
pair_metadata: usize,
) -> Result<[Option<MoeExpertBlock>; 3]> {
let mut blocks = std::array::from_fn::<_, 3, _>(|_| None);
let mut retained = self.host_bytes()?.checked_add(pair_metadata).ok_or(Error::Overflow)?;
for (index, role) in ROLES.into_iter().enumerate() {
@@ -77,23 +110,32 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
blocks[index] = Some(block);
}
source.finish().map_err(binding_error)?;
Ok(blocks)
}
fn detach_payloads(blocks: &mut [Option<MoeExpertBlock>; 3]) -> Result<DetachedPayloads<'ctx>> {
let mut pairs = Vec::new();
pairs.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
let actual_metadata = pairs
.capacity()
.checked_mul(std::mem::size_of::<(DeviceBuffer<'ctx>, Vec<u8>)>())
.and_then(|n| n.checked_add(fixed_preparation))
.and_then(|n| n.checked_add(Self::fixed_preparation()))
.ok_or(Error::Overflow)?;
let mut host_bytes = actual_metadata;
let mut bytes: [Option<Vec<u8>>; 3] = std::array::from_fn(|_| None);
for (destination, block) in bytes.iter_mut().zip(&mut blocks) {
for (destination, block) in bytes.iter_mut().zip(blocks) {
let payload = block.take().ok_or(Error::IdentityMismatch)?.into_bytes().into_vec();
host_bytes = host_bytes.checked_add(payload.capacity()).ok_or(Error::Overflow)?;
*destination = Some(payload);
}
if self.host_bytes()?.checked_add(host_bytes).ok_or(Error::Overflow)? > HOST_LIMIT {
return Err(Error::InputAllocation);
}
Ok(DetachedPayloads { pairs, bytes, host_bytes })
}
fn enqueue_stage(
&mut self,
slot: usize,
keys: [MoeWeightDescriptor; 3],
detached: DetachedPayloads<'ctx>,
) -> Result<()> {
let DetachedPayloads { mut pairs, mut bytes, host_bytes } = detached;
let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse);
let Slot::Idle { mut buffers, .. } = previous else {
return Err(Error::IdentityMismatch);
@@ -149,34 +191,48 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
};
match observed {
OwnedCopyPoll::Pending(copy) => self.slots[slot] = Slot::Pending { keys, copy, host_bytes },
OwnedCopyPoll::Complete(receipt) => {
if receipt.len() != 3 {
return Err(Error::IdentityMismatch);
}
let mut pairs = receipt.into_pairs();
let mut buffers = std::array::from_fn(|_| None);
let mut validation = Ok(());
for (index, destination) in buffers.iter_mut().enumerate() {
if let Some((buffer, payload)) = pairs[index].take() {
if buffer.len() != keys[index].bytes || payload.len() != keys[index].bytes {
validation = Err(Error::IdentityMismatch);
}
*destination = Some(buffer);
drop(payload); // Actual event + unregister completed.
} else {
validation = Err(Error::IdentityMismatch);
}
}
if pairs.iter().any(Option::is_some) {
validation = Err(Error::IdentityMismatch);
}
self.slots[slot] = Slot::Completed { keys, buffers };
validation?;
}
OwnedCopyPoll::Complete(receipt) => self.install_completed(slot, keys, receipt)?,
}
Ok(())
}
fn install_completed(
&mut self,
slot: usize,
keys: [MoeWeightDescriptor; 3],
receipt: leleka_cuda_driver::CompletedOwnedCopy<'ctx>,
) -> Result<()> {
if receipt.len() != 3 {
return Err(Error::IdentityMismatch);
}
let (buffers, valid) = Self::unpack_pairs(receipt.into_pairs(), &keys);
self.slots[slot] = Slot::Completed { keys, buffers };
if !valid {
return Err(Error::IdentityMismatch);
}
Ok(())
}
/// Takes the whole destination buffers out of a finished copy and drops the staging payloads.
pub(in super::super) fn unpack_pairs(
mut pairs: leleka_cuda_driver::OwnedCopyPairs<'ctx>,
keys: &[MoeWeightDescriptor; 3],
) -> (Buffers<'ctx>, bool) {
let mut buffers = std::array::from_fn(|_| None);
let mut valid = true;
for (index, destination) in buffers.iter_mut().enumerate() {
if let Some((buffer, payload)) = pairs[index].take() {
valid &= buffer.len() == keys[index].bytes && payload.len() == keys[index].bytes;
*destination = Some(buffer);
drop(payload); // Actual event + unregister completed.
} else {
valid = false;
}
}
valid &= !pairs.iter().any(Option::is_some);
(buffers, valid)
}
/// Fresh source equality and explicit callback finish are required even though bytes completed.
/// Caller retains real current-row/txn/origin/cancel/packet checks; these
/// buffers are temporary execution owners, never adaptive cache hits.
@@ -202,6 +258,9 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
if self.mapped.is_some() && result.is_ok() {
self.completed_loans = self.completed_loans.checked_add(1).ok_or(Error::Overflow)?;
}
self.settle_loan(result, cancel_observed)
}
fn settle_loan<T>(&mut self, result: Result<T>, cancel_observed: &Cell<bool>) -> Result<T> {
match result {
Ok(value) => Ok(value),
// Healthy cancellation: the loaned slot is already back to Idle with its whole
@@ -4,6 +4,30 @@
use super::*;
impl<'ctx> EphemeralRoutedOwner<'ctx> {
fn loan_completed(
&mut self,
slot: usize,
fresh: &[MoeWeightDescriptor; 3],
) -> Result<([MoeWeightDescriptor; 3], Buffers<'ctx>)> {
let Slot::Completed { keys, .. } = &self.slots[slot] else {
return Err(Error::IdentityMismatch);
};
if keys != fresh {
return Err(Error::IdentityMismatch);
}
let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse);
let Slot::Completed { keys, buffers } = previous else {
return Err(Error::IdentityMismatch);
};
Ok((keys, buffers))
}
pub(in super::super) fn borrow_triplet<'b>(buffers: &'b Buffers<'ctx>) -> Result<[&'b DeviceBuffer<'ctx>; 3]> {
Ok([
buffers[0].as_ref().ok_or(Error::IdentityMismatch)?,
buffers[1].as_ref().ok_or(Error::IdentityMismatch)?,
buffers[2].as_ref().ok_or(Error::IdentityMismatch)?,
])
}
pub(in super::super) fn with_triplet_inner<'source, 'group, T>(
&mut self,
slot: usize,
@@ -18,29 +42,18 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
) -> Result<T> {
self.validate_slot(binding, slot)?;
let fresh = Self::keys(binding, source, member)?;
let Slot::Completed { keys, .. } = &self.slots[slot] else {
return Err(Error::IdentityMismatch);
};
if *keys != fresh {
return Err(Error::IdentityMismatch);
}
let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse);
let Slot::Completed { keys, buffers } = previous else {
return Err(Error::IdentityMismatch);
};
let (keys, buffers) = self.loan_completed(slot, &fresh)?;
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let whole = [
buffers[0].as_ref().ok_or(Error::IdentityMismatch)?,
buffers[1].as_ref().ok_or(Error::IdentityMismatch)?,
buffers[2].as_ref().ok_or(Error::IdentityMismatch)?,
];
consume(whole, keys, source)
consume(Self::borrow_triplet(&buffers)?, keys, source)
}));
// The caller explicitly finishes at its packet/current-row boundary.
// The enclosing genuine with_moe_routed_source rejects success without
// that finish and always attempts cleanup on an error. Do not finish
// twice or move the callback's source check past its coverage gate.
self.slots[slot] = Slot::Idle { layer: Some(keys[0].layer), buffers };
self.settle_inner_loan(result)
}
fn settle_inner_loan<T>(&mut self, result: std::thread::Result<Result<T>>) -> Result<T> {
match result {
Ok(result) => {
let value = result?;
@@ -77,6 +90,23 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
Err(primary) => self.fail(primary),
}
}
fn drain_pending(
&mut self,
index: usize,
keys: [MoeWeightDescriptor; 3],
copy: PendingOwnedCopy<'ctx>,
) -> Result<()> {
let receipt = copy.wait().map_err(driver_error)?;
if receipt.len() != 3 {
return Err(Error::IdentityMismatch);
}
let (buffers, valid) = Self::unpack_pairs(receipt.into_pairs(), &keys);
self.slots[index] = Slot::Idle { layer: Some(keys[0].layer), buffers };
if !valid {
return Err(Error::IdentityMismatch);
}
Ok(())
}
pub(in super::super) fn drain_inner(&mut self) -> Result<()> {
if let Some(mapped) = &mut self.mapped {
return mapped.drain();
@@ -87,27 +117,7 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
Slot::Idle { layer, buffers } => (layer, buffers),
Slot::Completed { keys, buffers } => (Some(keys[0].layer), buffers),
Slot::Pending { keys, copy, .. } => {
let receipt = copy.wait().map_err(driver_error)?;
if receipt.len() != 3 {
return Err(Error::IdentityMismatch);
}
let mut pairs = receipt.into_pairs();
let mut buffers = std::array::from_fn(|_| None);
let mut valid = true;
for (role, buffer) in buffers.iter_mut().enumerate() {
if let Some((device, source)) = pairs[role].take() {
valid &= device.len() == keys[role].bytes && source.len() == keys[role].bytes;
*buffer = Some(device);
drop(source);
} else {
valid = false;
}
}
valid &= !pairs.iter().any(Option::is_some);
self.slots[index] = Slot::Idle { layer: Some(keys[0].layer), buffers };
if !valid {
return Err(Error::IdentityMismatch);
}
self.drain_pending(index, keys, copy)?;
continue;
}
Slot::InUse => return Err(Error::IdentityMismatch),
@@ -8,6 +8,12 @@ fn key(layer: u32, expert: u32, role: u8) -> MoeWeightDescriptor {
#[test]
fn original_scan_first_actual_age_seed_learned_main_protection_and_capacity() {
seeded_index_matches_scan_and_stays_coherent();
seed_refusals_restore_the_empty_owner();
learned_main_slot_bound_matches_expanded_multiset();
}
fn seeded_index_matches_scan_and_stays_coherent() {
// Reference FIRST: independent actual-age min over the complete routed map,
// including entries belonging to the historical ranked prefix.
let entries: Vec<_> =
@@ -34,9 +40,16 @@ fn original_scan_first_actual_age_seed_learned_main_protection_and_capacity() {
entries.iter().filter(|(key, _)| *key != victim).min_by_key(|(_, age)| *age).map(|(key, _)| *key);
assert_eq!(index.oldest(&[]).unwrap(), next_reference);
assert!(index.validate_coherence());
seeding_a_populated_index_is_refused(&mut index, &entries);
}
fn seeding_a_populated_index_is_refused(index: &mut LruIndex, entries: &[(MoeWeightDescriptor, u64)]) {
let before = index.oldest(&[]).unwrap();
assert!(index.seed_existing(49, entries.iter().copied()).is_err());
assert_eq!(index.oldest(&[]).unwrap(), before);
}
fn seed_refusals_restore_the_empty_owner() {
// Seed refusals restore the existing empty owner completely: duplicate full
// coordinate, changed descriptor sharing a slot, stale/zero/equal age, foreign
// coordinate and real owner-age overflow. A valid retry uses the same capacity.
@@ -63,6 +76,9 @@ fn original_scan_first_actual_age_seed_learned_main_protection_and_capacity() {
assert_eq!(empty.matches_existing(2, [(key(0, 0, 0), 2)].into_iter()).unwrap(), 1);
assert!(empty.matches_existing(2, [(collision, 2)].into_iter()).is_err());
assert!(empty.matches_existing(1, [(key(0, 0, 0), 2)].into_iter()).is_err());
}
fn learned_main_slot_bound_matches_expanded_multiset() {
// Independent expanded multiset FIRST proves the full per-matrix cardinality
// bound (rather than prefix-triplet count) under all actual role charges.
let charges = std::array::from_fn::<_, 48, _>(|layer| [3 + layer, 5 + layer, 9 + layer]);
@@ -69,15 +69,8 @@ impl LruIndex {
return Err(Error::Overflow);
}
age = next_age;
let key_slot = slot(key)?;
for &(prior, _) in &updates[..index] {
if slot(prior)? == key_slot {
return Err(Error::IdentityMismatch);
}
}
if self.position(key)?.is_none() {
additional += 1;
}
let is_new = self.admit_update(updates, index)?;
additional += usize::from(is_new);
nodes[index] = Some(Node { key, age: next_age });
}
if self.heap.len().checked_add(additional).ok_or(Error::Overflow)? > self.limit {
@@ -91,6 +84,17 @@ impl LruIndex {
len: updates.len(),
})
}
/// Refuses a repeated key slot inside one batch; reports whether the key is not yet resident.
fn admit_update(&self, updates: &[(MoeWeightDescriptor, u64)], index: usize) -> Result<bool> {
let key = updates[index].0;
let key_slot = slot(key)?;
for &(prior, _) in &updates[..index] {
if slot(prior)? == key_slot {
return Err(Error::IdentityMismatch);
}
}
Ok(self.position(key)?.is_none())
}
pub(in super::super) fn commit_updates(&mut self, prepared: PreparedUpdates) -> Result<()> {
if prepared.owner != self.positions.as_ptr() as usize
|| prepared.old_len != self.heap.len()
@@ -176,6 +180,34 @@ impl LruIndex {
pub(in super::super) fn oldest(&self, protected: &[MoeWeightDescriptor]) -> Result<Option<MoeWeightDescriptor>> {
self.search(protected).map(|(key, _)| key)
}
fn frontier_minimum(&self, frontier: &[usize; MAX_PROTECTED + 1], len: usize) -> usize {
let mut minimum = 0;
for i in 1..len {
if self.heap[frontier[i]].age < self.heap[frontier[minimum]].age {
minimum = i;
}
}
minimum
}
fn expand_children(
&self,
frontier: &mut [usize; MAX_PROTECTED + 1],
mut len: usize,
position: usize,
) -> Result<usize> {
for child in [position * 2 + 1, position * 2 + 2] {
if child < self.heap.len() {
// At most P protected nodes are expanded, so the frontier
// can contain at most P+1 nodes. No resident scan occurs.
if len == frontier.len() {
return Err(Error::IdentityMismatch);
}
frontier[len] = child;
len += 1;
}
}
Ok(len)
}
pub(super) fn search(&self, protected: &[MoeWeightDescriptor]) -> Result<(Option<MoeWeightDescriptor>, usize)> {
if protected.len() > MAX_PROTECTED {
return Err(Error::InvalidDimension);
@@ -190,12 +222,7 @@ impl LruIndex {
let mut len = 1;
let mut visits = 0;
while len != 0 {
let mut minimum = 0;
for i in 1..len {
if self.heap[frontier[i]].age < self.heap[frontier[minimum]].age {
minimum = i;
}
}
let minimum = self.frontier_minimum(&frontier, len);
let position = frontier[minimum];
len -= 1;
frontier[minimum] = frontier[len];
@@ -204,17 +231,7 @@ impl LruIndex {
if !protected.contains(&node.key) {
return Ok((Some(node.key), visits));
}
for child in [position * 2 + 1, position * 2 + 2] {
if child < self.heap.len() {
// At most P protected nodes are expanded, so the frontier
// can contain at most P+1 nodes. No resident scan occurs.
if len == frontier.len() {
return Err(Error::IdentityMismatch);
}
frontier[len] = child;
len += 1;
}
}
len = self.expand_children(&mut frontier, len, position)?;
}
Ok((None, visits))
}
@@ -12,40 +12,10 @@ impl LruIndex {
actual_age: u64,
entries: impl Iterator<Item = (MoeWeightDescriptor, u64)>,
) -> Result<()> {
if !self.heap.is_empty()
|| self.last_age != 0
|| self.positions.len() != MAX_KEYS
|| self.positions.iter().any(|&p| p != ABSENT)
{
if !self.is_pristine() {
return Err(Error::IdentityMismatch);
}
let operation = (|| {
for (key, age) in entries {
let key_slot = slot(key)?;
if age == 0 || age > actual_age || self.positions[key_slot] != ABSENT {
return Err(Error::IdentityMismatch);
}
if self.heap.len() >= self.limit || self.heap.len() >= self.heap.capacity() {
return Err(Error::InputAllocation);
}
self.positions[key_slot] = self.heap.len();
self.heap.push(Node { key, age });
}
// In-place unstable sort allocates no auxiliary owner; values are the
// real prior Entry ages, never reminted from iteration order.
self.heap.sort_unstable_by_key(|node| node.age);
if self.heap.windows(2).any(|pair| pair[0].age == pair[1].age) {
return Err(Error::IdentityMismatch);
}
for (position, node) in self.heap.iter().enumerate() {
self.positions[slot(node.key)?] = position;
}
self.last_age = actual_age;
if !self.seed_coherent(actual_age) {
return Err(Error::IdentityMismatch);
}
Ok(())
})();
let operation = self.load_seed(actual_age, entries);
if operation.is_err() {
self.heap.clear();
self.positions.fill(ABSENT);
@@ -54,6 +24,41 @@ impl LruIndex {
operation
}
#[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
fn is_pristine(&self) -> bool {
self.heap.is_empty()
&& self.last_age == 0
&& self.positions.len() == MAX_KEYS
&& !self.positions.iter().any(|&p| p != ABSENT)
}
#[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
fn load_seed(&mut self, actual_age: u64, entries: impl Iterator<Item = (MoeWeightDescriptor, u64)>) -> Result<()> {
for (key, age) in entries {
let key_slot = slot(key)?;
if age == 0 || age > actual_age || self.positions[key_slot] != ABSENT {
return Err(Error::IdentityMismatch);
}
if self.heap.len() >= self.limit || self.heap.len() >= self.heap.capacity() {
return Err(Error::InputAllocation);
}
self.positions[key_slot] = self.heap.len();
self.heap.push(Node { key, age });
}
// In-place unstable sort allocates no auxiliary owner; values are the
// real prior Entry ages, never reminted from iteration order.
self.heap.sort_unstable_by_key(|node| node.age);
if self.heap.windows(2).any(|pair| pair[0].age == pair[1].age) {
return Err(Error::IdentityMismatch);
}
for (position, node) in self.heap.iter().enumerate() {
self.positions[slot(node.key)?] = position;
}
self.last_age = actual_age;
if !self.seed_coherent(actual_age) {
return Err(Error::IdentityMismatch);
}
Ok(())
}
#[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
pub(super) fn seed_coherent(&self, actual_age: u64) -> bool {
if self.heap.len() > self.limit || self.positions.len() != MAX_KEYS || self.last_age > actual_age {
return false;
@@ -81,25 +81,38 @@ fn original_min_first_bounded_lru_index_matches_scan_and_refuses_incoherence() {
assert!(index.validate_coherence());
compare_old_first(&index, &oracle, &[]);
let keys = [descriptor(0), descriptor(1), descriptor(2), descriptor(3)];
update(&mut index, &mut oracle, &[(keys[0], 1), (keys[1], 2), (keys[2], 3)]);
update(&mut index, &mut oracle, &[(keys[3], 4)]);
basic_updates_and_removals(&mut index, &mut oracle, &keys);
descriptor_field_collisions_are_refused(&mut index, &keys);
let invalid = invalid_coordinates_are_refused(&index, &keys);
batch_refusals_are_atomic(&mut index, &mut oracle, &keys, invalid);
partial_triplet_states(&keys, invalid);
deterministic_long_churn();
let (mut full, mut full_oracle, capacities, age) = fill_every_domain_slot();
exercise_full_index(&mut full, &mut full_oracle, capacities, age);
}
fn basic_updates_and_removals(index: &mut LruIndex, oracle: &mut Oracle, keys: &[MoeWeightDescriptor; 4]) {
update(index, oracle, &[(keys[0], 1), (keys[1], 2), (keys[2], 3)]);
update(index, oracle, &[(keys[3], 4)]);
for protected in [&keys[..0], &keys[..1], &keys[..3], &keys[..4]] {
compare_old_first(&index, &oracle, protected);
compare_old_first(index, oracle, protected);
}
compare_old_first(&index, &oracle, &[descriptor(20), keys[0], keys[0]]);
let before = state(&index);
compare_old_first(index, oracle, &[descriptor(20), keys[0], keys[0]]);
let before = state(index);
assert!(index.oldest(&[keys[0]; 5]).is_err());
assert_eq!(state(&index), before);
update(&mut index, &mut oracle, &[(keys[0], 5), (keys[2], 6)]);
compare_old_first(&index, &oracle, &[]);
assert_eq!(state(index), before);
update(index, oracle, &[(keys[0], 5), (keys[2], 6)]);
compare_old_first(index, oracle, &[]);
index.remove(keys[1]).unwrap();
oracle.remove(&keys[1]);
assert_live(&index, &oracle);
compare_old_first(&index, &oracle, &[]);
let before = state(&index);
assert_live(index, oracle);
compare_old_first(index, oracle, &[]);
let before = state(index);
assert!(index.remove(keys[1]).is_err());
assert_eq!(state(&index), before);
assert_eq!(state(index), before);
}
fn descriptor_field_collisions_are_refused(index: &mut LruIndex, keys: &[MoeWeightDescriptor; 4]) {
// Every full descriptor field remains associated with its logical matrix slot.
for field in 0..4 {
let mut collision = keys[0];
@@ -109,11 +122,14 @@ fn original_min_first_bounded_lru_index_matches_scan_and_refuses_incoherence() {
2 => collision.columns += 1,
_ => collision.bytes += 1,
}
refused_prepare(&index, &[(collision, 7)]);
let before = state(&index);
refused_prepare(index, &[(collision, 7)]);
let before = state(index);
assert!(index.remove(collision).is_err());
assert_eq!(state(&index), before);
assert_eq!(state(index), before);
}
}
fn invalid_coordinates_are_refused(index: &LruIndex, keys: &[MoeWeightDescriptor; 4]) -> MoeWeightDescriptor {
let mut invalid = keys[0];
for field in 0..4 {
match field {
@@ -131,38 +147,53 @@ fn original_min_first_bounded_lru_index_matches_scan_and_refuses_incoherence() {
invalid.role = 4;
}
}
refused_prepare(&index, &[(invalid, 7)]);
let before = state(&index);
refused_prepare(index, &[(invalid, 7)]);
let before = state(index);
assert!(index.oldest(&[invalid]).is_err());
assert_eq!(state(&index), before);
assert_eq!(state(index), before);
}
refused_prepare(&index, &[]);
refused_prepare(&index, &[(keys[0], 7); 4]);
refused_prepare(&index, &[(keys[0], 6)]);
refused_prepare(&index, &[(keys[0], 8), (keys[2], 7)]);
refused_prepare(&index, &[(keys[0], 7), (keys[0], 8)]);
invalid
}
fn batch_refusals_are_atomic(
index: &mut LruIndex,
oracle: &mut Oracle,
keys: &[MoeWeightDescriptor; 4],
invalid: MoeWeightDescriptor,
) {
refused_prepare(index, &[]);
refused_prepare(index, &[(keys[0], 7); 4]);
refused_prepare(index, &[(keys[0], 6)]);
refused_prepare(index, &[(keys[0], 8), (keys[2], 7)]);
refused_prepare(index, &[(keys[0], 7), (keys[0], 8)]);
// Metadata batch preflight must be atomic on a late bad key and a stale owner.
refused_prepare(&index, &[(keys[1], 7), (descriptor(4), 8), (invalid, 9)]);
refused_prepare(index, &[(keys[1], 7), (descriptor(4), 8), (invalid, 9)]);
let stale = index.prepare_updates(&[(keys[1], 7)]).unwrap();
update(&mut index, &mut oracle, &[(keys[3], 8)]);
let before = state(&index);
update(index, oracle, &[(keys[3], 8)]);
let before = state(index);
assert!(index.commit_updates(stale).is_err());
assert_eq!(state(&index), before);
assert_eq!(state(index), before);
foreign_owner_commit_is_refused(index, keys);
let stale_remove = index.prepare_updates(&[(keys[1], 9)]).unwrap();
index.remove(keys[2]).unwrap();
oracle.remove(&keys[2]);
let before = state(index);
assert!(index.commit_updates(stale_remove).is_err());
assert_eq!(state(index), before);
assert_live(index, oracle);
}
fn foreign_owner_commit_is_refused(index: &LruIndex, keys: &[MoeWeightDescriptor; 4]) {
let foreign = index.prepare_updates(&[(keys[1], 9)]).unwrap();
let mut other = LruIndex::new().unwrap();
let other_before = state(&other);
assert!(other.commit_updates(foreign).is_err());
assert_eq!(state(&other), other_before);
assert!(other.validate_coherence());
let stale_remove = index.prepare_updates(&[(keys[1], 9)]).unwrap();
index.remove(keys[2]).unwrap();
oracle.remove(&keys[2]);
let before = state(&index);
assert!(index.commit_updates(stale_remove).is_err());
assert_eq!(state(&index), before);
assert_live(&index, &oracle);
}
fn partial_triplet_states(keys: &[MoeWeightDescriptor; 4], invalid: MoeWeightDescriptor) {
// Partial triplet metadata states are permitted; no weight-upload success is inferred.
let mut partial = LruIndex::with_capacity(3).unwrap();
let mut partial_oracle = Oracle::new();
@@ -178,7 +209,9 @@ fn original_min_first_bounded_lru_index_matches_scan_and_refuses_incoherence() {
assert!(partial.validate_coherence());
assert!(LruIndex::with_capacity(0).is_err());
assert!(LruIndex::with_capacity(MAX_KEYS + 1).is_err());
}
fn deterministic_long_churn() {
// Deterministic long churn: all live entries checked, full map scan sampled.
let mut churn = LruIndex::with_capacity(256).unwrap();
let mut churn_oracle = Oracle::new();
@@ -203,7 +236,11 @@ fn original_min_first_bounded_lru_index_matches_scan_and_refuses_incoherence() {
assert_eq!((churn.heap.capacity(), churn.positions.capacity()), capacities);
}
assert!(churn.validate_coherence());
}
type FullIndex = (LruIndex, Oracle, (usize, usize), u64);
fn fill_every_domain_slot() -> FullIndex {
// Cover every routed and shared domain slot, including the maximum valid key.
let mut full = LruIndex::new().unwrap();
let mut full_oracle = Oracle::new();
@@ -225,31 +262,36 @@ fn original_min_first_bounded_lru_index_matches_scan_and_refuses_incoherence() {
compare_old_first(&full, &full_oracle, &[]);
}
}
(full, full_oracle, capacities, age)
}
fn exercise_full_index(full: &mut LruIndex, full_oracle: &mut Oracle, capacities: (usize, usize), age: u64) {
assert_eq!(full.len(), 73920);
assert_live(&full, &full_oracle);
assert_live(full, full_oracle);
assert!(full.validate_coherence());
assert!(full.metadata_bytes().unwrap() <= HOST_LIMIT);
for protected in [vec![], vec![descriptor(0)], (0..4).map(descriptor).collect()] {
compare_old_first(&full, &full_oracle, &protected);
compare_old_first(full, full_oracle, &protected);
}
let end = descriptor(MAX_KEYS - 1);
update(&mut full, &mut full_oracle, &[(end, age + 1), (descriptor(0), age + 2)]);
update(full, full_oracle, &[(end, age + 1), (descriptor(0), age + 2)]);
full.remove(end).unwrap();
full_oracle.remove(&end);
update(&mut full, &mut full_oracle, &[(end, age + 3)]);
compare_old_first(&full, &full_oracle, &[descriptor(1), descriptor(2), descriptor(3), descriptor(4)]);
update(full, full_oracle, &[(end, age + 3)]);
compare_old_first(full, full_oracle, &[descriptor(1), descriptor(2), descriptor(3), descriptor(4)]);
assert_eq!((full.heap.capacity(), full.positions.capacity()), capacities);
assert!(full.validate_coherence());
// Existing caller age arithmetic cannot wrap into a valid metadata update.
update(&mut full, &mut full_oracle, &[(end, u64::MAX)]);
update(full, full_oracle, &[(end, u64::MAX)]);
assert_eq!(full.last_age.checked_add(1), None);
refused_prepare(&full, &[(descriptor(0), 0)]);
refused_prepare(&full, &[(descriptor(0), u64::MAX)]);
compare_old_first(&full, &full_oracle, &[]);
refused_prepare(full, &[(descriptor(0), 0)]);
refused_prepare(full, &[(descriptor(0), u64::MAX)]);
compare_old_first(full, full_oracle, &[]);
assert!(full.validate_coherence());
println!(
"LRU_METADATA_COMPLETE keys=73920 churn=8192 protected_max=4 lookup_visit_bound=2P+1 metadata_bytes={} device_resources=0",
"LRU_METADATA_COMPLETE keys=73920 churn=8192 protected_max=4 lookup_visit_bound=2P+1 \
metadata_bytes={} device_resources=0",
full.metadata_bytes().unwrap()
);
}
@@ -20,41 +20,76 @@ impl<'ctx> MoeWeightCache<'ctx> {
}
let mut report = MtpDenseShare::default();
for entry in self.dense.iter_mut() {
let Some(rt) = retained.dense.iter().find(|r| r.role == entry.role) else {
report.kept += 1;
continue;
};
if Rc::ptr_eq(&rt.buffer, &entry.buffer) {
continue;
}
if (rt.kind, rt.rows, rt.columns) != (entry.kind, entry.rows, entry.columns)
|| rt.buffer.len() != entry.buffer.len()
{
report.kept += 1;
continue;
}
let mine = entry.buffer.copy_to_owned(entry.buffer.len()).map_err(driver_error)?;
let theirs = rt.buffer.copy_to_owned(rt.buffer.len()).map_err(driver_error)?;
if !dense_copies_equal(
(entry.kind, entry.rows, entry.columns, &mine),
(rt.kind, rt.rows, rt.columns, &theirs),
) {
report.kept += 1;
report.differing += 1;
continue;
}
let old = std::mem::replace(&mut entry.buffer, Rc::clone(&rt.buffer));
if let Ok(buffer) = Rc::try_unwrap(old) {
report.released_bytes += buffer.len();
if buffer.release().is_err() {
self.failed.set(true);
return Err(Error::CudaExecution);
}
}
report.shared += 1;
Self::share_entry(&self.failed, entry, retained, &mut report)?;
}
Ok(report)
}
fn share_entry(
failed: &Cell<bool>,
entry: &mut Dense<'ctx>,
retained: &RetainedOriginalMtpWeights<'ctx>,
report: &mut MtpDenseShare,
) -> Result<()> {
let Some(rt) = retained.dense.iter().find(|r| r.role == entry.role) else {
report.kept += 1;
return Ok(());
};
if Rc::ptr_eq(&rt.buffer, &entry.buffer) {
return Ok(());
}
if (rt.kind, rt.rows, rt.columns) != (entry.kind, entry.rows, entry.columns)
|| rt.buffer.len() != entry.buffer.len()
{
report.kept += 1;
return Ok(());
}
if !Self::device_copies_equal(entry, rt)? {
report.kept += 1;
report.differing += 1;
return Ok(());
}
Self::adopt_rt_buffer(failed, entry, rt, report)
}
fn device_copies_equal(entry: &Dense<'ctx>, rt: &RetainedDense<'ctx>) -> Result<bool> {
let mine = entry.buffer.copy_to_owned(entry.buffer.len()).map_err(driver_error)?;
let theirs = rt.buffer.copy_to_owned(rt.buffer.len()).map_err(driver_error)?;
Ok(dense_copies_equal((entry.kind, entry.rows, entry.columns, &mine), (rt.kind, rt.rows, rt.columns, &theirs)))
}
fn adopt_rt_buffer(
failed: &Cell<bool>,
entry: &mut Dense<'ctx>,
rt: &RetainedDense<'ctx>,
report: &mut MtpDenseShare,
) -> Result<()> {
let old = std::mem::replace(&mut entry.buffer, Rc::clone(&rt.buffer));
if let Ok(buffer) = Rc::try_unwrap(old) {
report.released_bytes += buffer.len();
if buffer.release().is_err() {
failed.set(true);
return Err(Error::CudaExecution);
}
}
report.shared += 1;
Ok(())
}
fn retain_dense_roles(
&self,
binding: &ModelBinding,
context: &Context<'ctx>,
roles: Vec<MtpRole>,
) -> Result<Vec<RetainedDense<'ctx>>> {
let mut dense = Vec::new();
dense.try_reserve_exact(roles.len()).map_err(|_| Error::InputAllocation)?;
for role in roles {
let (kind, rows, columns, _) = self.mtp_matrix(binding, context, role)?;
let entry = self.dense.iter().find(|entry| entry.role == role).ok_or(Error::IdentityMismatch)?;
if self.dense.iter().filter(|entry| entry.role == role).count() != 1 {
return Err(Error::IdentityMismatch);
}
dense.push(RetainedDense { role, kind, rows, columns, buffer: Rc::clone(&entry.buffer) });
}
Ok(dense)
}
pub(in crate::qwen_forward) fn retain_original_mtp_weights(
&self,
binding: &ModelBinding,
@@ -66,16 +101,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
if roles.len() != self.dense.len() {
return Err(Error::IdentityMismatch);
}
let mut dense = Vec::new();
dense.try_reserve_exact(roles.len()).map_err(|_| Error::InputAllocation)?;
for role in roles {
let (kind, rows, columns, _) = self.mtp_matrix(binding, context, role)?;
let entry = self.dense.iter().find(|entry| entry.role == role).ok_or(Error::IdentityMismatch)?;
if self.dense.iter().filter(|entry| entry.role == role).count() != 1 {
return Err(Error::IdentityMismatch);
}
dense.push(RetainedDense { role, kind, rows, columns, buffer: Rc::clone(&entry.buffer) });
}
let dense = self.retain_dense_roles(binding, context, roles)?;
let experts = Rc::clone(self.bank.as_ref().ok_or(Error::IdentityMismatch)?);
if experts.len() != 707_788_800 {
return Err(Error::InvalidDimension);
@@ -3,6 +3,26 @@
#[allow(unused_imports)]
use super::*;
use leleka_cuda_driver::OriginalMtpRetainedFullWeights as FullWeights;
/// Head rows, their count and the optional draft-vocabulary subset pair, as the full forward binds them.
type HeadBinding<'ctx> = (Rc<DeviceBuffer<'ctx>>, usize, Option<(Rc<DeviceBuffer<'ctx>>, Rc<DeviceBuffer<'ctx>>)>);
/// Roles the scalar prefill graphs retain, in the order the driver binds them.
const SCALAR_PREFILL_ROLES: [(MtpRole, (MtpKind, usize, usize)); 11] = [
(MtpRole::EmbeddingNorm, (MtpKind::F32, 1, 2560)),
(MtpRole::FcEmbedding, (MtpKind::Q8_0, 2560, 2560)),
(MtpRole::HiddenNorm, (MtpKind::F32, 1, 10240)),
(MtpRole::FcHidden, (MtpKind::Q8_0, 2560, 2560)),
(MtpRole::AttentionNorm, (MtpKind::F32, 1, 10240)),
(MtpRole::AttentionDown, (MtpKind::Bf16, 320, 10240)),
(MtpRole::AttentionUp, (MtpKind::Bf16, 10240, 320)),
(MtpRole::KeyProjection, (MtpKind::Q8_0, 512, 2560)),
(MtpRole::ValueProjection, (MtpKind::Q8_0, 512, 2560)),
(MtpRole::KeyNorm, (MtpKind::F32, 1, 256)),
(MtpRole::AttentionInject, (MtpKind::Bf16, 4, 10240)),
];
impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
/// Original `MtpDrafter::load` weights, taken from the loaded RT bank.
/// Every role of the contract must be present with exactly the retained
@@ -15,6 +35,24 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
bank: &leleka_cuda_driver::OriginalMtpRtBank<'ctx>,
) -> Result<Self> {
bank.validate_context(context).map_err(driver_error)?;
let dense = Self::rt_dense(bank)?;
let experts = bank.experts();
if bank.expert_count() != 512 || experts.len() != 707_788_800 {
return Err(Error::InvalidDimension);
}
let extras = Self::rt_extras(bank, &dense)?;
Ok(Self {
binding: binding.identity(),
context,
dense,
experts,
source: WeightSource::RtDirectory,
dense_file_bytes: bank.dense_file_bytes(),
loaded_bytes: bank.vram_bytes(),
extras,
})
}
fn rt_dense(bank: &leleka_cuda_driver::OriginalMtpRtBank<'ctx>) -> Result<Vec<RetainedDense<'ctx>>> {
let roles = rt_dense_roles();
let mut dense = Vec::new();
dense.try_reserve_exact(roles.len()).map_err(|_| Error::InputAllocation)?;
@@ -27,10 +65,12 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
}
dense.push(RetainedDense { role, kind, rows, columns, buffer: tensor.buffer() });
}
let experts = bank.experts();
if bank.expert_count() != 512 || experts.len() != 707_788_800 {
return Err(Error::InvalidDimension);
}
Ok(dense)
}
fn rt_extras(
bank: &leleka_cuda_driver::OriginalMtpRtBank<'ctx>,
dense: &[RetainedDense<'ctx>],
) -> Result<Vec<Rc<DeviceBuffer<'ctx>>>> {
let mut extras = Vec::new();
extras.try_reserve_exact(bank.tensors().len()).map_err(|_| Error::InputAllocation)?;
for tensor in bank.tensors() {
@@ -39,16 +79,7 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
extras.push(buffer);
}
}
Ok(Self {
binding: binding.identity(),
context,
dense,
experts,
source: WeightSource::RtDirectory,
dense_file_bytes: bank.dense_file_bytes(),
loaded_bytes: bank.vram_bytes(),
extras,
})
Ok(extras)
}
pub(in crate::qwen_forward) fn dense_file_bytes(&self) -> u64 {
self.dense_file_bytes
@@ -107,6 +138,32 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
self.validate(binding, context)?;
Ok(Rc::clone(&self.experts))
}
fn acquire_matrix(
&self,
binding: &ModelBinding,
context: &Context<'ctx>,
role: MtpRole,
expected: (MtpKind, usize, usize),
) -> Result<Rc<DeviceBuffer<'ctx>>> {
let (kind, rows, columns, owner) = self.matrix(binding, context, role)?;
if (kind, rows, columns) != expected {
return Err(Error::InvalidDimension);
}
Ok(owner)
}
fn acquire_roles<const N: usize>(
&self,
binding: &ModelBinding,
context: &Context<'ctx>,
table: [(MtpRole, (MtpKind, usize, usize)); N],
) -> Result<[Rc<DeviceBuffer<'ctx>>; N]> {
let mut acquired = Vec::new();
acquired.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?;
for (role, expected) in table {
acquired.push(self.acquire_matrix(binding, context, role, expected)?);
}
acquired.try_into().map_err(|_| Error::InvalidDimension)
}
/// The scalar prefill graphs retain these exact model allocations, including
/// the genuine whole embedding table. Shape metadata cannot replace an Rc
/// owner or permit a different allocation to be substituted during capture.
@@ -117,26 +174,7 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
embedding: &super::super::super::executor::original_prompt::embedding::OriginalPromptEmbedding<'ctx>,
) -> Result<Rc<leleka_cuda_driver::OriginalMtpRetainedScalarWeights<'ctx>>> {
self.validate(binding, context)?;
let acquire = |role, expected| -> Result<Rc<DeviceBuffer<'ctx>>> {
let (kind, rows, columns, owner) = self.matrix(binding, context, role)?;
if (kind, rows, columns) != expected {
return Err(Error::InvalidDimension);
}
Ok(owner)
};
let roles = [
acquire(MtpRole::EmbeddingNorm, (MtpKind::F32, 1, 2560))?,
acquire(MtpRole::FcEmbedding, (MtpKind::Q8_0, 2560, 2560))?,
acquire(MtpRole::HiddenNorm, (MtpKind::F32, 1, 10240))?,
acquire(MtpRole::FcHidden, (MtpKind::Q8_0, 2560, 2560))?,
acquire(MtpRole::AttentionNorm, (MtpKind::F32, 1, 10240))?,
acquire(MtpRole::AttentionDown, (MtpKind::Bf16, 320, 10240))?,
acquire(MtpRole::AttentionUp, (MtpKind::Bf16, 10240, 320))?,
acquire(MtpRole::KeyProjection, (MtpKind::Q8_0, 512, 2560))?,
acquire(MtpRole::ValueProjection, (MtpKind::Q8_0, 512, 2560))?,
acquire(MtpRole::KeyNorm, (MtpKind::F32, 1, 256))?,
acquire(MtpRole::AttentionInject, (MtpKind::Bf16, 4, 10240))?,
];
let roles = self.acquire_roles(binding, context, SCALAR_PREFILL_ROLES)?;
let (table, _, _, _) = embedding.retain(binding, context)?;
let descriptor = embedding.borrow(binding, context)?;
let bank =
@@ -158,32 +196,11 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
id_vocab: usize,
draft_head: Option<&leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>,
) -> Result<Rc<leleka_cuda_driver::OriginalMtpRetainedFullWeights<'ctx>>> {
self.validate(binding, context)?;
if head.columns() != 2560 || id_vocab != head.vocabulary() {
return Err(Error::InvalidDimension);
}
let acquire = |role, expected| -> Result<Rc<DeviceBuffer<'ctx>>> {
let (kind, rows, columns, owner) = self.matrix(binding, context, role)?;
if (kind, rows, columns) != expected {
return Err(Error::InvalidDimension);
}
Ok(owner)
};
let roles = FULL_FORWARD_ROLES.map(|(role, expected)| acquire(role, expected));
let mut acquired = Vec::new();
acquired.try_reserve_exact(roles.len()).map_err(|_| Error::InputAllocation)?;
for role in roles {
acquired.push(role?);
}
let roles: [Rc<DeviceBuffer<'ctx>>; 15] = acquired.try_into().map_err(|_| Error::InvalidDimension)?;
self.admit_full_forward(binding, context, head, id_vocab)?;
let roles = self.acquire_roles(binding, context, FULL_FORWARD_ROLES)?;
let experts = self.expert_bank(binding, context)?;
// Literal bind: with a draft_vocab subset the draft head is the gathered
// rows (`dhead_`, `n_dvocab_` of them), else the native head itself.
let (head_weights, head_rows, subset) = match draft_head {
Some(draft) => (draft.rows(), draft.count(), Some(draft.subset_pair())),
None => (head.weights(), head.vocabulary(), None),
};
let weights = leleka_cuda_driver::OriginalMtpRetainedFullWeights::retain(
let (head_weights, head_rows, subset) = Self::select_head(head, draft_head);
let weights = FullWeights::retain(
context,
prefix,
roles,
@@ -199,6 +216,30 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
self.validate(binding, context)?;
Ok(Rc::new(weights))
}
/// Literal bind: with a draft_vocab subset the draft head is the gathered
/// rows (`dhead_`, `n_dvocab_` of them), else the native head itself.
fn admit_full_forward(
&self,
binding: &ModelBinding,
context: &Context<'ctx>,
head: &OriginalMtpNativeHead<'ctx>,
id_vocab: usize,
) -> Result<()> {
self.validate(binding, context)?;
if head.columns() != 2560 || id_vocab != head.vocabulary() {
return Err(Error::InvalidDimension);
}
Ok(())
}
fn select_head(
head: &OriginalMtpNativeHead<'ctx>,
draft_head: Option<&leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>,
) -> HeadBinding<'ctx> {
match draft_head {
Some(draft) => (draft.rows(), draft.count(), Some(draft.subset_pair())),
None => (head.weights(), head.vocabulary(), None),
}
}
pub(in crate::qwen_forward) fn metadata_bytes(&self) -> Result<usize> {
self.dense
.capacity()
@@ -40,6 +40,38 @@ impl<'ctx> MoeWeightCache<'ctx> {
Ok(all)
}
fn raw_shared(&self, key: &MoeWeightDescriptor) -> Result<&DeviceBuffer<'ctx>> {
let entry = self.main.get(key).ok_or(Error::IdentityMismatch)?;
if entry.charged_bytes != key.bytes {
return Err(Error::IdentityMismatch);
}
match &entry.weight {
EncodedWeight::Raw(buffer) => Ok(buffer),
_ => Err(Error::IdentityMismatch),
}
}
fn verify_moe_layer<'a>(
&'a self,
binding: &ModelBinding,
dense: &'a DenseWeightCache<'ctx>,
layer: usize,
keys: &[MoeWeightDescriptor; 4],
) -> Result<OriginalVerifyMoeLayerWeights<'a, 'ctx>> {
if keys.iter().any(|key| key.layer as usize != layer) {
return Err(Error::IdentityMismatch);
}
Ok(OriginalVerifyMoeLayerWeights {
router: dense.router(binding, layer as u32)?,
gate_inp_shexp: self.raw_shared(&keys[3])?,
gate_shexp: self.raw_shared(&keys[0])?,
gate_shexp_type: keys[0].raw_kind,
up_shexp: self.raw_shared(&keys[1])?,
up_shexp_type: keys[1].raw_kind,
down_shexp: self.raw_shared(&keys[2])?,
down_shexp_type: keys[2].raw_kind,
})
}
/// The router and shared-expert operands of the 48 layers plus the routed experts' formats.
pub(in crate::qwen_forward) fn original_verify_moe<'a>(
&'a self,
@@ -53,32 +85,10 @@ impl<'ctx> MoeWeightCache<'ctx> {
if shared.len() != 48 {
return Err(Error::InvalidLayer);
}
let raw = |key: &MoeWeightDescriptor| -> Result<&'a DeviceBuffer<'ctx>> {
let entry = self.main.get(key).ok_or(Error::IdentityMismatch)?;
if entry.charged_bytes != key.bytes {
return Err(Error::IdentityMismatch);
}
match &entry.weight {
EncodedWeight::Raw(buffer) => Ok(buffer),
_ => Err(Error::IdentityMismatch),
}
};
let mut layers = Vec::new();
layers.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?;
for (layer, keys) in shared.iter().enumerate() {
if keys.iter().any(|key| key.layer as usize != layer) {
return Err(Error::IdentityMismatch);
}
layers.push(OriginalVerifyMoeLayerWeights {
router: dense.router(binding, layer as u32)?,
gate_inp_shexp: raw(&keys[3])?,
gate_shexp: raw(&keys[0])?,
gate_shexp_type: keys[0].raw_kind,
up_shexp: raw(&keys[1])?,
up_shexp_type: keys[1].raw_kind,
down_shexp: raw(&keys[2])?,
down_shexp_type: keys[2].raw_kind,
});
layers.push(self.verify_moe_layer(binding, dense, layer, keys)?);
}
OriginalVerifyMoeBinding::new(self.context, geometry, layers, formats).map_err(driver_error)
}
@@ -3,10 +3,25 @@
#[allow(unused_imports)]
use super::*;
const RANKED_BASE: usize = 24 + PAIRS * 4;
impl RankedProfile {
pub(in super::super) fn parse(bytes: &[u8], expected_sha: [u8; 32]) -> Result<Self> {
const BASE: usize = 24 + PAIRS * 4;
if !matches!(bytes.len(), BASE | 196_632)
Self::check_header(bytes, expected_sha)?;
let mut pairs = Vec::new();
pairs.try_reserve_exact(PAIRS).map_err(|_| Error::InputAllocation)?;
let mut seen = [false; PAIRS];
for (rank, b) in bytes[24..RANKED_BASE].as_chunks::<4>().0.iter().enumerate() {
pairs.push(Self::parse_pair(bytes, rank, b, &mut seen)?);
}
let owner = Self { pairs };
if owner.metadata_bytes() > HOST_CAP {
return Err(Error::InputAllocation);
}
Ok(owner)
}
fn check_header(bytes: &[u8], expected_sha: [u8; 32]) -> Result<()> {
if !matches!(bytes.len(), RANKED_BASE | 196_632)
|| bytes[..4] != *b"STRP"
|| [1, 48, 512, 24_576, 24_576].into_iter().enumerate().any(|(i, value)| {
let p = 4 + i * 4;
@@ -16,33 +31,26 @@ impl RankedProfile {
{
return Err(Error::IdentityMismatch);
}
let mut pairs = Vec::new();
pairs.try_reserve_exact(PAIRS).map_err(|_| Error::InputAllocation)?;
let mut seen = [false; PAIRS];
for (rank, b) in bytes[24..BASE].as_chunks::<4>().0.iter().enumerate() {
let layer = u16::from_le_bytes([b[0], b[1]]);
let expert = u16::from_le_bytes([b[2], b[3]]);
if usize::from(layer) >= LAYERS || usize::from(expert) >= EXPERTS {
return Err(Error::InvalidDimension);
}
let cell = usize::from(layer) * EXPERTS + usize::from(expert);
if seen[cell] {
Ok(())
}
fn parse_pair(bytes: &[u8], rank: usize, b: &[u8; 4], seen: &mut [bool; PAIRS]) -> Result<(u16, u16)> {
let layer = u16::from_le_bytes([b[0], b[1]]);
let expert = u16::from_le_bytes([b[2], b[3]]);
if usize::from(layer) >= LAYERS || usize::from(expert) >= EXPERTS {
return Err(Error::InvalidDimension);
}
let cell = usize::from(layer) * EXPERTS + usize::from(expert);
if seen[cell] {
return Err(Error::IdentityMismatch);
}
seen[cell] = true;
if bytes.len() != RANKED_BASE {
let p = RANKED_BASE + cell * 4;
if i32::from_le_bytes(bytes[p..p + 4].try_into().unwrap()) != rank as i32 {
return Err(Error::IdentityMismatch);
}
seen[cell] = true;
if bytes.len() != BASE {
let p = BASE + cell * 4;
if i32::from_le_bytes(bytes[p..p + 4].try_into().unwrap()) != rank as i32 {
return Err(Error::IdentityMismatch);
}
}
pairs.push((layer, expert));
}
let owner = Self { pairs };
if owner.metadata_bytes() > HOST_CAP {
return Err(Error::InputAllocation);
}
Ok(owner)
Ok((layer, expert))
}
pub(in super::super) fn ordered_pairs(&self) -> &[(u16, u16)] {
&self.pairs
@@ -51,6 +59,52 @@ impl RankedProfile {
self.pairs.capacity() * std::mem::size_of::<(u16, u16)>() + std::mem::size_of::<Self>()
}
}
/// Charged bytes per layer triplet and the device capacity left for a pinned prefix.
struct PlanBudget {
totals: [usize; LAYERS],
#[cfg(test)]
largest_triplet: usize,
spill_reserve: usize,
capacity: usize,
}
impl PlanBudget {
fn capacity(limits: &ProfileLimits, spill_reserve: usize) -> Result<usize> {
let external = spill_reserve.checked_add(limits.working_reserve).ok_or(Error::Overflow)?;
limits
.main_cap
.checked_sub(spill_reserve)
.and_then(|main| {
limits
.device_budget
.checked_sub(limits.allocated)
.and_then(|v| v.checked_sub(external))
.map(|typed| main.min(typed))
})
.and_then(|typed| limits.physical_free.checked_sub(external).map(|free| typed.min(free)))
.ok_or(Error::InputAllocation)
}
fn new(charges: &[[usize; 3]; 48], limits: ProfileLimits) -> Result<Self> {
let mut totals = [0usize; LAYERS];
for (total, roles) in totals.iter_mut().zip(charges) {
if roles.contains(&0) {
return Err(Error::InvalidDimension);
}
*total = roles.iter().try_fold(0usize, |v, n| v.checked_add(*n)).ok_or(Error::Overflow)?;
}
let largest_triplet = *totals.iter().max().ok_or(Error::InvalidDimension)?;
let spill_reserve = limits.window_spill.checked_add(largest_triplet).ok_or(Error::Overflow)?;
let capacity = Self::capacity(&limits, spill_reserve)?;
Ok(Self {
totals,
#[cfg(test)]
largest_triplet,
spill_reserve,
capacity,
})
}
}
impl PrefixPlan {
/// A whole expert prefix, never a partially pinned Gate/Up/Down triplet.
/// Window live storage + worst missing triplet + working reserve are additive.
@@ -59,92 +113,25 @@ impl PrefixPlan {
charges: &[[usize; 3]; 48],
limits: ProfileLimits,
) -> Result<Self> {
let mut totals = [0usize; LAYERS];
for (total, roles) in totals.iter_mut().zip(charges) {
if roles.contains(&0) {
return Err(Error::InvalidDimension);
}
*total = roles.iter().try_fold(0usize, |v, n| v.checked_add(*n)).ok_or(Error::Overflow)?;
}
let largest_triplet = *totals.iter().max().ok_or(Error::InvalidDimension)?;
let spill_reserve = limits.window_spill.checked_add(largest_triplet).ok_or(Error::Overflow)?;
let external = spill_reserve.checked_add(limits.working_reserve).ok_or(Error::Overflow)?;
let capacity = limits
.main_cap
.checked_sub(spill_reserve)
.and_then(|main| {
limits
.device_budget
.checked_sub(limits.allocated)
.and_then(|v| v.checked_sub(external))
.map(|typed| main.min(typed))
})
.and_then(|typed| limits.physical_free.checked_sub(external).map(|free| typed.min(free)))
.ok_or(Error::InputAllocation)?;
let budget = PlanBudget::new(charges, limits)?;
let mut selected = Vec::new();
selected.try_reserve_exact(PAIRS).map_err(|_| Error::InputAllocation)?;
selected.resize(PAIRS, false);
if profile
.metadata_bytes()
.checked_add(selected.capacity() * std::mem::size_of::<bool>())
.is_none_or(|n| n > HOST_CAP)
{
return Err(Error::InputAllocation);
}
let mut charged_bytes = 0usize;
let mut prefix = 0;
for &(layer, expert) in profile.ordered_pairs() {
let next = charged_bytes.checked_add(totals[usize::from(layer)]).ok_or(Error::Overflow)?;
if next > capacity {
break;
}
selected[usize::from(layer) * EXPERTS + usize::from(expert)] = true;
charged_bytes = next;
prefix += 1;
}
if prefix == 0 {
return Err(Error::InputAllocation);
}
Ok(Self {
prefix,
charged_bytes,
spill_reserve,
#[cfg(test)]
largest_triplet,
selected,
})
Self::select_prefix(profile, &budget, selected)
}
pub(in super::super) fn new_shared_with_storage(
profile: &RankedProfile,
charges: &[[usize; 3]; 48],
limits: ProfileLimits,
mut selected: Vec<bool>,
selected: Vec<bool>,
) -> Result<Self> {
let mut totals = [0usize; LAYERS];
for (total, roles) in totals.iter_mut().zip(charges) {
if roles.contains(&0) {
return Err(Error::InvalidDimension);
}
*total = roles.iter().try_fold(0usize, |v, n| v.checked_add(*n)).ok_or(Error::Overflow)?;
}
let largest_triplet = *totals.iter().max().ok_or(Error::InvalidDimension)?;
let spill_reserve = limits.window_spill.checked_add(largest_triplet).ok_or(Error::Overflow)?;
let external = spill_reserve.checked_add(limits.working_reserve).ok_or(Error::Overflow)?;
let capacity = limits
.main_cap
.checked_sub(spill_reserve)
.and_then(|main| {
limits
.device_budget
.checked_sub(limits.allocated)
.and_then(|v| v.checked_sub(external))
.map(|typed| main.min(typed))
})
.and_then(|typed| limits.physical_free.checked_sub(external).map(|free| typed.min(free)))
.ok_or(Error::InputAllocation)?;
let budget = PlanBudget::new(charges, limits)?;
if selected.len() != PAIRS || selected.iter().any(|value| *value) {
return Err(Error::IdentityMismatch);
}
Self::select_prefix(profile, &budget, selected)
}
fn check_selected_metadata(profile: &RankedProfile, selected: &Vec<bool>) -> Result<()> {
if profile
.metadata_bytes()
.checked_add(selected.capacity() * std::mem::size_of::<bool>())
@@ -152,11 +139,15 @@ impl PrefixPlan {
{
return Err(Error::InputAllocation);
}
Ok(())
}
fn select_prefix(profile: &RankedProfile, budget: &PlanBudget, mut selected: Vec<bool>) -> Result<Self> {
Self::check_selected_metadata(profile, &selected)?;
let mut charged_bytes = 0usize;
let mut prefix = 0;
for &(layer, expert) in profile.ordered_pairs() {
let next = charged_bytes.checked_add(totals[usize::from(layer)]).ok_or(Error::Overflow)?;
if next > capacity {
let next = charged_bytes.checked_add(budget.totals[usize::from(layer)]).ok_or(Error::Overflow)?;
if next > budget.capacity {
break;
}
selected[usize::from(layer) * EXPERTS + usize::from(expert)] = true;
@@ -169,9 +160,9 @@ impl PrefixPlan {
Ok(Self {
prefix,
charged_bytes,
spill_reserve,
spill_reserve: budget.spill_reserve,
#[cfg(test)]
largest_triplet,
largest_triplet: budget.largest_triplet,
selected,
})
}
@@ -3,6 +3,14 @@
#[allow(unused_imports)]
use super::*;
/// Slot count and metadata ceiling proven when the weight map was reserved.
struct MapReservation {
count: usize,
main_slot_limit: usize,
#[cfg(test)]
metadata_bytes: usize,
}
impl<'ctx> MoeWeightCache<'ctx> {
/// Private candidate only. The caller creates all eager Dense owners first.
pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile(
@@ -40,126 +48,183 @@ impl<'ctx> MoeWeightCache<'ctx> {
) -> Result<Self> {
let profile = RankedProfile::parse(bytes, PROFILE_SHA)?;
let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(binding, context)?;
let operation = (|| {
cache.validate(binding, context)?;
if with_mtp_input {
cache.admit_mtp_input_workspace(binding)?;
}
// These are genuine bound tensor descriptors, not chosen routes.
let mut layer_keys = Vec::new();
layer_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?;
let mut charges = [[0usize; 3]; 48];
for (layer, charge) in charges.iter_mut().enumerate() {
let keys = [
binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?,
binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up).map_err(binding_error)?,
binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?,
];
for (n, key) in keys.iter().enumerate() {
charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, n)| n);
}
layer_keys.push(keys);
}
let (free, _) = context.memory_info().map_err(driver_error)?;
// Max simultaneously live original native micro64 allocation set;
// this exceeds the resident-MMQ packet peak. Weight triplet is separate.
// PrefixPlan subtracts this additive floor from main, typed and
// physical capacity. Its published spill_reserve is also rechecked
// by every unchanged preload_pinned_triplet before real uploads.
let window_spill = profile_window_spill_with_floor(reusable_spill_floor)?;
let plan = PrefixPlan::new(
&profile,
&charges,
ProfileLimits {
main_cap: MAIN_LIMIT,
allocated: context.allocated_bytes(),
device_budget: context.budget_bytes(),
physical_free: free,
working_reserve: WORKING_RESERVE,
window_spill,
},
)?;
let metadata_base = profile
.metadata_bytes()
.checked_add(plan.metadata_bytes())
.and_then(|n| n.checked_add(bytes.len()))
.and_then(|n| n.checked_add(std::mem::size_of::<PinnedPool>()))
.and_then(|n| n.checked_add(layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>()))
.and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?))
.ok_or(Error::Overflow)?;
let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?;
// One weight map, allocated before publishing any owner. A 2^15
// request fits every real complete prefix allowed by the 24GiB
// cap (smallest admitted triplet is >1.5MB). Actual capacity is
// rechecked rather than assumed, and bounds all later spill inserts.
cache.main.try_reserve(count.max(1 << 15)).map_err(|_| Error::InputAllocation)?;
let main_slot_limit = cache.main.capacity();
// Current pinned Rust std HashMap uses 7/8 load factor. 4/3 of
// reported capacity conservatively covers buckets, plus controls
// and the extra SIMD control group. This includes real owner tuples.
let buckets =
main_slot_limit.checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3).ok_or(Error::Overflow)?;
let map_bytes = buckets
.checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1)
.and_then(|n| n.checked_add(16 + std::mem::size_of::<HashMap<MoeWeightDescriptor, Entry<'ctx>>>()))
.ok_or(Error::Overflow)?;
let metadata_bytes = metadata_base.checked_add(map_bytes).ok_or(Error::Overflow)?;
if metadata_bytes > HOST_CAP || count > main_slot_limit {
return Err(Error::InputAllocation);
}
let expected_bytes = plan.charged_bytes;
cache.pinned = Some(PinnedPool {
plan,
loaded_matrices: 0,
shared: None,
#[cfg(test)]
metadata_bytes,
main_slot_limit,
#[cfg(test)]
fixed_resident_upload_bytes: cache.counters.upload_bytes,
#[cfg(test)]
fixed_resident_read_bytes: cache.counters.read_bytes,
pinned_hits: 0,
spill_hits: 0,
spill_misses: 0,
preload_read_bytes: 0,
preload_upload_bytes: 0,
});
let prefix = cache.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.prefix;
for &(layer, expert) in &profile.ordered_pairs()[..prefix] {
// Re-admit each actual expert source before reading any matrix.
let keys = [
binding
.moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Gate)
.map_err(binding_error)?,
binding
.moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Up)
.map_err(binding_error)?,
binding
.moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Down)
.map_err(binding_error)?,
];
let mut topology_keys = layer_keys[usize::from(layer)];
for key in &mut topology_keys {
key.expert = Some(u32::from(expert));
}
if keys != topology_keys {
return Err(Error::IdentityMismatch);
}
cache.preload_pinned_triplet(binding, keys)?;
}
if cache.main_bytes != expected_bytes
|| cache.spill_len()? != 0
|| cache.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count)
{
return Err(Error::IdentityMismatch);
}
cache.validate(binding, context)
})();
let operation =
cache.fill_ranked_profile(binding, context, bytes.len(), &profile, with_mtp_input, reusable_spill_floor);
if let Err(primary) = operation {
let _ = cache.close();
return Err(primary);
}
Ok(cache)
}
fn fill_ranked_profile(
&mut self,
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
profile_len: usize,
profile: &RankedProfile,
with_mtp_input: bool,
reusable_spill_floor: usize,
) -> Result<()> {
self.validate(binding, context)?;
if with_mtp_input {
self.admit_mtp_input_workspace(binding)?;
}
let (layer_keys, charges) = self.profile_layer_keys(binding)?;
let plan = Self::profile_prefix_plan(context, profile, &charges, reusable_spill_floor)?;
let reservation = self.reserve_profile_map(profile, &plan, profile_len, layer_keys.capacity())?;
let (expected_bytes, count) = (plan.charged_bytes, reservation.count);
self.install_profile_pool(plan, reservation);
self.preload_ranked_prefix(binding, profile, &layer_keys)?;
if self.main_bytes != expected_bytes
|| self.spill_len()? != 0
|| self.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count)
{
return Err(Error::IdentityMismatch);
}
self.validate(binding, context)
}
/// The genuine bound tensor descriptors of every layer's first expert and their layout charges.
fn profile_layer_keys(&self, binding: &ModelBinding) -> Result<(Vec<[MoeWeightDescriptor; 3]>, [[usize; 3]; 48])> {
let mut layer_keys = Vec::new();
layer_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?;
let mut charges = [[0usize; 3]; 48];
for (layer, charge) in charges.iter_mut().enumerate() {
let keys = [
binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?,
binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up).map_err(binding_error)?,
binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?,
];
for (n, key) in keys.iter().enumerate() {
charge[n] = self.weight_layout(*key)?.map_or(key.bytes, |(_, n)| n);
}
layer_keys.push(keys);
}
Ok((layer_keys, charges))
}
fn profile_prefix_plan(
context: &Context<'_>,
profile: &RankedProfile,
charges: &[[usize; 3]; 48],
reusable_spill_floor: usize,
) -> Result<PrefixPlan> {
let (free, _) = context.memory_info().map_err(driver_error)?;
// Max simultaneously live original native micro64 allocation set;
// this exceeds the resident-MMQ packet peak. Weight triplet is separate.
// PrefixPlan subtracts this additive floor from main, typed and
// physical capacity. Its published spill_reserve is also rechecked
// by every unchanged preload_pinned_triplet before real uploads.
let window_spill = profile_window_spill_with_floor(reusable_spill_floor)?;
PrefixPlan::new(
profile,
charges,
ProfileLimits {
main_cap: MAIN_LIMIT,
allocated: context.allocated_bytes(),
device_budget: context.budget_bytes(),
physical_free: free,
working_reserve: WORKING_RESERVE,
window_spill,
},
)
}
/// Reserves the one weight map before any owner is published and checks the metadata ceiling.
fn reserve_profile_map(
&mut self,
profile: &RankedProfile,
plan: &PrefixPlan,
profile_len: usize,
layer_keys_capacity: usize,
) -> Result<MapReservation> {
let metadata_base = self.profile_metadata_base(profile, plan, profile_len, layer_keys_capacity)?;
let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?;
// One weight map, allocated before publishing any owner. A 2^15
// request fits every real complete prefix allowed by the 24GiB
// cap (smallest admitted triplet is >1.5MB). Actual capacity is
// rechecked rather than assumed, and bounds all later spill inserts.
self.main.try_reserve(count.max(1 << 15)).map_err(|_| Error::InputAllocation)?;
let main_slot_limit = self.main.capacity();
let map_bytes = Self::map_metadata_bytes(main_slot_limit)?;
let metadata_bytes = metadata_base.checked_add(map_bytes).ok_or(Error::Overflow)?;
if metadata_bytes > HOST_CAP || count > main_slot_limit {
return Err(Error::InputAllocation);
}
Ok(MapReservation {
count,
main_slot_limit,
#[cfg(test)]
metadata_bytes,
})
}
fn profile_metadata_base(
&self,
profile: &RankedProfile,
plan: &PrefixPlan,
profile_len: usize,
layer_keys_capacity: usize,
) -> Result<usize> {
profile
.metadata_bytes()
.checked_add(plan.metadata_bytes())
.and_then(|n| n.checked_add(profile_len))
.and_then(|n| n.checked_add(std::mem::size_of::<PinnedPool>()))
.and_then(|n| n.checked_add(layer_keys_capacity * std::mem::size_of::<[MoeWeightDescriptor; 3]>()))
.and_then(|n| n.checked_add(self.lru.as_ref()?.metadata_bytes().ok()?))
.ok_or(Error::Overflow)
}
fn map_metadata_bytes(main_slot_limit: usize) -> Result<usize> {
// Current pinned Rust std HashMap uses 7/8 load factor. 4/3 of
// reported capacity conservatively covers buckets, plus controls
// and the extra SIMD control group. This includes real owner tuples.
let buckets =
main_slot_limit.checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3).ok_or(Error::Overflow)?;
buckets
.checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1)
.and_then(|n| n.checked_add(16 + std::mem::size_of::<HashMap<MoeWeightDescriptor, Entry<'ctx>>>()))
.ok_or(Error::Overflow)
}
fn install_profile_pool(&mut self, plan: PrefixPlan, reservation: MapReservation) {
self.pinned = Some(PinnedPool {
plan,
loaded_matrices: 0,
shared: None,
#[cfg(test)]
metadata_bytes: reservation.metadata_bytes,
main_slot_limit: reservation.main_slot_limit,
#[cfg(test)]
fixed_resident_upload_bytes: self.counters.upload_bytes,
#[cfg(test)]
fixed_resident_read_bytes: self.counters.read_bytes,
pinned_hits: 0,
spill_hits: 0,
spill_misses: 0,
preload_read_bytes: 0,
preload_upload_bytes: 0,
});
}
fn preload_ranked_prefix(
&mut self,
binding: &ModelBinding,
profile: &RankedProfile,
layer_keys: &[[MoeWeightDescriptor; 3]],
) -> Result<()> {
let prefix = self.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.prefix;
for &(layer, expert) in &profile.ordered_pairs()[..prefix] {
// Re-admit each actual expert source before reading any matrix.
let keys = ranked_keys(binding, layer, expert)?;
let mut topology_keys = layer_keys[usize::from(layer)];
for key in &mut topology_keys {
key.expert = Some(u32::from(expert));
}
if keys != topology_keys {
return Err(Error::IdentityMismatch);
}
self.preload_pinned_triplet(binding, keys)?;
}
Ok(())
}
}
fn ranked_keys(binding: &ModelBinding, layer: u16, expert: u16) -> Result<[MoeWeightDescriptor; 3]> {
let key = |role| binding.moe_preload_descriptor(u32::from(layer), u32::from(expert), role).map_err(binding_error);
Ok([key(MoeMatrixRole::Gate)?, key(MoeMatrixRole::Up)?, key(MoeMatrixRole::Down)?])
}
@@ -3,12 +3,39 @@
#[allow(unused_imports)]
use super::*;
/// Layouts, charges and the checked next counters of one pinned triplet upload.
#[derive(Clone, Copy)]
struct PinnedAdmission {
layouts: [Option<(leleka_cuda_driver::MmqFormat, usize)>; 3],
charges: [usize; 3],
extra: usize,
next_bytes: usize,
next_age: u64,
next_loaded: usize,
}
impl<'ctx> MoeWeightCache<'ctx> {
pub(in super::super) fn preload_pinned_triplet(
&mut self,
binding: &ModelBinding,
keys: [MoeWeightDescriptor; 3],
) -> Result<()> {
let admission = self.admit_pinned_triplet(&keys)?;
let raw = [
binding.moe_preload_block(keys[0]).map_err(binding_error)?,
binding.moe_preload_block(keys[1]).map_err(binding_error)?,
binding.moe_preload_block(keys[2]).map_err(binding_error)?,
];
let read_bytes = raw.iter().try_fold(0usize, |n, b| n.checked_add(b.len())).ok_or(Error::Overflow)?;
let mut owned: [Option<EncodedWeight<'ctx>>; 3] = std::array::from_fn(|_| None);
if let Err(primary) = self.upload_pinned_triplet(&admission, &keys, &raw, &mut owned) {
self.discard_owned(owned);
return Err(primary);
}
self.commit_pinned_triplet(&admission, keys, owned, &raw, read_bytes);
Ok(())
}
fn admit_pinned_triplet(&self, keys: &[MoeWeightDescriptor; 3]) -> Result<PinnedAdmission> {
if keys.iter().any(|key| !self.is_pinned(*key) || self.main.contains_key(key)) {
return Err(Error::IdentityMismatch);
}
@@ -35,66 +62,84 @@ impl<'ctx> MoeWeightCache<'ctx> {
.loaded_matrices
.checked_add(3)
.ok_or(Error::Overflow)?;
let raw = [
binding.moe_preload_block(keys[0]).map_err(binding_error)?,
binding.moe_preload_block(keys[1]).map_err(binding_error)?,
binding.moe_preload_block(keys[2]).map_err(binding_error)?,
];
let read_bytes = raw.iter().try_fold(0usize, |n, b| n.checked_add(b.len())).ok_or(Error::Overflow)?;
let mut owned: [Option<EncodedWeight<'ctx>>; 3] = std::array::from_fn(|_| None);
let operation: Result<()> = (|| {
if let [Some((gate, _)), Some((up, _)), Some((down, _))] = layouts {
let owners = if self.original_prompt_mmq {
self.context.mmq_original_weight_triplet([gate, up, down], [&raw[0], &raw[1], &raw[2]])
} else {
self.context.mmq_weight_triplet([gate, up, down], [&raw[0], &raw[1], &raw[2]])
}
.map_err(driver_error)?;
if owners.iter().zip(charges).any(|(owner, charge)| owner.allocated_bytes() != charge) {
for owner in owners.into_iter().rev() {
if owner.close().is_err() {
self.failed.set(true);
}
}
return Err(Error::IdentityMismatch);
}
for (i, owner) in owners.into_iter().enumerate() {
owned[i] = Some(EncodedWeight::Dual([gate, up, down][i], owner));
}
} else {
for i in 0..3 {
if raw[i].len() != keys[i].bytes {
return Err(Error::InvalidDimension);
}
let weight = if let Some((format, expected)) = layouts[i] {
let owner = self.context.mmq_weights(format, &raw[i]).map_err(driver_error)?;
if owner.allocated_bytes() != expected {
if owner.close().is_err() {
self.failed.set(true);
}
return Err(Error::IdentityMismatch);
}
EncodedWeight::Dual(format, owner)
} else {
// Original upload includes the same full encoded bytes.
EncodedWeight::Raw(self.upload(&raw[i])?)
};
owned[i] = Some(weight);
}
}
Ok(())
})();
if let Err(primary) = operation {
for owner in owned.into_iter().rev().flatten() {
Ok(PinnedAdmission { layouts, charges, extra, next_bytes, next_age, next_loaded })
}
fn upload_pinned_triplet(
&mut self,
admission: &PinnedAdmission,
keys: &[MoeWeightDescriptor; 3],
raw: &[Box<[u8]>; 3],
owned: &mut [Option<EncodedWeight<'ctx>>; 3],
) -> Result<()> {
if let [Some((gate, _)), Some((up, _)), Some((down, _))] = admission.layouts {
self.upload_dual_triplet([gate, up, down], admission.charges, raw, owned)
} else {
self.upload_mixed_triplet(admission, keys, raw, owned)
}
}
fn upload_dual_triplet(
&self,
formats: [leleka_cuda_driver::MmqFormat; 3],
charges: [usize; 3],
raw: &[Box<[u8]>; 3],
owned: &mut [Option<EncodedWeight<'ctx>>; 3],
) -> Result<()> {
let owners = if self.original_prompt_mmq {
self.context.mmq_original_weight_triplet(formats, [&raw[0], &raw[1], &raw[2]])
} else {
self.context.mmq_weight_triplet(formats, [&raw[0], &raw[1], &raw[2]])
}
.map_err(driver_error)?;
if owners.iter().zip(charges).any(|(owner, charge)| owner.allocated_bytes() != charge) {
for owner in owners.into_iter().rev() {
if owner.close().is_err() {
self.failed.set(true);
}
}
if self.context.is_poisoned() {
self.failed.set(true);
}
return Err(primary);
return Err(Error::IdentityMismatch);
}
for (i, owner) in owners.into_iter().enumerate() {
owned[i] = Some(EncodedWeight::Dual(formats[i], owner));
}
Ok(())
}
fn upload_mixed_triplet(
&mut self,
admission: &PinnedAdmission,
keys: &[MoeWeightDescriptor; 3],
raw: &[Box<[u8]>; 3],
owned: &mut [Option<EncodedWeight<'ctx>>; 3],
) -> Result<()> {
for i in 0..3 {
if raw[i].len() != keys[i].bytes {
return Err(Error::InvalidDimension);
}
let weight = if let Some((format, expected)) = admission.layouts[i] {
let owner = self.context.mmq_weights(format, &raw[i]).map_err(driver_error)?;
if owner.allocated_bytes() != expected {
if owner.close().is_err() {
self.failed.set(true);
}
return Err(Error::IdentityMismatch);
}
EncodedWeight::Dual(format, owner)
} else {
// Original upload includes the same full encoded bytes.
EncodedWeight::Raw(self.upload(&raw[i])?)
};
owned[i] = Some(weight);
}
Ok(())
}
fn commit_pinned_triplet(
&mut self,
admission: &PinnedAdmission,
keys: [MoeWeightDescriptor; 3],
owned: [Option<EncodedWeight<'ctx>>; 3],
raw: &[Box<[u8]>; 3],
read_bytes: usize,
) {
let PinnedAdmission { layouts, charges, extra, next_bytes, next_age, next_loaded } = *admission;
// Capacity, complete ownership, byte/age/count arithmetic checked above.
// No fallible work or allocation follows the first triplet insertion.
for (i, owner) in owned.into_iter().enumerate() {
@@ -110,17 +155,24 @@ impl<'ctx> MoeWeightCache<'ctx> {
pool.loaded_matrices = next_loaded;
pool.preload_read_bytes = pool.preload_read_bytes.saturating_add(read_bytes as u64);
pool.preload_upload_bytes = pool.preload_upload_bytes.saturating_add(extra as u64);
// Raw uploads already update source/upload counters; Dual uploads do not.
self.note_dual_traffic(&layouts, &charges, raw);
for (key, charge) in keys.into_iter().zip(charges) {
self.note_permanent_fill(key, key.bytes, charge);
}
}
/// Raw uploads already update source/upload counters; Dual uploads do not.
fn note_dual_traffic(
&mut self,
layouts: &[Option<(leleka_cuda_driver::MmqFormat, usize)>; 3],
charges: &[usize; 3],
raw: &[Box<[u8]>; 3],
) {
for i in 0..3 {
if layouts[i].is_some() {
self.counters.read_bytes = self.counters.read_bytes.saturating_add(raw[i].len() as u64);
self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(charges[i] as u64);
}
}
for (key, charge) in keys.into_iter().zip(charges) {
self.note_permanent_fill(key, key.bytes, charge);
}
Ok(())
}
#[cfg(test)]
pub(crate) fn test_profile_witness(&self) -> Result<ProfileWitness> {
@@ -128,26 +180,13 @@ impl<'ctx> MoeWeightCache<'ctx> {
if pool.loaded_matrices != pool.plan.prefix * 3 {
return Err(Error::IdentityMismatch);
}
let (reads, uploads) = self.witness_post_preload_pair(pool)?;
Ok(ProfileWitness {
main_slot_limit: pool.main_slot_limit,
fixed_resident_upload_bytes: pool.fixed_resident_upload_bytes,
spill_bytes: self
.main_bytes
.checked_sub(pool.plan.charged_bytes)
.and_then(|n| n.checked_sub(pool.shared.as_ref().map_or(0, |shared| shared.bytes)))
.ok_or(Error::IdentityMismatch)?,
post_preload_read_bytes: self
.counters
.read_bytes
.checked_sub(pool.fixed_resident_read_bytes)
.and_then(|n| n.checked_sub(pool.preload_read_bytes))
.ok_or(Error::IdentityMismatch)?,
post_preload_upload_bytes: self
.counters
.upload_bytes
.checked_sub(pool.fixed_resident_upload_bytes)
.and_then(|n| n.checked_sub(pool.preload_upload_bytes))
.ok_or(Error::IdentityMismatch)?,
spill_bytes: self.witness_spill_bytes(pool)?,
post_preload_read_bytes: reads,
post_preload_upload_bytes: uploads,
prefix: pool.plan.prefix,
pinned_bytes: pool.plan.charged_bytes,
spill_reserve: pool.plan.spill_reserve,
@@ -160,4 +199,29 @@ impl<'ctx> MoeWeightCache<'ctx> {
preload_upload_bytes: self.profile_preload_upload_bytes(),
})
}
#[cfg(test)]
fn witness_spill_bytes(&self, pool: &PinnedPool) -> Result<usize> {
self.main_bytes
.checked_sub(pool.plan.charged_bytes)
.and_then(|n| n.checked_sub(pool.shared.as_ref().map_or(0, |shared| shared.bytes)))
.ok_or(Error::IdentityMismatch)
}
#[cfg(test)]
fn witness_post_preload_pair(&self, pool: &PinnedPool) -> Result<(u64, u64)> {
let reads = Self::witness_post_preload(
self.counters.read_bytes,
pool.fixed_resident_read_bytes,
pool.preload_read_bytes,
)?;
let uploads = Self::witness_post_preload(
self.counters.upload_bytes,
pool.fixed_resident_upload_bytes,
pool.preload_upload_bytes,
)?;
Ok((reads, uploads))
}
#[cfg(test)]
fn witness_post_preload(counter: u64, fixed: u64, preload: u64) -> Result<u64> {
counter.checked_sub(fixed).and_then(|n| n.checked_sub(preload)).ok_or(Error::IdentityMismatch)
}
}
@@ -29,54 +29,10 @@ impl<'ctx> MoeWeightCache<'ctx> {
spill: usize,
shared: &mut cache_profile::SharedPermanentPool,
) -> Result<()> {
self.validate(binding, self.context)?;
crate::qwen_forward::shared_expert_workspace::validate_descriptors(&keys)?;
if keys.iter().any(|key| !shared.contains(*key) || self.main.contains_key(key)) {
return Err(Error::IdentityMismatch);
}
let extra = keys.iter().try_fold(0usize, |n, key| n.checked_add(key.bytes)).ok_or(Error::Overflow)?;
let next_bytes = self.main_bytes.checked_add(extra).ok_or(Error::Overflow)?;
let next_age = self.age.checked_add(4).ok_or(Error::Overflow)?;
if self.main.len().checked_add(4).is_none_or(|n| n > self.main.capacity()) {
return Err(Error::InputAllocation);
}
let (next_bytes, next_age) = self.admit_shared_quartet(binding, &keys, shared)?;
let mut owned: [Option<EncodedWeight<'ctx>>; 4] = std::array::from_fn(|_| None);
let operation = (|| {
// Each role keeps its complete spill/headroom admission before source
// read or allocation; no previous permanent weight may be evicted.
for (index, key) in keys.iter().copied().enumerate() {
let (free, _) = self.context.memory_info().map_err(driver_error)?;
let remaining =
keys[index..].iter().try_fold(0usize, |n, key| n.checked_add(key.bytes)).ok_or(Error::Overflow)?;
let required =
remaining.checked_add(spill).and_then(|n| n.checked_add(WORKING_RESERVE)).ok_or(Error::Overflow)?;
if required > free
|| self
.context
.allocated_bytes()
.checked_add(required)
.is_none_or(|n| n > self.context.budget_bytes())
|| next_bytes.checked_add(spill).is_none_or(|n| n > MAIN_LIMIT)
{
return Err(Error::InputAllocation);
}
let raw = binding.moe_shared_preload_block(key).map_err(binding_error)?;
if raw.len() != key.bytes {
return Err(Error::InvalidDimension);
}
owned[index] = Some(EncodedWeight::Raw(self.upload(&raw)?));
}
Ok(())
})();
if let Err(primary) = operation {
for owner in owned.into_iter().rev().flatten() {
if owner.close().is_err() {
self.failed.set(true);
}
}
if self.context.is_poisoned() {
self.failed.set(true);
}
if let Err(primary) = self.upload_shared_quartet(binding, &keys, spill, next_bytes, &mut owned) {
self.discard_owned(owned);
return Err(primary);
}
// All owners/geometry, byte/age/capacity arithmetic admitted before first
@@ -93,80 +49,87 @@ impl<'ctx> MoeWeightCache<'ctx> {
self.counters.misses = self.counters.misses.saturating_add(4);
Ok(())
}
fn admit_shared_quartet(
&self,
binding: &ModelBinding,
keys: &[MoeWeightDescriptor; 4],
shared: &cache_profile::SharedPermanentPool,
) -> Result<(usize, u64)> {
self.validate(binding, self.context)?;
crate::qwen_forward::shared_expert_workspace::validate_descriptors(keys)?;
if keys.iter().any(|key| !shared.contains(*key) || self.main.contains_key(key)) {
return Err(Error::IdentityMismatch);
}
let extra = keys.iter().try_fold(0usize, |n, key| n.checked_add(key.bytes)).ok_or(Error::Overflow)?;
let next_bytes = self.main_bytes.checked_add(extra).ok_or(Error::Overflow)?;
let next_age = self.age.checked_add(4).ok_or(Error::Overflow)?;
if self.main.len().checked_add(4).is_none_or(|n| n > self.main.capacity()) {
return Err(Error::InputAllocation);
}
Ok((next_bytes, next_age))
}
fn upload_shared_quartet(
&mut self,
binding: &ModelBinding,
keys: &[MoeWeightDescriptor; 4],
spill: usize,
next_bytes: usize,
owned: &mut [Option<EncodedWeight<'ctx>>; 4],
) -> Result<()> {
// Each role keeps its complete spill/headroom admission before source
// read or allocation; no previous permanent weight may be evicted.
for (index, key) in keys.iter().copied().enumerate() {
let (free, _) = self.context.memory_info().map_err(driver_error)?;
let remaining =
keys[index..].iter().try_fold(0usize, |n, key| n.checked_add(key.bytes)).ok_or(Error::Overflow)?;
let required =
remaining.checked_add(spill).and_then(|n| n.checked_add(WORKING_RESERVE)).ok_or(Error::Overflow)?;
if required > free
|| self.context.allocated_bytes().checked_add(required).is_none_or(|n| n > self.context.budget_bytes())
|| next_bytes.checked_add(spill).is_none_or(|n| n > MAIN_LIMIT)
{
return Err(Error::InputAllocation);
}
let raw = binding.moe_shared_preload_block(key).map_err(binding_error)?;
if raw.len() != key.bytes {
return Err(Error::InvalidDimension);
}
owned[index] = Some(EncodedWeight::Raw(self.upload(&raw)?));
}
Ok(())
}
/// Closes every owner built so far, newest first, and marks the cache failed on a close error or poison.
pub(super) fn discard_owned<const N: usize>(&self, owned: [Option<EncodedWeight<'ctx>>; N]) {
for owner in owned.into_iter().rev().flatten() {
if owner.close().is_err() {
self.failed.set(true);
}
}
if self.context.is_poisoned() {
self.failed.set(true);
}
}
/// Closed bookkeeping witness; does not certify model arithmetic or Ready.
pub(crate) fn shared_permanent_witness(&self) -> Result<cache_profile::SharedPermanentWitness> {
let shared = self.pinned.as_ref().and_then(|pool| pool.shared.as_ref()).ok_or(Error::IdentityMismatch)?;
if shared.descriptor_count() != 192
|| shared.roles[3..].iter().any(|role| role.evictions != 0 || role.eviction_bytes != 0)
{
return Err(Error::IdentityMismatch);
}
for layer in 0..48 {
for key in shared.quartet(layer)? {
let entry = self.main.get(&key).ok_or(Error::IdentityMismatch)?;
if entry.charged_bytes != key.bytes || !matches!(&entry.weight, EncodedWeight::Raw(_)) {
return Err(Error::IdentityMismatch);
}
}
}
let now = self.counters;
let mut delta = [0u64; 5];
for (index, (n, old)) in [now.hits, now.misses, now.read_bytes, now.upload_bytes, now.eviction_bytes]
.into_iter()
.zip(shared.baseline)
.enumerate()
{
delta[index] = n.checked_sub(old).ok_or(Error::IdentityMismatch)?;
}
let sum = |f: fn(&cache_profile::RoleTraffic) -> u64| -> Result<u64> {
shared.roles.iter().try_fold(0u64, |n, c| n.checked_add(f(c)).ok_or(Error::Overflow))
};
Ok(cache_profile::SharedPermanentWitness {
descriptors: shared.descriptor_count(),
bytes: shared.bytes,
roles: shared.roles,
preload_roles: shared.preload_roles,
request_roles: shared.request_roles()?,
inclusive_hits: delta[0],
inclusive_misses: delta[1],
inclusive_source_read_bytes: delta[2],
inclusive_upload_bytes: delta[3],
inclusive_eviction_bytes: delta[4],
successful_bytes_reconcile: sum(|c| c.hits)? == delta[0]
&& sum(|c| c.fills)? == delta[1]
&& sum(|c| c.source_read_bytes)? == delta[2]
&& sum(|c| c.upload_bytes)? == delta[3]
&& sum(|c| c.eviction_bytes)? == delta[4],
})
self.shared_witness(shared)
}
/// Actual shared-only counters; raw adaptive slots have their own witness.
pub(crate) fn strata_adaptive_shared_witness(&self) -> Result<cache_profile::SharedPermanentWitness> {
let shared = self.adaptive_shared.as_ref().ok_or(Error::IdentityMismatch)?;
self.shared_witness(shared)
}
fn shared_witness(
&self,
shared: &cache_profile::SharedPermanentPool,
) -> Result<cache_profile::SharedPermanentWitness> {
if shared.descriptor_count() != 192
|| shared.roles[3..].iter().any(|role| role.evictions != 0 || role.eviction_bytes != 0)
{
return Err(Error::IdentityMismatch);
}
for layer in 0..48 {
for key in shared.quartet(layer)? {
let entry = self.main.get(&key).ok_or(Error::IdentityMismatch)?;
if entry.charged_bytes != key.bytes || !matches!(&entry.weight, EncodedWeight::Raw(_)) {
return Err(Error::IdentityMismatch);
}
}
}
let now = self.counters;
let mut delta = [0u64; 5];
for (index, (n, old)) in [now.hits, now.misses, now.read_bytes, now.upload_bytes, now.eviction_bytes]
.into_iter()
.zip(shared.baseline)
.enumerate()
{
delta[index] = n.checked_sub(old).ok_or(Error::IdentityMismatch)?;
}
let sum = |f: fn(&cache_profile::RoleTraffic) -> u64| -> Result<u64> {
shared.roles.iter().try_fold(0u64, |n, c| n.checked_add(f(c)).ok_or(Error::Overflow))
};
self.check_shared_resident(shared)?;
let delta = self.shared_counter_delta(shared)?;
Ok(cache_profile::SharedPermanentWitness {
descriptors: shared.descriptor_count(),
bytes: shared.bytes,
@@ -178,11 +141,40 @@ impl<'ctx> MoeWeightCache<'ctx> {
inclusive_source_read_bytes: delta[2],
inclusive_upload_bytes: delta[3],
inclusive_eviction_bytes: delta[4],
successful_bytes_reconcile: sum(|c| c.hits)? == delta[0]
&& sum(|c| c.fills)? == delta[1]
&& sum(|c| c.source_read_bytes)? == delta[2]
&& sum(|c| c.upload_bytes)? == delta[3]
&& sum(|c| c.eviction_bytes)? == delta[4],
successful_bytes_reconcile: Self::traffic_reconciles(shared, &delta)?,
})
}
fn check_shared_resident(&self, shared: &cache_profile::SharedPermanentPool) -> Result<()> {
for layer in 0..48 {
for key in shared.quartet(layer)? {
let entry = self.main.get(&key).ok_or(Error::IdentityMismatch)?;
if entry.charged_bytes != key.bytes || !matches!(&entry.weight, EncodedWeight::Raw(_)) {
return Err(Error::IdentityMismatch);
}
}
}
Ok(())
}
fn shared_counter_delta(&self, shared: &cache_profile::SharedPermanentPool) -> Result<[u64; 5]> {
let now = self.counters;
let mut delta = [0u64; 5];
for (index, (n, old)) in [now.hits, now.misses, now.read_bytes, now.upload_bytes, now.eviction_bytes]
.into_iter()
.zip(shared.baseline)
.enumerate()
{
delta[index] = n.checked_sub(old).ok_or(Error::IdentityMismatch)?;
}
Ok(delta)
}
fn traffic_reconciles(shared: &cache_profile::SharedPermanentPool, delta: &[u64; 5]) -> Result<bool> {
let sum = |f: fn(&cache_profile::RoleTraffic) -> u64| -> Result<u64> {
shared.roles.iter().try_fold(0u64, |n, c| n.checked_add(f(c)).ok_or(Error::Overflow))
};
Ok(sum(|c| c.hits)? == delta[0]
&& sum(|c| c.fills)? == delta[1]
&& sum(|c| c.source_read_bytes)? == delta[2]
&& sum(|c| c.upload_bytes)? == delta[3]
&& sum(|c| c.eviction_bytes)? == delta[4])
}
}
@@ -26,20 +26,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
impl MoeWeightCache<'_> {
/// Actual current residency only; historical ranked prefix is not pinned now.
pub(crate) fn learned_main_witness(&self, binding: &ModelBinding) -> Result<cache_profile::LearnedMainWitness> {
self.validate(binding, self.context)?;
if !self.learned_main {
return Err(Error::IdentityMismatch);
}
let pool = self.pinned.as_ref().ok_or(Error::IdentityMismatch)?;
let shared = pool.shared.as_ref().ok_or(Error::IdentityMismatch)?;
let _ = self.shared_permanent_witness()?;
let index = self.lru.as_ref().ok_or(Error::IdentityMismatch)?;
let routed_matrices = index.matches_existing(
self.age,
self.main.iter().filter(|(key, _)| !shared.contains(**key)).map(|(key, entry)| (*key, entry.age)),
)?;
fn learned_main_totals(&self, shared: &cache_profile::SharedPermanentPool) -> Result<(usize, usize)> {
let mut routed_bytes = 0usize;
let mut main_bytes = 0usize;
for (key, entry) in &self.main {
@@ -57,10 +44,14 @@ impl MoeWeightCache<'_> {
routed_bytes = routed_bytes.checked_add(entry.charged_bytes).ok_or(Error::Overflow)?;
}
}
Ok((routed_bytes, main_bytes))
}
/// The residency totals and the learned metadata ceiling; returns the learned metadata bytes.
fn check_learned_main(&self, main_bytes: usize, routed_matrices: usize, main_slot_limit: usize) -> Result<usize> {
if main_bytes != self.main_bytes
|| main_bytes > MAIN_LIMIT
|| routed_matrices != self.spill_len()?
|| self.main.len() > pool.main_slot_limit
|| self.main.len() > main_slot_limit
{
return Err(Error::IdentityMismatch);
}
@@ -68,6 +59,24 @@ impl MoeWeightCache<'_> {
if metadata_bytes > HOST_CAP {
return Err(Error::IdentityMismatch);
}
Ok(metadata_bytes)
}
/// Actual current residency only; historical ranked prefix is not pinned now.
pub(crate) fn learned_main_witness(&self, binding: &ModelBinding) -> Result<cache_profile::LearnedMainWitness> {
self.validate(binding, self.context)?;
if !self.learned_main {
return Err(Error::IdentityMismatch);
}
let pool = self.pinned.as_ref().ok_or(Error::IdentityMismatch)?;
let shared = pool.shared.as_ref().ok_or(Error::IdentityMismatch)?;
let _ = self.shared_permanent_witness()?;
let index = self.lru.as_ref().ok_or(Error::IdentityMismatch)?;
let routed_matrices = index.matches_existing(
self.age,
self.main.iter().filter(|(key, _)| !shared.contains(**key)).map(|(key, entry)| (*key, entry.age)),
)?;
let (routed_bytes, main_bytes) = self.learned_main_totals(shared)?;
let metadata_bytes = self.check_learned_main(main_bytes, routed_matrices, pool.main_slot_limit)?;
Ok(cache_profile::LearnedMainWitness {
routed_matrices,
routed_bytes,
@@ -140,25 +140,37 @@ fn original_decoder_first_ranked_profile_prefix_spill_and_atomic_refusals() {
let simple = sanitized_profile(false);
assert_eq!(full.len(), 196_632);
assert_eq!(simple.len(), 98_328);
// Every valid original decoded pair, including the last rank, is compared.
let original_full = original_decode(&full).unwrap();
let original_simple = original_decode(&simple).unwrap();
let (profile, pair_only, original_full) = parse_matches_original_decoder(&full, &simple);
profile_refusals(&full, &simple, &original_full);
let case = PlanCase::new(profile);
let (accepted, tiny, spill, work) = case.accepted_and_ceilings(&original_full);
case.rejections_leave_state_unchanged(&accepted, tiny, spill, work);
case.accepts_every_expert(&pair_only);
}
/// Every valid original decoded pair, including the last rank, is compared.
fn parse_matches_original_decoder(full: &[u8], simple: &[u8]) -> (RankedProfile, RankedProfile, Vec<(u16, u16)>) {
let original_full = original_decode(full).unwrap();
let original_simple = original_decode(simple).unwrap();
assert_eq!(original_full, original_simple);
let profile = RankedProfile::parse(&full, digest(&full)).unwrap();
let pair_only = RankedProfile::parse(&simple, digest(&simple)).unwrap();
let profile = RankedProfile::parse(full, digest(full)).unwrap();
let pair_only = RankedProfile::parse(simple, digest(simple)).unwrap();
assert_eq!(profile.ordered_pairs(), original_full);
assert_eq!(pair_only.ordered_pairs(), original_simple);
assert_eq!(profile.ordered_pairs().len(), 24_576);
assert!(RankedProfile::parse(&full, [0; 32]).is_err());
assert!(RankedProfile::parse(full, [0; 32]).is_err());
(profile, pair_only, original_full)
}
fn profile_refusals(full: &[u8], simple: &[u8], original_full: &[(u16, u16)]) {
for length in [0usize, 4, 23, BASE_BYTES - 1, BASE_BYTES + 1, full.len() - 1] {
refused(&full[..length], Error::IdentityMismatch);
}
let mut extra = full.clone();
let mut extra = full.to_vec();
extra.push(0);
refused(&extra, Error::IdentityMismatch);
for field in 0..6 {
let mut bad = full.clone();
let mut bad = full.to_vec();
if field == 0 {
bad[0] = b'X';
} else {
@@ -166,117 +178,156 @@ fn original_decoder_first_ranked_profile_prefix_spill_and_atomic_refusals() {
}
refused(&bad, Error::IdentityMismatch);
}
let mut duplicate = simple.clone();
let mut duplicate = simple.to_vec();
duplicate[BASE_BYTES - 4..].copy_from_slice(&simple[24..28]);
assert!(original_decode(&duplicate).is_some()); // Original decoder is weaker.
refused(&duplicate, Error::IdentityMismatch);
for (offset, bound) in [(BASE_BYTES - 4, 48u16), (BASE_BYTES - 2, 512u16)] {
let mut bad = simple.clone();
let mut bad = simple.to_vec();
bad[offset..offset + 2].copy_from_slice(&bound.to_le_bytes());
refused(&bad, Error::InvalidDimension);
}
table_refusals(full, original_full);
}
fn table_refusals(full: &[u8], original_full: &[(u16, u16)]) {
let (last_layer, last_expert) = original_full[24_575];
let table_cell = BASE_BYTES + (usize::from(last_layer) * 512 + usize::from(last_expert)) * 4;
for incorrect in [-1i32, 0, 24_576, i32::MAX] {
let mut bad = full.clone();
let mut bad = full.to_vec();
bad[table_cell..table_cell + 4].copy_from_slice(&incorrect.to_le_bytes());
assert_eq!(original_decode(&bad).unwrap(), original_full);
refused(&bad, Error::IdentityMismatch);
}
let mut bad = full.clone();
let mut bad = full.to_vec();
let penultimate = full[BASE_BYTES - 8..BASE_BYTES - 4].to_vec();
let last = full[BASE_BYTES - 4..BASE_BYTES].to_vec();
bad[BASE_BYTES - 8..BASE_BYTES - 4].copy_from_slice(&last);
bad[BASE_BYTES - 4..BASE_BYTES].copy_from_slice(&penultimate);
refused(&bad, Error::IdentityMismatch); // Unique pairs, inconsistent table.
}
let charges = layer_charges();
let gib = 1024usize * 1024 * 1024;
let reserve = 128 * 1024 * 1024;
let window = 10_683_648;
let limits = ProfileLimits {
main_cap: 24 * gib,
allocated: 5 * gib,
device_budget: 28 * gib,
physical_free: 24 * gib,
working_reserve: reserve,
window_spill: window,
};
let accepted = compare_plan(&profile, &charges, limits);
assert!(accepted.prefix > 1 && accepted.prefix < 24_576);
assert_eq!(accepted.spill_reserve, window + 2_662_616);
let first_layer = usize::from(original_full[0].0);
let first: usize = charges[first_layer].iter().sum();
let spill = accepted.spill_reserve;
let work = spill + reserve;
let tiny = ProfileLimits {
main_cap: first + spill,
allocated: 12345,
device_budget: 12345 + first + work,
physical_free: first + work,
working_reserve: reserve,
window_spill: window,
};
assert_eq!(compare_plan(&profile, &charges, tiny).prefix, 1);
// Independently activate each ceiling at the same exact complete boundary.
for field in 0..3 {
let mut one = limits;
match field {
0 => one.main_cap = first + spill,
1 => one.device_budget = one.allocated + first + work,
_ => one.physical_free = first + work,
}
assert_eq!(compare_plan(&profile, &charges, one).prefix, 1);
const GIB: usize = 1024 * 1024 * 1024;
const RESERVE: usize = 128 * 1024 * 1024;
const WINDOW: usize = 10_683_648;
/// The ranked profile with the literal layer charges and the roomy limits the plan phases start from.
struct PlanCase {
profile: RankedProfile,
charges: [[usize; 3]; 48],
limits: ProfileLimits,
}
type Rejection = ([[usize; 3]; 48], ProfileLimits, Error);
impl PlanCase {
fn new(profile: RankedProfile) -> Self {
let limits = ProfileLimits {
main_cap: 24 * GIB,
allocated: 5 * GIB,
device_budget: 28 * GIB,
physical_free: 24 * GIB,
working_reserve: RESERVE,
window_spill: WINDOW,
};
Self { profile, charges: layer_charges(), limits }
}
let snapshot = (profile.pairs.clone(), accepted.selected.clone(), accepted.prefix, accepted.charged_bytes);
let mut rejects = Vec::new();
for field in 0..3 {
let mut no = tiny;
match field {
0 => no.main_cap -= 1,
1 => no.device_budget -= 1,
_ => no.physical_free -= 1,
}
rejects.push((charges, no, Error::InputAllocation));
/// Returns the accepted plan, the one-expert limits, the spill reserve and the spill plus working reserve.
fn accepted_and_ceilings(&self, original_full: &[(u16, u16)]) -> (PrefixPlan, ProfileLimits, usize, usize) {
let accepted = compare_plan(&self.profile, &self.charges, self.limits);
assert!(accepted.prefix > 1 && accepted.prefix < 24_576);
assert_eq!(accepted.spill_reserve, WINDOW + 2_662_616);
let first_layer = usize::from(original_full[0].0);
let first: usize = self.charges[first_layer].iter().sum();
let spill = accepted.spill_reserve;
let work = spill + RESERVE;
let tiny = ProfileLimits {
main_cap: first + spill,
allocated: 12345,
device_budget: 12345 + first + work,
physical_free: first + work,
working_reserve: RESERVE,
window_spill: WINDOW,
};
assert_eq!(compare_plan(&self.profile, &self.charges, tiny).prefix, 1);
self.each_ceiling_at_the_boundary(first, spill, work);
(accepted, tiny, spill, work)
}
let mut no = limits;
no.allocated = no.device_budget + 1;
rejects.push((charges, no, Error::InputAllocation));
let mut no = limits;
no.main_cap = spill - 1;
rejects.push((charges, no, Error::InputAllocation));
let mut no = limits;
no.physical_free = work - 1;
rejects.push((charges, no, Error::InputAllocation));
let mut bad_charges = charges;
bad_charges[47][2] = 0;
rejects.push((bad_charges, limits, Error::InvalidDimension));
bad_charges[47] = [usize::MAX, 1, 1];
rejects.push((bad_charges, limits, Error::Overflow));
let mut no = limits;
no.window_spill = usize::MAX;
rejects.push((charges, no, Error::Overflow));
let mut no = limits;
no.working_reserve = usize::MAX;
rejects.push((charges, no, Error::Overflow));
for (bad_charges, bad_limits, expected) in rejects {
assert!(matches!(PrefixPlan::new(&profile,&bad_charges,bad_limits),Err(error) if error == expected));
assert_eq!(
(profile.pairs.clone(), accepted.selected.clone(), accepted.prefix, accepted.charged_bytes),
snapshot
/// Independently activate each ceiling at the same exact complete boundary.
fn each_ceiling_at_the_boundary(&self, first: usize, spill: usize, work: usize) {
for field in 0..3 {
let mut one = self.limits;
match field {
0 => one.main_cap = first + spill,
1 => one.device_budget = one.allocated + first + work,
_ => one.physical_free = first + work,
}
assert_eq!(compare_plan(&self.profile, &self.charges, one).prefix, 1);
}
}
fn limit_rejections(&self, tiny: ProfileLimits, spill: usize, work: usize) -> Vec<Rejection> {
let mut rejects = Vec::new();
for field in 0..3 {
let mut no = tiny;
match field {
0 => no.main_cap -= 1,
1 => no.device_budget -= 1,
_ => no.physical_free -= 1,
}
rejects.push((self.charges, no, Error::InputAllocation));
}
let mut no = self.limits;
no.allocated = no.device_budget + 1;
rejects.push((self.charges, no, Error::InputAllocation));
let mut no = self.limits;
no.main_cap = spill - 1;
rejects.push((self.charges, no, Error::InputAllocation));
let mut no = self.limits;
no.physical_free = work - 1;
rejects.push((self.charges, no, Error::InputAllocation));
rejects
}
fn charge_rejections(&self) -> Vec<Rejection> {
let mut rejects = Vec::new();
let mut bad_charges = self.charges;
bad_charges[47][2] = 0;
rejects.push((bad_charges, self.limits, Error::InvalidDimension));
bad_charges[47] = [usize::MAX, 1, 1];
rejects.push((bad_charges, self.limits, Error::Overflow));
let mut no = self.limits;
no.window_spill = usize::MAX;
rejects.push((self.charges, no, Error::Overflow));
let mut no = self.limits;
no.working_reserve = usize::MAX;
rejects.push((self.charges, no, Error::Overflow));
rejects
}
fn rejections_leave_state_unchanged(&self, accepted: &PrefixPlan, tiny: ProfileLimits, spill: usize, work: usize) {
let snapshot = (self.profile.pairs.clone(), accepted.selected.clone(), accepted.prefix, accepted.charged_bytes);
let mut rejects = self.limit_rejections(tiny, spill, work);
rejects.extend(self.charge_rejections());
for (bad_charges, bad_limits, expected) in rejects {
assert!(matches!(PrefixPlan::new(&self.profile,&bad_charges,bad_limits),Err(error) if error == expected));
assert_eq!(
(self.profile.pairs.clone(), accepted.selected.clone(), accepted.prefix, accepted.charged_bytes),
snapshot
);
}
}
fn accepts_every_expert(&self, pair_only: &RankedProfile) {
let all_limits = ProfileLimits {
main_cap: 64 * GIB,
allocated: 0,
device_budget: 64 * GIB,
physical_free: 64 * GIB,
working_reserve: RESERVE,
window_spill: WINDOW,
};
assert_eq!(compare_plan(&self.profile, &self.charges, all_limits).prefix, 24_576);
assert_eq!(pair_only.ordered_pairs(), self.profile.ordered_pairs());
println!(
"RANKED_PROFILE_METADATA original_pairs=24576 optional_inverse_table=true full_domain_roles=73728 \
reserve_bytes={RESERVE} window_spill_bytes={WINDOW} no_model_or_device=true"
);
}
let all_limits = ProfileLimits {
main_cap: 64 * gib,
allocated: 0,
device_budget: 64 * gib,
physical_free: 64 * gib,
working_reserve: reserve,
window_spill: window,
};
assert_eq!(compare_plan(&profile, &charges, all_limits).prefix, 24_576);
assert_eq!(pair_only.ordered_pairs(), profile.ordered_pairs());
println!(
"RANKED_PROFILE_METADATA original_pairs=24576 optional_inverse_table=true full_domain_roles=73728 reserve_bytes={reserve} window_spill_bytes={window} no_model_or_device=true"
);
}
@@ -24,6 +24,19 @@ pub(in crate::qwen_forward) struct RoutedOutputBank<'ctx> {
impl<'ctx> RoutedOutputBank<'ctx> {
pub(in crate::qwen_forward) fn new(binding: BindingIdentity, context: &'ctx Context<'ctx>) -> Result<Self> {
Self::admit(context)?;
let mut bank = Self {
binding,
context,
slots: RefCell::new(std::array::from_fn(|_| None)),
failed: Cell::new(false),
completed: Cell::new(0),
};
bank.allocate_all()?;
Ok(bank)
}
fn admit(context: &Context<'_>) -> Result<()> {
if context.is_poisoned() {
return Err(Error::CudaExecution);
}
@@ -38,37 +51,34 @@ impl<'ctx> RoutedOutputBank<'ctx> {
if free < needed {
return Err(Error::InputAllocation);
}
let mut bank = Self {
binding,
context,
slots: RefCell::new(std::array::from_fn(|_| None)),
failed: Cell::new(false),
completed: Cell::new(0),
};
Ok(())
}
fn allocate_all(&mut self) -> Result<()> {
let mut actual = 0usize;
for columns in 1..=MAX_COLUMNS {
for (role, per_column) in ROLE_BYTES.into_iter().enumerate() {
let bytes = per_column * columns;
match context.allocate(bytes) {
match self.context.allocate(bytes) {
Ok(buffer) => {
bank.slots.get_mut()[(columns - 1) * ROLES + role] = Some(buffer);
self.slots.get_mut()[(columns - 1) * ROLES + role] = Some(buffer);
actual += bytes;
}
Err(error) => {
let primary = driver_error(error);
// drain attempts every partial owner; its error never
// replaces the allocation that prevented publication.
let _ = bank.drain();
let _ = self.drain();
return Err(primary);
}
}
}
}
if actual != ROUTED_OUTPUT_BANK_BYTES {
let _ = bank.drain();
let _ = self.drain();
return Err(Error::IdentityMismatch);
}
Ok(bank)
Ok(())
}
fn metadata_extent() -> usize {
@@ -109,6 +119,23 @@ impl<'ctx> RoutedOutputBank<'ctx> {
columns: usize,
execute: impl FnOnce([&mut DeviceBuffer<'ctx>; ROLES]) -> Result<R>,
) -> Result<R> {
let next = self.admit_loan(context, columns)?;
let mut loan = self.slots.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
let start = (columns - 1) * ROLES;
let roles: &mut [Option<DeviceBuffer<'ctx>>; ROLES] =
(&mut loan[start..start + ROLES]).try_into().map_err(|_| Error::IdentityMismatch)?;
self.check_role_extents(roles, columns)?;
let [gate, up, hidden, down] = roles;
let result = execute([
gate.as_mut().ok_or(Error::IdentityMismatch)?,
up.as_mut().ok_or(Error::IdentityMismatch)?,
hidden.as_mut().ok_or(Error::IdentityMismatch)?,
down.as_mut().ok_or(Error::IdentityMismatch)?,
]);
self.settle_loan(context, result, next)
}
fn admit_loan(&self, context: &Context<'_>, columns: usize) -> Result<u64> {
if !std::ptr::eq(self.context, context) {
return Err(Error::IdentityMismatch);
}
@@ -118,24 +145,20 @@ impl<'ctx> RoutedOutputBank<'ctx> {
if !(1..=MAX_COLUMNS).contains(&columns) {
return Err(Error::InvalidDimension);
}
let next = self.completed.get().checked_add(1).ok_or(Error::Overflow)?;
let mut loan = self.slots.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
let start = (columns - 1) * ROLES;
let roles: &mut [Option<DeviceBuffer<'ctx>>; ROLES] =
(&mut loan[start..start + ROLES]).try_into().map_err(|_| Error::IdentityMismatch)?;
self.completed.get().checked_add(1).ok_or(Error::Overflow)
}
fn check_role_extents(&self, roles: &[Option<DeviceBuffer<'ctx>>; ROLES], columns: usize) -> Result<()> {
for (slot, per_column) in roles.iter().zip(ROLE_BYTES) {
if slot.as_ref().is_none_or(|buffer| buffer.len() != per_column * columns) {
self.failed.set(true);
return Err(Error::IdentityMismatch);
}
}
let [gate, up, hidden, down] = roles;
let result = execute([
gate.as_mut().ok_or(Error::IdentityMismatch)?,
up.as_mut().ok_or(Error::IdentityMismatch)?,
hidden.as_mut().ok_or(Error::IdentityMismatch)?,
down.as_mut().ok_or(Error::IdentityMismatch)?,
]);
Ok(())
}
fn settle_loan<R>(&self, context: &Context<'_>, result: Result<R>, next: u64) -> Result<R> {
if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) {
self.failed.set(true);
}
@@ -1,38 +1,24 @@
//! Pure metadata/budget proof; never constructs a ModelBinding or device owner.
use super::*;
fn shared_descriptor(
layer: u32,
role: u8,
raw_kind: u32,
columns: usize,
rows: usize,
bytes: usize,
) -> MoeWeightDescriptor {
MoeWeightDescriptor { layer, expert: None, role, raw_kind, columns, rows, bytes }
}
fn descriptor_set() -> Vec<[MoeWeightDescriptor; 4]> {
(0..48u32)
.map(|layer| {
[
MoeWeightDescriptor {
layer,
expert: None,
role: 0,
raw_kind: 14,
columns: 2560,
rows: 640,
bytes: 1_344_000,
},
MoeWeightDescriptor {
layer,
expert: None,
role: 1,
raw_kind: 14,
columns: 2560,
rows: 640,
bytes: 1_344_000,
},
MoeWeightDescriptor {
layer,
expert: None,
role: 2,
raw_kind: 8,
columns: 640,
rows: 2560,
bytes: 1_740_800,
},
MoeWeightDescriptor { layer, expert: None, role: 3, raw_kind: 30, columns: 2560, rows: 1, bytes: 5120 },
shared_descriptor(layer, 0, 14, 2560, 640, 1_344_000),
shared_descriptor(layer, 1, 14, 2560, 640, 1_344_000),
shared_descriptor(layer, 2, 8, 640, 2560, 1_740_800),
shared_descriptor(layer, 3, 30, 2560, 1, 5120),
]
})
.collect()
@@ -52,163 +38,195 @@ fn reference_prefix(profile: &RankedProfile, totals: &[usize; 48], capacity: usi
}
(count, bytes)
}
#[test]
fn original_plan_first_shared_main_only_precharge_and_actual_role_counter_ledger() {
let profile =
RankedProfile { pairs: (0..48u16).flat_map(|layer| (0..512u16).map(move |expert| (layer, expert))).collect() };
let charges = std::array::from_fn::<_, 48, _>(|layer| [627_200 + layer, 627_200 + layer, 921_816 + layer]);
let totals = charges.map(|roles| roles.into_iter().sum::<usize>());
let shared_keys = descriptor_set();
let shared_total: usize = shared_keys.iter().flatten().map(|key| key.bytes).sum();
assert_eq!(shared_total, SHARED_MAX_BYTES);
let window_spill = (1usize << 30) + 16_975_108;
let largest = *totals.iter().max().unwrap();
let spill = window_spill + largest;
let safety = 128 * 1024 * 1024;
let base = 2usize << 30;
let budget = 28usize << 30;
let initial_free = 26usize << 30;
// Old production planner FIRST, using the independently precharged ledger.
// The new API receives actual post-upload allocated/free and reduces MAIN only.
let old_limits = ProfileLimits {
main_cap: (24usize << 30) - shared_total,
allocated: base + shared_total,
device_budget: budget,
physical_free: initial_free - shared_total,
working_reserve: safety,
window_spill,
};
let old = PrefixPlan::new(&profile, &charges, old_limits).unwrap();
let remaining = remaining_shared_main(24usize << 30, shared_total).unwrap();
assert_eq!(remaining, (24usize << 30) - shared_total);
let current = PrefixPlan::new_shared_with_storage(
&profile,
&charges,
ProfileLimits {
main_cap: remaining,
allocated: base + shared_total,
device_budget: budget,
physical_free: initial_free - shared_total,
working_reserve: safety,
/// The literal profile, charges and budget ceilings every phase of the proof shares.
struct SharedLedger {
profile: RankedProfile,
charges: [[usize; 3]; 48],
totals: [usize; 48],
shared_keys: Vec<[MoeWeightDescriptor; 4]>,
shared_total: usize,
window_spill: usize,
spill: usize,
safety: usize,
base: usize,
budget: usize,
initial_free: usize,
remaining: usize,
}
impl SharedLedger {
fn new() -> Self {
let profile = RankedProfile {
pairs: (0..48u16).flat_map(|layer| (0..512u16).map(move |expert| (layer, expert))).collect(),
};
let charges = std::array::from_fn::<_, 48, _>(|layer| [627_200 + layer, 627_200 + layer, 921_816 + layer]);
let totals = charges.map(|roles| roles.into_iter().sum::<usize>());
let shared_keys = descriptor_set();
let shared_total: usize = shared_keys.iter().flatten().map(|key| key.bytes).sum();
assert_eq!(shared_total, SHARED_MAX_BYTES);
let window_spill = (1usize << 30) + 16_975_108;
let spill = window_spill + *totals.iter().max().unwrap();
let remaining = remaining_shared_main(24usize << 30, shared_total).unwrap();
assert_eq!(remaining, (24usize << 30) - shared_total);
Self {
profile,
charges,
totals,
shared_keys,
shared_total,
window_spill,
},
selected_storage(),
)
.unwrap();
let independently_available = ((24usize << 30) - shared_total - spill)
.min(budget - base - shared_total - spill - safety)
.min(initial_free - shared_total - spill - safety);
let expected = reference_prefix(&profile, &totals, independently_available);
assert_eq!((current.prefix, current.charged_bytes), expected);
assert_eq!(
(current.prefix, current.charged_bytes, current.spill_reserve),
(old.prefix, old.charged_bytes, old.spill_reserve)
);
assert_eq!(current.selected, old.selected);
// Each independent MAIN / typed / physical boundary is exact; one byte short refuses.
for constraint in 0..3 {
for deficit in [0usize, 1] {
let mut limits = ProfileLimits {
main_cap: remaining,
allocated: base + shared_total,
device_budget: budget,
physical_free: initial_free - shared_total,
working_reserve: safety,
window_spill,
};
match constraint {
0 => limits.main_cap = spill + totals[0] - deficit,
1 => limits.device_budget = limits.allocated + spill + safety + totals[0] - deficit,
_ => limits.physical_free = spill + safety + totals[0] - deficit,
}
let first = PrefixPlan::new(&profile, &charges, limits);
let next = PrefixPlan::new_shared_with_storage(&profile, &charges, limits, selected_storage());
if deficit == 0 {
assert_eq!(first.unwrap().prefix, 1);
assert_eq!(next.unwrap().prefix, 1);
} else {
assert!(matches!(first, Err(Error::InputAllocation)));
assert!(matches!(next, Err(Error::InputAllocation)));
spill,
safety: 128 * 1024 * 1024,
base: 2usize << 30,
budget: 28usize << 30,
initial_free: 26usize << 30,
remaining,
}
}
/// The production planner's limits after the shared quartets were actually charged.
fn limits(&self) -> ProfileLimits {
ProfileLimits {
main_cap: self.remaining,
allocated: self.base + self.shared_total,
device_budget: self.budget,
physical_free: self.initial_free - self.shared_total,
working_reserve: self.safety,
window_spill: self.window_spill,
}
}
/// Limits before any shared upload: the storage and overflow refusals do not depend on the charge.
fn uncharged_limits(&self) -> ProfileLimits {
ProfileLimits {
main_cap: self.remaining,
allocated: self.base,
device_budget: self.budget,
physical_free: self.initial_free,
working_reserve: self.safety,
window_spill: self.window_spill,
}
}
fn new_matches_old_planner(&self) {
// Old production planner FIRST, using the independently precharged ledger.
// The new API receives actual post-upload allocated/free and reduces MAIN only.
let old_limits = ProfileLimits { main_cap: (24usize << 30) - self.shared_total, ..self.limits() };
let old = PrefixPlan::new(&self.profile, &self.charges, old_limits).unwrap();
let current =
PrefixPlan::new_shared_with_storage(&self.profile, &self.charges, self.limits(), selected_storage())
.unwrap();
let independently_available = ((24usize << 30) - self.shared_total - self.spill)
.min(self.budget - self.base - self.shared_total - self.spill - self.safety)
.min(self.initial_free - self.shared_total - self.spill - self.safety);
let expected = reference_prefix(&self.profile, &self.totals, independently_available);
assert_eq!((current.prefix, current.charged_bytes), expected);
assert_eq!(
(current.prefix, current.charged_bytes, current.spill_reserve),
(old.prefix, old.charged_bytes, old.spill_reserve)
);
assert_eq!(current.selected, old.selected);
}
/// Each independent MAIN / typed / physical boundary is exact; one byte short refuses.
fn boundaries_are_exact(&self) {
for constraint in 0..3 {
for deficit in [0usize, 1] {
let mut limits = self.limits();
match constraint {
0 => limits.main_cap = self.spill + self.totals[0] - deficit,
1 => limits.device_budget = limits.allocated + self.spill + self.safety + self.totals[0] - deficit,
_ => limits.physical_free = self.spill + self.safety + self.totals[0] - deficit,
}
let first = PrefixPlan::new(&self.profile, &self.charges, limits);
let next =
PrefixPlan::new_shared_with_storage(&self.profile, &self.charges, limits, selected_storage());
if deficit == 0 {
assert_eq!(first.unwrap().prefix, 1);
assert_eq!(next.unwrap().prefix, 1);
} else {
assert!(matches!(first, Err(Error::InputAllocation)));
assert!(matches!(next, Err(Error::InputAllocation)));
}
}
}
}
assert!(matches!(remaining_shared_main(shared_total - 1, shared_total), Err(Error::InputAllocation)));
assert!(matches!(remaining_shared_main(usize::MAX, SHARED_MAX_BYTES + 1), Err(Error::InvalidDimension)));
assert!(matches!(remaining_shared_main(usize::MAX, 0), Err(Error::InvalidDimension)));
assert!(matches!(
PrefixPlan::new_shared_with_storage(
&profile,
&charges,
ProfileLimits {
main_cap: remaining,
allocated: base,
device_budget: budget,
physical_free: initial_free,
working_reserve: safety,
window_spill: usize::MAX,
},
selected_storage()
),
Err(Error::Overflow)
));
let mut changed_storage = selected_storage();
changed_storage[24_575] = true;
assert!(matches!(
PrefixPlan::new_shared_with_storage(
&profile,
&charges,
ProfileLimits {
main_cap: remaining,
allocated: base,
device_budget: budget,
physical_free: initial_free,
working_reserve: safety,
window_spill,
},
changed_storage
),
Err(Error::IdentityMismatch)
));
// Exact whole descriptor identity, never just layer/role/count matches.
let mut pool = SharedPermanentPool::new(shared_keys.clone()).unwrap();
assert_eq!(pool.descriptor_count(), 192);
assert_eq!(pool.bytes, shared_total);
assert!(pool.metadata_bytes().unwrap() < HOST_CAP);
for key in shared_keys.iter().flatten().copied() {
assert!(pool.contains(key));
let mut bad = key;
bad.bytes += 1;
assert!(!pool.contains(bad));
bad = key;
bad.raw_kind += 1;
assert!(!pool.contains(bad));
bad = key;
bad.expert = Some(0);
assert!(!pool.contains(bad));
pool.fill(key, key.bytes, key.bytes);
fn refusals(&self) {
let shared_total = self.shared_total;
assert!(matches!(remaining_shared_main(shared_total - 1, shared_total), Err(Error::InputAllocation)));
assert!(matches!(remaining_shared_main(usize::MAX, SHARED_MAX_BYTES + 1), Err(Error::InvalidDimension)));
assert!(matches!(remaining_shared_main(usize::MAX, 0), Err(Error::InvalidDimension)));
let overflow = ProfileLimits { window_spill: usize::MAX, ..self.uncharged_limits() };
assert!(matches!(
PrefixPlan::new_shared_with_storage(&self.profile, &self.charges, overflow, selected_storage()),
Err(Error::Overflow)
));
let mut changed_storage = selected_storage();
changed_storage[24_575] = true;
assert!(matches!(
PrefixPlan::new_shared_with_storage(&self.profile, &self.charges, self.uncharged_limits(), changed_storage),
Err(Error::IdentityMismatch)
));
}
// A quartet that is internally consistent but sits at the wrong layer index is an identity mismatch;
// a quartet whose members disagree on the layer fails descriptor validation first.
let mut malformed = shared_keys.clone();
malformed[47].iter_mut().for_each(|key| key.layer = 0);
assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::IdentityMismatch)));
let mut malformed = shared_keys.clone();
malformed[47][3].layer = 0;
assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::InvalidDimension)));
let mut malformed = shared_keys.clone();
malformed[0][0].bytes -= 1;
assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::InvalidDimension)));
let mut malformed = shared_keys.clone();
malformed.pop();
assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::InvalidDimension)));
assert_eq!(pool.roles.iter().map(|c| c.source_read_bytes).sum::<u64>(), shared_total as u64);
assert_eq!(pool.roles.iter().map(|c| c.upload_bytes).sum::<u64>(), shared_total as u64);
assert_eq!(pool.roles.iter().map(|c| c.fills).sum::<u64>(), 192);
pool.finish_preload();
for key in shared_keys.iter().flatten().copied() {
pool.hit(key);
/// Exact whole descriptor identity, never just layer/role/count matches.
fn exact_descriptor_identity(&self) -> SharedPermanentPool {
let mut pool = SharedPermanentPool::new(self.shared_keys.clone()).unwrap();
assert_eq!(pool.descriptor_count(), 192);
assert_eq!(pool.bytes, self.shared_total);
assert!(pool.metadata_bytes().unwrap() < HOST_CAP);
for key in self.shared_keys.iter().flatten().copied() {
assert!(pool.contains(key));
let mut bad = key;
bad.bytes += 1;
assert!(!pool.contains(bad));
bad = key;
bad.raw_kind += 1;
assert!(!pool.contains(bad));
bad = key;
bad.expert = Some(0);
assert!(!pool.contains(bad));
pool.fill(key, key.bytes, key.bytes);
}
pool
}
let routed = MoeWeightDescriptor {
/// A quartet that is internally consistent but sits at the wrong layer index is an identity mismatch;
/// a quartet whose members disagree on the layer fails descriptor validation first.
fn malformed_quartets_refuse(&self) {
let mut malformed = self.shared_keys.clone();
malformed[47].iter_mut().for_each(|key| key.layer = 0);
assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::IdentityMismatch)));
let mut malformed = self.shared_keys.clone();
malformed[47][3].layer = 0;
assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::InvalidDimension)));
let mut malformed = self.shared_keys.clone();
malformed[0][0].bytes -= 1;
assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::InvalidDimension)));
let mut malformed = self.shared_keys.clone();
malformed.pop();
assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::InvalidDimension)));
}
fn drive_pool_traffic(&self, pool: &mut SharedPermanentPool) {
pool.finish_preload();
for key in self.shared_keys.iter().flatten().copied() {
pool.hit(key);
}
let routed = shared_routed_descriptor();
pool.fill(routed, routed.bytes, routed.bytes + 216);
pool.hit(routed);
pool.evict(routed, routed.bytes + 216);
}
fn request_ledger(&self, pool: &SharedPermanentPool) {
let requests = pool.request_roles().unwrap();
assert_eq!(requests.iter().map(|c| c.hits).sum::<u64>(), 193);
assert_eq!(requests.iter().map(|c| c.fills).sum::<u64>(), 1);
assert_eq!(requests[2].source_read_bytes, 921_600);
assert_eq!(requests[2].upload_bytes, 921_816);
assert_eq!(requests[2].evictions, 1);
assert_eq!(requests[2].eviction_bytes, 921_816);
assert!(requests[3..].iter().all(|c| c.fills == 0 && c.evictions == 0 && c.upload_bytes == 0 && c.hits == 48));
assert_eq!(pool.preload_roles.iter().map(|c| c.upload_bytes).sum::<u64>(), self.shared_total as u64);
}
}
fn shared_routed_descriptor() -> MoeWeightDescriptor {
MoeWeightDescriptor {
layer: 47,
expert: Some(511),
role: 2,
@@ -216,17 +234,21 @@ fn original_plan_first_shared_main_only_precharge_and_actual_role_counter_ledger
columns: 640,
rows: 2560,
bytes: 921_600,
};
pool.fill(routed, routed.bytes, routed.bytes + 216);
pool.hit(routed);
pool.evict(routed, routed.bytes + 216);
let requests = pool.request_roles().unwrap();
assert_eq!(requests.iter().map(|c| c.hits).sum::<u64>(), 193);
assert_eq!(requests.iter().map(|c| c.fills).sum::<u64>(), 1);
assert_eq!(requests[2].source_read_bytes, 921_600);
assert_eq!(requests[2].upload_bytes, 921_816);
assert_eq!(requests[2].evictions, 1);
assert_eq!(requests[2].eviction_bytes, 921_816);
assert!(requests[3..].iter().all(|c| c.fills == 0 && c.evictions == 0 && c.upload_bytes == 0 && c.hits == 48));
assert_eq!(pool.preload_roles.iter().map(|c| c.upload_bytes).sum::<u64>(), shared_total as u64);
}
}
#[test]
fn original_plan_first_shared_main_only_precharge_and_actual_role_counter_ledger() {
let ledger = SharedLedger::new();
ledger.new_matches_old_planner();
ledger.boundaries_are_exact();
ledger.refusals();
let mut pool = ledger.exact_descriptor_identity();
ledger.malformed_quartets_refuse();
let total = ledger.shared_total as u64;
assert_eq!(pool.roles.iter().map(|c| c.source_read_bytes).sum::<u64>(), total);
assert_eq!(pool.roles.iter().map(|c| c.upload_bytes).sum::<u64>(), total);
assert_eq!(pool.roles.iter().map(|c| c.fills).sum::<u64>(), 192);
ledger.drive_pool_traffic(&mut pool);
ledger.request_ledger(&pool);
}
@@ -3,6 +3,17 @@
#[allow(unused_imports)]
use super::*;
#[path = "impl_adaptivecache/preload.rs"]
mod preload;
type Staged<'ctx> = (Swap, Vec<(DeviceBuffer<'ctx>, Vec<u8>)>);
/// Slot buffers and transfer queue, both reserved up front so later phases never allocate.
struct Reserved<'ctx> {
buffers: Vec<Option<[DeviceBuffer<'ctx>; 3]>>,
transfers: Vec<Transfer<'ctx>>,
}
impl<'ctx> AdaptiveCache<'ctx> {
pub(in super::super) fn preload(
binding: &ModelBinding,
@@ -16,24 +27,26 @@ impl<'ctx> AdaptiveCache<'ctx> {
let largest = template.iter().try_fold(0usize, |max, keys| Ok::<_, Error>(max.max(blob_bytes(keys)?)))?;
let spill_reserve = limits.window_spill.checked_add(largest).ok_or(Error::Overflow)?;
let policy = AdaptivePolicy::new(profile, template, limits)?;
let mut buffers = reserve(policy.initial_slots().len())?;
buffers.resize_with(policy.initial_slots().len(), || None);
let transfers = reserve(ADAPT_SWAPS)?;
let metadata = policy
.metadata_bytes()
.checked_add(buffers.capacity() * std::mem::size_of::<Option<[DeviceBuffer<'ctx>; 3]>>())
.and_then(|n| n.checked_add(transfers.capacity() * std::mem::size_of::<Transfer<'ctx>>()))
.and_then(|n| n.checked_add(external_metadata))
.ok_or(Error::Overflow)?;
if metadata > HOST_CAP {
return Err(Error::InputAllocation);
let reserved = Self::reserve_owners(&policy, external_metadata)?;
let mut owner = Self::unpublished(binding, context, policy, reserved);
if let Err(primary) = owner.preload_slots(binding, spill_reserve, shared_bytes) {
let _ = owner.close();
return Err(primary);
}
let mut owner = Self {
Ok(owner)
}
fn unpublished(
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
policy: AdaptivePolicy,
reserved: Reserved<'ctx>,
) -> Self {
Self {
binding: binding.identity(),
context,
policy,
buffers,
transfers,
buffers: reserved.buffers,
transfers: reserved.transfers,
failed: false,
uploads: 0,
swaps: 0,
@@ -41,69 +54,7 @@ impl<'ctx> AdaptiveCache<'ctx> {
occurrences: 0,
hits: 0,
misses: 0,
};
let operation = (|| {
for slot in 0..owner.buffers.len() {
let keys = owner.policy.slots[slot].keys;
owner.revalidate_keys(binding, keys)?;
let mut loaded: [Option<DeviceBuffer<'ctx>>; 3] = std::array::from_fn(|_| None);
let load = (|| {
for (role, key) in keys.iter().copied().enumerate() {
// Future whole slot plus fixed spill is never credited as
// already free. Actual typed/physical snapshots each role.
let remaining = keys[role..]
.iter()
.try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?;
let required = remaining
.checked_add(spill_reserve)
.and_then(|n| n.checked_add(WORKING_RESERVE))
.ok_or(Error::Overflow)?;
let (free, _) = context.memory_info().map_err(driver_error)?;
if required > free
|| context
.allocated_bytes()
.checked_add(required)
.is_none_or(|n| n > context.budget_bytes())
|| shared_bytes
.checked_add(owner.policy.charged_bytes())
.and_then(|n| n.checked_add(spill_reserve))
.is_none_or(|n| n > super::super::MAIN_LIMIT)
{
return Err(Error::InputAllocation);
}
let raw = binding.moe_preload_block(key).map_err(binding_error)?;
if raw.len() != key.bytes {
return Err(Error::InvalidDimension);
}
let mut buffer = context.allocate(key.bytes).map_err(driver_error)?;
if let Err(primary) = buffer.copy_from(&raw).map_err(driver_error) {
if buffer.release().is_err() {
owner.failed = true;
}
return Err(primary);
}
loaded[role] = Some(buffer);
owner.uploads = owner.uploads.checked_add(key.bytes as u64).ok_or(Error::Overflow)?;
}
Ok(())
})();
if let Err(primary) = load {
for buffer in loaded.into_iter().rev().flatten() {
if buffer.release().is_err() {
owner.failed = true;
}
}
return Err(primary);
}
owner.buffers[slot] = Some(loaded.map(Option::unwrap));
}
owner.validate(binding)
})();
if let Err(primary) = operation {
let _ = owner.close();
return Err(primary);
}
Ok(owner)
}
pub(in super::super) fn validate(&self, binding: &ModelBinding) -> Result<()> {
if self.failed || self.context.is_poisoned() {
@@ -198,37 +149,9 @@ impl<'ctx> AdaptiveCache<'ctx> {
let selected: [Option<Swap>; ADAPT_SWAPS] = std::array::from_fn(|i| self.policy.ranked.get(i).copied());
// All staged byte owners are reserved before any enqueue. Full actual
// finite source checks are maintained; bank retains outgoing source too.
let mut staged = reserve::<(Swap, Vec<(DeviceBuffer<'ctx>, Vec<u8>)>)>(ADAPT_SWAPS)?;
let mut staged = reserve::<Staged<'ctx>>(ADAPT_SWAPS)?;
let mut swaps_vec = reserve::<Swap>(ADAPT_SWAPS)?;
let mut staged_bytes = 0usize;
let preparation = (|| {
for swap in selected.into_iter().flatten() {
let keys = self.policy.incoming_keys(swap)?;
self.revalidate_keys(binding, keys)?;
staged_bytes = staged_bytes.checked_add(blob_bytes(&keys)?).ok_or(Error::Overflow)?;
if staged_bytes > 512 * 1024 * 1024 {
return Err(Error::InputAllocation);
}
let mut raw: [Option<Vec<u8>>; 3] = std::array::from_fn(|_| None);
for (role, key) in keys.iter().copied().enumerate() {
let block = binding.moe_preload_block(key).map_err(binding_error)?;
if block.len() != key.bytes {
return Err(Error::InvalidDimension);
}
raw[role] = Some(block.into_vec());
}
let mut pairs = reserve(3)?;
let raw = raw.map(Option::unwrap);
let owned = self.buffers[swap.slot].take().ok_or(Error::IdentityMismatch)?;
for (buffer, bytes) in owned.into_iter().zip(raw) {
pairs.push((buffer, bytes));
}
staged.push((swap, pairs));
swaps_vec.push(swap);
}
Ok(())
})();
if let Err(primary) = preparation {
if let Err(primary) = self.stage_swaps(binding, selected, &mut staged, &mut swaps_vec) {
for (swap, pairs) in staged.drain(..) {
let mut owned = pairs.into_iter().map(|(buffer, _)| buffer);
self.buffers[swap.slot] = Some(std::array::from_fn(|_| owned.next().unwrap()));
@@ -237,13 +160,56 @@ impl<'ctx> AdaptiveCache<'ctx> {
}
if let Err(primary) = self.policy.mark_enqueued(&swaps_vec) {
self.failed = true;
for (_, pairs) in staged.drain(..) {
for (buffer, _) in pairs.into_iter().rev() {
let _ = buffer.release();
}
}
Self::release_staged(&mut staged);
return Err(primary);
}
self.enqueue_staged(staged)
}
fn stage_swaps(
&mut self,
binding: &ModelBinding,
selected: [Option<Swap>; ADAPT_SWAPS],
staged: &mut Vec<Staged<'ctx>>,
swaps_vec: &mut Vec<Swap>,
) -> Result<()> {
let mut staged_bytes = 0usize;
for swap in selected.into_iter().flatten() {
let keys = self.policy.incoming_keys(swap)?;
self.revalidate_keys(binding, keys)?;
staged_bytes = staged_bytes.checked_add(blob_bytes(&keys)?).ok_or(Error::Overflow)?;
if staged_bytes > 512 * 1024 * 1024 {
return Err(Error::InputAllocation);
}
let raw = Self::read_incoming(binding, &keys)?;
let mut pairs = reserve(3)?;
let owned = self.buffers[swap.slot].take().ok_or(Error::IdentityMismatch)?;
for (buffer, bytes) in owned.into_iter().zip(raw) {
pairs.push((buffer, bytes));
}
staged.push((swap, pairs));
swaps_vec.push(swap);
}
Ok(())
}
fn read_incoming(binding: &ModelBinding, keys: &[MoeWeightDescriptor; 3]) -> Result<[Vec<u8>; 3]> {
let mut raw: [Option<Vec<u8>>; 3] = std::array::from_fn(|_| None);
for (role, key) in keys.iter().copied().enumerate() {
let block = binding.moe_preload_block(key).map_err(binding_error)?;
if block.len() != key.bytes {
return Err(Error::InvalidDimension);
}
raw[role] = Some(block.into_vec());
}
Ok(raw.map(Option::unwrap))
}
fn release_staged(staged: &mut Vec<Staged<'ctx>>) {
for (_, pairs) in staged.drain(..) {
for (buffer, _) in pairs.into_iter().rev() {
let _ = buffer.release();
}
}
}
fn enqueue_staged(&mut self, mut staged: Vec<Staged<'ctx>>) -> Result<()> {
let mut primary = None;
for (swap, pairs) in staged.drain(..) {
if primary.is_some() {
@@ -269,76 +235,88 @@ impl<'ctx> AdaptiveCache<'ctx> {
/// every transfer in the round completes, matching source's batch event.
pub(in super::super) fn poll(&mut self, binding: &ModelBinding, wait: bool) -> Result<()> {
self.validate(binding)?;
let operation = (|| {
// Admit every success counter before any incoming publication.
let next_swaps = self.swaps.checked_add(self.transfers.len() as u64).ok_or(Error::Overflow)?;
let next_uploads = self.transfers.iter().try_fold(self.swap_uploads, |n, transfer| {
n.checked_add(self.policy.slots[transfer.swap.slot].bytes as u64).ok_or(Error::Overflow)
})?;
for transfer in &mut self.transfers {
if let Some(pending) = transfer.pending.take() {
if wait {
transfer.complete = Some(pending.wait().map_err(driver_error)?);
} else {
match pending.poll().map_err(driver_error)? {
OwnedCopyPoll::Pending(owner) => transfer.pending = Some(owner),
OwnedCopyPoll::Complete(receipt) => transfer.complete = Some(receipt),
}
}
}
}
if self.transfers.iter().any(|t| t.complete.is_none()) {
return Ok(());
}
if self.transfers.iter().any(|t| t.complete.as_ref().is_none_or(|receipt| receipt.len() != 3)) {
return Err(Error::IdentityMismatch);
}
for swap in &self.policy.pending {
if self.policy.resident[cell(swap.layer, swap.incoming)?] != -1
|| self.policy.resident[cell(swap.layer, swap.outgoing)?] != -1
|| self.policy.slots[swap.slot].keys[0].expert != Some(swap.outgoing)
{
return Err(Error::IdentityMismatch);
}
}
for transfer in self.transfers.drain(..) {
let receipt = transfer.complete.ok_or(Error::IdentityMismatch)?;
if receipt.len() != 3 {
for (buffer, _) in receipt.into_pairs().into_iter().flatten() {
let _ = buffer.release();
}
return Err(Error::IdentityMismatch);
}
let mut pairs = receipt.into_pairs();
let buffers = [
pairs[0].take().ok_or(Error::IdentityMismatch)?.0,
pairs[1].take().ok_or(Error::IdentityMismatch)?.0,
pairs[2].take().ok_or(Error::IdentityMismatch)?.0,
];
if buffers
.iter()
.zip(self.policy.slots[transfer.swap.slot].keys)
.any(|(buffer, key)| buffer.len() != key.bytes)
{
for buffer in buffers.into_iter().rev() {
let _ = buffer.release();
}
return Err(Error::IdentityMismatch);
}
// Genuine receipt is consumed and whole buffers installed before
// metadata incoming publication. No fake external Ready bit.
self.buffers[transfer.swap.slot] = Some(buffers);
self.policy.publish_completed(0)?;
}
self.swaps = next_swaps;
self.swap_uploads = next_uploads;
self.validate(binding)
})();
let operation = self.poll_transfers(binding, wait);
if operation.is_err() {
self.failed = true;
}
operation
}
fn poll_transfers(&mut self, binding: &ModelBinding, wait: bool) -> Result<()> {
// Admit every success counter before any incoming publication.
let next_swaps = self.swaps.checked_add(self.transfers.len() as u64).ok_or(Error::Overflow)?;
let next_uploads = self.transfers.iter().try_fold(self.swap_uploads, |n, transfer| {
n.checked_add(self.policy.slots[transfer.swap.slot].bytes as u64).ok_or(Error::Overflow)
})?;
for transfer in &mut self.transfers {
Self::advance_transfer(transfer, wait)?;
}
if self.transfers.iter().any(|t| t.complete.is_none()) {
return Ok(());
}
self.check_round_complete()?;
for transfer in self.transfers.drain(..) {
Self::publish_transfer(&mut self.policy, &mut self.buffers, transfer)?;
}
self.swaps = next_swaps;
self.swap_uploads = next_uploads;
self.validate(binding)
}
fn advance_transfer(transfer: &mut Transfer<'ctx>, wait: bool) -> Result<()> {
if let Some(pending) = transfer.pending.take() {
if wait {
transfer.complete = Some(pending.wait().map_err(driver_error)?);
} else {
match pending.poll().map_err(driver_error)? {
OwnedCopyPoll::Pending(owner) => transfer.pending = Some(owner),
OwnedCopyPoll::Complete(receipt) => transfer.complete = Some(receipt),
}
}
}
Ok(())
}
fn check_round_complete(&self) -> Result<()> {
if self.transfers.iter().any(|t| t.complete.as_ref().is_none_or(|receipt| receipt.len() != 3)) {
return Err(Error::IdentityMismatch);
}
for swap in &self.policy.pending {
if self.policy.resident[cell(swap.layer, swap.incoming)?] != -1
|| self.policy.resident[cell(swap.layer, swap.outgoing)?] != -1
|| self.policy.slots[swap.slot].keys[0].expert != Some(swap.outgoing)
{
return Err(Error::IdentityMismatch);
}
}
Ok(())
}
fn publish_transfer(
policy: &mut AdaptivePolicy,
slots: &mut [Option<[DeviceBuffer<'ctx>; 3]>],
transfer: Transfer<'ctx>,
) -> Result<()> {
let receipt = transfer.complete.ok_or(Error::IdentityMismatch)?;
if receipt.len() != 3 {
for (buffer, _) in receipt.into_pairs().into_iter().flatten() {
let _ = buffer.release();
}
return Err(Error::IdentityMismatch);
}
let mut pairs = receipt.into_pairs();
let buffers = [
pairs[0].take().ok_or(Error::IdentityMismatch)?.0,
pairs[1].take().ok_or(Error::IdentityMismatch)?.0,
pairs[2].take().ok_or(Error::IdentityMismatch)?.0,
];
if buffers.iter().zip(policy.slots[transfer.swap.slot].keys).any(|(buffer, key)| buffer.len() != key.bytes) {
for buffer in buffers.into_iter().rev() {
let _ = buffer.release();
}
return Err(Error::IdentityMismatch);
}
// Genuine receipt is consumed and whole buffers installed before
// metadata incoming publication. No fake external Ready bit.
slots[transfer.swap.slot] = Some(buffers);
policy.publish_completed(0)
}
pub(in super::super) fn witness(&self, binding: &ModelBinding) -> Result<AdaptiveWitness> {
self.validate(binding)?;
Ok(AdaptiveWitness {
@@ -0,0 +1,101 @@
//! Slot preload phases of the adaptive cache: reservation, per-role admission and upload.
#[allow(unused_imports)]
use super::*;
impl<'ctx> AdaptiveCache<'ctx> {
pub(super) fn reserve_owners(policy: &AdaptivePolicy, external_metadata: usize) -> Result<Reserved<'ctx>> {
let mut buffers = reserve(policy.initial_slots().len())?;
buffers.resize_with(policy.initial_slots().len(), || None);
let transfers = reserve(ADAPT_SWAPS)?;
let metadata = policy
.metadata_bytes()
.checked_add(buffers.capacity() * std::mem::size_of::<Option<[DeviceBuffer<'ctx>; 3]>>())
.and_then(|n| n.checked_add(transfers.capacity() * std::mem::size_of::<Transfer<'ctx>>()))
.and_then(|n| n.checked_add(external_metadata))
.ok_or(Error::Overflow)?;
if metadata > HOST_CAP {
return Err(Error::InputAllocation);
}
Ok(Reserved { buffers, transfers })
}
pub(super) fn preload_slots(
&mut self,
binding: &ModelBinding,
spill_reserve: usize,
shared_bytes: usize,
) -> Result<()> {
for slot in 0..self.buffers.len() {
let keys = self.policy.slots[slot].keys;
self.revalidate_keys(binding, keys)?;
let mut loaded: [Option<DeviceBuffer<'ctx>>; 3] = std::array::from_fn(|_| None);
if let Err(primary) = self.load_slot(binding, keys, spill_reserve, shared_bytes, &mut loaded) {
for buffer in loaded.into_iter().rev().flatten() {
if buffer.release().is_err() {
self.failed = true;
}
}
return Err(primary);
}
self.buffers[slot] = Some(loaded.map(Option::unwrap));
}
self.validate(binding)
}
pub(super) fn load_slot(
&mut self,
binding: &ModelBinding,
keys: [MoeWeightDescriptor; 3],
spill_reserve: usize,
shared_bytes: usize,
loaded: &mut [Option<DeviceBuffer<'ctx>>; 3],
) -> Result<()> {
for (role, key) in keys.iter().copied().enumerate() {
self.admit_role_upload(&keys[role..], spill_reserve, shared_bytes)?;
loaded[role] = Some(self.upload_role(binding, key)?);
self.uploads = self.uploads.checked_add(key.bytes as u64).ok_or(Error::Overflow)?;
}
Ok(())
}
/// Future whole slot plus fixed spill is never credited as already free.
/// Actual typed/physical snapshots each role.
pub(super) fn admit_role_upload(
&self,
remaining_keys: &[MoeWeightDescriptor],
spill_reserve: usize,
shared_bytes: usize,
) -> Result<()> {
let context = self.context;
let remaining = remaining_keys.iter().try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?;
let required =
remaining.checked_add(spill_reserve).and_then(|n| n.checked_add(WORKING_RESERVE)).ok_or(Error::Overflow)?;
let (free, _) = context.memory_info().map_err(driver_error)?;
if required > free
|| context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes())
|| shared_bytes
.checked_add(self.policy.charged_bytes())
.and_then(|n| n.checked_add(spill_reserve))
.is_none_or(|n| n > super::super::super::MAIN_LIMIT)
{
return Err(Error::InputAllocation);
}
Ok(())
}
pub(super) fn upload_role(
&mut self,
binding: &ModelBinding,
key: MoeWeightDescriptor,
) -> Result<DeviceBuffer<'ctx>> {
let raw = binding.moe_preload_block(key).map_err(binding_error)?;
if raw.len() != key.bytes {
return Err(Error::InvalidDimension);
}
let mut buffer = self.context.allocate(key.bytes).map_err(driver_error)?;
if let Err(primary) = buffer.copy_from(&raw).map_err(driver_error) {
if buffer.release().is_err() {
self.failed = true;
}
return Err(primary);
}
Ok(buffer)
}
}
@@ -39,6 +39,13 @@ pub(super) fn blob_bytes(keys: &[MoeWeightDescriptor; 3]) -> Result<usize> {
}
Ok(bytes)
}
/// Usage counters, residency map and the initial slots of the ranked prefix.
struct InitialSlots {
usage: Vec<f32>,
resident: Vec<i32>,
slots: Vec<Slot>,
}
impl AdaptivePolicy {
/// Caller supplies actual bound descriptors, never arbitrary ready weights.
/// Real Context/free/typed snapshots form limits. This does not upload or
@@ -48,6 +55,31 @@ impl AdaptivePolicy {
template: [[MoeWeightDescriptor; 3]; LAYERS],
limits: ProfileLimits,
) -> Result<Self> {
let charges = Self::template_charges(&template)?;
// Same full expert ranked prefix and existing 24GiB/physical/typed/
// window/largest-triplet/128MiB subtraction. Raw native slots do not
// borrow the unrelated padded MMQ layout's charges.
let plan = PrefixPlan::new(profile, &charges, limits)?;
let InitialSlots { usage, resident, slots } = Self::initial_slots_for(profile, &plan, &template)?;
let (candidates, victims) = (reserve(EXPERTS)?, reserve(EXPERTS)?);
let (ranked, pending) = (reserve(CELLS)?, reserve(ADAPT_SWAPS)?);
let mut owner = Self {
usage,
resident,
slots,
candidates,
victims,
ranked,
pending,
rounds: 0,
template,
charged_bytes: plan.charged_bytes,
metadata_bytes: 0,
};
owner.metadata_bytes = owner.measure_metadata()?;
Ok(owner)
}
fn template_charges(template: &[[MoeWeightDescriptor; 3]; LAYERS]) -> Result<[[usize; 3]; LAYERS]> {
let mut charges = [[0usize; 3]; LAYERS];
for (layer, keys) in template.iter().enumerate() {
if keys[0].layer as usize != layer || keys[0].expert != Some(0) {
@@ -56,10 +88,13 @@ impl AdaptivePolicy {
blob_bytes(keys)?;
charges[layer] = keys.map(|key| key.bytes);
}
// Same full expert ranked prefix and existing 24GiB/physical/typed/
// window/largest-triplet/128MiB subtraction. Raw native slots do not
// borrow the unrelated padded MMQ layout's charges.
let plan = PrefixPlan::new(profile, &charges, limits)?;
Ok(charges)
}
fn initial_slots_for(
profile: &RankedProfile,
plan: &PrefixPlan,
template: &[[MoeWeightDescriptor; 3]; LAYERS],
) -> Result<InitialSlots> {
let mut usage = reserve(CELLS)?;
usage.resize(CELLS, 0.0);
let mut resident = reserve(CELLS)?;
@@ -78,40 +113,25 @@ impl AdaptivePolicy {
resident[index] = i32::try_from(slots.len()).map_err(|_| Error::Overflow)?;
slots.push(Slot { keys, bytes });
}
let candidates = reserve(EXPERTS)?;
let victims = reserve(EXPERTS)?;
let ranked = reserve(CELLS)?;
let pending = reserve(ADAPT_SWAPS)?;
let mut owner = Self {
usage,
resident,
slots,
candidates,
victims,
ranked,
pending,
rounds: 0,
template,
charged_bytes: plan.charged_bytes,
metadata_bytes: 0,
};
Ok(InitialSlots { usage, resident, slots })
}
fn measure_metadata(&self) -> Result<usize> {
let mut metadata = std::mem::size_of::<Self>();
for bytes in [
owner.usage.capacity() * std::mem::size_of::<f32>(),
owner.resident.capacity() * std::mem::size_of::<i32>(),
owner.slots.capacity() * std::mem::size_of::<Slot>(),
owner.candidates.capacity() * std::mem::size_of::<(f32, u32)>(),
owner.victims.capacity() * std::mem::size_of::<(f32, u32)>(),
owner.ranked.capacity() * std::mem::size_of::<Swap>(),
owner.pending.capacity() * std::mem::size_of::<Swap>(),
self.usage.capacity() * std::mem::size_of::<f32>(),
self.resident.capacity() * std::mem::size_of::<i32>(),
self.slots.capacity() * std::mem::size_of::<Slot>(),
self.candidates.capacity() * std::mem::size_of::<(f32, u32)>(),
self.victims.capacity() * std::mem::size_of::<(f32, u32)>(),
self.ranked.capacity() * std::mem::size_of::<Swap>(),
self.pending.capacity() * std::mem::size_of::<Swap>(),
] {
metadata = metadata.checked_add(bytes).ok_or(Error::Overflow)?;
}
if metadata > HOST_CAP {
return Err(Error::InputAllocation);
}
owner.metadata_bytes = metadata;
Ok(owner)
Ok(metadata)
}
pub(in super::super) fn metadata_bytes(&self) -> usize {
self.metadata_bytes
@@ -164,45 +184,54 @@ impl AdaptivePolicy {
return Ok(&self.ranked);
}
for layer in 0..LAYERS {
self.candidates.clear();
self.victims.clear();
for expert in 0..EXPERTS {
let index = layer * EXPERTS + expert;
let value = self.usage[index];
if !value.is_finite() {
return Err(Error::NonFinite);
}
if self.resident[index] < 0 {
if value >= 2.0 {
self.candidates.push((value, expert as u32));
}
} else {
self.victims.push((value, expert as u32));
}
}
self.candidates.sort_unstable_by(|a, b| b.0.total_cmp(&a.0));
self.victims.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
for (&candidate, &victim) in self.candidates.iter().zip(&self.victims) {
if candidate.0 < victim.0 + 1.5 {
break;
}
let slot = self.resident[layer * EXPERTS + victim.1 as usize];
if slot < 0 {
return Err(Error::IdentityMismatch);
}
self.ranked.push(Swap {
gain: candidate.0 - victim.0,
layer: layer as u32,
incoming: candidate.1,
outgoing: victim.1,
slot: slot as usize,
});
}
self.scan_layer(layer)?;
self.rank_layer_swaps(layer)?;
}
self.ranked.sort_unstable_by(|a, b| b.gain.total_cmp(&a.gain));
self.ranked.truncate(ADAPT_SWAPS);
Ok(&self.ranked)
}
/// Splits one layer's experts into swap candidates (not resident, used twice or more) and victims.
fn scan_layer(&mut self, layer: usize) -> Result<()> {
self.candidates.clear();
self.victims.clear();
for expert in 0..EXPERTS {
let index = layer * EXPERTS + expert;
let value = self.usage[index];
if !value.is_finite() {
return Err(Error::NonFinite);
}
if self.resident[index] < 0 {
if value >= 2.0 {
self.candidates.push((value, expert as u32));
}
} else {
self.victims.push((value, expert as u32));
}
}
Ok(())
}
fn rank_layer_swaps(&mut self, layer: usize) -> Result<()> {
self.candidates.sort_unstable_by(|a, b| b.0.total_cmp(&a.0));
self.victims.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
for (&candidate, &victim) in self.candidates.iter().zip(&self.victims) {
if candidate.0 < victim.0 + 1.5 {
break;
}
let slot = self.resident[layer * EXPERTS + victim.1 as usize];
if slot < 0 {
return Err(Error::IdentityMismatch);
}
self.ranked.push(Swap {
gain: candidate.0 - victim.0,
layer: layer as u32,
incoming: candidate.1,
outgoing: victim.1,
slot: slot as usize,
});
}
Ok(())
}
pub(in super::super) fn incoming_keys(&self, swap: Swap) -> Result<[MoeWeightDescriptor; 3]> {
self.validate_swap(swap)?;
let mut keys = self.template[swap.layer as usize];
@@ -33,24 +33,27 @@ fn fixture() -> (RankedProfile, [[MoeWeightDescriptor; 3]; LAYERS]) {
});
(profile, template)
}
/// Candidates (not resident, score of two or more) and victims of one layer, as the old source builds them.
fn layer_tables(usage: &[f32], resident: &[i32], layer: usize) -> (Vec<(f32, u32)>, Vec<(f32, u32)>) {
let mut cand = Vec::new();
let mut vict = Vec::new();
for expert in 0..EXPERTS {
let value = usage[layer * EXPERTS + expert];
if resident[layer * EXPERTS + expert] >= 0 {
vict.push((value, expert as u32));
} else if value >= 2.0 {
cand.push((value, expert as u32));
}
}
(cand, vict)
}
/// Literal independent old-source algorithm FIRST, using separate host tables.
/// Equal-score ordering is deliberately not an acceptance claim: original
/// std::sort/partial_sort comparators do not specify ties.
fn original(usage: &[f32], resident: &[i32]) -> Vec<Swap> {
let mut swaps = Vec::new();
for layer in 0..LAYERS {
let mut cand = Vec::new();
let mut vict = Vec::new();
for expert in 0..EXPERTS {
let value = usage[layer * EXPERTS + expert];
if resident[layer * EXPERTS + expert] < 0 {
if value >= 2.0 {
cand.push((value, expert as u32));
}
} else {
vict.push((value, expert as u32));
}
}
let (mut cand, mut vict) = layer_tables(usage, resident, layer);
cand.sort_unstable_by(|a, b| b.0.partial_cmp(&a.0).unwrap());
vict.sort_unstable_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
for i in 0..cand.len().min(vict.len()) {
@@ -70,31 +73,44 @@ fn original(usage: &[f32], resident: &[i32]) -> Vec<Swap> {
swaps.truncate(96);
swaps
}
#[test]
fn original_policy_first_actual_frequency_threshold_pending_decay_and_same_layer_slots() {
let (profile, template) = fixture();
let slots = 2 * LAYERS;
let capacity = slots * 768;
let limits = ProfileLimits {
fn test_limits(capacity: usize) -> ProfileLimits {
ProfileLimits {
main_cap: capacity + 768,
allocated: 0,
device_budget: capacity + 768 + 128 * 1024 * 1024,
physical_free: capacity + 768 + 128 * 1024 * 1024,
working_reserve: 128 * 1024 * 1024,
window_spill: 0,
};
}
}
#[test]
fn original_policy_first_actual_frequency_threshold_pending_decay_and_same_layer_slots() {
let (profile, template) = fixture();
let slots = 2 * LAYERS;
let capacity = slots * 768;
let limits = test_limits(capacity);
let mut owner = AdaptivePolicy::new(&profile, template, limits).unwrap();
assert_eq!(owner.initial_slots().len(), slots);
assert_eq!(owner.charged_bytes(), capacity);
assert!(owner.metadata_bytes() <= 16 * 1024 * 1024);
// Distinct, source-domain finite scores avoid unspecified equal-score tie
// choices. Repeated true IDs count each occurrence; no per-matrix proxy.
observe_scores(&mut owner);
let old_usage = owner.usage.clone();
let got = due_window_matches_original(&mut owner);
pending_transition_publishes_in_place(&mut owner, &got, &old_usage);
refused_observations_and_overflow(&mut owner);
candidate_floor_and_threshold_equality(&profile, template, limits);
}
/// Distinct, source-domain finite scores avoid unspecified equal-score tie
/// choices. Repeated true IDs count each occurrence; no per-matrix proxy.
fn observe_scores(owner: &mut AdaptivePolicy) {
for layer in 0..LAYERS {
owner.observe(layer as u32, &[0, 0, 1]).unwrap();
owner.observe(layer as u32, &vec![2; 20 + 2 * layer]).unwrap();
owner.observe(layer as u32, &vec![3; 10 + layer]).unwrap();
owner.observe(layer as u32, &[4]).unwrap(); // floor2 refuses singleton
}
}
fn due_window_matches_original(owner: &mut AdaptivePolicy) -> Vec<Swap> {
let old_usage = owner.usage.clone();
let old_resident = owner.resident.clone();
let expected = original(&old_usage, &old_resident);
@@ -104,12 +120,15 @@ fn original_policy_first_actual_frequency_threshold_pending_decay_and_same_layer
}
let got = owner.completed_window().unwrap().to_vec();
assert_eq!(got, expected);
got
}
fn pending_transition_publishes_in_place(owner: &mut AdaptivePolicy, got: &[Swap], old_usage: &[f32]) {
// Pure metadata transition, explicitly not a real event/driver proof.
owner.mark_enqueued(&got).unwrap();
for (now, old) in owner.usage.iter().zip(&old_usage) {
owner.mark_enqueued(got).unwrap();
for (now, old) in owner.usage.iter().zip(old_usage) {
assert_eq!(now.to_bits(), (old * 0.7).to_bits());
}
for swap in &got {
for swap in got {
assert_eq!(owner.resident_slot(swap.layer, swap.outgoing).unwrap(), None);
assert_eq!(owner.resident_slot(swap.layer, swap.incoming).unwrap(), None);
assert_eq!(owner.incoming_keys_for_test(*swap)[0].layer, swap.layer);
@@ -125,14 +144,22 @@ fn original_policy_first_actual_frequency_threshold_pending_decay_and_same_layer
assert_eq!(owner.resident_slot(swap.layer, swap.incoming).unwrap(), Some(swap.slot));
assert_eq!(owner.slots[swap.slot].keys[0].expert, Some(swap.incoming));
}
}
fn refused_observations_and_overflow(owner: &mut AdaptivePolicy) {
let before = owner.usage.clone();
assert_eq!(owner.observe(48, &[0]), Err(Error::InvalidExpert));
assert_eq!(owner.observe(0, &[512]), Err(Error::InvalidExpert));
assert_eq!(owner.usage, before);
owner.rounds = u64::MAX;
assert_eq!(owner.completed_window().unwrap_err(), Error::Overflow);
// Exact candidate floor and threshold equality source comparisons FIRST.
let mut singleton = AdaptivePolicy::new(&profile, template, limits).unwrap();
}
/// Exact candidate floor and threshold equality source comparisons FIRST.
fn candidate_floor_and_threshold_equality(
profile: &RankedProfile,
template: [[MoeWeightDescriptor; 3]; LAYERS],
limits: ProfileLimits,
) {
let mut singleton = AdaptivePolicy::new(profile, template, limits).unwrap();
singleton.usage[0] = 0.5;
singleton.usage[1] = 0.75;
singleton.usage[2] = 2.0;
@@ -71,43 +71,20 @@ impl CpuMissWorkspace {
return Err(CpuMissError::Identity);
}
source.validate_binding(binding).map_err(CpuMissError::Source)?;
if !(1..=leleka_native_cpu_expert::MAX_ROWS).contains(&activations.len()) {
return Err(CpuMissError::Shape);
}
for input in activations {
if input.len() != H {
return Err(CpuMissError::Shape);
}
if input.iter().any(|x| !x.is_finite()) {
return Err(CpuMissError::NonFinite);
}
}
check_activations(activations)?;
let gate = source.descriptor(member, MoeMatrixRole::Gate).map_err(CpuMissError::Source)?;
let up = source.descriptor(member, MoeMatrixRole::Up).map_err(CpuMissError::Source)?;
let down = source.descriptor(member, MoeMatrixRole::Down).map_err(CpuMissError::Source)?;
let (gu, dt) = validate_triplet([gate, up, down])?;
let gate_bytes = source.block(member, MoeMatrixRole::Gate).map_err(CpuMissError::Source)?.into_bytes();
let up_bytes = source.block(member, MoeMatrixRole::Up).map_err(CpuMissError::Source)?.into_bytes();
let down_bytes = source.block(member, MoeMatrixRole::Down).map_err(CpuMissError::Source)?.into_bytes();
if [gate_bytes.len(), up_bytes.len(), down_bytes.len()] != [gate.bytes, up.bytes, down.bytes] {
return Err(CpuMissError::Shape);
}
let mut input = Vec::new();
input.try_reserve_exact(activations.len() * H).map_err(|_| CpuMissError::Allocation)?;
for row in activations {
input.extend_from_slice(row);
}
let job =
PreparedJob::new(gu, dt, gate_bytes, up_bytes, down_bytes, input.into_boxed_slice(), activations.len())
.map_err(native_error)?;
let [gate_bytes, up_bytes, down_bytes] = read_triplet_bytes(source, member, [gate, up, down])?;
let input = flatten_activations(activations)?;
let job = PreparedJob::new(gu, dt, gate_bytes, up_bytes, down_bytes, input, activations.len())
.map_err(native_error)?;
source.validate_binding(binding).map_err(CpuMissError::Source)?;
Ok(PreparedCpuMiss { binding: binding.identity(), descriptors: [gate, up, down], job })
}
/// Single bounded batch; actor metadata never crosses the coordinator thread.
/// Root must include all preparation peak/live owners in its host admission.
pub(crate) fn start(&mut self, jobs: Vec<PreparedCpuMiss>, allowance: usize) -> Result<PendingCpuMissBatch<'_>> {
let count = jobs.len();
if !(1..=leleka_native_cpu_expert::MAX_JOBS).contains(&count)
fn check_jobs(&self, jobs: &Vec<PreparedCpuMiss>) -> Result<()> {
if !(1..=leleka_native_cpu_expert::MAX_JOBS).contains(&jobs.len())
|| jobs.capacity() > leleka_native_cpu_expert::MAX_JOBS
{
return Err(CpuMissError::Shape);
@@ -125,28 +102,20 @@ impl CpuMissWorkspace {
return Err(CpuMissError::Shape);
}
}
Ok(())
}
/// Single bounded batch; actor metadata never crosses the coordinator thread.
/// Root must include all preparation peak/live owners in its host admission.
pub(crate) fn start(&mut self, jobs: Vec<PreparedCpuMiss>, allowance: usize) -> Result<PendingCpuMissBatch<'_>> {
let count = jobs.len();
self.check_jobs(&jobs)?;
if allowance > leleka_native_cpu_expert::MAX_BATCH_BYTES {
return Err(CpuMissError::Allocation);
}
let mut descriptors = Vec::new();
descriptors.try_reserve_exact(count).map_err(|_| CpuMissError::Allocation)?;
let mut native = Vec::new();
native.try_reserve_exact(count).map_err(|_| CpuMissError::Allocation)?;
let mut results = Vec::new();
results.try_reserve_exact(count).map_err(|_| CpuMissError::Allocation)?;
let metadata = jobs
.capacity()
.checked_mul(std::mem::size_of::<PreparedCpuMiss>())
.and_then(|n| {
descriptors
.capacity()
.checked_mul(std::mem::size_of::<[MoeWeightDescriptor; 3]>())
.and_then(|m| n.checked_add(m))
})
.and_then(|n| {
results.capacity().checked_mul(std::mem::size_of::<CpuMissRows>()).and_then(|m| n.checked_add(m))
})
.ok_or(CpuMissError::Allocation)?;
let mut descriptors = reserve_vec(count)?;
let mut native = reserve_vec(count)?;
let results = reserve_vec(count)?;
let metadata = batch_metadata(&jobs, &descriptors, &results)?;
let remaining = allowance.checked_sub(metadata).ok_or(CpuMissError::Allocation)?;
for job in jobs {
descriptors.push(job.descriptors);
@@ -194,44 +163,110 @@ fn native_error(error: leleka_native_cpu_expert::Error) -> CpuMissError {
E::NativeFailure | E::Closed => CpuMissError::NativeFailure,
}
}
fn triplet_coordinates_match(gate: &MoeWeightDescriptor, up: &MoeWeightDescriptor, down: &MoeWeightDescriptor) -> bool {
gate.expert.is_some()
&& gate.expert == up.expert
&& gate.expert == down.expert
&& gate.layer == up.layer
&& gate.layer == down.layer
&& gate.role == 0
&& up.role == 1
&& down.role == 2
}
fn triplet_geometry_matches(gate: &MoeWeightDescriptor, up: &MoeWeightDescriptor, down: &MoeWeightDescriptor) -> bool {
gate.columns == H
&& up.columns == H
&& gate.rows == FF
&& up.rows == FF
&& down.columns == FF
&& down.rows == H
&& gate.raw_kind == up.raw_kind
&& gate.bytes == up.bytes
}
fn gate_up_layout(raw_kind: u32) -> Result<(GateUpFormat, usize, usize)> {
match raw_kind {
18 => Ok((GateUpFormat::Iq3Xxs, 256, 98)),
21 => Ok((GateUpFormat::Iq3S, 256, 110)),
22 => Ok((GateUpFormat::Iq2S, 256, 82)),
23 => Ok((GateUpFormat::Iq4Xs, 256, 136)),
42 => Ok((GateUpFormat::Q2_0, 64, 18)),
_ => Err(CpuMissError::Unsupported),
}
}
fn down_layout(raw_kind: u32) -> Result<(DownFormat, usize, usize)> {
match raw_kind {
20 => Ok((DownFormat::Iq4Nl, 32, 18)),
42 => Ok((DownFormat::Q2_0, 64, 18)),
_ => Err(CpuMissError::Unsupported),
}
}
pub(crate) fn validate_triplet([gate, up, down]: [MoeWeightDescriptor; 3]) -> Result<(GateUpFormat, DownFormat)> {
if gate.expert.is_none()
|| gate.expert != up.expert
|| gate.expert != down.expert
|| gate.layer != up.layer
|| gate.layer != down.layer
|| gate.role != 0
|| up.role != 1
|| down.role != 2
|| gate.columns != H
|| up.columns != H
|| gate.rows != FF
|| up.rows != FF
|| down.columns != FF
|| down.rows != H
|| gate.raw_kind != up.raw_kind
|| gate.bytes != up.bytes
{
if !triplet_coordinates_match(&gate, &up, &down) || !triplet_geometry_matches(&gate, &up, &down) {
return Err(CpuMissError::Shape);
}
let (gu, block, bytes) = match gate.raw_kind {
18 => (GateUpFormat::Iq3Xxs, 256, 98),
21 => (GateUpFormat::Iq3S, 256, 110),
22 => (GateUpFormat::Iq2S, 256, 82),
23 => (GateUpFormat::Iq4Xs, 256, 136),
42 => (GateUpFormat::Q2_0, 64, 18),
_ => return Err(CpuMissError::Unsupported),
};
let (dt, dblock, dbytes) = match down.raw_kind {
20 => (DownFormat::Iq4Nl, 32, 18),
42 => (DownFormat::Q2_0, 64, 18),
_ => return Err(CpuMissError::Unsupported),
};
let (gu, block, bytes) = gate_up_layout(gate.raw_kind)?;
let (dt, dblock, dbytes) = down_layout(down.raw_kind)?;
if gate.bytes != H / block * bytes * FF || down.bytes != FF / dblock * dbytes * H {
return Err(CpuMissError::Shape);
}
Ok((gu, dt))
}
fn check_activations(activations: &[&[f32]]) -> Result<()> {
if !(1..=leleka_native_cpu_expert::MAX_ROWS).contains(&activations.len()) {
return Err(CpuMissError::Shape);
}
for input in activations {
if input.len() != H {
return Err(CpuMissError::Shape);
}
if input.iter().any(|x| !x.is_finite()) {
return Err(CpuMissError::NonFinite);
}
}
Ok(())
}
fn read_triplet_bytes(
source: &mut MoeRoutedSourceScope<'_, '_>,
member: usize,
[gate, up, down]: [MoeWeightDescriptor; 3],
) -> Result<[Box<[u8]>; 3]> {
let gate_bytes = source.block(member, MoeMatrixRole::Gate).map_err(CpuMissError::Source)?.into_bytes();
let up_bytes = source.block(member, MoeMatrixRole::Up).map_err(CpuMissError::Source)?.into_bytes();
let down_bytes = source.block(member, MoeMatrixRole::Down).map_err(CpuMissError::Source)?.into_bytes();
if [gate_bytes.len(), up_bytes.len(), down_bytes.len()] != [gate.bytes, up.bytes, down.bytes] {
return Err(CpuMissError::Shape);
}
Ok([gate_bytes, up_bytes, down_bytes])
}
fn flatten_activations(activations: &[&[f32]]) -> Result<Box<[f32]>> {
let mut input = Vec::new();
input.try_reserve_exact(activations.len() * H).map_err(|_| CpuMissError::Allocation)?;
for row in activations {
input.extend_from_slice(row);
}
Ok(input.into_boxed_slice())
}
fn reserve_vec<T>(count: usize) -> Result<Vec<T>> {
let mut vec = Vec::new();
vec.try_reserve_exact(count).map_err(|_| CpuMissError::Allocation)?;
Ok(vec)
}
fn batch_metadata(
jobs: &Vec<PreparedCpuMiss>,
descriptors: &Vec<[MoeWeightDescriptor; 3]>,
results: &Vec<CpuMissRows>,
) -> Result<usize> {
jobs.capacity()
.checked_mul(std::mem::size_of::<PreparedCpuMiss>())
.and_then(|n| {
descriptors
.capacity()
.checked_mul(std::mem::size_of::<[MoeWeightDescriptor; 3]>())
.and_then(|m| n.checked_add(m))
})
.and_then(|n| results.capacity().checked_mul(std::mem::size_of::<CpuMissRows>()).and_then(|m| n.checked_add(m)))
.ok_or(CpuMissError::Allocation)
}
pub(crate) fn runtime_error(error: CpuMissError) -> super::contract::Error {
use super::contract::{Error, Stage};
@@ -11,6 +11,44 @@ use leleka_cuda_driver::{
};
impl<'ctx> DenseWeightCache<'ctx> {
fn verify_gr_half<'a>(&'a self, binding: &ModelBinding, role: GrRole) -> Result<HcHalfBuffers<'a, 'ctx>> {
let entry = self.gr(binding, role)?;
let [norm, down, up, inject] = self.gr_buffers(entry)?;
Ok(HcHalfBuffers {
norm: norm.ok_or(Error::IdentityMismatch)?,
down: down.ok_or(Error::IdentityMismatch)?,
up: up.ok_or(Error::IdentityMismatch)?,
inject: inject.ok_or(Error::IdentityMismatch)?,
})
}
fn verify_gr_output<'a>(&'a self, binding: &ModelBinding) -> Result<HcOutputBuffers<'a, 'ctx>> {
let entry = self.gr(binding, GrRole::Final)?;
let [norm, down, up, _] = self.gr_buffers(entry)?;
Ok(HcOutputBuffers {
norm: norm.ok_or(Error::IdentityMismatch)?,
down: down.ok_or(Error::IdentityMismatch)?,
up: up.ok_or(Error::IdentityMismatch)?,
})
}
fn verify_ple_buffers<'a>(
&'a self,
binding: &ModelBinding,
ple_scratch: &'a DeviceBuffer<'ctx>,
ple_history: &'a DeviceBuffer<'ctx>,
) -> Result<PleBuffers<'a, 'ctx>> {
let ple = self.ple(binding, self.context)?;
let [norm_key, norm_query, norm_conv, conv1d] = self.ple_aux(ple)?;
Ok(PleBuffers {
key: PleKeyBuffer::Bf16(self.ple_key(ple)?),
value: self.ple_value(ple)?,
norm_key,
norm_query,
norm_conv,
conv1d,
scratch: ple_scratch,
history: ple_history,
})
}
/// `hc_*` weights of every layer half, the `output_hc_*` mixer and the PLE block. `ple_history` must be
/// the buffer the verify journal snapshots; `ple_scratch` at least `PLE_SCRATCH_BYTES`.
pub(in crate::qwen_forward) fn original_verify_gr<'a>(
@@ -20,45 +58,40 @@ impl<'ctx> DenseWeightCache<'ctx> {
ple_history: &'a DeviceBuffer<'ctx>,
) -> Result<OriginalVerifyGrBinding<'a, 'ctx>> {
self.check(binding)?;
let half = |role: GrRole| -> Result<HcHalfBuffers<'a, 'ctx>> {
let entry = self.gr(binding, role)?;
let [norm, down, up, inject] = self.gr_buffers(entry)?;
Ok(HcHalfBuffers {
norm: norm.ok_or(Error::IdentityMismatch)?,
down: down.ok_or(Error::IdentityMismatch)?,
up: up.ok_or(Error::IdentityMismatch)?,
inject: inject.ok_or(Error::IdentityMismatch)?,
})
};
let mut layers = Vec::new();
layers.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?;
for layer in 0..48u32 {
layers.push(HcLayerBuffers { attention: half(GrRole::Attention(layer))?, ffn: half(GrRole::Ffn(layer))? });
layers.push(HcLayerBuffers {
attention: self.verify_gr_half(binding, GrRole::Attention(layer))?,
ffn: self.verify_gr_half(binding, GrRole::Ffn(layer))?,
});
}
let output = {
let entry = self.gr(binding, GrRole::Final)?;
let [norm, down, up, _] = self.gr_buffers(entry)?;
HcOutputBuffers {
norm: norm.ok_or(Error::IdentityMismatch)?,
down: down.ok_or(Error::IdentityMismatch)?,
up: up.ok_or(Error::IdentityMismatch)?,
}
};
let ple = self.ple(binding, self.context)?;
let [norm_key, norm_query, norm_conv, conv1d] = self.ple_aux(ple)?;
let ple = PleBuffers {
key: PleKeyBuffer::Bf16(self.ple_key(ple)?),
value: self.ple_value(ple)?,
norm_key,
norm_query,
norm_conv,
conv1d,
scratch: ple_scratch,
history: ple_history,
};
let output = self.verify_gr_output(binding)?;
let ple = self.verify_ple_buffers(binding, ple_scratch, ple_history)?;
OriginalVerifyGrBinding::new(self.context, layers, output, Some(ple)).map_err(driver_error)
}
fn verify_qsa_layer<'a>(
&'a self,
binding: &ModelBinding,
layer: u32,
) -> Result<OriginalVerifyQsaLayerWeights<'a, 'ctx>> {
let entry = self.qsa(binding, layer)?;
// norms: [q, k, index q, index k]; the index-k gamma belongs to the journal
let norms = self.qsa_norms(entry)?;
let (index_k, kind_k) = self.qsa_matrix(entry, QsaMatrixRole::IndexK)?;
let (index_q, kind_q) = self.qsa_matrix(entry, QsaMatrixRole::IndexQ)?;
if kind_k != QsaMatrixKind::Bf16 || kind_q != QsaMatrixKind::Bf16 {
return Err(Error::Unsupported(crate::qwen_forward::contract::Stage::QsaIndex));
}
Ok(OriginalVerifyQsaLayerWeights {
attn_q_norm: norms[0],
attn_k_norm: norms[1],
index_q_norm: norms[2],
index_k_proj: index_k,
index_q_proj: index_q,
})
}
/// The twelve QSA layers' Q/K norms, indexer Q norm and the BF16 indexer K/Q projections.
pub(in crate::qwen_forward) fn original_verify_qsa<'a>(
&'a self,
@@ -72,21 +105,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
if layer.kind() != BoundLayerKind::Qsa {
continue;
}
let entry = self.qsa(binding, layer.index())?;
// norms: [q, k, index q, index k]; the index-k gamma belongs to the journal
let norms = self.qsa_norms(entry)?;
let (index_k, kind_k) = self.qsa_matrix(entry, QsaMatrixRole::IndexK)?;
let (index_q, kind_q) = self.qsa_matrix(entry, QsaMatrixRole::IndexQ)?;
if kind_k != QsaMatrixKind::Bf16 || kind_q != QsaMatrixKind::Bf16 {
return Err(Error::Unsupported(crate::qwen_forward::contract::Stage::QsaIndex));
}
layers.push(OriginalVerifyQsaLayerWeights {
attn_q_norm: norms[0],
attn_k_norm: norms[1],
index_q_norm: norms[2],
index_k_proj: index_k,
index_q_proj: index_q,
});
layers.push(self.verify_qsa_layer(binding, layer.index())?);
}
let layers: [OriginalVerifyQsaLayerWeights<'a, 'ctx>; 12] =
layers.try_into().map_err(|_| Error::InvalidDimension)?;
@@ -74,56 +74,52 @@ impl<'ctx> DenseWeightCache<'ctx> {
}
let mut result = Self::new_qsa_selected_router_gr_batch_qk(binding, context)?;
result.native_prompt_capacity = capacity;
match QsaAttentionScratch::new_experimental(binding, context, result.mirror_failed.clone()) {
Ok(slot) => {
if slot.allocated_bytes() != super::super::super::qsa_attention::attention_scratch::SCRATCH_BYTES {
let _ = slot.close();
let _ = result.close();
return Err(Error::InvalidDimension);
}
result.qsa_attention_workspace = Some(RefCell::new(slot));
}
Err(primary) => {
let _ = result.close();
return Err(primary);
}
if let Err(primary) = result.attach_prompt_owners(binding, context, capacity) {
let _ = result.close();
return Err(primary);
}
// Actual scratch, mapped/canonical KV ledger and exact64 banks are eager before routed PrefixPlan.
Ok(result)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn attach_prompt_owners(
&mut self,
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
capacity: usize,
) -> Result<()> {
let slot = QsaAttentionScratch::new_experimental(binding, context, self.mirror_failed.clone())?;
if slot.allocated_bytes() != super::super::super::qsa_attention::attention_scratch::SCRATCH_BYTES {
let _ = slot.close();
return Err(Error::InvalidDimension);
}
self.qsa_attention_workspace = Some(RefCell::new(slot));
self.attach_prompt_queues(context, capacity)?;
self.attach_prompt_resources(context, capacity)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn attach_prompt_queues(&mut self, context: &'ctx Context<'ctx>, capacity: usize) -> Result<()> {
// This selected actor eagerly owns the actual PLE queue before any
// expert cache budget is admitted. Default actors retain their path.
match context.ple_closed_queue() {
Ok(queue) => result.ple_queue = Some(RefCell::new(queue)),
Err(error) => {
let primary = driver_error(error);
let _ = result.close();
return Err(primary);
}
}
self.ple_queue = Some(RefCell::new(context.ple_closed_queue().map_err(driver_error)?));
// Literal prefill GEMM has one model-lifetime vendor handle, stream and
// actual 32 MiB workspace. Each producer releases its exclusive loan
// after completion; a row bank never carries it across attention.
match context.native_batch_workspace() {
Ok(workspace) => result.native_batch_workspace = Some(RefCell::new(workspace)),
Err(error) => {
let primary = driver_error(error);
let _ = result.close();
return Err(primary);
}
}
self.native_batch_workspace = Some(RefCell::new(context.native_batch_workspace().map_err(driver_error)?));
// Original selected mode17 profile has STRATA_PREFILL_BF16X2 absent.
// HighOnly is explicit. Hi+Lo is a separately qualified load profile.
match if capacity == 64 {
let queue = if capacity == 64 {
context.ple_batch_queue(leleka_cuda_driver::PleBf16Mode::HighOnly)
} else {
context.ple_batch_queue_for_prompt(leleka_cuda_driver::PleBf16Mode::HighOnly, capacity)
} {
Ok(queue) => result.ple_batch_queue = Some(RefCell::new(queue)),
Err(error) => {
let primary = driver_error(error);
let _ = result.close();
return Err(primary);
}
}
match if capacity == 64 {
.map_err(driver_error)?;
self.ple_batch_queue = Some(RefCell::new(queue));
Ok(())
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn attach_prompt_resources(&mut self, context: &'ctx Context<'ctx>, capacity: usize) -> Result<()> {
let resources = if capacity == 64 {
super::super::super::gdn::prefill_batch::GdnBatchResources::new(
context,
super::super::super::gdn::prefill_batch::Bf16Profile::HighOnly,
@@ -134,52 +130,33 @@ impl<'ctx> DenseWeightCache<'ctx> {
super::super::super::gdn::prefill_batch::Bf16Profile::HighOnly,
capacity,
)
} {
Ok(resources) => result.gdn_batch_resources = Some(RefCell::new(resources)),
Err(primary) => {
let _ = result.close();
return Err(primary);
}
}
match if capacity == 64 {
}?;
self.gdn_batch_resources = Some(RefCell::new(resources));
let owner = if capacity == 64 {
context.qsa_native_batch_workspace(leleka_cuda_driver::QsaNativePacking::HighOnly)
} else {
context.qsa_native_batch_workspace_for_prompt(leleka_cuda_driver::QsaNativePacking::HighOnly, capacity)
} {
Ok(owner) => result.qsa_native_workspace = Some(RefCell::new(owner)),
Err(error) => {
let primary = driver_error(error);
let _ = result.close();
return Err(primary);
}
}
match if capacity == 64 {
super::super::super::qsa_native_resources::NativeQsaResources::new(context, result.mirror_failed.clone())
.map_err(driver_error)?;
self.qsa_native_workspace = Some(RefCell::new(owner));
self.attach_native_qsa_resources(context, capacity)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn attach_native_qsa_resources(&mut self, context: &'ctx Context<'ctx>, capacity: usize) -> Result<()> {
let owner = if capacity == 64 {
super::super::super::qsa_native_resources::NativeQsaResources::new(context, self.mirror_failed.clone())
} else {
super::super::super::qsa_native_resources::NativeQsaResources::new_for_prompt(
context,
result.mirror_failed.clone(),
self.mirror_failed.clone(),
capacity,
)
} {
Ok(owner) => result.native_qsa = Some(RefCell::new(owner)),
Err(primary) => {
let _ = result.close();
return Err(primary);
}
}
}?;
self.native_qsa = Some(RefCell::new(owner));
// The selected native target and verification journal share one actual
// closed fused program owner, charged before any routed PrefixPlan.
match context.gdn_fused_t1() {
Ok(owner) => result.native_gdn_fused = Some(Rc::new(RefCell::new(owner))),
Err(error) => {
let primary = driver_error(error);
let _ = result.close();
return Err(primary);
}
}
// Actual scratch, mapped/canonical KV ledger and exact64 banks are eager before routed PrefixPlan.
Ok(result)
self.native_gdn_fused = Some(Rc::new(RefCell::new(context.gdn_fused_t1().map_err(driver_error)?)));
Ok(())
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in super::super::super) fn native_qsa(
@@ -18,52 +18,9 @@ impl<'ctx> DenseWeightCache<'ctx> {
// never allocates the legacy capacity-sized PLE/GDN/QSA row banks.
let mut cache = startup_step("new_with_selected", Self::new_with_selected(binding, context, false))?;
cache.native_prompt_capacity = capacity;
let loaded = (|| -> Result<()> {
cache.native_batch_workspace = Some(RefCell::new(
startup_step("native_batch_workspace", context.native_batch_workspace()).map_err(driver_error)?,
));
cache.ple_queue =
Some(RefCell::new(startup_step("ple_closed_queue", context.ple_closed_queue()).map_err(driver_error)?));
cache.native_gdn_fused = Some(Rc::new(RefCell::new(
startup_step("gdn_fused_t1", context.gdn_fused_t1()).map_err(driver_error)?,
)));
cache.gdn_verification = Some(Rc::new(RefCell::new(startup_step(
"gdn verification workspace",
super::super::super::gdn::verification::Workspace::new(
cache.binding.clone(),
context,
cache.mirror_failed.clone(),
),
)?)));
cache.gdn_qk_workspace = Some(Rc::new(startup_step(
"gdn qk scratch",
QkScratch::new(cache.binding.clone(), context, cache.mirror_failed.clone()),
)?));
cache.router_scratch = Some(RefCell::new(startup_step(
"router scratch",
RouterScratch::new(cache.binding.clone(), context, cache.mirror_failed.clone()),
)?));
cache.gr_batch_workspace = Some(RefCell::new(
startup_step("gr_batch_inject_workspace", context.gr_batch_inject_workspace()).map_err(driver_error)?,
));
cache.gdn_four_borrow = true;
startup_step("validate", cache.validate(binding))
})();
if loaded.is_ok()
&& let Some(slabs) = cache.slabs.as_ref()
{
let stats = slabs.stats();
eprintln!(
"leleka-serve dense weights: {} buffers; {} slabs of {} MiB hold {} of them ({:.1} MiB), {} buffers above {} MiB keep their own allocation ({:.1} MiB driver-estimated)",
cache.buffers.len(),
stats.slabs,
SlabPolicy::DENSE.slab_bytes >> 20,
stats.carved,
stats.carved_bytes as f64 / 1048576.0,
stats.direct,
SlabPolicy::DENSE.direct_above >> 20,
stats.direct_bytes as f64 / 1048576.0,
);
let loaded = cache.load_prompt_owners(binding, context);
if loaded.is_ok() {
cache.report_dense_slabs();
}
match loaded {
Ok(()) => Ok(cache),
@@ -74,6 +31,66 @@ impl<'ctx> DenseWeightCache<'ctx> {
}
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn load_prompt_owners(&mut self, binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result<()> {
self.load_prompt_workspaces(context)?;
self.load_prompt_scratch(context)?;
startup_step("validate", self.validate(binding))
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn load_prompt_workspaces(&mut self, context: &'ctx Context<'ctx>) -> Result<()> {
self.native_batch_workspace = Some(RefCell::new(
startup_step("native_batch_workspace", context.native_batch_workspace()).map_err(driver_error)?,
));
self.ple_queue =
Some(RefCell::new(startup_step("ple_closed_queue", context.ple_closed_queue()).map_err(driver_error)?));
self.native_gdn_fused =
Some(Rc::new(RefCell::new(startup_step("gdn_fused_t1", context.gdn_fused_t1()).map_err(driver_error)?)));
Ok(())
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn load_prompt_scratch(&mut self, context: &'ctx Context<'ctx>) -> Result<()> {
self.gdn_verification = Some(Rc::new(RefCell::new(startup_step(
"gdn verification workspace",
super::super::super::gdn::verification::Workspace::new(
self.binding.clone(),
context,
self.mirror_failed.clone(),
),
)?)));
self.gdn_qk_workspace = Some(Rc::new(startup_step(
"gdn qk scratch",
QkScratch::new(self.binding.clone(), context, self.mirror_failed.clone()),
)?));
self.router_scratch = Some(RefCell::new(startup_step(
"router scratch",
RouterScratch::new(self.binding.clone(), context, self.mirror_failed.clone()),
)?));
self.gr_batch_workspace = Some(RefCell::new(
startup_step("gr_batch_inject_workspace", context.gr_batch_inject_workspace()).map_err(driver_error)?,
));
self.gdn_four_borrow = true;
Ok(())
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn report_dense_slabs(&self) {
let Some(slabs) = self.slabs.as_ref() else {
return;
};
let stats = slabs.stats();
eprintln!(
"leleka-serve dense weights: {} buffers; {} slabs of {} MiB hold {} of them ({:.1} MiB), {} buffers \
above {} MiB keep their own allocation ({:.1} MiB driver-estimated)",
self.buffers.len(),
stats.slabs,
SlabPolicy::DENSE.slab_bytes >> 20,
stats.carved,
stats.carved_bytes as f64 / 1048576.0,
stats.direct,
SlabPolicy::DENSE.direct_above >> 20,
stats.direct_bytes as f64 / 1048576.0,
);
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in crate::qwen_forward) fn native_prompt_capacity(
&self,
binding: &ModelBinding,
@@ -13,13 +13,28 @@ impl<'ctx> DenseWeightCache<'ctx> {
if n != 48 {
return Err(Error::InvalidDimension);
}
let mut result = Self {
let slabs = SlabAllocator::new(context, dense_slab_policy()).map_err(driver_error)?;
let mut result = Self::unloaded(binding, context, slabs);
result.modules =
Some(super::super::super::chunk_modules::ChunkModules::new(context, result.mirror_failed.clone()));
match result.load_eager(binding, selected, n) {
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)
}
}
}
fn unloaded(binding: &ModelBinding, context: &'ctx Context<'ctx>, slabs: SlabAllocator<'ctx>) -> Self {
Self {
modules: None,
binding: binding.identity(),
owner: Rc::new(()),
context,
buffers: Vec::new(),
slabs: Some(SlabAllocator::new(context, dense_slab_policy()).map_err(driver_error)?),
slabs: Some(slabs),
gdn: Vec::new(),
gdn_mirrors: Vec::new(),
mirror_failed: Rc::new(Cell::new(false)),
@@ -60,138 +75,106 @@ impl<'ctx> DenseWeightCache<'ctx> {
router: Vec::new(),
ple: None,
counters: Cell::new(DenseCacheCounters::default()),
};
result.modules =
Some(super::super::super::chunk_modules::ChunkModules::new(context, result.mirror_failed.clone()));
let loaded = (|| -> Result<()> {
// Optional fixed byte workspace is eagerly charged before lazy MoE growth.
if selected {
result.qsa_selected = Some(RefCell::new(QsaSelectedCache::new(
result.binding.clone(),
context,
result.mirror_failed.clone(),
)?));
}
result.qsa_keys = Some(RefCell::new(QsaIndexKeyCache::new(
result.binding.clone(),
context,
result.mirror_failed.clone(),
)?));
result.qsa_input = Some(RefCell::new(QsaInputScratch::new(
result.binding.clone(),
context,
result.mirror_failed.clone(),
)?));
// Fixed activation scratch is charged before any lazy MoE growth.
result.gdn_input = Some(RefCell::new(GdnInputScratch::new(
result.binding.clone(),
context,
result.mirror_failed.clone(),
)?));
result.gr_scratch = Some(RefCell::new(GrScratch::new(binding, context, result.mirror_failed.clone())?));
result.gdn.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?;
result.gdn_mirrors.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
};
let mirror = gdn
.as_ref()
.map(|_| GdnStateMirror::new(result.binding.clone(), id, context, result.mirror_failed.clone()))
.transpose()?
.map(RefCell::new);
result.gdn.push(gdn);
result.gdn_mirrors.push(mirror);
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)?;
let mirror_count = result.gdn_mirrors.iter().filter(|entry| entry.is_some()).count();
if mirror_count.checked_mul(786432 * 4) != Some(ALL_MIRROR_BYTES) {
return Err(Error::InvalidDimension);
}
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)
}
}
}
fn load_eager(&mut self, binding: &ModelBinding, selected: bool, n: usize) -> Result<()> {
self.add_scratch_owners(binding, selected)?;
self.gdn.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?;
self.gdn_mirrors.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?;
self.qsa.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?;
self.gr.try_reserve_exact(n * 2 + 1).map_err(|_| Error::InputAllocation)?;
self.router.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?;
for layer in binding.ordered_layers() {
self.add_layer(binding, layer.index(), layer.kind())?;
}
self.add_gr(binding, GrRole::Final)?;
self.add_ple(binding)?;
let mirror_count = self.gdn_mirrors.iter().filter(|entry| entry.is_some()).count();
if mirror_count.checked_mul(786432 * 4) != Some(ALL_MIRROR_BYTES) {
return Err(Error::InvalidDimension);
}
self.validate(binding)?;
Ok(())
}
fn add_scratch_owners(&mut self, binding: &ModelBinding, selected: bool) -> Result<()> {
let context = self.context;
// Optional fixed byte workspace is eagerly charged before lazy MoE growth.
if selected {
self.qsa_selected =
Some(RefCell::new(QsaSelectedCache::new(self.binding.clone(), context, self.mirror_failed.clone())?));
}
self.qsa_keys =
Some(RefCell::new(QsaIndexKeyCache::new(self.binding.clone(), context, self.mirror_failed.clone())?));
self.qsa_input =
Some(RefCell::new(QsaInputScratch::new(self.binding.clone(), context, self.mirror_failed.clone())?));
// Fixed activation scratch is charged before any lazy MoE growth.
self.gdn_input =
Some(RefCell::new(GdnInputScratch::new(self.binding.clone(), context, self.mirror_failed.clone())?));
self.gr_scratch = Some(RefCell::new(GrScratch::new(binding, context, self.mirror_failed.clone())?));
Ok(())
}
fn add_layer(&mut self, binding: &ModelBinding, id: u32, kind: BoundLayerKind) -> Result<()> {
let gdn = if kind == BoundLayerKind::Gdn { Some(self.add_gdn_layer(binding, id)?) } else { None };
let qsa = if kind == BoundLayerKind::Qsa { Some(self.add_qsa_layer(binding, id)?) } else { None };
let mirror = gdn
.as_ref()
.map(|_| GdnStateMirror::new(self.binding.clone(), id, self.context, self.mirror_failed.clone()))
.transpose()?
.map(RefCell::new);
self.gdn.push(gdn);
self.gdn_mirrors.push(mirror);
self.qsa.push(qsa);
for role in [GrRole::Attention(id), GrRole::Ffn(id)] {
self.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 = self.add(block.bytes(), block.bytes().len())?;
self.router.push(index);
Ok(())
}
fn add_gdn_layer(&mut self, binding: &ModelBinding, id: u32) -> Result<GdnResident> {
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] = (self.add(block.bytes(), weights.source_bytes(role).map_err(binding_error)?)?, block.kind());
}
let aux = [
self.add_f32(weights.conv())?,
self.add_f32(weights.dt())?,
self.add_f32(weights.a())?,
self.add_f32(weights.norm())?,
];
Ok(GdnResident { owner: self.owner.clone(), weights, matrices, aux })
}
fn add_qsa_layer(&mut self, binding: &ModelBinding, id: u32) -> Result<QsaResident> {
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] = (self.add(block.bytes(), weights.source_bytes(role).map_err(binding_error)?)?, block.kind());
}
let norms = [
self.add_f32(weights.q_norm())?,
self.add_f32(weights.k_norm())?,
self.add_f32(weights.index_q_norm())?,
self.add_f32(weights.index_k_norm())?,
];
Ok(QsaResident { owner: self.owner.clone(), weights, matrices, norms })
}
}
@@ -68,6 +68,17 @@ impl<'ctx> DenseWeightCache<'ctx> {
self.gr.push(GrResident { owner: self.owner.clone(), weights, buffers });
Ok(())
}
fn ple_conv_bytes(weights: &PleWeights) -> Result<Vec<u8>> {
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());
}
Ok(conv)
}
pub(in super::super) fn add_ple(&mut self, binding: &ModelBinding) -> Result<()> {
let weights = Rc::new(binding.ple_weights().map_err(binding_error)?);
// Key retains one complete immutable matrix with the same total byte
@@ -85,14 +96,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
}
let value = self.add(value_matrix.bytes(), value_matrix.bytes().len())?;
drop(value_matrix);
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 conv = Self::ple_conv_bytes(&weights)?;
let aux = [
self.add_f32(weights.norm_key())?,
self.add_f32(weights.norm_query())?,
@@ -138,6 +138,41 @@ impl<'ctx> DenseWeightCache<'ctx> {
}
gamma.try_into().map_err(|_| Error::InvalidDimension)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn verify_gdn_projections<'a>(
&'a self,
binding: &ModelBinding,
layer: u32,
) -> Result<OriginalVerifyGdnProjections<'a, 'ctx>> {
let resident = self.gdn(binding, layer)?;
let matrix = |role| -> Result<OriginalVerifyNativeMatrix<'a, 'ctx>> {
let (buffer, kind) = self.gdn_matrix(resident, role)?;
Ok(OriginalVerifyNativeMatrix { kind: gdn_native_type(kind)?, buffer })
};
Ok(OriginalVerifyGdnProjections {
qkv: matrix(GdnMatrixRole::Qkv)?,
gate: matrix(GdnMatrixRole::Z)?,
out: matrix(GdnMatrixRole::Out)?,
})
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn verify_qsa_projections<'a>(
&'a self,
binding: &ModelBinding,
layer: u32,
) -> Result<OriginalVerifyQsaProjections<'a, 'ctx>> {
let resident = self.qsa(binding, layer)?;
let matrix = |role| -> Result<OriginalVerifyNativeMatrix<'a, 'ctx>> {
let (buffer, kind) = self.qsa_matrix(resident, role)?;
Ok(OriginalVerifyNativeMatrix { kind: qsa_native_type(kind)?, buffer })
};
Ok(OriginalVerifyQsaProjections {
k: matrix(QsaMatrixRole::K)?,
v: matrix(QsaMatrixRole::V)?,
q: matrix(QsaMatrixRole::Q)?,
out: matrix(QsaMatrixRole::Out)?,
})
}
/// The native-format (GGUF block) MMVQ projection matrices of the 36 GDN and 12 QSA
/// layers for the literal Verifier window: the cache's own allocations, borrowed.
/// A matrix the cache holds as BF16 has no native MMVQ owner and is refused.
@@ -148,57 +183,14 @@ impl<'ctx> DenseWeightCache<'ctx> {
geometry: &OriginalVerifyGeometry,
) -> Result<OriginalVerifyProjBinding<'a, 'ctx>> {
self.check(binding)?;
let gdn_type = |kind: GdnMatrixKind| -> Result<u32> {
match kind {
GdnMatrixKind::Q8_0 => Ok(8),
GdnMatrixKind::Q4K => Ok(12),
GdnMatrixKind::Q5K => Ok(13),
GdnMatrixKind::Q6K => Ok(14),
GdnMatrixKind::Iq4Nl => Ok(20),
GdnMatrixKind::Iq4Xs => Ok(23),
GdnMatrixKind::Bf16 => Err(Error::Unsupported(super::super::super::contract::Stage::Gdn)),
}
};
let qsa_type = |kind: QsaMatrixKind| -> Result<u32> {
match kind {
QsaMatrixKind::Q4K => Ok(12),
QsaMatrixKind::Q5K => Ok(13),
QsaMatrixKind::Q6K => Ok(14),
QsaMatrixKind::Iq4Xs => Ok(23),
QsaMatrixKind::Bf16 => Err(Error::Unsupported(super::super::super::contract::Stage::QsaAttention)),
}
};
let mut gdn = Vec::new();
let mut qsa = Vec::new();
gdn.try_reserve_exact(36).map_err(|_| Error::InputAllocation)?;
qsa.try_reserve_exact(12).map_err(|_| Error::InputAllocation)?;
for layer in binding.ordered_layers() {
match layer.kind() {
BoundLayerKind::Gdn => {
let resident = self.gdn(binding, layer.index())?;
let mut matrix = |role| -> Result<OriginalVerifyNativeMatrix<'_, 'ctx>> {
let (buffer, kind) = self.gdn_matrix(resident, role)?;
Ok(OriginalVerifyNativeMatrix { kind: gdn_type(kind)?, buffer })
};
gdn.push(OriginalVerifyGdnProjections {
qkv: matrix(GdnMatrixRole::Qkv)?,
gate: matrix(GdnMatrixRole::Z)?,
out: matrix(GdnMatrixRole::Out)?,
});
}
BoundLayerKind::Qsa => {
let resident = self.qsa(binding, layer.index())?;
let mut matrix = |role| -> Result<OriginalVerifyNativeMatrix<'_, 'ctx>> {
let (buffer, kind) = self.qsa_matrix(resident, role)?;
Ok(OriginalVerifyNativeMatrix { kind: qsa_type(kind)?, buffer })
};
qsa.push(OriginalVerifyQsaProjections {
k: matrix(QsaMatrixRole::K)?,
v: matrix(QsaMatrixRole::V)?,
q: matrix(QsaMatrixRole::Q)?,
out: matrix(QsaMatrixRole::Out)?,
});
}
BoundLayerKind::Gdn => gdn.push(self.verify_gdn_projections(binding, layer.index())?),
BoundLayerKind::Qsa => qsa.push(self.verify_qsa_projections(binding, layer.index())?),
}
}
OriginalVerifyProjBinding::new(self.context, geometry, gdn, qsa).map_err(driver_error)
@@ -234,3 +226,27 @@ impl<'ctx> DenseWeightCache<'ctx> {
])
}
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn gdn_native_type(kind: GdnMatrixKind) -> Result<u32> {
match kind {
GdnMatrixKind::Q8_0 => Ok(8),
GdnMatrixKind::Q4K => Ok(12),
GdnMatrixKind::Q5K => Ok(13),
GdnMatrixKind::Q6K => Ok(14),
GdnMatrixKind::Iq4Nl => Ok(20),
GdnMatrixKind::Iq4Xs => Ok(23),
GdnMatrixKind::Bf16 => Err(Error::Unsupported(super::super::super::contract::Stage::Gdn)),
}
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn qsa_native_type(kind: QsaMatrixKind) -> Result<u32> {
match kind {
QsaMatrixKind::Q4K => Ok(12),
QsaMatrixKind::Q5K => Ok(13),
QsaMatrixKind::Q6K => Ok(14),
QsaMatrixKind::Iq4Xs => Ok(23),
QsaMatrixKind::Bf16 => Err(Error::Unsupported(super::super::super::contract::Stage::QsaAttention)),
}
}
@@ -26,136 +26,71 @@ impl<'ctx> DenseWeightCache<'ctx> {
self.retained_context(binding, context)?;
self.modules.as_ref().ok_or(Error::IdentityMismatch)
}
pub(crate) fn close(self) -> Result<()> {
pub(crate) fn close(mut self) -> Result<()> {
let mut error = self.mirror_failed.get().then_some(Error::CudaExecution);
for guard in self.gdn_guards.take() {
if let Err(e) = guard.close() {
error.get_or_insert(driver_error(e));
}
}
for buffer in self.gdn_scratch.take() {
if let Err(e) = buffer.release() {
error.get_or_insert(driver_error(e));
}
}
if let Some(modules) = self.modules
&& let Err(e) = modules.close()
{
error.get_or_insert(e);
}
if let Some(selected) = self.qsa_selected
&& let Err(e) = selected.into_inner().close()
{
error.get_or_insert(e);
}
if let Some(keys) = self.qsa_keys
&& let Err(e) = keys.into_inner().close()
{
error.get_or_insert(e);
}
if let Some(slot) = self.gdn_verification {
let result =
Rc::try_unwrap(slot).map_err(|_| Error::IdentityMismatch).and_then(|slot| slot.into_inner().close());
if let Err(failure) = result {
error.get_or_insert(failure);
}
}
self.close_scratch_and_modules(&mut error);
self.close_attention_scratch(&mut error);
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(owner) = self.native_gdn_fused {
let result = Rc::try_unwrap(owner)
.map_err(|_| Error::IdentityMismatch)
.and_then(|owner| owner.into_inner().close().map_err(driver_error));
if let Err(failure) = result {
error.get_or_insert(failure);
}
}
if let Some(slot) = self.qsa_attention_workspace
&& let Err(e) = slot.into_inner().close()
{
error.get_or_insert(e);
}
if let Some(slot) = self.qsa_input
&& let Err(e) = slot.into_inner().close()
{
error.get_or_insert(e);
}
if let Some(slot) = self.gdn_qk_workspace
&& let Err(e) = QkScratch::close(slot)
{
error.get_or_insert(e);
}
if let Some(slot) = self.gdn_input
&& let Err(e) = slot.into_inner().close()
{
error.get_or_insert(e);
}
if let Some(slot) = self.gr_scratch
&& let Err(e) = slot.into_inner().close()
{
error.get_or_insert(e);
}
if let Some(slot) = self.router_scratch
&& let Err(e) = slot.into_inner().close()
{
error.get_or_insert(e);
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(slot) = self.gr_batch_workspace
&& let Err(e) = slot.into_inner().close()
{
error.get_or_insert(driver_error(e));
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(queue) = self.ple_queue
&& let Err(e) = queue.into_inner().close()
{
error.get_or_insert(driver_error(e));
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(queue) = self.ple_batch_queue
&& let Err(e) = queue.into_inner().close()
{
error.get_or_insert(driver_error(e));
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(resources) = self.gdn_batch_resources
&& let Err(e) = resources.into_inner().close()
{
error.get_or_insert(e);
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(owner) = self.native_qsa
&& let Err(e) = owner.into_inner().close()
{
error.get_or_insert(e);
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(owner) = self.qsa_native_workspace
&& let Err(e) = owner.into_inner().close()
{
error.get_or_insert(driver_error(e));
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(workspace) = self.native_batch_workspace
&& let Err(e) = workspace.into_inner().close()
{
error.get_or_insert(driver_error(e));
}
for mirror in self.gdn_mirrors.into_iter().flatten() {
if let Err(e) = mirror.into_inner().close() {
error.get_or_insert(e);
}
}
for b in self.buffers {
if let Err(e) = b.release() {
error.get_or_insert(driver_error(e));
}
}
if let Some(slabs) = self.slabs
&& let Err(e) = slabs.release()
{
error.get_or_insert(driver_error(e));
}
self.close_batch_workspaces(&mut error);
self.close_buffers_and_slabs(&mut error);
error.map_or(Ok(()), Err)
}
fn close_scratch_and_modules(&mut self, error: &mut Option<Error>) {
for guard in self.gdn_guards.take() {
close_into(error, Some(guard), |guard| guard.close().map_err(driver_error));
}
for buffer in self.gdn_scratch.take() {
close_into(error, Some(buffer), |buffer| buffer.release().map_err(driver_error));
}
close_into(error, self.modules.take(), |modules| modules.close());
close_into(error, self.qsa_selected.take(), |selected| selected.into_inner().close());
close_into(error, self.qsa_keys.take(), |keys| keys.into_inner().close());
close_into(error, self.gdn_verification.take(), |slot| {
Rc::try_unwrap(slot).map_err(|_| Error::IdentityMismatch).and_then(|slot| slot.into_inner().close())
});
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
close_into(error, self.native_gdn_fused.take(), |owner| {
Rc::try_unwrap(owner)
.map_err(|_| Error::IdentityMismatch)
.and_then(|owner| owner.into_inner().close().map_err(driver_error))
});
}
fn close_attention_scratch(&mut self, error: &mut Option<Error>) {
close_into(error, self.qsa_attention_workspace.take(), |slot| slot.into_inner().close());
close_into(error, self.qsa_input.take(), |slot| slot.into_inner().close());
close_into(error, self.gdn_qk_workspace.take(), QkScratch::close);
close_into(error, self.gdn_input.take(), |slot| slot.into_inner().close());
close_into(error, self.gr_scratch.take(), |slot| slot.into_inner().close());
close_into(error, self.router_scratch.take(), |slot| slot.into_inner().close());
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn close_batch_workspaces(&mut self, error: &mut Option<Error>) {
close_into(error, self.gr_batch_workspace.take(), |slot| slot.into_inner().close().map_err(driver_error));
close_into(error, self.ple_queue.take(), |queue| queue.into_inner().close().map_err(driver_error));
close_into(error, self.ple_batch_queue.take(), |queue| queue.into_inner().close().map_err(driver_error));
close_into(error, self.gdn_batch_resources.take(), |resources| resources.into_inner().close());
close_into(error, self.native_qsa.take(), |owner| owner.into_inner().close());
close_into(error, self.qsa_native_workspace.take(), |owner| owner.into_inner().close().map_err(driver_error));
close_into(error, self.native_batch_workspace.take(), |workspace| {
workspace.into_inner().close().map_err(driver_error)
});
}
fn close_buffers_and_slabs(&mut self, error: &mut Option<Error>) {
for mirror in std::mem::take(&mut self.gdn_mirrors).into_iter().flatten() {
close_into(error, Some(mirror), |mirror| mirror.into_inner().close());
}
for b in std::mem::take(&mut self.buffers) {
close_into(error, Some(b), |b| b.release().map_err(driver_error));
}
close_into(error, self.slabs.take(), |slabs| slabs.release().map_err(driver_error));
}
}
/// Runs one release and keeps the first failure of the whole close.
fn close_into<T>(error: &mut Option<Error>, item: Option<T>, close: impl FnOnce(T) -> Result<()>) {
if let Some(item) = item
&& let Err(e) = close(item)
{
error.get_or_insert(e);
}
}
@@ -1,5 +1,8 @@
//! Only the explicitly selected new full-model MMQ gate. Old observers unchanged.
use super::*;
use crate::qwen_forward::mtp::MtpChunkNumericSnapshot;
use crate::qwen_forward::mtp_decode::MtpDecoder;
use crate::qwen_forward::session::ResetReplaySnapshot;
impl QwenForward {
pub(crate) fn test_mmq_on_loaded<'driver>(
binding: &ModelBinding,
@@ -21,221 +24,368 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>(
moe: &mut MoeWeightCache<'driver>,
dense: &DenseWeightCache<'_>,
) {
use crate::qwen_forward::mtp_decode::MtpDecoder;
let vocab = Dimension::new(248320).expect("vocabulary refused");
let bounds = crate::qwen_forward::contract::position_dimension();
let ids: Vec<_> = [0, 1, 0, 1].into_iter().map(|n| TokenId::new(n, vocab).expect("fixed token refused")).collect();
let next = TokenId::new(0, vocab).expect("known next refused");
let follow = TokenId::new(1, vocab).expect("known successor refused");
let fresh = session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused");
let mut run = MmqRun::new(binding, session, output, kar, moe, dense);
let fresh = run.session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused");
assert!(fresh.has_prefix(0, [-1, -1]), "fresh target required");
let mut scalar_draft = MtpDecoder::new(binding).expect("baseline draft refused");
output.test_reset_replay_record(true).expect("head observer refused");
for index in 0..3 {
let source = QwenForward::prefill_for_mtp_cached(
binding,
ids[index],
Position::new(index as u64, bounds).unwrap(),
session,
output,
Some(&mut *kar),
moe,
dense,
)
.expect("scalar known-next target refused");
scalar_draft
.warm_prefill(binding, session, &source, ids[index + 1], moe)
.expect("scalar known-next warm refused");
}
let source = QwenForward::step_for_mtp_cached(
binding,
ids[3],
Position::new(3, bounds).unwrap(),
session,
output,
Some(&mut *kar),
Some(&mut *moe),
Some(dense),
)
.expect("scalar final target refused");
let baseline_logits = output.test_reset_replay_take_logits().expect("scalar head missing");
let baseline_greedy = source.predicted(session).expect("scalar source invalid");
let baseline_streams: Vec<_> = source
.streams(binding, ids[3], Position::new(3, bounds).unwrap(), session)
.expect("scalar residual invalid")
.iter()
.map(|v| v.to_bits())
.collect();
let baseline_state = session.test_reset_replay_snapshot(binding).expect("scalar state invalid");
let baseline_draft = scalar_draft.test_chunk_snapshot();
scalar_draft.warm_retained(binding, session, &source, next, moe).expect("scalar retained edge refused");
let continuation = QwenForward::step_for_mtp_cached(
binding,
next,
Position::new(4, bounds).unwrap(),
session,
output,
Some(&mut *kar),
Some(&mut *moe),
Some(dense),
)
.expect("scalar continuation refused");
scalar_draft.warm_retained(binding, session, &continuation, follow, moe).expect("scalar continuation warm refused");
let continued_greedy = continuation.predicted(session).expect("baseline continuation origin invalid");
let continued_logits = output.test_reset_replay_take_logits().expect("baseline continuation head missing");
let continued_state = session.test_reset_replay_snapshot(binding).expect("scalar continuation state invalid");
let continued_draft = scalar_draft.test_chunk_snapshot();
QwenForward::reset(session).expect("real owner reset refused");
run.warm_scalar_prefix(&mut scalar_draft);
let (source, baseline, baseline_streams) = run.scalar_final_step(&mut scalar_draft);
let continued = run.scalar_continuation(&mut scalar_draft, &source);
QwenForward::reset(run.session).expect("real owner reset refused");
let mut candidate_draft = MtpDecoder::new(binding).expect("candidate draft refused");
let fresh_draft = candidate_draft.test_chunk_snapshot();
let mut callbacks = 0;
let aborted = QwenForward::prefill_chunk_mmq_joint(
binding,
&ids,
None,
session,
&mut candidate_draft,
output,
Some(&mut *kar),
moe,
dense,
512 * 1024 * 1024,
|| {
run.late_row_cancel(&mut candidate_draft, &fresh, &fresh_draft);
run.mtp_row_cancel(&mut candidate_draft, &fresh, &fresh_draft);
let chunk = run.candidate_chunk(&mut candidate_draft);
let head_exact = run.compare_head(&baseline, &chunk);
let exact = run.compare_chunk(&baseline, &baseline_streams, &chunk, &candidate_draft, head_exact);
let continued_exact = run.candidate_continuation(&mut candidate_draft, &chunk, &continued, &exact);
let continued_draft_exact = candidate_draft.test_chunk_eq(&continued.draft);
run.output.test_reset_replay_record(false).expect("head observer did not drain");
report_gate_b(&exact, &continued_exact, &chunk, continued_draft_exact);
}
pub(super) fn pos(n: u64) -> Position {
Position::new(n, crate::qwen_forward::contract::position_dimension()).unwrap()
}
/// The loaded model, caches and fixed four-token chunk that every phase of the observation shares.
pub(super) struct MmqRun<'a, 'driver, 'o, 'p, 'k, 'd> {
pub(super) binding: &'a ModelBinding,
pub(super) session: &'a mut QwenSession<'driver>,
pub(super) output: &'a OutputStage<'o, 'p>,
pub(super) kar: &'a mut KarPleCache<'k>,
pub(super) moe: &'a mut MoeWeightCache<'driver>,
pub(super) dense: &'a DenseWeightCache<'d>,
pub(super) ids: Vec<TokenId>,
pub(super) next: TokenId,
pub(super) follow: TokenId,
}
/// What one scalar target step leaves behind: head words, greedy token, committed state and draft snapshot.
pub(super) struct Observation {
pub(super) logits: Box<[u32]>,
pub(super) greedy: TokenId,
pub(super) state: ResetReplaySnapshot,
pub(super) draft: MtpChunkNumericSnapshot,
}
/// The candidate chunk product with the resident-MMQ dispatch counters of its run.
pub(super) struct ChunkRun {
pub(super) product: TargetStepProduct,
pub(super) logits: Box<[u32]>,
pub(super) resident_layers: u64,
pub(super) resident_columns: u64,
pub(super) native_fallback_layers: u64,
}
/// Exactness flags of the candidate chunk against the scalar baseline.
pub(super) struct ChunkExact {
pub(super) head: bool,
pub(super) residual: bool,
pub(super) target: bool,
pub(super) draft: bool,
}
/// Exactness flags of the continuation step.
struct ContinuedExact {
head: bool,
target: bool,
}
impl<'a, 'driver, 'o, 'p, 'k, 'd> MmqRun<'a, 'driver, 'o, 'p, 'k, 'd> {
pub(super) fn new(
binding: &'a ModelBinding,
session: &'a mut QwenSession<'driver>,
output: &'a OutputStage<'o, 'p>,
kar: &'a mut KarPleCache<'k>,
moe: &'a mut MoeWeightCache<'driver>,
dense: &'a DenseWeightCache<'d>,
) -> Self {
let vocab = Dimension::new(248320).expect("vocabulary refused");
let ids: Vec<_> =
[0, 1, 0, 1].into_iter().map(|n| TokenId::new(n, vocab).expect("fixed token refused")).collect();
let next = TokenId::new(0, vocab).expect("known next refused");
let follow = TokenId::new(1, vocab).expect("known successor refused");
Self { binding, session, output, kar, moe, dense, ids, next, follow }
}
}
impl MmqRun<'_, '_, '_, '_, '_, '_> {
pub(super) fn warm_scalar_prefix(&mut self, scalar_draft: &mut MtpDecoder) {
self.output.test_reset_replay_record(true).expect("head observer refused");
for index in 0..3 {
let source = QwenForward::prefill_for_mtp_cached(
self.binding,
self.ids[index],
pos(index as u64),
self.session,
self.output,
Some(&mut *self.kar),
self.moe,
self.dense,
)
.expect("scalar known-next target refused");
scalar_draft
.warm_prefill(self.binding, self.session, &source, self.ids[index + 1], self.moe)
.expect("scalar known-next warm refused");
}
}
pub(super) fn mtp_step(&mut self, token: TokenId, position: u64) -> Result<TargetStepProduct> {
QwenForward::step_for_mtp_cached(
self.binding,
token,
pos(position),
self.session,
self.output,
Some(&mut *self.kar),
Some(&mut *self.moe),
Some(self.dense),
)
}
pub(super) fn scalar_final_step(
&mut self,
scalar_draft: &mut MtpDecoder,
) -> (TargetStepProduct, Observation, Vec<u32>) {
let source = self.mtp_step(self.ids[3], 3).expect("scalar final target refused");
let logits = self.output.test_reset_replay_take_logits().expect("scalar head missing");
let greedy = source.predicted(self.session).expect("scalar source invalid");
let streams: Vec<_> = source
.streams(self.binding, self.ids[3], pos(3), self.session)
.expect("scalar residual invalid")
.iter()
.map(|v| v.to_bits())
.collect();
let state = self.session.test_reset_replay_snapshot(self.binding).expect("scalar state invalid");
let draft = scalar_draft.test_chunk_snapshot();
(source, Observation { logits, greedy, state, draft }, streams)
}
pub(super) fn scalar_continuation(
&mut self,
scalar_draft: &mut MtpDecoder,
source: &TargetStepProduct,
) -> Observation {
scalar_draft
.warm_retained(self.binding, self.session, source, self.next, self.moe)
.expect("scalar retained edge refused");
let continuation = self.mtp_step(self.next, 4).expect("scalar continuation refused");
scalar_draft
.warm_retained(self.binding, self.session, &continuation, self.follow, self.moe)
.expect("scalar continuation warm refused");
let greedy = continuation.predicted(self.session).expect("baseline continuation origin invalid");
let logits = self.output.test_reset_replay_take_logits().expect("baseline continuation head missing");
let state = self.session.test_reset_replay_snapshot(self.binding).expect("scalar continuation state invalid");
let draft = scalar_draft.test_chunk_snapshot();
Observation { logits, greedy, state, draft }
}
fn joint_chunk(
&mut self,
candidate_draft: &mut MtpDecoder,
cancelled: impl FnMut() -> bool,
) -> Result<Option<TargetStepProduct>> {
QwenForward::prefill_chunk_mmq_joint(
self.binding,
&self.ids,
None,
self.session,
candidate_draft,
self.output,
Some(&mut *self.kar),
self.moe,
self.dense,
512 * 1024 * 1024,
cancelled,
)
}
pub(super) fn late_row_cancel(
&mut self,
candidate_draft: &mut MtpDecoder,
fresh: &ResetReplaySnapshot,
fresh_draft: &MtpChunkNumericSnapshot,
) {
let mut callbacks = 0;
let aborted = self.joint_chunk(candidate_draft, || {
callbacks += 1;
callbacks == 16
},
);
assert!(matches!(aborted, Err(Error::Unsupported(Stage::Executor))), "late-row cancellation not refused");
let after_abort = session.test_reset_replay_snapshot(binding).expect("abort snapshot refused");
assert!(fresh.numeric_eq(&after_abort), "cancel changed committed target");
assert!(candidate_draft.test_chunk_eq(&fresh_draft), "cancel changed committed draft");
// Real phase-local cancellation: the second MTP callback occurs after
// the first actual private draft warm. Group routing changes the number
// of earlier target callbacks, so no global callback ordinal is guessed.
let mut mtp_callbacks = 0;
let mtp_aborted: Result<()> = (|| {
});
assert!(matches!(aborted, Err(Error::Unsupported(Stage::Executor))), "late-row cancellation not refused");
let after_abort = self.session.test_reset_replay_snapshot(self.binding).expect("abort snapshot refused");
assert!(fresh.numeric_eq(&after_abort), "cancel changed committed target");
assert!(candidate_draft.test_chunk_eq(fresh_draft), "cancel changed committed draft");
}
/// Real phase-local cancellation: the second MTP callback occurs after
/// the first actual private draft warm. Group routing changes the number
/// of earlier target callbacks, so no global callback ordinal is guessed.
pub(super) fn mtp_row_cancel(
&mut self,
candidate_draft: &mut MtpDecoder,
fresh: &ResetReplaySnapshot,
fresh_draft: &MtpChunkNumericSnapshot,
) {
let mtp_aborted = self.staged_mtp_abort(candidate_draft);
assert!(
matches!(mtp_aborted, Err(Error::Unsupported(Stage::Executor))),
"actual MTP-row cancellation not refused"
);
self.check_mtp_cancel_unchanged(candidate_draft, fresh, fresh_draft);
}
fn staged_mtp_abort(&mut self, candidate_draft: &mut MtpDecoder) -> Result<()> {
let mut mtp_callbacks = 0;
let mut pending = QwenForward::prepare_prefill_chunk_with_policy(
binding,
&ids,
self.binding,
&self.ids,
None,
session,
output,
Some(&mut *kar),
moe,
dense,
self.session,
self.output,
Some(&mut *self.kar),
self.moe,
self.dense,
512 * 1024 * 1024,
|| false,
ChunkMoePolicy::ExperimentalResidentMmq,
)?;
let _ready = candidate_draft.stage_prefill_chunk(binding, &mut pending, moe, &mut || {
let _ready = candidate_draft.stage_prefill_chunk(self.binding, &mut pending, self.moe, &mut || {
mtp_callbacks += 1;
mtp_callbacks == 2
})?;
Err(Error::IdentityMismatch)
})();
assert!(matches!(mtp_aborted, Err(Error::Unsupported(Stage::Executor))), "actual MTP-row cancellation not refused");
let discarded = output.test_reset_replay_take_logits().expect("computed canceled head observation missing");
assert_eq!(discarded.len(), 248320, "canceled full head extent changed");
drop(discarded);
assert!(
fresh.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("MTP abort target invalid")),
"MTP cancel changed committed target"
);
assert!(candidate_draft.test_chunk_eq(&fresh_draft), "MTP cancel changed committed draft");
let before_dispatch = moe.test_mmq_dispatch_witness();
let actual = QwenForward::prefill_chunk_mmq_joint(
binding,
&ids,
None,
session,
&mut candidate_draft,
output,
Some(&mut *kar),
moe,
dense,
512 * 1024 * 1024,
|| false,
)
.expect("candidate chunk refused")
.expect("genuine final product missing");
let after_dispatch = moe.test_mmq_dispatch_witness();
let resident_layers = after_dispatch.0 - before_dispatch.0;
let resident_columns = after_dispatch.1 - before_dispatch.1;
let native_fallback_layers = after_dispatch.2 - before_dispatch.2;
assert!(
resident_layers > 0 && resident_columns > 0,
"candidate completed without any actual resident MMQ producer"
);
assert_eq!(resident_layers + native_fallback_layers, 48, "candidate layer producer coverage incomplete");
let actual_logits = output.test_reset_replay_take_logits().expect("chunk head missing");
let mismatch_words = baseline_logits.iter().zip(actual_logits.iter()).filter(|(a, b)| a != b).count();
let max_abs = baseline_logits
.iter()
.zip(actual_logits.iter())
.map(|(a, b)| (f64::from(f32::from_bits(*a)) - f64::from(f32::from_bits(*b))).abs())
.fold(0.0f64, f64::max);
let actual_greedy = actual.predicted(session).expect("MMQ current origin invalid");
}
fn check_mtp_cancel_unchanged(
&mut self,
candidate_draft: &MtpDecoder,
fresh: &ResetReplaySnapshot,
fresh_draft: &MtpChunkNumericSnapshot,
) {
let discarded =
self.output.test_reset_replay_take_logits().expect("computed canceled head observation missing");
assert_eq!(discarded.len(), 248320, "canceled full head extent changed");
drop(discarded);
assert!(
fresh.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding).expect("MTP abort target invalid")),
"MTP cancel changed committed target"
);
assert!(candidate_draft.test_chunk_eq(fresh_draft), "MTP cancel changed committed draft");
}
pub(super) fn candidate_chunk(&mut self, candidate_draft: &mut MtpDecoder) -> ChunkRun {
let before_dispatch = self.moe.test_mmq_dispatch_witness();
let product = self
.joint_chunk(candidate_draft, || false)
.expect("candidate chunk refused")
.expect("genuine final product missing");
let after_dispatch = self.moe.test_mmq_dispatch_witness();
let resident_layers = after_dispatch.0 - before_dispatch.0;
let resident_columns = after_dispatch.1 - before_dispatch.1;
let native_fallback_layers = after_dispatch.2 - before_dispatch.2;
assert!(
resident_layers > 0 && resident_columns > 0,
"candidate completed without any actual resident MMQ producer"
);
assert_eq!(resident_layers + native_fallback_layers, 48, "candidate layer producer coverage incomplete");
let logits = self.output.test_reset_replay_take_logits().expect("chunk head missing");
ChunkRun { product, logits, resident_layers, resident_columns, native_fallback_layers }
}
/// Compares the full head words and reports the first observation line; returns the exact-head flag.
fn compare_head(&mut self, baseline: &Observation, chunk: &ChunkRun) -> bool {
let mismatch_words = baseline.logits.iter().zip(chunk.logits.iter()).filter(|(a, b)| a != b).count();
let max_abs = baseline
.logits
.iter()
.zip(chunk.logits.iter())
.map(|(a, b)| (f64::from(f32::from_bits(*a)) - f64::from(f32::from_bits(*b))).abs())
.fold(0.0f64, f64::max);
let actual_greedy = chunk.product.predicted(self.session).expect("MMQ current origin invalid");
eprintln!(
"resident MMQ model observation rows=4 fullhead_words=248320 mismatches={} max_abs={} greedy_equal={} \
baseline_greedy={} candidate_greedy={}; tensor equality reported; GateC remains unqualified",
mismatch_words,
max_abs,
baseline.greedy == actual_greedy,
baseline.greedy.get(),
actual_greedy.get()
);
baseline.logits.as_ref() == chunk.logits.as_ref()
}
fn compare_chunk(
&mut self,
baseline: &Observation,
baseline_streams: &[u32],
chunk: &ChunkRun,
candidate_draft: &MtpDecoder,
head: bool,
) -> ChunkExact {
let predicted = chunk.product.predicted(self.session).expect("chunk current origin invalid");
assert_eq!(baseline.greedy, predicted, "greedy mismatch");
let actual_streams =
chunk.product.streams(self.binding, self.ids[3], pos(3), self.session).expect("chunk residual invalid");
let residual = baseline_streams.iter().zip(actual_streams.iter()).all(|(a, b)| *a == b.to_bits());
let target = baseline
.state
.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding).expect("chunk state invalid"));
let draft = candidate_draft.test_chunk_eq(&baseline.draft);
ChunkExact { head, residual, target, draft }
}
/// Resume fence, retained edge, one continuation step and its warm; returns the greedy token and head words.
pub(super) fn candidate_continuation_step(
&mut self,
candidate_draft: &mut MtpDecoder,
chunk: &ChunkRun,
) -> (TokenId, Box<[u32]>) {
candidate_draft
.validate_resume(self.binding, self.session, &chunk.product, &[0, 1, 0, 1])
.expect("chunk resume fence refused");
candidate_draft
.warm_retained(self.binding, self.session, &chunk.product, self.next, self.moe)
.expect("chunk retained edge refused");
let continuation = self.mtp_step(self.next, 4).expect("chunk continuation refused");
candidate_draft
.warm_retained(self.binding, self.session, &continuation, self.follow, self.moe)
.expect("chunk continuation warm refused");
let actual_greedy = continuation.predicted(self.session).expect("candidate continuation origin invalid");
let actual_logits = self.output.test_reset_replay_take_logits().expect("candidate continuation head missing");
(actual_greedy, actual_logits)
}
fn candidate_continuation(
&mut self,
candidate_draft: &mut MtpDecoder,
chunk: &ChunkRun,
continued: &Observation,
exact: &ChunkExact,
) -> ContinuedExact {
let (actual_greedy, actual_logits) = self.candidate_continuation_step(candidate_draft, chunk);
let head = continued.logits.as_ref() == actual_logits.as_ref();
let target = continued
.state
.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding).expect("chunk continuation invalid"));
report_continuation(continued.greedy == actual_greedy, exact, head, target);
assert_eq!(continued.greedy, actual_greedy, "MMQ continuation greedy mismatch");
ContinuedExact { head, target }
}
}
fn report_continuation(greedy_equal: bool, exact: &ChunkExact, head: bool, target: bool) {
eprintln!(
"resident MMQ model observation rows=4 fullhead_words=248320 mismatches={} max_abs={} greedy_equal={} baseline_greedy={} candidate_greedy={}; tensor equality reported; GateC remains unqualified",
mismatch_words,
max_abs,
baseline_greedy == actual_greedy,
baseline_greedy.get(),
actual_greedy.get()
"resident MMQ model observation continuation_greedy_equal={} head_exact={} residual_exact={} target_exact={} draft_exact={} continued_head_exact={} continued_target_exact={}",
greedy_equal, exact.head, exact.residual, exact.target, exact.draft, head, target
);
let head_exact = baseline_logits.as_ref() == actual_logits.as_ref();
assert_eq!(baseline_greedy, actual.predicted(session).expect("chunk current origin invalid"), "greedy mismatch");
let actual_streams =
actual.streams(binding, ids[3], Position::new(3, bounds).unwrap(), session).expect("chunk residual invalid");
let residual_exact = baseline_streams.iter().zip(actual_streams.iter()).all(|(a, b)| *a == b.to_bits());
let target_exact =
baseline_state.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("chunk state invalid"));
let draft_exact = candidate_draft.test_chunk_eq(&baseline_draft);
candidate_draft.validate_resume(binding, session, &actual, &[0, 1, 0, 1]).expect("chunk resume fence refused");
candidate_draft.warm_retained(binding, session, &actual, next, moe).expect("chunk retained edge refused");
let continuation = QwenForward::step_for_mtp_cached(
binding,
next,
Position::new(4, bounds).unwrap(),
session,
output,
Some(&mut *kar),
Some(&mut *moe),
Some(dense),
)
.expect("chunk continuation refused");
candidate_draft
.warm_retained(binding, session, &continuation, follow, moe)
.expect("chunk continuation warm refused");
let actual_continued_greedy = continuation.predicted(session).expect("candidate continuation origin invalid");
let actual_continued_logits = output.test_reset_replay_take_logits().expect("candidate continuation head missing");
let continued_head_exact = continued_logits.as_ref() == actual_continued_logits.as_ref();
let continued_target_exact =
continued_state.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("chunk continuation invalid"));
}
fn report_gate_b(exact: &ChunkExact, continued: &ContinuedExact, chunk: &ChunkRun, continued_draft_exact: bool) {
eprintln!(
"resident MMQ model observation continuation_greedy_equal={} head_exact={} residual_exact={} target_exact={} draft_exact={} continued_head_exact={} continued_target_exact={}",
continued_greedy == actual_continued_greedy,
head_exact,
residual_exact,
target_exact,
draft_exact,
continued_head_exact,
continued_target_exact
);
assert_eq!(continued_greedy, actual_continued_greedy, "MMQ continuation greedy mismatch");
let continued_draft_exact = candidate_draft.test_chunk_eq(&continued_draft);
output.test_reset_replay_record(false).expect("head observer did not drain");
eprintln!(
"resident MMQ bounded greedy GateB PASS rows=4 layers=48 actual_final_outputs=2 logit_words=248320 final_head_exact={} residual_exact={} target_exact={} draft_exact={} continued_head_exact={} continued_target_exact={} continued_draft_exact={} early_cancelled_prefix_unchanged=true canceled_actual_mtp_warm=true actual_q6_attention_columns=true actual_ffn_gr_batch=true actual_resident_mmq=true resident_layers={} resident_columns={} native_fallback_layers={} experimental=true GateC=false longcontext=false speed_claim=false",
head_exact,
residual_exact,
target_exact,
draft_exact,
continued_head_exact,
continued_target_exact,
"resident MMQ bounded greedy GateB PASS rows=4 layers=48 actual_final_outputs=2 logit_words=248320 \
final_head_exact={} residual_exact={} target_exact={} draft_exact={} continued_head_exact={} \
continued_target_exact={} continued_draft_exact={} early_cancelled_prefix_unchanged=true \
canceled_actual_mtp_warm=true actual_q6_attention_columns=true actual_ffn_gr_batch=true \
actual_resident_mmq=true resident_layers={} resident_columns={} native_fallback_layers={} \
experimental=true GateC=false longcontext=false speed_claim=false",
exact.head,
exact.residual,
exact.target,
exact.draft,
continued.head,
continued.target,
continued_draft_exact,
resident_layers,
resident_columns,
native_fallback_layers
chunk.resident_layers,
chunk.resident_columns,
chunk.native_fallback_layers
);
}
@@ -4,7 +4,7 @@
use super::*;
use crate::qwen_forward::{
mtp::{self, MtpChunkStage, MtpSession},
session::chunk::{VerifiedDraftPublication, VerifiedTargetPrefix},
session::chunk::{ChunkRowResidual, VerifiedDraftPublication, VerifiedTargetPrefix},
};
pub(in crate::qwen_forward) struct PreparedMtpTargetWindow<'session, 'driver> {
@@ -63,21 +63,50 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
if self.txn.device_gdn_lease()?.is_some() {
let dense = dense.ok_or(Error::IdentityMismatch)?;
self.txn.seal_device_gdn_prefix(binding, dense, &self.prefix, &mut cancelled)?;
}
self.seal_leased_gdn(binding, dense, &mut cancelled)?;
let start = self.txn.start_position();
let count = self.prefix.count();
let rows = self.copy_accepted_rows(count)?;
// The existing stage validates actual draft KV/window/epoch/owner and
// requires genuine draft.next_position == actual target chunk start.
let mut stage = draft.stage_chunk(binding, &self.txn)?;
self.warm_accepted_rows(binding, cache, &mut stage, &rows, &mut cancelled)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let ready = ReadyVerifiedDraft { stage, binding, start, count, warmed: rows.len() };
self.txn.publish_verified_joint(self.prefix, ready)?.into_target_product().ok_or(Error::IdentityMismatch)
}
fn seal_leased_gdn(
&mut self,
binding: &ModelBinding,
dense: Option<&DenseWeightCache<'_>>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
if self.txn.device_gdn_lease()?.is_some() {
let dense = dense.ok_or(Error::IdentityMismatch)?;
self.txn.seal_device_gdn_prefix(binding, dense, &self.prefix, cancelled)?;
}
Ok(())
}
fn copy_accepted_rows(&self, count: usize) -> Result<Vec<ChunkRowResidual>> {
let mut rows = Vec::new();
rows.try_reserve_exact(count - 1).map_err(|_| Error::InputAllocation)?;
rows.extend(self.txn.rows().iter().take(count - 1).cloned());
if rows.len().checked_add(1) != Some(count) {
return Err(Error::IdentityMismatch);
}
// The existing stage validates actual draft KV/window/epoch/owner and
// requires genuine draft.next_position == actual target chunk start.
let mut stage = draft.stage_chunk(binding, &self.txn)?;
Ok(rows)
}
fn warm_accepted_rows(
&mut self,
binding: &ModelBinding,
cache: &MoeWeightCache<'_>,
stage: &mut MtpChunkStage<'_>,
rows: &[ChunkRowResidual],
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
let start = self.txn.start_position();
for (index, row) in rows.iter().enumerate() {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
@@ -86,15 +115,19 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> {
if position.get() != start.checked_add(index as u64).ok_or(Error::Overflow)? || next.is_none() {
return Err(Error::IdentityMismatch);
}
mtp::warm_chunk_row(binding, &mut self.txn, row, &mut stage, cache)?;
mtp::warm_chunk_row(binding, &mut self.txn, row, stage, cache)?;
}
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let ready = ReadyVerifiedDraft { stage, binding, start, count, warmed: rows.len() };
self.txn.publish_verified_joint(self.prefix, ready)?.into_target_product().ok_or(Error::IdentityMismatch)
Ok(())
}
}
/// The borrowed inputs of the verification chunk that the session, caches and cancel hook do not carry.
struct VerificationChunk<'a, 'o, 'p, 'd> {
binding: &'a ModelBinding,
proposals: &'a [TokenId],
output: &'a OutputStage<'o, 'p>,
dense_cache: &'a DenseWeightCache<'d>,
host_remaining: usize,
}
// Descending bounded admission, never a numeric/identity/poison retry.
fn legal_target_rows(limit: usize, mut preflight: impl FnMut(usize) -> Result<()>) -> Result<usize> {
if !(1..=4).contains(&limit) {
@@ -124,6 +157,47 @@ impl QwenForward {
legal_target_rows(limit, |rows| QwenChunkTxn::preflight_mtp_verification(target, binding, rows, host_remaining))
}
fn admit_mtp_window(
seed: TokenId,
proposals: &[TokenId],
moe_cache: &MoeWeightCache<'_>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
if !(1..=4).contains(&proposals.len())
|| proposals.first().copied() != Some(seed)
|| !moe_cache.requires_iq3_mmq_admission()
{
return Err(Error::IdentityMismatch);
}
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
Ok(())
}
fn prepare_verification_chunk<'session, 'driver>(
inputs: VerificationChunk<'_, '_, '_, '_>,
session: &'session mut QwenSession<'driver>,
kar_cache: Option<&mut KarPleCache<'_>>,
moe_cache: &mut MoeWeightCache<'driver>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<QwenChunkTxn<'session, 'driver>> {
Self::prepare_prefill_chunk_with_policy_windowed(
inputs.binding,
inputs.proposals,
None,
session,
inputs.output,
kar_cache,
moe_cache,
inputs.dense_cache,
inputs.host_remaining,
cancelled,
ChunkMoePolicy::ExperimentalMtpVerification,
true,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
None,
)
}
/// Explicit source-only candidate. Preserves Native/scalar MTP/defaults.
/// Existing Q6/MoE/GR batching survives; GDN uses unchanged scalar pending
/// producers here so every possible accepted prefix has actual state.
@@ -142,33 +216,11 @@ impl QwenForward {
mut cancelled: impl FnMut() -> bool,
) -> Result<PreparedMtpTargetWindow<'session, 'driver>> {
let seed = QwenChunkTxn::validate_verification_source(binding, source, eos, session)?;
if !(1..=4).contains(&proposals.len())
|| proposals.first().copied() != Some(seed)
|| !moe_cache.requires_iq3_mmq_admission()
{
return Err(Error::IdentityMismatch);
}
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
Self::admit_mtp_window(seed, proposals, moe_cache, &mut cancelled)?;
// Refuse the complete journal charge before cache/provider growth.
QwenChunkTxn::preflight_mtp_verification(session, binding, proposals.len(), host_remaining)?;
let txn = Self::prepare_prefill_chunk_with_policy_windowed(
binding,
proposals,
None,
session,
output,
kar_cache,
moe_cache,
dense_cache,
host_remaining,
&mut cancelled,
ChunkMoePolicy::ExperimentalMtpVerification,
true,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
None,
)?;
let inputs = VerificationChunk { binding, proposals, output, dense_cache, host_remaining };
let txn = Self::prepare_verification_chunk(inputs, session, kar_cache, moe_cache, &mut cancelled)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
@@ -1,5 +1,7 @@
//! Separate native-certified activation model observer. Original failed observer unchanged.
use super::mmq_evaluation::{ChunkExact, ChunkRun, MmqRun, Observation, pos};
use super::*;
use crate::qwen_forward::mtp_decode::MtpDecoder;
#[derive(Debug)]
pub(crate) struct HeadObservation {
@@ -62,201 +64,90 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>(
moe: &mut MoeWeightCache<'driver>,
dense: &DenseWeightCache<'_>,
) -> NativeMmqReport {
use crate::qwen_forward::mtp_decode::MtpDecoder;
let vocab = Dimension::new(248320).expect("vocabulary refused");
let bounds = crate::qwen_forward::contract::position_dimension();
let ids: Vec<_> = [0, 1, 0, 1].into_iter().map(|n| TokenId::new(n, vocab).expect("fixed token refused")).collect();
let next = TokenId::new(0, vocab).expect("known next refused");
let follow = TokenId::new(1, vocab).expect("known successor refused");
let fresh = session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused");
let mut run = MmqRun::new(binding, session, output, kar, moe, dense);
let fresh = run.session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused");
assert!(fresh.has_prefix(0, [-1, -1]), "fresh target required");
let mut scalar_draft = MtpDecoder::new(binding).expect("baseline draft refused");
output.test_reset_replay_record(true).expect("head observer refused");
for index in 0..3 {
let source = QwenForward::prefill_for_mtp_cached(
binding,
ids[index],
Position::new(index as u64, bounds).unwrap(),
session,
output,
Some(&mut *kar),
moe,
dense,
)
.expect("scalar known-next target refused");
scalar_draft
.warm_prefill(binding, session, &source, ids[index + 1], moe)
.expect("scalar known-next warm refused");
}
let source = QwenForward::step_for_mtp_cached(
binding,
ids[3],
Position::new(3, bounds).unwrap(),
session,
output,
Some(&mut *kar),
Some(&mut *moe),
Some(dense),
)
.expect("scalar final target refused");
let baseline_logits = output.test_reset_replay_take_logits().expect("scalar head missing");
let baseline_greedy = source.predicted(session).expect("scalar source invalid");
let baseline_streams: Vec<_> = source
.streams(binding, ids[3], Position::new(3, bounds).unwrap(), session)
.expect("scalar residual invalid")
.iter()
.map(|v| v.to_bits())
.collect();
let baseline_state = session.test_reset_replay_snapshot(binding).expect("scalar state invalid");
let baseline_draft = scalar_draft.test_chunk_snapshot();
scalar_draft.warm_retained(binding, session, &source, next, moe).expect("scalar retained edge refused");
let continuation = QwenForward::step_for_mtp_cached(
binding,
next,
Position::new(4, bounds).unwrap(),
session,
output,
Some(&mut *kar),
Some(&mut *moe),
Some(dense),
)
.expect("scalar continuation refused");
scalar_draft.warm_retained(binding, session, &continuation, follow, moe).expect("scalar continuation warm refused");
let continued_greedy = continuation.predicted(session).expect("baseline continuation origin invalid");
let continued_logits = output.test_reset_replay_take_logits().expect("baseline continuation head missing");
let continued_state = session.test_reset_replay_snapshot(binding).expect("scalar continuation state invalid");
let continued_draft = scalar_draft.test_chunk_snapshot();
QwenForward::reset(session).expect("real owner reset refused");
run.warm_scalar_prefix(&mut scalar_draft);
let (source, baseline, baseline_streams) = run.scalar_final_step(&mut scalar_draft);
let continued = run.scalar_continuation(&mut scalar_draft, &source);
QwenForward::reset(run.session).expect("real owner reset refused");
let mut candidate_draft = MtpDecoder::new(binding).expect("candidate draft refused");
let fresh_draft = candidate_draft.test_chunk_snapshot();
let mut callbacks = 0;
let aborted = QwenForward::prefill_chunk_mmq_joint(
binding,
&ids,
None,
session,
&mut candidate_draft,
output,
Some(&mut *kar),
moe,
dense,
512 * 1024 * 1024,
|| {
callbacks += 1;
callbacks == 16
},
);
assert!(matches!(aborted, Err(Error::Unsupported(Stage::Executor))), "late-row cancellation not refused");
let after_abort = session.test_reset_replay_snapshot(binding).expect("abort snapshot refused");
assert!(fresh.numeric_eq(&after_abort), "cancel changed committed target");
assert!(candidate_draft.test_chunk_eq(&fresh_draft), "cancel changed committed draft");
// Real phase-local cancellation: the second MTP callback occurs after
// the first actual private draft warm. Group routing changes the number
// of earlier target callbacks, so no global callback ordinal is guessed.
let mut mtp_callbacks = 0;
let mtp_aborted: Result<()> = (|| {
let mut pending = QwenForward::prepare_prefill_chunk_with_policy(
binding,
&ids,
None,
session,
output,
Some(&mut *kar),
moe,
dense,
512 * 1024 * 1024,
|| false,
ChunkMoePolicy::ExperimentalResidentMmq,
)?;
let _ready = candidate_draft.stage_prefill_chunk(binding, &mut pending, moe, &mut || {
mtp_callbacks += 1;
mtp_callbacks == 2
})?;
Err(Error::IdentityMismatch)
})();
assert!(matches!(mtp_aborted, Err(Error::Unsupported(Stage::Executor))), "actual MTP-row cancellation not refused");
let discarded = output.test_reset_replay_take_logits().expect("computed canceled head observation missing");
assert_eq!(discarded.len(), 248320, "canceled full head extent changed");
drop(discarded);
assert!(
fresh.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("MTP abort target invalid")),
"MTP cancel changed committed target"
);
assert!(candidate_draft.test_chunk_eq(&fresh_draft), "MTP cancel changed committed draft");
let before_dispatch = moe.test_mmq_dispatch_witness();
let actual = QwenForward::prefill_chunk_mmq_joint(
binding,
&ids,
None,
session,
&mut candidate_draft,
output,
Some(&mut *kar),
moe,
dense,
512 * 1024 * 1024,
|| false,
)
.expect("candidate chunk refused")
.expect("genuine final product missing");
let after_dispatch = moe.test_mmq_dispatch_witness();
let resident_layers = after_dispatch.0 - before_dispatch.0;
let resident_columns = after_dispatch.1 - before_dispatch.1;
let native_fallback_layers = after_dispatch.2 - before_dispatch.2;
assert!(
resident_layers > 0 && resident_columns > 0,
"candidate completed without any actual resident MMQ producer"
);
assert_eq!(resident_layers + native_fallback_layers, 48, "candidate layer producer coverage incomplete");
let actual_logits = output.test_reset_replay_take_logits().expect("chunk head missing");
let actual_greedy = actual.predicted(session).expect("MMQ current origin invalid");
let head_exact = baseline_logits.as_ref() == actual_logits.as_ref();
let actual_streams =
actual.streams(binding, ids[3], Position::new(3, bounds).unwrap(), session).expect("chunk residual invalid");
let residual_exact = baseline_streams.iter().zip(actual_streams.iter()).all(|(a, b)| *a == b.to_bits());
let target_exact =
baseline_state.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("chunk state invalid"));
let draft_exact = candidate_draft.test_chunk_eq(&baseline_draft);
candidate_draft.validate_resume(binding, session, &actual, &[0, 1, 0, 1]).expect("chunk resume fence refused");
candidate_draft.warm_retained(binding, session, &actual, next, moe).expect("chunk retained edge refused");
let continuation = QwenForward::step_for_mtp_cached(
binding,
next,
Position::new(4, bounds).unwrap(),
session,
output,
Some(&mut *kar),
Some(&mut *moe),
Some(dense),
)
.expect("chunk continuation refused");
candidate_draft
.warm_retained(binding, session, &continuation, follow, moe)
.expect("chunk continuation warm refused");
let actual_continued_greedy = continuation.predicted(session).expect("candidate continuation origin invalid");
let actual_continued_logits = output.test_reset_replay_take_logits().expect("candidate continuation head missing");
let continued_head_exact = continued_logits.as_ref() == actual_continued_logits.as_ref();
let continued_target_exact =
continued_state.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("chunk continuation invalid"));
let continued_draft_exact = candidate_draft.test_chunk_eq(&continued_draft);
output.test_reset_replay_record(false).expect("head observer did not drain");
run.late_row_cancel(&mut candidate_draft, &fresh, &fresh_draft);
run.mtp_row_cancel(&mut candidate_draft, &fresh, &fresh_draft);
let chunk = run.candidate_chunk(&mut candidate_draft);
let (exact, actual_greedy) = run.native_exactness(&baseline, &baseline_streams, &chunk, &candidate_draft);
let after = run.native_continuation(&mut candidate_draft, &chunk, &continued);
run.output.test_reset_replay_record(false).expect("head observer did not drain");
native_report(&baseline, &continued, &chunk, &exact, actual_greedy, &after)
}
fn native_report(
baseline: &Observation,
continued: &Observation,
chunk: &ChunkRun,
exact: &ChunkExact,
actual_greedy: TokenId,
after: &NativeContinued,
) -> NativeMmqReport {
NativeMmqReport {
final_head: HeadObservation::new(&baseline_logits, &actual_logits, baseline_greedy, actual_greedy),
continuation_head: HeadObservation::new(
&continued_logits,
&actual_continued_logits,
continued_greedy,
actual_continued_greedy,
),
head_exact,
residual_exact,
target_exact,
draft_exact,
continued_head_exact,
continued_target_exact,
continued_draft_exact,
resident_layers,
resident_columns,
native_fallback_layers,
final_head: HeadObservation::new(&baseline.logits, &chunk.logits, baseline.greedy, actual_greedy),
continuation_head: HeadObservation::new(&continued.logits, &after.logits, continued.greedy, after.greedy),
head_exact: exact.head,
residual_exact: exact.residual,
target_exact: exact.target,
draft_exact: exact.draft,
continued_head_exact: after.head,
continued_target_exact: after.target,
continued_draft_exact: after.draft,
resident_layers: chunk.resident_layers,
resident_columns: chunk.resident_columns,
native_fallback_layers: chunk.native_fallback_layers,
}
}
/// What the continuation step after the candidate chunk observed.
struct NativeContinued {
logits: Box<[u32]>,
greedy: TokenId,
head: bool,
target: bool,
draft: bool,
}
impl MmqRun<'_, '_, '_, '_, '_, '_> {
/// Exactness of the candidate chunk against the scalar baseline, and the candidate's greedy token.
fn native_exactness(
&mut self,
baseline: &Observation,
baseline_streams: &[u32],
chunk: &ChunkRun,
candidate_draft: &MtpDecoder,
) -> (ChunkExact, TokenId) {
let actual_greedy = chunk.product.predicted(self.session).expect("MMQ current origin invalid");
let head = baseline.logits.as_ref() == chunk.logits.as_ref();
let actual_streams =
chunk.product.streams(self.binding, self.ids[3], pos(3), self.session).expect("chunk residual invalid");
let residual = baseline_streams.iter().zip(actual_streams.iter()).all(|(a, b)| *a == b.to_bits());
let target = baseline
.state
.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding).expect("chunk state invalid"));
let draft = candidate_draft.test_chunk_eq(&baseline.draft);
(ChunkExact { head, residual, target, draft }, actual_greedy)
}
fn native_continuation(
&mut self,
candidate_draft: &mut MtpDecoder,
chunk: &ChunkRun,
continued: &Observation,
) -> NativeContinued {
let (greedy, logits) = self.candidate_continuation_step(candidate_draft, chunk);
let head = continued.logits.as_ref() == logits.as_ref();
let target = continued
.state
.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding).expect("chunk continuation invalid"));
let draft = candidate_draft.test_chunk_eq(&continued.draft);
NativeContinued { logits, greedy, head, target, draft }
}
}
@@ -3,6 +3,20 @@
#[allow(unused_imports)]
use super::*;
/// The device copies one `gates` call owns: alpha and beta always, dt and a only when no resident copy is lent.
struct GateUploads<'a> {
alpha: DeviceBuffer<'a>,
beta: DeviceBuffer<'a>,
dt_owned: Option<DeviceBuffer<'a>>,
a_owned: Option<DeviceBuffer<'a>>,
}
/// The sigmoid and softplus-gate outputs, still on the device, with their downloaded values.
struct GateOutputs<'a> {
gate: DeviceBuffer<'a>,
sigmoid: DeviceBuffer<'a>,
gate_values: Box<[f32]>,
sigmoid_values: Box<[f32]>,
}
pub(super) fn gates(
context: &Context<'_>,
alpha: &[f32],
@@ -11,6 +25,23 @@ pub(super) fn gates(
a: &[f32],
resident: Option<[&DeviceBuffer<'_>; 2]>,
) -> Result<CandidatePair> {
let GateUploads { alpha, beta, dt_owned, a_owned } = upload_gate_inputs(context, alpha, beta, dt, a, 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)?;
release([alpha, beta, gate, sigmoid])?;
release_owned(dt_owned)?;
release_owned(a_owned)?;
Ok((gate_values, sigmoid_values))
}
fn upload_gate_inputs<'a>(
context: &'a Context<'_>,
alpha: &[f32],
beta: &[f32],
dt: &[f32],
a: &[f32],
resident: Option<[&DeviceBuffer<'_>; 2]>,
) -> Result<GateUploads<'a>> {
for values in [alpha, beta, dt, a] {
validate_values(values, 48)?;
}
@@ -18,22 +49,28 @@ pub(super) fn gates(
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 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)?;
Ok(GateUploads { alpha, beta, dt_owned, a_owned })
}
fn run_gate_kernels<'a>(
context: &'a Context<'_>,
alpha: &DeviceBuffer<'_>,
beta: &DeviceBuffer<'_>,
dt: &DeviceBuffer<'_>,
a: &DeviceBuffer<'_>,
) -> Result<GateOutputs<'a>> {
let mut gate = allocate(context, 48)?;
let mut sigmoid = allocate(context, 48)?;
context.gdn_beta_sigmoid_f32(&beta, &mut sigmoid).map_err(driver_error)?;
context.gdn_beta_sigmoid_f32(beta, &mut sigmoid).map_err(driver_error)?;
let sigmoid_values = download(&sigmoid, 48)?;
context.gdn_gate_softplus_f32(&alpha, dt, a, &mut gate).map_err(driver_error)?;
context.gdn_gate_softplus_f32(alpha, dt, a, &mut gate).map_err(driver_error)?;
let gate_values = download(&gate, 48)?;
release([alpha, beta, gate, sigmoid])?;
if let Some(v) = dt_owned {
Ok(GateOutputs { gate, sigmoid, gate_values, sigmoid_values })
}
fn release_owned(buffer: Option<DeviceBuffer<'_>>) -> Result<()> {
if let Some(v) = buffer {
v.release().map_err(driver_error)?;
}
if let Some(v) = a_owned {
v.release().map_err(driver_error)?;
}
Ok((gate_values, sigmoid_values))
Ok(())
}
#[allow(clippy::too_many_arguments)] // Source-defined immutable state and six operands.
pub(super) fn recur(
@@ -64,6 +64,25 @@ impl GdnStage {
#[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);
Self::validate_step_inputs(binding, layer, input, prior, txn)?;
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);
}
if projection.is_some() {
return Err(Error::IdentityMismatch);
}
// Reaching here means no cache: no resident weights, no mirror, no input lease and no aux buffers.
Self::step_uncached(binding, layer, input, prior, context)
}
fn validate_step_inputs(
binding: &ModelBinding,
layer: LayerId,
input: &ResidualReady,
prior: &GdnPrior,
txn: &mut QwenStepTxn,
) -> Result<()> {
txn.validate_binding(&binding.identity())?;
let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?;
if expected != layer || input.identity().layer() != layer {
@@ -76,65 +95,29 @@ impl GdnStage {
input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?;
txn.validate_input(input.identity().token(), input.identity().position())?;
txn.validate_gdn_prior(prior, layer)?;
validate_values(input.mixed(), 2560)?;
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);
}
if projection.is_some() {
return Err(Error::IdentityMismatch);
}
let resident = cache.map(|c| c.gdn(binding, layer.get())).transpose()?;
let mut mirror = cache.map(|c| c.gdn_mirror(binding, layer.get(), context)).transpose()?;
let mut mirror_next = None;
let operation = (|| -> Result<GdnReady> {
let input_lease = cache.map(|c| c.gdn_input(binding, layer.get(), context, input.mixed())).transpose()?;
let weights = if let Some(r) = resident {
r.weights.clone()
} else {
std::rc::Rc::new(binding.gdn_weights(layer.get()).map_err(binding_error)?)
};
let aux = cache.zip(resident).map(|(c, r)| c.gdn_aux(r)).transpose()?;
let qkv =
project(context, binding, &weights, GdnMatrixRole::Qkv, input.mixed(), cache, input_lease.as_ref())?;
let (history, h) = convolve(context, prior.history(), &qkv, weights.conv(), aux.map(|v| v[0]))?;
let qk = normalize_qk(context, &h, weights.epsilon())?;
let alpha =
project(context, binding, &weights, GdnMatrixRole::Alpha, input.mixed(), cache, input_lease.as_ref())?;
let beta_raw =
project(context, binding, &weights, GdnMatrixRole::Beta, input.mixed(), cache, input_lease.as_ref())?;
let (gate, beta) = gates(context, &alpha, &beta_raw, weights.dt(), weights.a(), aux.map(|v| [v[1], v[2]]))?;
let (next_state, readout) = if let Some(mirror) = mirror.as_deref_mut() {
let (readout, next) = mirror.compute(prior, &qk[..2048], &qk[2048..4096], &h[4096..], &gate, &beta)?;
mirror_next = Some(next);
(None, readout)
} else {
let (state, readout) =
recur(context, prior.values(), &qk[..2048], &qk[2048..4096], &h[4096..], &gate, &beta)?;
(Some(state), readout)
};
let z = project(context, binding, &weights, GdnMatrixRole::Z, input.mixed(), cache, input_lease.as_ref())?;
let normalized = out_norm(context, &readout, &z, weights.norm(), weights.epsilon(), aux.map(|v| v[3]))?;
let output = project(context, binding, &weights, GdnMatrixRole::Out, &normalized, cache, None)?;
validate_values(&output, 2560)?;
// No numeric/session candidate can retain the scratch borrow.
drop(input_lease);
let pending = if let Some(next) = mirror_next.take() {
mirror.as_deref_mut().ok_or(Error::IdentityMismatch)?.publish(next, input.identity(), history)?
} else {
GdnPending::new(prior, input.identity(), next_state.ok_or(Error::IdentityMismatch)?, history)?
};
Ok(GdnReady { identity: input.identity(), binding: binding.identity(), output, pending: Some(pending) })
})();
if let Some(next) = mirror_next {
// Downstream failures never publish a mirror key. Explicitly free
// the completed candidate; cleanup uncertainty poisons the cache.
let cleanup = mirror.as_deref_mut().ok_or(Error::IdentityMismatch)?.discard(next);
if operation.is_ok() {
cleanup?;
}
}
operation
validate_values(input.mixed(), 2560)
}
fn step_uncached(
binding: &ModelBinding,
layer: LayerId,
input: &ResidualReady,
prior: &GdnPrior,
context: &Context<'_>,
) -> Result<GdnReady> {
let weights = std::rc::Rc::new(binding.gdn_weights(layer.get()).map_err(binding_error)?);
let mixed = input.mixed();
let qkv = project(context, binding, &weights, GdnMatrixRole::Qkv, mixed, None, 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 (state, readout) = recur(context, prior.values(), &qk[..2048], &qk[2048..4096], &h[4096..], &gate, &beta)?;
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)?;
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) })
}
}
@@ -12,18 +12,41 @@ pub(super) fn project(
cache: Option<&DenseWeightCache<'_>>,
source: Option<&GdnInputLease<'_, '_, '_>>,
) -> Result<Box<[f32]>> {
let (c, r) = weights.shape(role);
let (c, _) = weights.shape(role);
validate_values(activation, c)?;
if let Some(source) = source {
source.buffer(&binding.identity(), context, weights.layer(), role, activation)?;
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)?;
return project_retained(context, matrix, kind, c, r, source);
return project_leased(context, binding, weights, role, activation, cache, source);
}
project_uploaded(context, binding, weights, role, activation, cache)
}
fn project_leased(
context: &Context<'_>,
binding: &ModelBinding,
weights: &GdnWeights,
role: GdnMatrixRole,
activation: &[f32],
cache: Option<&DenseWeightCache<'_>>,
source: &GdnInputLease<'_, '_, '_>,
) -> Result<Box<[f32]>> {
let (c, r) = weights.shape(role);
source.buffer(&binding.identity(), context, weights.layer(), role, activation)?;
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)
}
fn project_uploaded(
context: &Context<'_>,
binding: &ModelBinding,
weights: &GdnWeights,
role: GdnMatrixRole,
activation: &[f32],
cache: Option<&DenseWeightCache<'_>>,
) -> Result<Box<[f32]>> {
let (c, r) = weights.shape(role);
let a = upload(context, activation)?;
let mut owned = None;
let (matrix, kind) = if let Some(cache) = cache {
@@ -39,13 +62,21 @@ pub(super) fn project(
};
let mut output = allocate(context, r)?;
dispatch_projection(context, matrix, &a, &mut output, kind, c, r).map_err(driver_error)?;
let values = download(&output, r)?;
release_projection(output, owned, a, r)
}
fn release_projection(
output: DeviceBuffer<'_>,
owned: Option<DeviceBuffer<'_>>,
a: DeviceBuffer<'_>,
rows: usize,
) -> Result<Box<[f32]>> {
let values = download(&output, rows)?;
output.release().map_err(driver_error)?;
if let Some(buffer) = owned {
buffer.release().map_err(driver_error)?;
}
a.release().map_err(driver_error)?;
validate_values(&values, r)?;
validate_values(&values, rows)?;
Ok(values)
}
@@ -66,21 +97,37 @@ pub(super) fn dispatch_projection(
matrix,
a,
output,
ProjectionSpec {
rows: r,
columns: c,
kind: ProjectionKind::Dense(match kind {
GdnMatrixKind::Q8_0 => DenseFormat::Q8_0,
GdnMatrixKind::Q4K => DenseFormat::Q4_K,
GdnMatrixKind::Iq4Nl => DenseFormat::IQ4_NL,
GdnMatrixKind::Iq4Xs => DenseFormat::IQ4_XS,
_ => return Err(DriverError::InvalidProjectionShape),
}),
},
ProjectionSpec { rows: r, columns: c, kind: ProjectionKind::Dense(dense_format(kind)?) },
),
}
}
fn dense_format(kind: GdnMatrixKind) -> std::result::Result<DenseFormat, DriverError> {
match kind {
GdnMatrixKind::Q8_0 => Ok(DenseFormat::Q8_0),
GdnMatrixKind::Q4K => Ok(DenseFormat::Q4_K),
GdnMatrixKind::Iq4Nl => Ok(DenseFormat::IQ4_NL),
GdnMatrixKind::Iq4Xs => Ok(DenseFormat::IQ4_XS),
_ => Err(DriverError::InvalidProjectionShape),
}
}
fn allocate_for_lease<'a>(
context: &'a Context<'_>,
rows: usize,
source: &GdnInputLease<'_, '_, '_>,
) -> Result<DeviceBuffer<'a>> {
match allocate(context, rows) {
Ok(output) => Ok(output),
Err(error) => {
if error == Error::CudaExecution {
source.poison();
}
Err(error)
}
}
}
pub(super) fn project_retained(
context: &Context<'_>,
matrix: &DeviceBuffer<'_>,
@@ -91,15 +138,7 @@ pub(super) fn project_retained(
) -> Result<Box<[f32]>> {
// The actual device input comes only from the lease, never an unrelated buffer.
let activation = source.activation(context, columns)?;
let mut output = match allocate(context, rows) {
Ok(output) => output,
Err(error) => {
if error == Error::CudaExecution {
source.poison();
}
return Err(error);
}
};
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)?;
download(&output, rows)
@@ -2,6 +2,8 @@
#[allow(unused_imports)]
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>(
@@ -14,7 +16,6 @@ pub(super) fn step_cached<'ctx>(
txn: &QwenStepTxn<'_, '_>,
projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>,
) -> Result<GdnReady> {
use chain::Role;
let context = cache.retained_context(binding, current_context)?;
let failed = cache.transport_failure_flag(binding, context)?;
let resident = cache.gdn(binding, layer.get())?;
@@ -22,107 +23,43 @@ pub(super) fn step_cached<'ctx>(
let aux = cache.gdn_aux(resident)?;
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 = chain::Chain::new(context, binding.identity(), input.identity(), failed.clone())?;
chain.validate(context, &binding.identity(), input.identity())?;
if cache.has_gdn_qk_workspace() {
chain.set_qk_workspace(cache.gdn_qk_workspace(binding, context, input.identity())?)?;
}
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 = (|| -> Result<CandidatePair> {
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, binding, cache, txn, layer, input)?
} else {
project_chain_input(
&mut chain,
context,
binding,
&weights,
GdnMatrixRole::Qkv,
&input_lease,
input.mixed(),
cache,
)?
};
let history = chain.upload(Role::History, prior.history())?;
let (next_history, h) = chain.convolve(&history, &qkv, aux[0])?;
let qk = chain.normalize_qk(&h, weights.epsilon())?;
let alpha = project_chain_input(
&mut chain,
context,
binding,
&weights,
GdnMatrixRole::Alpha,
&input_lease,
input.mixed(),
cache,
)?;
let beta_raw = project_chain_input(
&mut chain,
context,
binding,
&weights,
GdnMatrixRole::Beta,
&input_lease,
input.mixed(),
cache,
)?;
let (gate, beta) = chain.gates(&alpha, &beta_raw, aux[1], aux[2])?;
let history = next_history.into_values();
let four_borrow = cache.gdn_four_borrow(binding, context)?;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let four_borrow = four_borrow_gpu::policy(four_borrow)?;
let (readout, next) = if four_borrow {
let inputs = chain.borrow_scalar_recurrence(prior, txn, [&qk, &h, &gate, &beta])?;
let recurrence = mirror.compute_borrowed(prior, input.identity(), txn, inputs);
// Attempt all retained-source frees even on recurrence refusal.
// Keep primary failure and the shared sticky cleanup fence.
let cleanup = chain.release_chunk_sources();
let values = recurrence?;
cleanup?;
values
} else {
let h = h.into_values();
let qk = qk.into_values();
let gate = gate.into_values();
let beta = beta.into_values();
// Recurrence's unchanged128MiB preflight sees no additional retained
// activation allocations. Host state/history remain the canonical proof.
chain.drain()?;
let (readout, next) = mirror.compute_retained(
prior,
input.identity(),
chain.scope_key(),
[&qk[..2048], &qk[2048..4096], &h[4096..], &gate, &beta],
)?;
(readout, next)
};
mirror_next = 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 readout = chain.import_readout(readout, prior)?;
let z = project_chain_input(
&mut chain,
context,
binding,
&weights,
GdnMatrixRole::Z,
&input_lease,
input.mixed(),
cache,
)?;
let normalized = chain.out_norm(&readout, &z, aux[3], weights.epsilon())?;
let (matrix, kind) = cache.gdn_matrix(resident, GdnMatrixRole::Out)?;
let output = chain.project_out(matrix, kind, &normalized)?.into_values();
validate_values(&output, 2560)?;
Ok((history, output))
})();
let operation = step.run(&mut chain, &mut mirror, &mut mirror_next, txn, layer, 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)
}
fn open_chain<'ctx>(
binding: &ModelBinding,
input: &ResidualReady,
context: &'ctx Context<'ctx>,
cache: &DenseWeightCache<'ctx>,
failed: &Rc<Cell<bool>>,
) -> Result<chain::Chain<'ctx>> {
let mut chain = chain::Chain::new(context, binding.identity(), input.identity(), failed.clone())?;
chain.validate(context, &binding.identity(), input.identity())?;
if cache.has_gdn_qk_workspace() {
chain.set_qk_workspace(cache.gdn_qk_workspace(binding, context, input.identity())?)?;
}
Ok(chain)
}
/// Combines the step result with the chain cleanup, discards a computed candidate on failure and publishes on success.
fn settle_cached<'ctx>(
operation: Result<CandidatePair>,
cleanup: Result<()>,
mirror: &mut GdnStateMirror<'ctx>,
mut mirror_next: Option<mirror::MirrorNext<'ctx>>,
binding: &ModelBinding,
input: &ResidualReady,
) -> Result<GdnReady> {
let result = operation.and_then(|values| cleanup.map(|()| values));
let (history, output) = match result {
Ok(values) => values,
@@ -137,6 +74,136 @@ pub(super) fn step_cached<'ctx>(
Ok(GdnReady { identity: input.identity(), binding: binding.identity(), output, pending: Some(pending) })
}
/// The four device products the recurrence reads.
struct RecurrenceInputs {
qk: chain::Product,
h: chain::Product,
gate: chain::Product,
beta: chain::Product,
}
/// 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,
prior: &'a GdnPrior,
context: &'ctx Context<'ctx>,
cache: &'a DenseWeightCache<'ctx>,
weights: &'a GdnWeights,
resident: &'a GdnResident,
aux: [&'a DeviceBuffer<'ctx>; 4],
lease: &'a GdnInputLease<'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)
}
fn run(
&self,
chain: &mut chain::Chain<'ctx>,
mirror: &mut GdnStateMirror<'ctx>,
mirror_next: &mut Option<mirror::MirrorNext<'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);
#[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)?;
Ok((history, output))
}
/// Projections, convolution, q/k normalisation and gates; returns the next history and the recurrence inputs.
fn leading_products(
&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)?
} else {
self.project(chain, GdnMatrixRole::Qkv)?
};
let history = chain.upload(chain::Role::History, self.prior.history())?;
let (next_history, h) = chain.convolve(&history, &qkv, self.aux[0])?;
let qk = chain.normalize_qk(&h, self.weights.epsilon())?;
let alpha = self.project(chain, GdnMatrixRole::Alpha)?;
let beta_raw = self.project(chain, GdnMatrixRole::Beta)?;
let (gate, beta) = chain.gates(&alpha, &beta_raw, self.aux[1], self.aux[2])?;
Ok((next_history.into_values(), RecurrenceInputs { qk, h, gate, beta }))
}
fn recurrence(
&self,
chain: &mut chain::Chain<'ctx>,
mirror: &mut GdnStateMirror<'ctx>,
txn: &QwenStepTxn<'_, '_>,
inputs: RecurrenceInputs,
) -> Result<(mirror::MirrorReadout<'ctx>, mirror::MirrorNext<'ctx>)> {
let four_borrow = self.cache.gdn_four_borrow(self.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 {
self.borrowed_recurrence(chain, mirror, txn, &inputs)
} else {
self.retained_recurrence(chain, mirror, inputs)
}
}
fn borrowed_recurrence(
&self,
chain: &mut chain::Chain<'ctx>,
mirror: &mut GdnStateMirror<'ctx>,
txn: &QwenStepTxn<'_, '_>,
inputs: &RecurrenceInputs,
) -> 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);
// Attempt all retained-source frees even on recurrence refusal.
// Keep primary failure and the shared sticky cleanup fence.
let cleanup = chain.release_chunk_sources();
let values = recurrence?;
cleanup?;
Ok(values)
}
fn retained_recurrence(
&self,
chain: &mut chain::Chain<'ctx>,
mirror: &mut GdnStateMirror<'ctx>,
inputs: RecurrenceInputs,
) -> Result<(mirror::MirrorReadout<'ctx>, mirror::MirrorNext<'ctx>)> {
let h = inputs.h.into_values();
let qk = inputs.qk.into_values();
let gate = inputs.gate.into_values();
let beta = inputs.beta.into_values();
// Recurrence's unchanged128MiB preflight sees no additional retained
// activation allocations. Host state/history remain the canonical proof.
chain.drain()?;
mirror.compute_retained(
self.prior,
self.input.identity(),
chain.scope_key(),
[&qk[..2048], &qk[2048..4096], &h[4096..], &gate, &beta],
)
}
fn finish(&self, chain: &mut chain::Chain<'ctx>, readout: mirror::MirrorReadout<'ctx>) -> Result<Box<[f32]>> {
let readout = chain.import_readout(readout, self.prior)?;
let z = self.project(chain, GdnMatrixRole::Z)?;
let normalized = chain.out_norm(&readout, &z, self.aux[3], self.weights.epsilon())?;
let (matrix, kind) = self.cache.gdn_matrix(self.resident, GdnMatrixRole::Out)?;
let output = chain.project_out(matrix, kind, &normalized)?.into_values();
validate_values(&output, 2560)?;
Ok(output)
}
}
#[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>,
@@ -157,15 +157,15 @@ impl<'chain, 'ctx> RecurrenceBorrow<'chain, 'ctx> {
}
}
impl<'chain, 'ctx> ScalarRecurrenceBorrow<'chain, 'ctx> {
pub(in super::super) fn into_parts(
self,
fn validate_borrow(
&self,
context: &Context<'_>,
binding: &BindingIdentity,
failed: &Rc<Cell<bool>>,
prior: &super::super::GdnPrior,
identity: TokenLayer,
txn: &super::super::QwenStepTxn<'_, '_>,
) -> Result<RecurrenceParts<'chain, 'ctx>> {
) -> Result<()> {
txn.validate_binding(binding)?;
txn.validate_input(identity.token(), identity.position())?;
txn.validate_gdn_prior(prior, identity.layer())?;
@@ -177,6 +177,18 @@ impl<'chain, 'ctx> ScalarRecurrenceBorrow<'chain, 'ctx> {
{
return Err(Error::IdentityMismatch);
}
Ok(())
}
pub(in super::super) fn into_parts(
self,
context: &Context<'_>,
binding: &BindingIdentity,
failed: &Rc<Cell<bool>>,
prior: &super::super::GdnPrior,
identity: TokenLayer,
txn: &super::super::QwenStepTxn<'_, '_>,
) -> Result<RecurrenceParts<'chain, 'ctx>> {
self.validate_borrow(context, binding, failed, prior, identity, txn)?;
let [qk, h, gate, beta] = self.products;
Ok((
self.scope,