Merge branch 'claude/size3-en2' into claude/hexagonal-finish-14ee3a

This commit is contained in:
Pavlo Ratushnyi
2026-11-07 09:27:18 +01:00
31 changed files with 585 additions and 309 deletions
@@ -41,10 +41,7 @@ fn adaptive_idle(w: &AdaptiveWitness) -> bool {
}
pub(super) fn learned_main_moe<'c>(binding: &ModelBinding, context: &'c Context<'_>, bytes: &[u8]) -> Cache<'c> {
let cache = MoeWeightCache::
new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent_learned_main_lru(
binding, context, bytes,
)?;
let cache = MoeWeightCache::new_profile_shared_permanent_learned_main_lru(binding, context, bytes)?;
let checked = match cache.learned_main_witness(binding) {
Ok(witness) => learned_main_check(&cache, &witness),
Err(primary) => Err(primary),
@@ -162,8 +162,7 @@ fn resident_moe<'c>(
context: &'c leleka_cuda_driver::Context<'_>,
profile: &[u8],
) -> MoeWeightCache<'c> {
MoeWeightCache::
new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent_learned_main_lru(
MoeWeightCache::new_profile_shared_permanent_learned_main_lru(
binding, context, profile,
)
.unwrap()
@@ -45,21 +45,22 @@ struct IndexLine<'a> {
bytes: u64,
}
fn parse_index_number(fields: &mut std::str::SplitAsciiWhitespace<'_>) -> 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)
}
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()?;
let rows = parse_index_number(&mut fields)?;
let columns = parse_index_number(&mut fields)?;
let offset = parse_index_number(&mut fields)?;
let bytes = parse_index_number(&mut fields)?;
if fields.next().is_some() {
return Err(InputBindingError::Metadata);
}
@@ -111,6 +112,14 @@ impl IndexScan {
}
}
impl IndexScan {
fn complete(&self) -> bool {
self.count == 29
&& DESCRIPTORS.iter().enumerate().all(|(i, d)| d.dense.is_some() == self.seen[i])
&& self.spans.iter().map(|s| s.1).max() == Some(DENSE_BYTES)
}
}
impl MtpIndex {
pub(super) fn inspect(bytes: &[u8]) -> InputResult<Self> {
if bytes.is_empty() || bytes.len() > INDEX_LIMIT || !bytes.is_ascii() {
@@ -121,10 +130,7 @@ impl MtpIndex {
for line in text.lines() {
scan.accept(&parse_index_line(line)?)?;
}
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)
{
if !scan.complete() {
return Err(InputBindingError::Metadata);
}
Ok(Self)
@@ -78,7 +78,7 @@ fn range(first: usize, count: usize, rows: usize) -> InputResult<()> {
}
Ok(())
}
fn admit_ple(a: &mut Qwen4ExpArtifact) -> InputResult<()> {
fn check_ple_topology(a: &Qwen4ExpArtifact) -> InputResult<()> {
let t = a.topology();
if t.ple_layers() != [1]
|| t.hc_count() != 4
@@ -88,19 +88,29 @@ fn admit_ple(a: &mut Qwen4ExpArtifact) -> InputResult<()> {
{
return Err(E::Metadata);
}
// Admit every descriptor before allocation or reading any payload.
Ok(())
}
fn admit_ple_matrices(a: &mut Qwen4ExpArtifact) -> InputResult<()> {
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)?;
}
Ok(())
}
fn admit_ple_norms(a: &mut Qwen4ExpArtifact) -> InputResult<()> {
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(())
descriptor(d.kind(), d.dimensions(), d.byte_length(), 1, &[4, HC as u64], HC * 4 * 2)
}
fn admit_ple(a: &mut Qwen4ExpArtifact) -> InputResult<()> {
check_ple_topology(a)?;
// Admit every descriptor before allocation or reading any payload.
admit_ple_matrices(a)?;
admit_ple_norms(a)
}
fn read_conv(a: &mut Qwen4ExpArtifact) -> InputResult<Box<[u16]>> {
let mut conv = Vec::new();
@@ -92,15 +92,17 @@ fn index(role: QsaMatrixRole) -> usize {
QsaMatrixRole::Out => 5,
}
}
fn kind(value: u32, role: QsaMatrixRole) -> InputResult<QsaMatrixKind> {
let permitted = match role {
fn kind_permitted(value: u32, role: QsaMatrixRole) -> bool {
match role {
QsaMatrixRole::Q => matches!(value, 12 | 13 | 14 | 23),
QsaMatrixRole::K => matches!(value, 14 | 23),
QsaMatrixRole::V => matches!(value, 13 | 14),
QsaMatrixRole::IndexQ | QsaMatrixRole::IndexK => value == 30,
QsaMatrixRole::Out => matches!(value, 12 | 14),
};
if !permitted {
}
}
fn kind(value: u32, role: QsaMatrixRole) -> InputResult<QsaMatrixKind> {
if !kind_permitted(value, role) {
return Err(E::UnsupportedKind);
}
Ok(match value {
@@ -227,6 +229,13 @@ fn stream_qsa_rows(
}
Ok(bytes)
}
fn check_qsa_block_tensor(a: &mut Qwen4ExpArtifact, m: &Matrix, role: QsaMatrixRole) -> InputResult<()> {
let tensor = a.tensor(m.role).map_err(|_| E::Geometry)?;
if tensor.kind() != m.kind {
return Err(E::Geometry);
}
descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), role, m.columns, m.rows)
}
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)?;
@@ -255,11 +264,7 @@ impl ModelBinding {
block_range(first, count, m.rows)?;
}
let mut a = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?;
let tensor = a.tensor(m.role).map_err(|_| E::Geometry)?;
if tensor.kind() != m.kind {
return Err(E::Geometry);
}
descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), role, m.columns, m.rows)?;
check_qsa_block_tensor(&mut a, &m, role)?;
let row = super::decode::row_bytes(m.kind, m.columns)?;
let bytes = stream_qsa_rows(&mut a, m, first, count, row)?;
finish_qsa_block(m, role, count, row, bytes)
@@ -7,8 +7,10 @@ const MODEL_SOURCE_CAP: u64 = 52 * 1024 * 1024 * 1024;
const POOL_BYTES: u64 = 160 * 1024 * 1024;
const FUTURE_HEADROOM: u64 = 8 * 1024 * 1024 * 1024;
pub(super) fn admit_pool(binding: &ModelBinding, metadata: usize) -> Result<()> {
let report = binding.resident_expert_source_report().map_err(binding_error)?.ok_or(Error::IdentityMismatch)?;
fn check_pool_report(
report: &leleka_model_format::qwen4exp::ResidentExpertSourceReport,
metadata: usize,
) -> Result<()> {
if report.bank_count != 144
|| report.source_cap_bytes != MODEL_SOURCE_CAP
|| report.future_headroom_bytes != FUTURE_HEADROOM
@@ -17,12 +19,16 @@ pub(super) fn admit_pool(binding: &ModelBinding, metadata: usize) -> Result<()>
{
return Err(Error::IdentityMismatch);
}
let metadata = u64::try_from(metadata).map_err(|_| Error::Overflow)?;
let charged =
report.charged_bytes.checked_add(metadata).and_then(|n| n.checked_add(POOL_BYTES)).ok_or(Error::Overflow)?;
Ok(())
}
fn check_pool_charge(charged_bytes: u64, metadata: u64) -> Result<()> {
let charged = charged_bytes.checked_add(metadata).and_then(|n| n.checked_add(POOL_BYTES)).ok_or(Error::Overflow)?;
if charged > MODEL_SOURCE_CAP {
return Err(Error::InputAllocation);
}
Ok(())
}
fn check_pool_headroom(metadata: u64) -> Result<()> {
// Existing bank/KAR/Dense owners are already reflected in MemAvailable.
// Charge only not-yet-constructed pool/metadata and genuine future safety.
// This is a fail-closed snapshot, not a reservation against other processes.
@@ -33,6 +39,13 @@ pub(super) fn admit_pool(binding: &ModelBinding, metadata: usize) -> Result<()>
}
Ok(())
}
pub(super) fn admit_pool(binding: &ModelBinding, metadata: usize) -> Result<()> {
let report = binding.resident_expert_source_report().map_err(binding_error)?.ok_or(Error::IdentityMismatch)?;
check_pool_report(&report, metadata)?;
let metadata = u64::try_from(metadata).map_err(|_| Error::Overflow)?;
check_pool_charge(report.charged_bytes, metadata)?;
check_pool_headroom(metadata)
}
fn read_meminfo() -> Result<String> {
#[cfg(not(target_os = "windows"))]
{
@@ -150,14 +150,7 @@ impl<'ctx> MappedStage<'ctx> {
source: &mut MoeRoutedSourceScope<'_, '_>,
member: usize,
) -> Result<()> {
self.validate(binding, slot)?;
let keys = EphemeralRoutedOwner::keys(binding, source, member)?;
if !matches!(self.slots[slot], MappedSlot::Idle { .. }) {
return Err(Error::IdentityMismatch);
}
if keys.iter().zip(self.maximum).any(|(key, max)| key.bytes > max) {
return Err(Error::InputAllocation);
}
let keys = self.admitted_keys(binding, slot, source, member)?;
// Same exact Gate then Up then Down full encoded finite precedence.
let spans = Self::mapped_spans(source, member)?;
let bank = self.bank.as_ref().ok_or(Error::IdentityMismatch)?;
@@ -170,6 +163,23 @@ impl<'ctx> MappedStage<'ctx> {
self.slots[slot] = MappedSlot::Pending { keys, copy };
Ok(())
}
fn admitted_keys(
&self,
binding: &ModelBinding,
slot: usize,
source: &MoeRoutedSourceScope<'_, '_>,
member: usize,
) -> Result<[MoeWeightDescriptor; 3]> {
self.validate(binding, slot)?;
let keys = EphemeralRoutedOwner::keys(binding, source, member)?;
if !matches!(self.slots[slot], MappedSlot::Idle { .. }) {
return Err(Error::IdentityMismatch);
}
if keys.iter().zip(self.maximum).any(|(key, max)| key.bytes > max) {
return Err(Error::InputAllocation);
}
Ok(keys)
}
fn mapped_spans(
source: &MoeRoutedSourceScope<'_, '_>,
member: usize,
@@ -100,18 +100,7 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
source.descriptor(member, ROLES[2]).map_err(binding_error)?,
];
for (role, key) in keys.iter().enumerate() {
let shape = if role == 2 { (2560, 640) } else { (640, 2560) };
if key.layer >= 48
|| key.layer != keys[0].layer
|| key.expert.is_none()
|| key.expert != keys[0].expert
|| key.expert.is_some_and(|x| x >= 512)
|| key.role as usize != role
|| (key.rows, key.columns) != shape
|| key.bytes == 0
|| !key.bytes.is_multiple_of(256)
|| if role == 2 { !matches!(key.raw_kind, 20 | 42) } else { !matches!(key.raw_kind, 18 | 21 | 22 | 23) }
{
if !key_identity_ok(key, &keys[0]) || !key_shape_ok(key, role) {
return Err(Error::IdentityMismatch);
}
}
@@ -173,3 +162,19 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
}
}
}
fn key_identity_ok(key: &MoeWeightDescriptor, first: &MoeWeightDescriptor) -> bool {
key.layer < 48
&& key.layer == first.layer
&& key.expert.is_some()
&& key.expert == first.expert
&& !key.expert.is_some_and(|x| x >= 512)
}
fn key_shape_ok(key: &MoeWeightDescriptor, role: usize) -> bool {
let shape = if role == 2 { (2560, 640) } else { (640, 2560) };
let kind_ok = if role == 2 { matches!(key.raw_kind, 20 | 42) } else { matches!(key.raw_kind, 18 | 21 | 22 | 23) };
key.role as usize == role
&& (key.rows, key.columns) == shape
&& key.bytes != 0
&& key.bytes.is_multiple_of(256)
&& kind_ok
}
@@ -97,12 +97,7 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
let mut retained = self.host_bytes()?.checked_add(pair_metadata).ok_or(Error::Overflow)?;
for (index, role) in ROLES.into_iter().enumerate() {
let block = source.block(member, role).map_err(binding_error)?;
if block.bytes().len() != keys[index].bytes
|| block.rows() != keys[index].rows
|| block.columns() != keys[index].columns
{
return Err(Error::IdentityMismatch);
}
check_block_matches(&block, &keys[index])?;
retained = retained.checked_add(block.bytes().len()).ok_or(Error::Overflow)?;
if retained > HOST_LIMIT {
return Err(Error::InputAllocation);
@@ -280,3 +275,9 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
healthy_cancel(error, observed, self.failed, self.context.is_poisoned())
}
}
fn check_block_matches(block: &MoeExpertBlock, key: &MoeWeightDescriptor) -> Result<()> {
if block.bytes().len() != key.bytes || block.rows() != key.rows || block.columns() != key.columns {
return Err(Error::IdentityMismatch);
}
Ok(())
}
@@ -33,16 +33,25 @@ impl LruIndex {
#[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 });
self.seed_insert(key, age, actual_age)?;
}
self.seed_finish(actual_age)
}
#[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
fn seed_insert(&mut self, key: MoeWeightDescriptor, age: u64, actual_age: u64) -> Result<()> {
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 });
Ok(())
}
#[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
fn seed_finish(&mut self, actual_age: u64) -> Result<()> {
// 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);
@@ -63,17 +72,24 @@ impl LruIndex {
if self.heap.len() > self.limit || self.positions.len() != MAX_KEYS || self.last_age > actual_age {
return false;
}
self.positions_coherent() && self.heap_coherent()
}
#[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
fn positions_coherent(&self) -> bool {
let occupied = self.positions.iter().filter(|&&p| p != ABSENT).count();
occupied == self.heap.len()
&& self.positions.iter().enumerate().all(|(key_slot, &position)| {
position == ABSENT || self.heap.get(position).is_some_and(|node| slot(node.key).ok() == Some(key_slot))
})
&& self.heap.iter().enumerate().all(|(i, node)| {
node.age != 0
&& node.age <= self.last_age
&& slot(node.key).is_ok_and(|key_slot| self.positions[key_slot] == i)
&& (i == 0 || self.heap[(i - 1) / 2].age < node.age)
})
}
#[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
fn heap_coherent(&self) -> bool {
self.heap.iter().enumerate().all(|(i, node)| {
node.age != 0
&& node.age <= self.last_age
&& slot(node.key).is_ok_and(|key_slot| self.positions[key_slot] == i)
&& (i == 0 || self.heap[(i - 1) / 2].age < node.age)
})
}
#[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
pub(in super::super) fn matches_existing(
@@ -11,6 +11,14 @@ struct MapReservation {
metadata_bytes: usize,
}
/// The ranked profile and the sizing inputs of one fill.
struct ProfileFill<'a> {
profile_len: usize,
profile: &'a RankedProfile,
with_mtp_input: bool,
reusable_spill_floor: 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(
@@ -48,8 +56,8 @@ 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.fill_ranked_profile(binding, context, bytes.len(), &profile, with_mtp_input, reusable_spill_floor);
let fill = ProfileFill { profile_len: bytes.len(), profile: &profile, with_mtp_input, reusable_spill_floor };
let operation = cache.fill_ranked_profile(binding, context, &fill);
if let Err(primary) = operation {
let _ = cache.close();
return Err(primary);
@@ -60,28 +68,30 @@ impl<'ctx> MoeWeightCache<'ctx> {
&mut self,
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
profile_len: usize,
profile: &RankedProfile,
with_mtp_input: bool,
reusable_spill_floor: usize,
fill: &ProfileFill<'_>,
) -> Result<()> {
let (profile, reusable_spill_floor) = (fill.profile, fill.reusable_spill_floor);
self.validate(binding, context)?;
if with_mtp_input {
if fill.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 reservation = self.reserve_profile_map(profile, &plan, fill.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)?;
self.check_profile_loaded(expected_bytes, count)?;
self.validate(binding, context)
}
fn check_profile_loaded(&self, expected_bytes: usize, count: usize) -> Result<()> {
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)
Ok(())
}
/// 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])> {
@@ -5,6 +5,11 @@ use super::*;
/// Layouts, charges and the checked next counters of one pinned triplet upload.
#[derive(Clone, Copy)]
struct PinnedLayouts {
layouts: [Option<(leleka_cuda_driver::MmqFormat, usize)>; 3],
charges: [usize; 3],
extra: usize,
}
struct PinnedAdmission {
layouts: [Option<(leleka_cuda_driver::MmqFormat, usize)>; 3],
charges: [usize; 3],
@@ -39,10 +44,18 @@ impl<'ctx> MoeWeightCache<'ctx> {
if keys.iter().any(|key| !self.is_pinned(*key) || self.main.contains_key(key)) {
return Err(Error::IdentityMismatch);
}
let layouts = self.pinned_layouts(keys)?;
let spill = self.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.spill_reserve;
self.check_pinned_room(layouts.extra, spill)?;
self.pinned_admission(layouts)
}
fn pinned_layouts(&self, keys: &[MoeWeightDescriptor; 3]) -> Result<PinnedLayouts> {
let layouts = [self.weight_layout(keys[0])?, self.weight_layout(keys[1])?, self.weight_layout(keys[2])?];
let charges = std::array::from_fn::<_, 3, _>(|i| layouts[i].map_or(keys[i].bytes, |(_, n)| n));
let extra = charges.iter().try_fold(0usize, |n, v| n.checked_add(*v)).ok_or(Error::Overflow)?;
let spill = self.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.spill_reserve;
Ok(PinnedLayouts { layouts, charges, extra })
}
fn check_pinned_room(&self, extra: usize, spill: usize) -> Result<()> {
// Requery real physical room for each upload, leaving the complete spill
// allowance and working reserve intact. No eviction of already pinned owners.
let (free, _) = self.context.memory_info().map_err(driver_error)?;
@@ -53,6 +66,10 @@ impl<'ctx> MoeWeightCache<'ctx> {
{
return Err(Error::InputAllocation);
}
Ok(())
}
fn pinned_admission(&self, found: PinnedLayouts) -> Result<PinnedAdmission> {
let PinnedLayouts { layouts, charges, extra } = found;
let next_bytes = self.main_bytes.checked_add(extra).ok_or(Error::Overflow)?;
let next_age = self.age.checked_add(3).ok_or(Error::Overflow)?;
let next_loaded = self
@@ -79,17 +79,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
// 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);
}
self.check_shared_room(&keys[index..], spill, next_bytes)?;
let raw = binding.moe_shared_preload_block(key).map_err(binding_error)?;
if raw.len() != key.bytes {
return Err(Error::InvalidDimension);
@@ -98,6 +88,20 @@ impl<'ctx> MoeWeightCache<'ctx> {
}
Ok(())
}
fn check_shared_room(&self, remaining_keys: &[MoeWeightDescriptor], spill: usize, next_bytes: usize) -> Result<()> {
let (free, _) = self.context.memory_info().map_err(driver_error)?;
let remaining =
remaining_keys.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);
}
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() {
@@ -8,7 +8,7 @@ use super::*;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
impl<'ctx> MoeWeightCache<'ctx> {
/// New policy only: keep genuine preload bytes, then learn routed main residency.
pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent_learned_main_lru(
pub(crate) fn new_profile_shared_permanent_learned_main_lru(
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
bytes: &[u8],
@@ -11,7 +11,7 @@ fn digest(bytes: &[u8]) -> [u8; 32] {
// Independent translation of expert_cache.cpp read_expert_profile's valid
// decoding/order. The original intentionally ignores version and trailing table.
fn original_decode(bytes: &[u8]) -> Option<Vec<(u16, u16)>> {
fn original_header(bytes: &[u8]) -> Option<[u32; 5]> {
if bytes.len() < 24 || &bytes[..4] != b"STRP" {
return None;
}
@@ -22,6 +22,10 @@ fn original_decode(bytes: &[u8]) -> Option<Vec<(u16, u16)>> {
if header[1] != 48 || header[2] != 512 || header[4] > header[3] {
return None;
}
Some(header)
}
fn original_decode(bytes: &[u8]) -> Option<Vec<(u16, u16)>> {
let header = original_header(bytes)?;
let count = usize::try_from(header[4]).ok()?;
let end = count.checked_mul(4)?.checked_add(24)?;
let raw = bytes.get(24..end)?;
@@ -6,7 +6,8 @@ use super::*;
#[path = "impl_adaptivecache/preload.rs"]
mod preload;
type Staged<'ctx> = (Swap, Vec<(DeviceBuffer<'ctx>, Vec<u8>)>);
type StagedPairs<'ctx> = Vec<(DeviceBuffer<'ctx>, Vec<u8>)>;
type Staged<'ctx> = (Swap, StagedPairs<'ctx>);
/// Slot buffers and transfer queue, both reserved up front so later phases never allocate.
struct Reserved<'ctx> {
@@ -85,6 +86,21 @@ impl<'ctx> AdaptiveCache<'ctx> {
/// consumer. Cache hits/matrix-role callbacks must never call this method.
pub(in super::super) fn observe_row(&mut self, binding: &ModelBinding, weights: &MoeExpertWeights) -> Result<()> {
self.validate(binding)?;
let (layer, ids) = Self::routed_ids(binding, weights)?;
let mut hits = 0u64;
for &expert in &ids {
hits += u64::from(self.policy.resident_slot(layer, expert)?.is_some());
}
let occurrences = self.occurrences.checked_add(10).ok_or(Error::Overflow)?;
let next_hits = self.hits.checked_add(hits).ok_or(Error::Overflow)?;
let next_misses = self.misses.checked_add(10 - hits).ok_or(Error::Overflow)?;
self.policy.observe(layer, &ids)?;
self.occurrences = occurrences;
self.hits = next_hits;
self.misses = next_misses;
Ok(())
}
fn routed_ids(binding: &ModelBinding, weights: &MoeExpertWeights) -> Result<(u32, [u32; 10])> {
let mut ids = [0u32; 10];
let mut layer = None;
for (slot, id) in ids.iter_mut().enumerate() {
@@ -98,18 +114,7 @@ impl<'ctx> AdaptiveCache<'ctx> {
*id = key.expert.ok_or(Error::InvalidExpert)?;
}
let layer = layer.ok_or(Error::IdentityMismatch)?;
let mut hits = 0u64;
for &expert in &ids {
hits += u64::from(self.policy.resident_slot(layer, expert)?.is_some());
}
let occurrences = self.occurrences.checked_add(10).ok_or(Error::Overflow)?;
let next_hits = self.hits.checked_add(hits).ok_or(Error::Overflow)?;
let next_misses = self.misses.checked_add(10 - hits).ok_or(Error::Overflow)?;
self.policy.observe(layer, &ids)?;
self.occurrences = occurrences;
self.hits = next_hits;
self.misses = next_misses;
Ok(())
Ok((layer, ids))
}
/// Missing, in-flight incoming, and evicted outgoing are genuine CPU misses.
/// This does no source read, upload, eviction, or GPU miss fill.
@@ -140,10 +145,7 @@ impl<'ctx> AdaptiveCache<'ctx> {
/// No unsafe Send/Sync retrofit.
/// Dedicated actual copy streams permit overlap after the method returns.
pub(in super::super) fn completed_window(&mut self, binding: &ModelBinding) -> Result<()> {
self.validate(binding)?;
let due = self.policy.rounds.checked_add(1).ok_or(Error::Overflow)? % ADAPT_EVERY == 0;
self.policy.completed_window()?;
if !due || !self.transfers.is_empty() {
if !self.window_swaps_due(binding)? {
return Ok(());
}
let selected: [Option<Swap>; ADAPT_SWAPS] = std::array::from_fn(|i| self.policy.ranked.get(i).copied());
@@ -152,10 +154,7 @@ impl<'ctx> AdaptiveCache<'ctx> {
let mut staged = reserve::<Staged<'ctx>>(ADAPT_SWAPS)?;
let mut swaps_vec = reserve::<Swap>(ADAPT_SWAPS)?;
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()));
}
self.restore_staged(&mut staged);
return Err(primary);
}
if let Err(primary) = self.policy.mark_enqueued(&swaps_vec) {
@@ -165,6 +164,18 @@ impl<'ctx> AdaptiveCache<'ctx> {
}
self.enqueue_staged(staged)
}
fn window_swaps_due(&mut self, binding: &ModelBinding) -> Result<bool> {
self.validate(binding)?;
let due = self.policy.rounds.checked_add(1).ok_or(Error::Overflow)? % ADAPT_EVERY == 0;
self.policy.completed_window()?;
Ok(due && self.transfers.is_empty())
}
fn restore_staged(&mut self, staged: &mut Vec<Staged<'ctx>>) {
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()));
}
}
fn stage_swaps(
&mut self,
binding: &ModelBinding,
@@ -174,23 +185,32 @@ impl<'ctx> AdaptiveCache<'ctx> {
) -> 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));
}
let pairs = self.stage_one_swap(binding, swap, &mut staged_bytes)?;
staged.push((swap, pairs));
swaps_vec.push(swap);
}
Ok(())
}
fn stage_one_swap(
&mut self,
binding: &ModelBinding,
swap: Swap,
staged_bytes: &mut usize,
) -> Result<StagedPairs<'ctx>> {
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));
}
Ok(pairs)
}
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() {
@@ -14,21 +14,21 @@ pub(super) fn cell(layer: u32, expert: u32) -> Result<usize> {
}
Ok(layer as usize * EXPERTS + expert as usize)
}
fn blob_key_identity_ok(key: &MoeWeightDescriptor, layer: u32, expert: u32, role: usize) -> bool {
key.layer == layer && key.expert == Some(expert) && key.role as usize == role
}
fn blob_key_shape_ok(key: &MoeWeightDescriptor, role: usize) -> bool {
let (rows, columns) = if role == 2 { (2560, 640) } else { (640, 2560) };
let kind_ok = if role == 2 { matches!(key.raw_kind, 20 | 42) } else { matches!(key.raw_kind, 18 | 21 | 22 | 23) };
(key.rows, key.columns) == (rows, columns) && key.bytes != 0 && key.bytes % 256 == 0 && kind_ok
}
pub(super) fn blob_bytes(keys: &[MoeWeightDescriptor; 3]) -> Result<usize> {
let layer = keys[0].layer;
let expert = keys[0].expert.ok_or(Error::InvalidExpert)?;
cell(layer, expert)?;
let mut bytes = 0usize;
for (role, key) in keys.iter().enumerate() {
let (rows, columns) = if role == 2 { (2560, 640) } else { (640, 2560) };
if key.layer != layer
|| key.expert != Some(expert)
|| key.role as usize != role
|| (key.rows, key.columns) != (rows, columns)
|| key.bytes == 0
|| key.bytes % 256 != 0
|| if role == 2 { !matches!(key.raw_kind, 20 | 42) } else { !matches!(key.raw_kind, 18 | 21 | 22 | 23) }
{
if !blob_key_identity_ok(key, layer, expert, role) || !blob_key_shape_ok(key, role) {
return Err(Error::InvalidDimension);
}
bytes = bytes.checked_add(key.bytes).ok_or(Error::Overflow)?;
@@ -39,6 +39,9 @@ pub(super) fn blob_bytes(keys: &[MoeWeightDescriptor; 3]) -> Result<usize> {
}
Ok(bytes)
}
fn swaps_conflict(a: &Swap, b: &Swap) -> bool {
a.slot == b.slot || (a.layer == b.layer && (a.incoming == b.incoming || a.outgoing == b.outgoing))
}
/// Usage counters, residency map and the initial slots of the ranked prefix.
struct InitialSlots {
usage: Vec<f32>,
@@ -255,6 +258,15 @@ impl AdaptivePolicy {
}
Ok(())
}
fn validate_enqueue_batch(&self, swaps: &[Swap]) -> Result<()> {
for (index, &swap) in swaps.iter().enumerate() {
self.validate_swap(swap)?;
if swaps[..index].iter().any(|s| swaps_conflict(s, &swap)) {
return Err(Error::IdentityMismatch);
}
}
Ok(())
}
/// PRIVATE adapter seam, only after the real driver took ownership of the
/// entire selected slot batch. Incoming and outgoing both CPU until genuine
/// event completion. Not exposed as an external launch/ready certificate.
@@ -262,15 +274,7 @@ impl AdaptivePolicy {
if !self.pending.is_empty() || swaps.len() > ADAPT_SWAPS {
return Err(Error::IdentityMismatch);
}
for (index, &swap) in swaps.iter().enumerate() {
self.validate_swap(swap)?;
if swaps[..index].iter().any(|s| {
s.slot == swap.slot
|| (s.layer == swap.layer && (s.incoming == swap.incoming || s.outgoing == swap.outgoing))
}) {
return Err(Error::IdentityMismatch);
}
}
self.validate_enqueue_batch(swaps)?;
for &swap in swaps {
self.resident[cell(swap.layer, swap.outgoing)?] = -1;
self.pending.push(swap);
@@ -58,7 +58,8 @@ impl<'ctx> ChunkModules<'ctx> {
Err(error) => {
#[cfg(test)]
eprintln!(
"PUBLIC CUDA stage=q6-module-new allocated={} budget={} shared_failed={} context_poisoned={} error={error:?}",
"PUBLIC CUDA stage=q6-module-new allocated={} budget={} shared_failed={} \
context_poisoned={} error={error:?}",
self.context.allocated_bytes(),
self.context.budget_bytes(),
self.failed.get(),
@@ -81,7 +82,8 @@ impl<'ctx> ChunkModules<'ctx> {
Err(error) => {
#[cfg(test)]
eprintln!(
"PUBLIC CUDA stage=gr-module-new allocated={} budget={} shared_failed={} context_poisoned={} error={error:?}",
"PUBLIC CUDA stage=gr-module-new allocated={} budget={} shared_failed={} \
context_poisoned={} error={error:?}",
self.context.allocated_bytes(),
self.context.budget_bytes(),
self.failed.get(),
@@ -51,6 +51,12 @@ impl CpuMissRows {
self.values
}
}
fn triplet_descriptors(source: &MoeRoutedSourceScope<'_, '_>, member: usize) -> Result<[MoeWeightDescriptor; 3]> {
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)?;
Ok([gate, up, down])
}
impl CpuMissWorkspace {
pub(crate) fn new(binding: &ModelBinding, workers: i32) -> Result<Self> {
Ok(Self { binding: binding.identity(), pool: CpuPool::new(workers).map_err(native_error)? })
@@ -72,9 +78,7 @@ impl CpuMissWorkspace {
}
source.validate_binding(binding).map_err(CpuMissError::Source)?;
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 [gate, up, down] = triplet_descriptors(source, member)?;
let (gu, dt) = validate_triplet([gate, up, down])?;
let [gate_bytes, up_bytes, down_bytes] = read_triplet_bytes(source, member, [gate, up, down])?;
let input = flatten_activations(activations)?;
@@ -3,6 +3,10 @@
#[allow(unused_imports)]
use super::*;
fn reserve_table<T>(table: &mut Vec<T>, count: usize) -> Result<()> {
table.try_reserve_exact(count).map_err(|_| Error::InputAllocation)
}
impl<'ctx> DenseWeightCache<'ctx> {
pub(in super::super) fn new_with_selected(
binding: &ModelBinding,
@@ -79,21 +83,28 @@ impl<'ctx> DenseWeightCache<'ctx> {
}
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)?;
self.reserve_layer_tables(n)?;
for layer in binding.ordered_layers() {
self.add_layer(binding, layer.index(), layer.kind())?;
}
self.add_gr(binding, GrRole::Final)?;
self.add_ple(binding)?;
self.check_mirror_bytes()?;
self.validate(binding)?;
Ok(())
}
fn reserve_layer_tables(&mut self, n: usize) -> Result<()> {
reserve_table(&mut self.gdn, n)?;
reserve_table(&mut self.gdn_mirrors, n)?;
reserve_table(&mut self.qsa, n)?;
reserve_table(&mut self.gr, n * 2 + 1)?;
reserve_table(&mut self.router, n)
}
fn check_mirror_bytes(&self) -> Result<()> {
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<()> {
@@ -127,6 +138,9 @@ impl<'ctx> DenseWeightCache<'ctx> {
for role in [GrRole::Attention(id), GrRole::Ffn(id)] {
self.add_gr(binding, role)?;
}
self.add_router_layer(binding, id)
}
fn add_router_layer(&mut self, binding: &ModelBinding, id: u32) -> Result<()> {
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())?;
@@ -79,23 +79,29 @@ impl<'ctx> DenseWeightCache<'ctx> {
}
Ok(conv)
}
fn add_ple_matrix(
&mut self,
binding: &ModelBinding,
weights: &PleWeights,
role: PleMatrixRole,
rows: usize,
bytes: usize,
) -> Result<usize> {
let matrix = binding.ple_matrix_full(weights, role).map_err(binding_error)?;
if matrix.rows() != rows || matrix.bytes().len() != bytes {
return Err(Error::InvalidDimension);
}
let index = self.add(matrix.bytes(), matrix.bytes().len())?;
drop(matrix);
Ok(index)
}
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
// charge as its former 160 tiles; per-row projection math is unchanged.
let key_matrix = binding.ple_matrix_full(&weights, PleMatrixRole::Key).map_err(binding_error)?;
if key_matrix.rows() != 10240 || key_matrix.bytes().len() != 52_428_800 {
return Err(Error::InvalidDimension);
}
let key = self.add(key_matrix.bytes(), key_matrix.bytes().len())?;
drop(key_matrix);
let key = self.add_ple_matrix(binding, &weights, PleMatrixRole::Key, 10240, 52_428_800)?;
// Value retains one whole immutable matrix; forty CTAs keep the original row arithmetic.
let value_matrix = binding.ple_matrix_full(&weights, PleMatrixRole::Value).map_err(binding_error)?;
if value_matrix.rows() != 2560 || value_matrix.bytes().len() != 2560 * 2560 * 2 {
return Err(Error::InvalidDimension);
}
let value = self.add(value_matrix.bytes(), value_matrix.bytes().len())?;
drop(value_matrix);
let value = self.add_ple_matrix(binding, &weights, PleMatrixRole::Value, 2560, 2560 * 2560 * 2)?;
let conv = Self::ple_conv_bytes(&weights)?;
let aux = [
self.add_f32(weights.norm_key())?,
@@ -107,17 +107,25 @@ impl<'ctx> DenseWeightCache<'ctx> {
if layer.kind() != BoundLayerKind::Gdn {
continue;
}
let resident = self.gdn(binding, layer.index())?;
let (alpha, alpha_kind) = self.gdn_matrix(resident, GdnMatrixRole::Alpha)?;
let (beta, beta_kind) = self.gdn_matrix(resident, GdnMatrixRole::Beta)?;
if alpha_kind != GdnMatrixKind::Bf16 || beta_kind != GdnMatrixKind::Bf16 {
return Err(Error::Unsupported(super::super::super::contract::Stage::Gdn));
}
let aux = self.gdn_aux(resident)?;
retained.push(OriginalVerifyGdnWeights { conv: aux[0], alpha, beta, dt: aux[1], a: aux[2], norm: aux[3] });
retained.push(self.original_verify_gdn_layer(binding, layer.index())?);
}
retained.try_into().map_err(|_| Error::InvalidDimension)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn original_verify_gdn_layer<'a>(
&'a self,
binding: &ModelBinding,
index: u32,
) -> Result<OriginalVerifyGdnWeights<'a, 'ctx>> {
let resident = self.gdn(binding, index)?;
let (alpha, alpha_kind) = self.gdn_matrix(resident, GdnMatrixRole::Alpha)?;
let (beta, beta_kind) = self.gdn_matrix(resident, GdnMatrixRole::Beta)?;
if alpha_kind != GdnMatrixKind::Bf16 || beta_kind != GdnMatrixKind::Bf16 {
return Err(Error::Unsupported(super::super::super::contract::Stage::Gdn));
}
let aux = self.gdn_aux(resident)?;
Ok(OriginalVerifyGdnWeights { conv: aux[0], alpha, beta, dt: aux[1], a: aux[2], norm: aux[3] })
}
/// The twelve QSA layers' indexer K norm gamma (128 F32 each), in layer order: the verifier's
/// indexer append re-normalizes each raw index key with exactly these cache allocations.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -364,7 +364,8 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
fn report_continuation(greedy_equal: bool, exact: &ChunkExact, head: bool, target: bool) {
eprintln!(
"resident MMQ model observation continuation_greedy_equal={} head_exact={} residual_exact={} target_exact={} draft_exact={} continued_head_exact={} continued_target_exact={}",
"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
);
}
@@ -72,6 +72,40 @@ fn release_owned(buffer: Option<DeviceBuffer<'_>>) -> Result<()> {
}
Ok(())
}
/// The host-side operands of one recurrence step.
struct RecurHost<'h> {
state: &'h [f32],
q: &'h [f32],
k: &'h [f32],
v: &'h [f32],
gate: &'h [f32],
beta: &'h [f32],
}
impl RecurHost<'_> {
fn validate(&self) -> Result<()> {
let operands = [
(self.state, STATE_ELEMENTS),
(self.q, 2048),
(self.k, 2048),
(self.v, VALUES),
(self.gate, 48),
(self.beta, 48),
];
for (values, count) in operands {
validate_values(values, count)?;
}
Ok(())
}
fn upload_all<'a>(&self, context: &'a Context<'_>) -> Result<[DeviceBuffer<'a>; 6]> {
let state = upload(context, self.state)?;
let q = upload(context, self.q)?;
let k = upload(context, self.k)?;
let v = upload(context, self.v)?;
let gate = upload(context, self.gate)?;
let beta = upload(context, self.beta)?;
Ok([state, q, k, v, gate, beta])
}
}
#[allow(clippy::too_many_arguments)] // Source-defined immutable state and six operands.
pub(super) fn recur(
context: &Context<'_>,
@@ -82,15 +116,9 @@ pub(super) fn recur(
gate: &[f32],
beta: &[f32],
) -> Result<CandidatePair> {
for (values, count) in [(state, STATE_ELEMENTS), (q, 2048), (k, 2048), (v, VALUES), (gate, 48), (beta, 48)] {
validate_values(values, count)?;
}
let state = upload(context, state)?;
let q = upload(context, q)?;
let k = upload(context, k)?;
let v = upload(context, v)?;
let gate = upload(context, gate)?;
let beta = upload(context, beta)?;
let host = RecurHost { state, q, k, v, gate, beta };
host.validate()?;
let [state, q, k, v, gate, beta] = host.upload_all(context)?;
let mut next = allocate(context, STATE_ELEMENTS)?;
let mut output = allocate(context, VALUES)?;
context.gdn_step_f32(&state, &q, &k, &v, &gate, &beta, &mut next, &mut output).map_err(driver_error)?;
@@ -107,21 +135,46 @@ pub(super) fn out_norm(
epsilon: f32,
resident: Option<&DeviceBuffer<'_>>,
) -> Result<Box<[f32]>> {
let (input, z) = upload_out_norm_inputs(context, input, z, gamma)?;
let owned = upload_unless_resident(context, resident, gamma)?;
let gamma = resident.or(owned.as_ref()).ok_or(Error::IdentityMismatch)?;
let mut output = allocate(context, VALUES)?;
context.gdn_out_norm_f32(&input, &z, gamma, &mut output, epsilon).map_err(driver_error)?;
let values = download(&output, VALUES)?;
release_with_owned([input, z, output], owned)?;
Ok(values)
}
/// Uploads `values` only when no resident device copy is supplied.
pub(super) fn upload_unless_resident<'a>(
context: &'a Context<'_>,
resident: Option<&DeviceBuffer<'_>>,
values: &[f32],
) -> Result<Option<DeviceBuffer<'a>>> {
if resident.is_none() { Ok(Some(upload(context, values)?)) } else { Ok(None) }
}
/// Releases the operand buffers, then the optionally uploaded constant.
pub(super) fn release_with_owned<const N: usize>(
buffers: [DeviceBuffer<'_>; N],
owned: Option<DeviceBuffer<'_>>,
) -> Result<()> {
release(buffers)?;
if let Some(v) = owned {
v.release().map_err(driver_error)?;
}
Ok(())
}
fn upload_out_norm_inputs<'a>(
context: &'a Context<'_>,
input: &[f32],
z: &[f32],
gamma: &[f32],
) -> Result<(DeviceBuffer<'a>, DeviceBuffer<'a>)> {
validate_values(input, VALUES)?;
validate_values(z, VALUES)?;
validate_values(gamma, 128)?;
let input = upload(context, input)?;
let z = upload(context, z)?;
let owned = if resident.is_none() { Some(upload(context, gamma)?) } else { None };
let gamma = resident.or(owned.as_ref()).ok_or(Error::IdentityMismatch)?;
let mut output = allocate(context, VALUES)?;
context.gdn_out_norm_f32(&input, &z, gamma, &mut output, epsilon).map_err(driver_error)?;
let values = download(&output, VALUES)?;
release([input, z, output])?;
if let Some(v) = owned {
v.release().map_err(driver_error)?;
}
Ok(values)
Ok((input, z))
}
pub(super) fn allocate<'a>(context: &'a Context<'_>, count: usize) -> Result<DeviceBuffer<'a>> {
context.allocate(count.checked_mul(4).ok_or(Error::Overflow)?).map_err(driver_error)
@@ -76,14 +76,7 @@ impl GdnStage {
// 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())?;
fn check_step_layer(binding: &ModelBinding, layer: LayerId, input: &ResidualReady) -> Result<()> {
let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?;
if expected != layer || input.identity().layer() != layer {
return Err(Error::IdentityMismatch);
@@ -92,11 +85,38 @@ impl GdnStage {
if descriptor.index() != layer.get() || descriptor.kind() != BoundLayerKind::Gdn {
return Err(Error::InvalidLayer);
}
Ok(())
}
fn validate_step_inputs(
binding: &ModelBinding,
layer: LayerId,
input: &ResidualReady,
prior: &GdnPrior,
txn: &mut QwenStepTxn,
) -> Result<()> {
txn.validate_binding(&binding.identity())?;
Self::check_step_layer(binding, layer, input)?;
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)
}
fn uncached_recurrence(
binding: &ModelBinding,
weights: &GdnWeights,
mixed: &[f32],
prior: &GdnPrior,
context: &Context<'_>,
) -> Result<(Box<[f32]>, CandidatePair)> {
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 pair = recur(context, prior.values(), &qk[..2048], &qk[2048..4096], &h[4096..], &gate, &beta)?;
Ok((history, pair))
}
fn step_uncached(
binding: &ModelBinding,
layer: LayerId,
@@ -106,13 +126,7 @@ impl GdnStage {
) -> 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 (history, (state, readout)) = Self::uncached_recurrence(binding, &weights, mixed, prior, context)?;
let z = project(context, binding, &weights, GdnMatrixRole::Z, mixed, None, None)?;
let normalized = out_norm(context, &readout, &z, weights.norm(), weights.epsilon(), None)?;
let output = project(context, binding, &weights, GdnMatrixRole::Out, &normalized, None, None)?;
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: fn project, fn dispatch_projection, fn project_retained, fn convolve, fn normalize_qk.
use super::gates_fn::{release_with_owned, upload_unless_resident};
#[allow(unused_imports)]
use super::*;
@@ -14,20 +15,26 @@ pub(super) fn project(
) -> Result<Box<[f32]>> {
let (c, _) = weights.shape(role);
validate_values(activation, c)?;
let operands = ProjectionOperands { binding, weights, role, activation, cache };
if let Some(source) = source {
return project_leased(context, binding, weights, role, activation, cache, source);
return project_leased(context, &operands, source);
}
project_uploaded(context, binding, weights, role, activation, cache)
project_uploaded(context, &operands)
}
/// What one GDN projection reads besides the context and the optional input lease.
struct ProjectionOperands<'a, 'c> {
binding: &'a ModelBinding,
weights: &'a GdnWeights,
role: GdnMatrixRole,
activation: &'a [f32],
cache: Option<&'a DenseWeightCache<'c>>,
}
fn project_leased(
context: &Context<'_>,
binding: &ModelBinding,
weights: &GdnWeights,
role: GdnMatrixRole,
activation: &[f32],
cache: Option<&DenseWeightCache<'_>>,
operands: &ProjectionOperands<'_, '_>,
source: &GdnInputLease<'_, '_, '_>,
) -> Result<Box<[f32]>> {
let ProjectionOperands { binding, weights, role, activation, cache } = *operands;
let (c, r) = weights.shape(role);
source.buffer(&binding.identity(), context, weights.layer(), role, activation)?;
let cache = cache.ok_or(Error::IdentityMismatch)?;
@@ -38,14 +45,8 @@ fn project_leased(
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]>> {
fn project_uploaded(context: &Context<'_>, operands: &ProjectionOperands<'_, '_>) -> Result<Box<[f32]>> {
let ProjectionOperands { binding, weights, role, activation, cache } = *operands;
let (c, r) = weights.shape(role);
let a = upload(context, activation)?;
let mut owned = None;
@@ -53,10 +54,7 @@ fn project_uploaded(
let entry = cache.gdn(binding, weights.layer())?;
cache.gdn_matrix(entry, role)?
} else {
let block = binding.gdn_matrix_block(weights, role, 0, r).map_err(binding_error)?;
let mut buffer = context.allocate(block.bytes().len()).map_err(driver_error)?;
buffer.copy_from(block.bytes()).map_err(driver_error)?;
let kind = block.kind();
let (buffer, kind) = upload_matrix_block(context, binding, weights, (role, r))?;
owned = Some(buffer);
(owned.as_ref().ok_or(Error::IdentityMismatch)?, kind)
};
@@ -64,6 +62,17 @@ fn project_uploaded(
dispatch_projection(context, matrix, &a, &mut output, kind, c, r).map_err(driver_error)?;
release_projection(output, owned, a, r)
}
fn upload_matrix_block<'a>(
context: &'a Context<'_>,
binding: &ModelBinding,
weights: &GdnWeights,
(role, rows): (GdnMatrixRole, usize),
) -> Result<(DeviceBuffer<'a>, GdnMatrixKind)> {
let block = binding.gdn_matrix_block(weights, role, 0, rows).map_err(binding_error)?;
let mut buffer = context.allocate(block.bytes().len()).map_err(driver_error)?;
buffer.copy_from(block.bytes()).map_err(driver_error)?;
Ok((buffer, block.kind()))
}
fn release_projection(
output: DeviceBuffer<'_>,
owned: Option<DeviceBuffer<'_>>,
@@ -159,25 +168,43 @@ pub(super) fn convolve(
weights: &[f32],
resident: Option<&DeviceBuffer<'_>>,
) -> Result<CandidatePair> {
let (hist, x) = upload_convolution_inputs(context, history, input, weights)?;
let owned = upload_unless_resident(context, resident, weights)?;
let w = resident.or(owned.as_ref()).ok_or(Error::IdentityMismatch)?;
let [mut next, mut raw, mut h] = allocate_convolution_outputs(context)?;
context.gdn_conv_silu_f32(&hist, &x, w, &mut next, &mut raw, &mut h).map_err(driver_error)?;
let values = download_convolution(&next, &raw, &h)?;
release_with_owned([hist, x, next, raw, h], owned)?;
Ok(values)
}
fn upload_convolution_inputs<'a>(
context: &'a Context<'_>,
history: &[f32],
input: &[f32],
weights: &[f32],
) -> Result<(DeviceBuffer<'a>, DeviceBuffer<'a>)> {
validate_values(history, HISTORY_ELEMENTS)?;
validate_values(input, CHANNELS)?;
validate_values(weights, 4 * CHANNELS)?;
let hist = upload(context, history)?;
let x = upload(context, input)?;
let owned = if resident.is_none() { Some(upload(context, weights)?) } else { None };
let w = resident.or(owned.as_ref()).ok_or(Error::IdentityMismatch)?;
let mut next = allocate(context, HISTORY_ELEMENTS)?;
let mut raw = allocate(context, CHANNELS)?;
let mut h = allocate(context, CHANNELS)?;
context.gdn_conv_silu_f32(&hist, &x, w, &mut next, &mut raw, &mut h).map_err(driver_error)?;
Ok((hist, x))
}
fn allocate_convolution_outputs<'a>(context: &'a Context<'_>) -> Result<[DeviceBuffer<'a>; 3]> {
let next = allocate(context, HISTORY_ELEMENTS)?;
let raw = allocate(context, CHANNELS)?;
let h = allocate(context, CHANNELS)?;
Ok([next, raw, h])
}
fn download_convolution(
next: &DeviceBuffer<'_>,
raw: &DeviceBuffer<'_>,
h: &DeviceBuffer<'_>,
) -> Result<CandidatePair> {
// Validate raw too: a later SiLU must never mask a failed convolution.
let _raw = download(&raw, CHANNELS)?;
let next_values = download(&next, HISTORY_ELEMENTS)?;
let h_values = download(&h, CHANNELS)?;
release([hist, x, next, raw, h])?;
if let Some(w) = owned {
w.release().map_err(driver_error)?;
}
let _raw = download(raw, CHANNELS)?;
let next_values = download(next, HISTORY_ELEMENTS)?;
let h_values = download(h, CHANNELS)?;
Ok((next_values, h_values))
}
pub(super) fn normalize_qk(context: &Context<'_>, h: &[f32], epsilon: f32) -> Result<Box<[f32]>> {
@@ -204,6 +204,27 @@ impl<'ctx> CachedGdn<'_, '_, '_, 'ctx> {
}
}
fn chain_output_role(role: GdnMatrixRole) -> Result<chain::Role> {
Ok(match role {
GdnMatrixRole::Qkv => chain::Role::Qkv,
GdnMatrixRole::Alpha => chain::Role::Alpha,
GdnMatrixRole::Beta => chain::Role::BetaRaw,
GdnMatrixRole::Z => chain::Role::Z,
GdnMatrixRole::Out => return Err(Error::IdentityMismatch),
})
}
fn checked_gdn_matrix<'c, 'ctx>(
cache: &'c DenseWeightCache<'ctx>,
binding: &ModelBinding,
weights: &GdnWeights,
role: GdnMatrixRole,
) -> Result<(&'c DeviceBuffer<'ctx>, GdnMatrixKind)> {
let resident = cache.gdn(binding, weights.layer())?;
if !std::ptr::eq(resident.weights.as_ref(), weights) {
return Err(Error::IdentityMismatch);
}
cache.gdn_matrix(resident, role)
}
#[allow(clippy::too_many_arguments)] // Explicit closed provider and current input-lease checks.
pub(super) fn project_chain_input<'ctx>(
chain: &mut chain::Chain<'ctx>,
@@ -215,21 +236,11 @@ pub(super) fn project_chain_input<'ctx>(
activation: &[f32],
cache: &DenseWeightCache<'ctx>,
) -> Result<chain::Product> {
let output_role = match role {
GdnMatrixRole::Qkv => chain::Role::Qkv,
GdnMatrixRole::Alpha => chain::Role::Alpha,
GdnMatrixRole::Beta => chain::Role::BetaRaw,
GdnMatrixRole::Z => chain::Role::Z,
GdnMatrixRole::Out => return Err(Error::IdentityMismatch),
};
let output_role = chain_output_role(role)?;
let (columns, rows) = weights.shape(role);
validate_values(activation, columns)?;
let activation = source.buffer(&binding.identity(), context, weights.layer(), role, activation)?;
let resident = cache.gdn(binding, weights.layer())?;
if !std::ptr::eq(resident.weights.as_ref(), weights) {
return Err(Error::IdentityMismatch);
}
let (matrix, kind) = cache.gdn_matrix(resident, role)?;
let (matrix, kind) = checked_gdn_matrix(cache, binding, weights, role)?;
let product = chain.project(matrix, kind, activation, output_role)?;
validate_values(product.values(), rows)?;
Ok(product)
@@ -93,15 +93,22 @@ impl<'ctx> Chain<'ctx> {
return Err(Error::IdentityMismatch);
}
validate_values(&product.values, role.count())?;
self.check_returning_qk(product.slot, role)?;
self.slot_buffer(product.slot, role)
}
fn check_returning_qk(&self, slot: usize, role: Role) -> Result<()> {
if let Some(returning) = &self.qk_return
&& returning.slot == product.slot
&& returning.slot == slot
{
if role != Role::Qk || returning.row != self.identity || !Rc::ptr_eq(&returning.epoch, &self.epoch) {
return Err(Error::IdentityMismatch);
}
returning.owner.validate(self.context, &self.binding, &self.failed)?;
}
let buffer = self.buffers.get(product.slot).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?;
Ok(())
}
fn slot_buffer(&self, slot: usize, role: Role) -> Result<&DeviceBuffer<'ctx>> {
let buffer = self.buffers.get(slot).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?;
if buffer.len() != role.count() * 4 {
return Err(Error::InvalidDimension);
}
@@ -119,19 +126,8 @@ impl<'ctx> Chain<'ctx> {
if product_role != role || !Rc::ptr_eq(&self.epoch, epoch) {
return Err(Error::IdentityMismatch);
}
if let Some(returning) = &self.qk_return
&& returning.slot == slot
{
if role != Role::Qk || returning.row != self.identity || !Rc::ptr_eq(&returning.epoch, &self.epoch) {
return Err(Error::IdentityMismatch);
}
returning.owner.validate(self.context, &self.binding, &self.failed)?;
}
let buffer = self.buffers.get(slot).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?;
if buffer.len() != role.count() * 4 {
return Err(Error::InvalidDimension);
}
Ok(buffer)
self.check_returning_qk(slot, role)?;
self.slot_buffer(slot, role)
}
pub(in super::super::super) fn device_buffer(
&self,
@@ -4,6 +4,15 @@
use super::*;
use leleka_cuda_driver::{GdnRowCompletion, GdnRowPrefix};
fn check_distinct_slots(slots: &[usize; 4]) -> Result<()> {
for (index, slot) in slots.iter().enumerate() {
if slots[..index].contains(slot) {
return Err(Error::IdentityMismatch);
}
}
Ok(())
}
// The eight chain slots one queued row writes.
struct RowSlots {
raw: DeviceOperand,
@@ -179,25 +188,28 @@ impl<'ctx> Chain<'ctx> {
self.release_in_scope(&slots)?;
Ok(RecurrenceBorrow { row: row.readout_key(), scope: Rc::clone(&self.epoch), chain: self, products })
}
fn validate_scalar_txn(
&self,
prior: &super::super::super::GdnPrior,
txn: &super::super::super::QwenStepTxn<'_, '_>,
) -> Result<()> {
txn.validate_binding(&self.binding)?;
txn.validate_input(self.identity.token(), self.identity.position())?;
txn.validate_gdn_prior(prior, self.identity.layer())?;
self.validate(txn.cuda_context()?, &self.binding, self.identity)
}
pub(in super::super::super) fn borrow_scalar_recurrence<'chain>(
&'chain mut self,
prior: &super::super::super::GdnPrior,
txn: &super::super::super::QwenStepTxn<'_, '_>,
products: [&'chain Product; 4],
) -> Result<ScalarRecurrenceBorrow<'chain, 'ctx>> {
txn.validate_binding(&self.binding)?;
txn.validate_input(self.identity.token(), self.identity.position())?;
txn.validate_gdn_prior(prior, self.identity.layer())?;
self.validate(txn.cuda_context()?, &self.binding, self.identity)?;
self.validate_scalar_txn(prior, txn)?;
for (product, role) in products.into_iter().zip([Role::Qk, Role::H, Role::Gate, Role::Beta]) {
self.buffer(product, role)?;
}
let slots = products.map(|product| product.slot);
for (index, slot) in slots.iter().enumerate() {
if slots[..index].contains(slot) {
return Err(Error::IdentityMismatch);
}
}
check_distinct_slots(&slots)?;
// All witnesses and current producer identities precede any cleanup.
self.release_in_scope(&slots)?;
Ok(ScalarRecurrenceBorrow { prior: prior.clone(), scope: Rc::clone(&self.epoch), chain: self, products })
@@ -188,6 +188,13 @@ impl<'ctx> Chain<'ctx> {
}
Ok(operand)
}
fn check_fused_row_inputs(&self, inputs: &FusedInputs<'_, 'ctx>) -> Result<()> {
self.check()?;
if self.verification_pool.is_none() {
return Err(Error::IdentityMismatch);
}
validate_values(inputs.prior_history, Role::NextHistory.count())
}
pub(in crate::qwen_forward::gdn) fn run_fused_verification_row(
&mut self,
program: &mut GdnFusedT1<'ctx>,
@@ -195,11 +202,7 @@ impl<'ctx> Chain<'ctx> {
next_state: &DeviceBuffer<'ctx>,
inputs: FusedInputs<'_, 'ctx>,
) -> Result<FusedRow> {
self.check()?;
if self.verification_pool.is_none() {
return Err(Error::IdentityMismatch);
}
validate_values(inputs.prior_history, Role::NextHistory.count())?;
self.check_fused_row_inputs(&inputs)?;
// Product allocations first: all of them are chain slots, so any later refusal is freed by the ordinary
// drain. The candidate history slot is seeded with the canonical prior (the Original updates it in place).
let slots = self.reserve_fused_slots(Self::reserve_fused_verified)?;
@@ -240,14 +240,7 @@ impl<'ctx> GdnChunkDevice<'ctx> {
}
}
pub(in super::super::super) fn finish_row(&mut self, row: GdnChunkRow, history: Box<[f32]>) -> Result<ChunkEdge> {
if self.failed.get() {
return Err(Error::CudaExecution);
}
if !self.valid || !self.inflight {
return Err(Error::IdentityMismatch);
}
row.validate(&self.start, self.cursor, &self.start.binding())?;
validate_values(&history, HISTORY_ELEMENTS)?;
self.check_finish_row(&row, &history)?;
if let Some((workspace, lease)) = &self.verification {
let proof = workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.record(
lease,
@@ -256,16 +249,27 @@ impl<'ctx> GdnChunkDevice<'ctx> {
history,
)?;
self.verified_rows.push(proof.clone());
std::mem::swap(&mut self.state, &mut self.next);
self.history = None;
self.cursor = self.cursor.checked_add(1).ok_or(Error::Overflow)?;
self.inflight = false;
self.advance_row(None)?;
return Ok(ChunkEdge { row, verified: Some(proof) });
}
std::mem::swap(&mut self.state, &mut self.next);
self.history = Some(history);
self.cursor = self.cursor.checked_add(1).ok_or(Error::Overflow)?;
self.inflight = false;
self.advance_row(Some(history))?;
Ok(ChunkEdge { row, verified: None })
}
fn check_finish_row(&self, row: &GdnChunkRow, history: &[f32]) -> Result<()> {
if self.failed.get() {
return Err(Error::CudaExecution);
}
if !self.valid || !self.inflight {
return Err(Error::IdentityMismatch);
}
row.validate(&self.start, self.cursor, &self.start.binding())?;
validate_values(history, HISTORY_ELEMENTS)
}
fn advance_row(&mut self, history: Option<Box<[f32]>>) -> Result<()> {
std::mem::swap(&mut self.state, &mut self.next);
self.history = history;
self.cursor = self.cursor.checked_add(1).ok_or(Error::Overflow)?;
self.inflight = false;
Ok(())
}
}