STRA-338 size: model-format: qwen4exp expert capture, expert banks, file source and memory probe split into helpers (fn_lines 95->30, complexity 39->10)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 14:04:31 +01:00
parent 56131aaa28
commit 8a2350f0a8
9 changed files with 577 additions and 388 deletions
@@ -70,6 +70,14 @@ const PLE_LAYER_TENSORS: [LayerEntry; 6] = [
(LayerRole::PleValue, "ple_value.weight", &[2560, 2560], Some(30)),
];
/// The gate, up and down routed-expert tensors of every layer, in layer order.
pub(super) fn expert_roles() -> impl Iterator<Item = TensorRole> {
(0..48).flat_map(|layer| {
[LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts]
.map(|role| TensorRole::Layer { layer, role })
})
}
fn expected_tensor(role: TensorRole, name: String, dimensions: &[u64], shard: u8, kind: Option<u32>) -> ExpectedTensor {
ExpectedTensor { role, name, dimensions: dimensions.to_vec(), shard, kind }
}
@@ -13,10 +13,8 @@ pub(super) fn capture_admit(capacity: usize, future: usize, available: usize) ->
Ok(())
}
pub(super) fn provisional_descriptor(
index: &TensorIndex,
role: TensorRole,
) -> Result<BankDescriptor, ResidentExpertSourceError> {
/// The GGUF name of the routed-expert tensor a role stands for.
fn expert_tensor_name(role: TensorRole) -> Result<String, ResidentExpertSourceError> {
let TensorRole::Layer { layer, role: layer_role } = role else {
return Err(ResidentExpertSourceError::Geometry);
};
@@ -26,7 +24,14 @@ pub(super) fn provisional_descriptor(
LayerRole::FfnDownExperts => "ffn_down_exps.weight",
_ => return Err(ResidentExpertSourceError::Geometry),
};
let name = format!("blk.{layer}.{suffix}");
Ok(format!("blk.{layer}.{suffix}"))
}
pub(super) fn provisional_descriptor(
index: &TensorIndex,
role: TensorRole,
) -> Result<BankDescriptor, ResidentExpertSourceError> {
let name = expert_tensor_name(role)?;
let (tensor_number, tensor) = index
.tensors
.iter()
@@ -42,17 +42,47 @@ impl ProvisionalExpertSource {
index: &TensorIndex,
retained_kar: Option<&File>,
) -> Result<(), ResidentExpertSourceError> {
// Observation ONLY: seals/SHA/CRC stay at the original later KAR gate.
// The keeper's already retained memfd pages are in MemAvailable, so its
// 55 GiB is not also charged as a future allocation.
let observed_kar = retained_kar
.and_then(|file| file.metadata().ok())
.filter(|metadata| metadata.is_file() && metadata.len() == RETAINED_KAR_BYTES)
.ok_or(ResidentExpertSourceError::MemoryAdmission)?;
let _ = observed_kar;
check_retained_kar(retained_kar)?;
if index.summary.file_size != PINNED_IDENTITIES[0].0 || index.tensors.len() != 1223 {
return Err(ResidentExpertSourceError::Geometry);
}
self.reserve_tables()?;
// First geometry pass prevents allocation before complete closed layout.
self.add_source_bytes(index)?;
let planned = self.charged.checked_add(self.source_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
self.observed = memory_available()?;
capture_admit(planned, FUTURE_OWNERS, self.observed)?;
let mut remaining = self.source_bytes;
for role in expert_roles() {
let descriptor = provisional_descriptor(index, role)?;
self.check_disjoint(&descriptor)?;
remaining = self.allocate_cell(descriptor, remaining)?;
}
capture_admit(0, FUTURE_OWNERS, memory_available()?)?;
Ok(())
}
/// First geometry pass: the bytes of every expert tensor, summed into `source_bytes`.
pub(super) fn add_source_bytes(&mut self, index: &TensorIndex) -> Result<(), ResidentExpertSourceError> {
for role in expert_roles() {
let descriptor = provisional_descriptor(index, role)?;
self.source_bytes =
self.source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?;
}
Ok(())
}
/// Adds an allocation to the charged total, which must stay within the source cap.
pub(super) fn charge(&mut self, charged_bytes: usize) -> Result<(), ResidentExpertSourceError> {
self.charged = self.charged.checked_add(charged_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
if self.charged as u64 > SOURCE_CAP {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
Ok(())
}
/// Room for the cell and bank tables, charged with the size of the capture itself.
fn reserve_tables(&mut self) -> Result<(), ResidentExpertSourceError> {
self.cells.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?;
self.banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?;
self.charged = self
@@ -62,83 +92,80 @@ impl ProvisionalExpertSource {
.and_then(|n| n.checked_add(self.banks.capacity().checked_mul(size_of::<Bank>())?))
.and_then(|n| n.checked_add(size_of::<Self>() + size_of::<ResidentExpertBank>()))
.ok_or(ResidentExpertSourceError::MemoryAdmission)?;
// First geometry pass prevents allocation before complete closed layout.
for layer in 0..48 {
for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] {
let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?;
self.source_bytes =
self.source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?;
}
}
let planned = self.charged.checked_add(self.source_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
self.observed = memory_available()?;
capture_admit(planned, FUTURE_OWNERS, self.observed)?;
let mut remaining = self.source_bytes;
for layer in 0..48 {
for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] {
let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?;
for previous in &self.cells {
let left = previous.descriptor.absolute_start;
let right = left + previous.descriptor.bytes as u64;
let start = descriptor.absolute_start;
let end = start + descriptor.bytes as u64;
if left < end && start < right {
return Err(ResidentExpertSourceError::Geometry);
}
}
capture_admit(remaining, FUTURE_OWNERS, memory_available()?)?;
let mut bytes = Vec::new();
bytes.try_reserve_exact(descriptor.bytes).map_err(|_| ResidentExpertSourceError::Allocation)?;
let charged_bytes = bytes.capacity();
self.charged =
self.charged.checked_add(charged_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
if self.charged as u64 > SOURCE_CAP {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
capture_admit(
remaining
.checked_sub(descriptor.bytes)
.and_then(|n| n.checked_add(charged_bytes))
.ok_or(ResidentExpertSourceError::MemoryAdmission)?,
FUTURE_OWNERS,
memory_available()?,
)?;
bytes.resize(descriptor.bytes, 0);
self.cells.push(CapturedTensor {
descriptor,
bytes: bytes.into_boxed_slice(),
charged_bytes,
covered: 0,
});
remaining -= descriptor.bytes;
}
}
capture_admit(0, FUTURE_OWNERS, memory_available()?)?;
Ok(())
}
pub(crate) fn observe(&mut self, position: u64, chunk: &[u8]) {
if let Some(incremental) = &mut self.incremental {
#[cfg(test)]
let available = incremental.test_available;
let result = incremental.observe_inner(position, chunk, || {
#[cfg(test)]
if let Some(available) = available {
return Ok(available);
}
memory_available()
});
if let Err(error) = result {
self.fail(error);
/// The descriptor's file range overlaps none of the cells captured so far.
fn check_disjoint(&self, descriptor: &BankDescriptor) -> Result<(), ResidentExpertSourceError> {
for previous in &self.cells {
let left = previous.descriptor.absolute_start;
let right = left + previous.descriptor.bytes as u64;
let start = descriptor.absolute_start;
let end = start + descriptor.bytes as u64;
if left < end && start < right {
return Err(ResidentExpertSourceError::Geometry);
}
}
Ok(())
}
/// Admits, allocates and charges the cell of one tensor; returns the bytes still to allocate after it.
fn allocate_cell(
&mut self,
descriptor: BankDescriptor,
remaining: usize,
) -> Result<usize, ResidentExpertSourceError> {
capture_admit(remaining, FUTURE_OWNERS, memory_available()?)?;
let mut bytes = Vec::new();
bytes.try_reserve_exact(descriptor.bytes).map_err(|_| ResidentExpertSourceError::Allocation)?;
let charged_bytes = bytes.capacity();
self.charge(charged_bytes)?;
capture_admit(
remaining
.checked_sub(descriptor.bytes)
.and_then(|n| n.checked_add(charged_bytes))
.ok_or(ResidentExpertSourceError::MemoryAdmission)?,
FUTURE_OWNERS,
memory_available()?,
)?;
bytes.resize(descriptor.bytes, 0);
self.cells.push(CapturedTensor { descriptor, bytes: bytes.into_boxed_slice(), charged_bytes, covered: 0 });
Ok(remaining - descriptor.bytes)
}
pub(crate) fn observe(&mut self, position: u64, chunk: &[u8]) {
if self.incremental.is_some() {
self.observe_incremental(position, chunk);
return;
}
if self.error.is_some() {
return;
}
let Some(end) = position.checked_add(chunk.len() as u64) else {
self.fail(ResidentExpertSourceError::Geometry);
if let Err(error) = self.copy_chunk(position, chunk) {
self.fail(error);
}
}
fn observe_incremental(&mut self, position: u64, chunk: &[u8]) {
let Some(incremental) = &mut self.incremental else {
return;
};
#[cfg(test)]
let available = incremental.test_available;
let result = incremental.observe_inner(position, chunk, || {
#[cfg(test)]
if let Some(available) = available {
return Ok(available);
}
memory_available()
});
if let Err(error) = result {
self.fail(error);
}
}
/// Copies the part of the chunk that lies inside each cell; the cells must fill up in file order.
fn copy_chunk(&mut self, position: u64, chunk: &[u8]) -> Result<(), ResidentExpertSourceError> {
let end = position.checked_add(chunk.len() as u64).ok_or(ResidentExpertSourceError::Geometry)?;
for cell in &mut self.cells {
let start = cell.descriptor.absolute_start;
let bank_end = start + cell.descriptor.bytes as u64;
@@ -150,13 +177,13 @@ impl ProvisionalExpertSource {
let offset = (left - start) as usize;
let count = (right - left) as usize;
if offset != cell.covered {
self.fail(ResidentExpertSourceError::Geometry);
return;
return Err(ResidentExpertSourceError::Geometry);
}
let source = (left - position) as usize;
cell.bytes[offset..offset + count].copy_from_slice(&chunk[source..source + count]);
cell.covered += count;
}
Ok(())
}
pub(crate) fn bind_verified(&mut self, source: &mut VerifiedGgufFile) {
if self.error.is_none()
@@ -184,3 +211,14 @@ impl ProvisionalExpertSource {
}
}
}
/// Observation ONLY: seals/SHA/CRC stay at the original later KAR gate.
/// The keeper's already retained memfd pages are in MemAvailable, so its
/// 55 GiB is not also charged as a future allocation.
pub(super) fn check_retained_kar(retained_kar: Option<&File>) -> Result<(), ResidentExpertSourceError> {
retained_kar
.and_then(|file| file.metadata().ok())
.filter(|metadata| metadata.is_file() && metadata.len() == RETAINED_KAR_BYTES)
.map(|_| ())
.ok_or(ResidentExpertSourceError::MemoryAdmission)
}
@@ -16,17 +16,28 @@ impl ProvisionalExpertSource {
index: &TensorIndex,
retained_kar: Option<&File>,
) -> Result<(), ResidentExpertSourceError> {
// Observation ONLY: seals/SHA/CRC stay at the original later KAR gate.
// The keeper's already retained memfd pages are in MemAvailable, so its
// 55 GiB is not also charged as a future allocation.
let observed_kar = retained_kar
.and_then(|file| file.metadata().ok())
.filter(|metadata| metadata.is_file() && metadata.len() == RETAINED_KAR_BYTES)
.ok_or(ResidentExpertSourceError::MemoryAdmission)?;
let _ = observed_kar;
check_retained_kar(retained_kar)?;
if index.summary.file_size != PINNED_IDENTITIES[0].0 || index.tensors.len() != 1223 {
return Err(ResidentExpertSourceError::Geometry);
}
self.reserve_incremental_tables()?;
// First geometry pass prevents allocation before complete closed layout.
self.add_source_bytes(index)?;
let planned = self.charged.checked_add(self.source_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
self.observed = memory_available()?;
capture_admit(planned, FUTURE_OWNERS, self.observed)?;
let mut remaining = self.source_bytes;
for role in expert_roles() {
let descriptor = provisional_descriptor(index, role)?;
self.check_incremental_disjoint(&descriptor)?;
remaining = self.reserve_incremental_cell(descriptor, remaining)?;
}
capture_admit(self.charged, FUTURE_OWNERS, memory_available()?)?;
Ok(())
}
/// Room for the cell, bank and incremental tables, charged with the size of the capture itself.
fn reserve_incremental_tables(&mut self) -> Result<(), ResidentExpertSourceError> {
self.cells.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?;
self.banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?;
let mut incremental_cells = Vec::new();
@@ -46,81 +57,53 @@ impl ProvisionalExpertSource {
})
.and_then(|n| n.checked_add(size_of::<Self>() + size_of::<ResidentExpertBank>()))
.ok_or(ResidentExpertSourceError::MemoryAdmission)?;
// First geometry pass prevents allocation before complete closed layout.
for layer in 0..48 {
for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] {
let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?;
self.source_bytes =
self.source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?;
}
}
let planned = self.charged.checked_add(self.source_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
self.observed = memory_available()?;
capture_admit(planned, FUTURE_OWNERS, self.observed)?;
let mut remaining = self.source_bytes;
for layer in 0..48 {
for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] {
let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?;
for previous in &self.incremental.as_ref().ok_or(ResidentExpertSourceError::Geometry)?.cells {
let left = previous.descriptor.absolute_start;
let right = left + previous.descriptor.bytes as u64;
let start = descriptor.absolute_start;
let end = start + descriptor.bytes as u64;
if left < end && start < right {
return Err(ResidentExpertSourceError::Geometry);
}
}
// Reserved but untouched pages remain a full commitment. Unlike the
// original zero-fill, reserve does not make them resident yet.
let committed =
self.charged.checked_add(remaining).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
capture_admit(committed, FUTURE_OWNERS, memory_available()?)?;
let mut bytes = Vec::new();
bytes.try_reserve_exact(descriptor.bytes).map_err(|_| ResidentExpertSourceError::Allocation)?;
let charged_bytes = bytes.capacity();
self.charged =
self.charged.checked_add(charged_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
if self.charged as u64 > SOURCE_CAP {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
capture_admit(
self.charged
.checked_add(
remaining
.checked_sub(descriptor.bytes)
.ok_or(ResidentExpertSourceError::MemoryAdmission)?,
)
.ok_or(ResidentExpertSourceError::MemoryAdmission)?,
FUTURE_OWNERS,
memory_available()?,
)?;
self.incremental.as_mut().ok_or(ResidentExpertSourceError::Geometry)?.cells.push(IncrementalTensor {
descriptor,
bytes,
charged_bytes,
covered: 0,
});
remaining -= descriptor.bytes;
}
}
capture_admit(self.charged, FUTURE_OWNERS, memory_available()?)?;
Ok(())
}
pub(super) fn finish_incremental(&mut self, source: &VerifiedGgufFile) -> Result<(), ResidentExpertSourceError> {
let incremental = self.incremental.as_ref().ok_or(ResidentExpertSourceError::Geometry)?;
if !self.cells.is_empty() || incremental.cells.len() != BANKS || self.cells.capacity() < incremental.cells.len()
{
return Err(ResidentExpertSourceError::Geometry);
}
for cell in &incremental.cells {
if cell.covered != cell.descriptor.bytes
|| cell.bytes.len() != cell.descriptor.bytes
|| cell.bytes.capacity() != cell.charged_bytes
|| provisional_descriptor(source.index(), cell.descriptor.role)? != cell.descriptor
{
/// The descriptor's file range overlaps none of the cells reserved so far.
fn check_incremental_disjoint(&self, descriptor: &BankDescriptor) -> Result<(), ResidentExpertSourceError> {
for previous in &self.incremental.as_ref().ok_or(ResidentExpertSourceError::Geometry)?.cells {
let left = previous.descriptor.absolute_start;
let right = left + previous.descriptor.bytes as u64;
let start = descriptor.absolute_start;
let end = start + descriptor.bytes as u64;
if left < end && start < right {
return Err(ResidentExpertSourceError::Geometry);
}
}
Ok(())
}
/// Admits, reserves and charges the cell of one tensor; returns the bytes still to reserve after it.
fn reserve_incremental_cell(
&mut self,
descriptor: BankDescriptor,
remaining: usize,
) -> Result<usize, ResidentExpertSourceError> {
// Reserved but untouched pages remain a full commitment. Unlike the
// original zero-fill, reserve does not make them resident yet.
let committed = self.charged.checked_add(remaining).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
capture_admit(committed, FUTURE_OWNERS, memory_available()?)?;
let mut bytes = Vec::new();
bytes.try_reserve_exact(descriptor.bytes).map_err(|_| ResidentExpertSourceError::Allocation)?;
let charged_bytes = bytes.capacity();
self.charge(charged_bytes)?;
let rest = self.admit_rest(remaining, descriptor.bytes)?;
let cells = &mut self.incremental.as_mut().ok_or(ResidentExpertSourceError::Geometry)?.cells;
cells.push(IncrementalTensor { descriptor, bytes, charged_bytes, covered: 0 });
Ok(rest)
}
/// The bytes left to reserve after `taken`, once the charged total plus them is admitted.
fn admit_rest(&self, remaining: usize, taken: usize) -> Result<usize, ResidentExpertSourceError> {
let rest = remaining.checked_sub(taken).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
let total = self.charged.checked_add(rest).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
capture_admit(total, FUTURE_OWNERS, memory_available()?)?;
Ok(rest)
}
pub(super) fn finish_incremental(&mut self, source: &VerifiedGgufFile) -> Result<(), ResidentExpertSourceError> {
self.check_incremental_complete(source)?;
// Original whole SHA/strict index completed before bind calls this.
// Move only fully initialized spans into the unchanged opaque gate.
let incremental = self.incremental.take().ok_or(ResidentExpertSourceError::Geometry)?;
@@ -134,6 +117,31 @@ impl ProvisionalExpertSource {
}
Ok(())
}
/// Every incremental cell is fully written, exactly as large as charged, and still the source's descriptor.
fn check_incremental_complete(&self, source: &VerifiedGgufFile) -> Result<(), ResidentExpertSourceError> {
let incremental = self.incremental.as_ref().ok_or(ResidentExpertSourceError::Geometry)?;
if !self.cells.is_empty() || incremental.cells.len() != BANKS || self.cells.capacity() < incremental.cells.len()
{
return Err(ResidentExpertSourceError::Geometry);
}
for cell in &incremental.cells {
if !incremental_cell_complete(cell, source)? {
return Err(ResidentExpertSourceError::Geometry);
}
}
Ok(())
}
}
fn incremental_cell_complete(
cell: &IncrementalTensor,
source: &VerifiedGgufFile,
) -> Result<bool, ResidentExpertSourceError> {
Ok(cell.covered == cell.descriptor.bytes
&& cell.bytes.len() == cell.descriptor.bytes
&& cell.bytes.capacity() == cell.charged_bytes
&& provisional_descriptor(source.index(), cell.descriptor.role)? == cell.descriptor)
}
impl Qwen4ExpArtifact {
/// Separately selected incremental capture; original prezeroed API remains.
@@ -19,6 +19,16 @@ impl Qwen4ExpArtifact {
&mut self,
mut capture: ProvisionalExpertSource,
) -> Result<ResidentExpertSourceReport, ResidentExpertSourceError> {
self.check_capture_admissible(&mut capture)?;
let identity = self.revalidate_capture(&capture)?;
let observed = charge_retention(&mut capture)?;
self.mint_banks(&mut capture, identity)?;
capture_admit(0, 0, memory_available()?)?;
Ok(self.publish_resident_experts(capture, observed))
}
/// The model is not already enabled and fits the closed layout, and the capture ended without error.
fn check_capture_admissible(&self, capture: &mut ProvisionalExpertSource) -> Result<(), ResidentExpertSourceError> {
if self.resident_experts.is_some() {
return Err(ResidentExpertSourceError::AlreadyEnabled);
}
@@ -31,40 +41,55 @@ impl Qwen4ExpArtifact {
if capture.cells.len() != BANKS || !capture.banks.is_empty() || capture.charged as u64 > SOURCE_CAP {
return Err(ResidentExpertSourceError::Geometry);
}
Ok(())
}
/// Revalidate EVERY bound descriptor before minting even the first final
/// tensor. Full finite admission still happens at each selected role.
fn revalidate_capture(&mut self, capture: &ProvisionalExpertSource) -> Result<u64, ResidentExpertSourceError> {
let identity = capture.source.ok_or(ResidentExpertSourceError::Geometry)?;
self.shards[0]
.validate_capture_identity(identity)
.map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?;
// Revalidate EVERY bound descriptor before minting even the first final
// tensor. Full finite admission still happens at each selected role.
for (number, cell) in capture.cells.iter().enumerate() {
let resolved = self.roles.get(&cell.descriptor.role).ok_or(ResidentExpertSourceError::Geometry)?;
if slot(cell.descriptor.role).map_err(ResidentExpertSourceError::Read)? != number
|| checked_descriptor(cell.descriptor.role, resolved)? != cell.descriptor
|| cell.covered != cell.bytes.len()
{
return Err(ResidentExpertSourceError::Geometry);
}
self.shards[0]
.stream_tensor(cell.descriptor.tensor_number, 0, 0, |_| Ok(()))
.map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?;
self.revalidate_cell(number, cell)?;
}
// Existing captured Boxes stay in place. Charge only the new small
// shared owners/directory before any wrapping/publication.
let retention = retention_metadata_bytes()?;
capture.charged = capture.charged.checked_add(retention).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
if capture.charged as u64 > SOURCE_CAP {
return Err(ResidentExpertSourceError::MemoryAdmission);
Ok(identity)
}
fn revalidate_cell(&mut self, number: usize, cell: &CapturedTensor) -> Result<(), ResidentExpertSourceError> {
let resolved = self.roles.get(&cell.descriptor.role).ok_or(ResidentExpertSourceError::Geometry)?;
if slot(cell.descriptor.role).map_err(ResidentExpertSourceError::Read)? != number
|| checked_descriptor(cell.descriptor.role, resolved)? != cell.descriptor
|| cell.covered != cell.bytes.len()
{
return Err(ResidentExpertSourceError::Geometry);
}
let observed = memory_available()?;
capture_admit(retention, 0, observed)?; // payload pages already resident
for cell in capture.cells {
self.shards[0]
.stream_tensor(cell.descriptor.tensor_number, 0, 0, |_| Ok(()))
.map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))
}
/// Existing captured Boxes stay in place: each becomes a retained bank tensor of the source.
fn mint_banks(
&mut self,
capture: &mut ProvisionalExpertSource,
identity: u64,
) -> Result<(), ResidentExpertSourceError> {
for cell in std::mem::take(&mut capture.cells) {
let tensor = self.shards[0]
.admit_captured_tensor(identity, cell.descriptor.tensor_number, cell.bytes, cell.charged_bytes)
.map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?;
capture.banks.push(Bank { descriptor: cell.descriptor, tensor: tensor.into_retained() });
}
capture_admit(0, 0, memory_available()?)?;
Ok(())
}
fn publish_resident_experts(
&mut self,
capture: ProvisionalExpertSource,
observed: usize,
) -> ResidentExpertSourceReport {
let report = ResidentExpertSourceReport {
source_bytes: capture.source_bytes as u64,
charged_bytes: capture.charged as u64,
@@ -83,10 +108,23 @@ impl Qwen4ExpArtifact {
copied_spans: Cell::new(0),
copied_bytes: Cell::new(0),
});
Ok(report)
report
}
}
/// Charge only the new small shared owners/directory before any wrapping/publication; returns the observed
/// available memory.
fn charge_retention(capture: &mut ProvisionalExpertSource) -> Result<usize, ResidentExpertSourceError> {
let retention = retention_metadata_bytes()?;
capture.charged = capture.charged.checked_add(retention).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
if capture.charged as u64 > SOURCE_CAP {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
let observed = memory_available()?;
capture_admit(retention, 0, observed)?; // payload pages already resident
Ok(observed)
}
#[cfg(test)]
impl ProvisionalExpertSource {
pub(crate) fn test_cells(index: &TensorIndex) -> Self {
@@ -157,36 +195,69 @@ impl IncrementalCapture {
let end = position.checked_add(chunk.len() as u64).ok_or(ResidentExpertSourceError::Geometry)?;
let mut remaining = self.remaining_commitment()?;
for cell in &mut self.cells {
let start = cell.descriptor.absolute_start;
let bank_end =
start.checked_add(cell.descriptor.bytes as u64).ok_or(ResidentExpertSourceError::Geometry)?;
let left = start.max(position);
let right = bank_end.min(end);
if left >= right {
let Some(span) = cell_overlap(cell, position, end)? else {
continue;
}
let offset = usize::try_from(left - start).map_err(|_| ResidentExpertSourceError::Geometry)?;
let count = usize::try_from(right - left).map_err(|_| ResidentExpertSourceError::Geometry)?;
let next = offset.checked_add(count).ok_or(ResidentExpertSourceError::Geometry)?;
if offset != cell.covered
|| offset != cell.bytes.len()
|| next > cell.descriptor.bytes
|| next > cell.bytes.capacity()
{
return Err(ResidentExpertSourceError::Geometry);
}
let source = usize::try_from(left - position).map_err(|_| ResidentExpertSourceError::Geometry)?;
let selected = chunk
.get(source..source.checked_add(count).ok_or(ResidentExpertSourceError::Geometry)?)
.ok_or(ResidentExpertSourceError::Geometry)?;
// Actual snapshot immediately BEFORE touching this span. All other
// reserved banks and capacity slack stay committed; no VM credit.
let next_remaining = remaining.checked_sub(count).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
capture_admit(remaining, FUTURE_OWNERS, available()?)?;
cell.bytes.extend_from_slice(selected); // proven within reservation
cell.covered = next;
remaining = next_remaining;
};
remaining = append_span(cell, &span, chunk, remaining, &mut available)?;
}
Ok(())
}
}
/// The part of a chunk that falls inside one cell: where it goes in the cell, how long it is, where it starts in the chunk.
struct ChunkSpan {
offset: usize,
count: usize,
source: usize,
next: usize,
}
fn cell_overlap(
cell: &IncrementalTensor,
position: u64,
end: u64,
) -> Result<Option<ChunkSpan>, ResidentExpertSourceError> {
let start = cell.descriptor.absolute_start;
let bank_end = start.checked_add(cell.descriptor.bytes as u64).ok_or(ResidentExpertSourceError::Geometry)?;
let left = start.max(position);
let right = bank_end.min(end);
if left >= right {
return Ok(None);
}
let offset = usize::try_from(left - start).map_err(|_| ResidentExpertSourceError::Geometry)?;
let count = usize::try_from(right - left).map_err(|_| ResidentExpertSourceError::Geometry)?;
let next = offset.checked_add(count).ok_or(ResidentExpertSourceError::Geometry)?;
let source = usize::try_from(left - position).map_err(|_| ResidentExpertSourceError::Geometry)?;
Ok(Some(ChunkSpan { offset, count, source, next }))
}
/// The span continues exactly where the cell stopped, inside the descriptor and the reservation.
fn span_fits(cell: &IncrementalTensor, span: &ChunkSpan) -> bool {
span.offset == cell.covered
&& span.offset == cell.bytes.len()
&& span.next <= cell.descriptor.bytes
&& span.next <= cell.bytes.capacity()
}
/// Appends the span to the cell after the memory admission; returns the commitment that is left.
fn append_span(
cell: &mut IncrementalTensor,
span: &ChunkSpan,
chunk: &[u8],
remaining: usize,
available: &mut impl FnMut() -> Result<usize, ResidentExpertSourceError>,
) -> Result<usize, ResidentExpertSourceError> {
if !span_fits(cell, span) {
return Err(ResidentExpertSourceError::Geometry);
}
let selected = chunk
.get(span.source..span.source.checked_add(span.count).ok_or(ResidentExpertSourceError::Geometry)?)
.ok_or(ResidentExpertSourceError::Geometry)?;
// Actual snapshot immediately BEFORE touching this span. All other
// reserved banks and capacity slack stay committed; no VM credit.
let next_remaining = remaining.checked_sub(span.count).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
capture_admit(remaining, FUTURE_OWNERS, available()?)?;
cell.bytes.extend_from_slice(selected); // proven within reservation
cell.covered = span.next;
Ok(next_remaining)
}
@@ -7,36 +7,51 @@ impl Qwen4ExpArtifact {
/// Explicit fresh-owner load; called before publishing a selected binding.
/// No tensor finite admission is performed on unused expert banks.
pub fn load_resident_expert_source(&mut self) -> Result<ResidentExpertSourceReport, ResidentExpertSourceError> {
self.check_expert_layout()?;
let mut plan = Vec::new();
plan.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?;
let mut banks = Vec::new();
banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?;
let metadata = resident_metadata_bytes(plan.capacity(), banks.capacity())?;
let source_bytes = self.plan_banks(&mut plan)?;
let observed = admit_plan(source_bytes, metadata)?;
let (charged, remaining) = self.load_banks(plan, &mut banks, metadata, source_bytes)?;
self.verify_loaded_banks(&banks, remaining)?;
let report = self.bank_report(source_bytes, charged, observed, FUTURE_HEADROOM, false);
Ok(self.publish_banks(banks, report))
}
/// The model is not already enabled and has the closed expert layout.
fn check_expert_layout(&self) -> Result<(), ResidentExpertSourceError> {
if self.resident_experts.is_some() {
return Err(ResidentExpertSourceError::AlreadyEnabled);
}
if self.topology.block_count != 48 || self.topology.expert_count != 512 {
return Err(ResidentExpertSourceError::Geometry);
}
let mut plan = Vec::new();
plan.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?;
let mut banks = Vec::new();
banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?;
let metadata = plan
.capacity()
.checked_mul(size_of::<BankDescriptor>())
.and_then(|v| v.checked_add(banks.capacity().checked_mul(size_of::<Bank>())?))
.and_then(|v| v.checked_add(size_of::<ResidentExpertBank>() + 2 * size_of::<usize>()))
.and_then(|v| v.checked_add(retention_metadata_bytes().ok()?))
.ok_or(ResidentExpertSourceError::Geometry)?;
Ok(())
}
/// The descriptor of every expert tensor, in bank order, pushed on `plan`; returns their total bytes.
fn plan_banks(&self, plan: &mut Vec<BankDescriptor>) -> Result<usize, ResidentExpertSourceError> {
let mut source_bytes = 0usize;
for layer in 0..48 {
for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] {
let role = TensorRole::Layer { layer, role };
let tensor = self.roles.get(&role).ok_or(ResidentExpertSourceError::Geometry)?;
let descriptor = checked_descriptor(role, tensor)?;
source_bytes = source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?;
plan.push(descriptor);
}
for role in expert_roles() {
let tensor = self.roles.get(&role).ok_or(ResidentExpertSourceError::Geometry)?;
let descriptor = checked_descriptor(role, tensor)?;
source_bytes = source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?;
plan.push(descriptor);
}
let planned = source_bytes.checked_add(metadata).ok_or(ResidentExpertSourceError::Geometry)?;
let observed = memory_available()?;
admit(planned, observed)?;
Ok(source_bytes)
}
/// Reads every planned tensor into a resident bank under the memory admission; returns (charged, remaining) bytes.
fn load_banks(
&mut self,
plan: Vec<BankDescriptor>,
banks: &mut Vec<Bank>,
metadata: usize,
source_bytes: usize,
) -> Result<(usize, usize), ResidentExpertSourceError> {
let mut charged = metadata;
let mut remaining = source_bytes;
for descriptor in plan {
@@ -46,16 +61,9 @@ impl Qwen4ExpArtifact {
SOURCE_CAP.checked_sub(charged as u64).ok_or(ResidentExpertSourceError::MemoryAdmission)?,
)
.map_err(|_| ResidentExpertSourceError::MemoryAdmission)?;
let tensor =
self.shards[0].load_resident_tensor(descriptor.tensor_number, ceiling).map_err(
|error| match error {
gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation,
gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission,
gguf::ResidentLoadError::Source(error) => {
ResidentExpertSourceError::Read(BindingError::Io(error))
}
},
)?;
let tensor = self.shards[0]
.load_resident_tensor(descriptor.tensor_number, ceiling)
.map_err(load_error_to_source_error)?;
charged = charged.checked_add(tensor.charged_bytes()).ok_or(ResidentExpertSourceError::MemoryAdmission)?;
if charged as u64 > SOURCE_CAP {
return Err(ResidentExpertSourceError::MemoryAdmission);
@@ -63,7 +71,11 @@ impl Qwen4ExpArtifact {
remaining = remaining.checked_sub(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?;
banks.push(Bank { descriptor, tensor: tensor.into_retained() });
}
// Bank publication itself retains the same current-source refusal.
Ok((charged, remaining))
}
/// Bank publication itself retains the same current-source refusal.
fn verify_loaded_banks(&mut self, banks: &[Bank], remaining: usize) -> Result<(), ResidentExpertSourceError> {
let last = banks.last().ok_or(ResidentExpertSourceError::Geometry)?;
self.shards[0]
.stream_tensor(last.descriptor.tensor_number, 0, 0, |_| Ok(()))
@@ -72,26 +84,41 @@ impl Qwen4ExpArtifact {
if remaining != 0 || banks.len() != BANKS {
return Err(ResidentExpertSourceError::Geometry);
}
let report = ResidentExpertSourceReport {
Ok(())
}
fn bank_report(
&self,
source_bytes: usize,
charged: usize,
observed: usize,
headroom: u64,
file_mapped: bool,
) -> ResidentExpertSourceReport {
ResidentExpertSourceReport {
source_bytes: source_bytes as u64,
charged_bytes: charged as u64,
bank_count: BANKS as u32,
source_cap_bytes: SOURCE_CAP,
observed_mem_available_bytes: observed as u64,
future_headroom_bytes: FUTURE_HEADROOM,
future_headroom_bytes: headroom,
shard0_sha256: self.shards[0].artifact_sha256(),
copied_spans: 0,
copied_bytes: 0,
file_mapped: false,
};
file_mapped,
}
}
fn publish_banks(&mut self, banks: Vec<Bank>, report: ResidentExpertSourceReport) -> ResidentExpertSourceReport {
self.resident_experts = Some(ResidentExpertBank {
banks: Rc::new(banks),
report,
copied_spans: Cell::new(0),
copied_bytes: Cell::new(0),
});
Ok(report)
report
}
pub fn resident_expert_source_report(&self) -> Option<ResidentExpertSourceReport> {
self.resident_experts.as_ref().map(|bank| bank.report())
}
@@ -103,61 +130,62 @@ impl Qwen4ExpArtifact {
/// sees exactly what the resident copy would hold. No `MemAvailable` admission: the mapping commits no RAM.
#[cfg(any(target_os = "linux", windows))]
pub fn load_mapped_expert_source(&mut self) -> Result<ResidentExpertSourceReport, ResidentExpertSourceError> {
if self.resident_experts.is_some() {
return Err(ResidentExpertSourceError::AlreadyEnabled);
}
if self.topology.block_count != 48 || self.topology.expert_count != 512 {
return Err(ResidentExpertSourceError::Geometry);
}
self.check_expert_layout()?;
let mut banks = Vec::new();
banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?;
let mut source_bytes = 0usize;
for layer in 0..48 {
for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] {
let role = TensorRole::Layer { layer, role };
let tensor = self.roles.get(&role).ok_or(ResidentExpertSourceError::Geometry)?;
let descriptor = checked_descriptor(role, tensor)?;
source_bytes = source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?;
if source_bytes as u64 > SOURCE_CAP {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
let mapped =
self.shards[0].map_resident_tensor(descriptor.tensor_number).map_err(|error| match error {
gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation,
gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission,
gguf::ResidentLoadError::Source(error) => {
ResidentExpertSourceError::Read(BindingError::Io(error))
}
})?;
if mapped.len() != descriptor.bytes {
return Err(ResidentExpertSourceError::Geometry);
}
banks.push(Bank { descriptor, tensor: mapped.into_retained() });
for role in expert_roles() {
let tensor = self.roles.get(&role).ok_or(ResidentExpertSourceError::Geometry)?;
let descriptor = checked_descriptor(role, tensor)?;
source_bytes = source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?;
if source_bytes as u64 > SOURCE_CAP {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
banks.push(self.map_bank(descriptor)?);
}
if banks.len() != BANKS {
return Err(ResidentExpertSourceError::Geometry);
}
let report = ResidentExpertSourceReport {
source_bytes: source_bytes as u64,
charged_bytes: source_bytes as u64,
bank_count: BANKS as u32,
source_cap_bytes: SOURCE_CAP,
observed_mem_available_bytes: 0,
future_headroom_bytes: 0,
shard0_sha256: self.shards[0].artifact_sha256(),
copied_spans: 0,
copied_bytes: 0,
file_mapped: true,
};
self.resident_experts = Some(ResidentExpertBank {
banks: Rc::new(banks),
report,
copied_spans: Cell::new(0),
copied_bytes: Cell::new(0),
});
Ok(report)
let report = self.bank_report(source_bytes, source_bytes, 0, 0, true);
Ok(self.publish_banks(banks, report))
}
/// One bank as a read-only mapping of the tensor in shard 0.
#[cfg(any(target_os = "linux", windows))]
fn map_bank(&mut self, descriptor: BankDescriptor) -> Result<Bank, ResidentExpertSourceError> {
let mapped =
self.shards[0].map_resident_tensor(descriptor.tensor_number).map_err(load_error_to_source_error)?;
if mapped.len() != descriptor.bytes {
return Err(ResidentExpertSourceError::Geometry);
}
Ok(Bank { descriptor, tensor: mapped.into_retained() })
}
}
fn load_error_to_source_error(error: gguf::ResidentLoadError) -> ResidentExpertSourceError {
match error {
gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation,
gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission,
gguf::ResidentLoadError::Source(error) => ResidentExpertSourceError::Read(BindingError::Io(error)),
}
}
/// The bytes of the plan, bank and retention tables (of the given capacities), charged before anything is read.
fn resident_metadata_bytes(plan_capacity: usize, banks_capacity: usize) -> Result<usize, ResidentExpertSourceError> {
plan_capacity
.checked_mul(size_of::<BankDescriptor>())
.and_then(|v| v.checked_add(banks_capacity.checked_mul(size_of::<Bank>())?))
.and_then(|v| v.checked_add(size_of::<ResidentExpertBank>() + 2 * size_of::<usize>()))
.and_then(|v| v.checked_add(retention_metadata_bytes().ok()?))
.ok_or(ResidentExpertSourceError::Geometry)
}
/// The memory admission of the whole plan; returns the observed available memory.
fn admit_plan(source_bytes: usize, metadata: usize) -> Result<usize, ResidentExpertSourceError> {
let planned = source_bytes.checked_add(metadata).ok_or(ResidentExpertSourceError::Geometry)?;
let observed = memory_available()?;
admit(planned, observed)?;
Ok(observed)
}
impl ResidentExpertBankLease {
pub fn bank_count(&self) -> usize {
@@ -7,8 +7,7 @@ impl Qwen4ExpArtifact {
/// Short actual artifact borrow; result owns all144 existing allocations.
pub fn resident_expert_bank_lease(&self) -> Result<ResidentExpertBankLease, BindingError> {
let bank = self.resident_experts.as_ref().ok_or(BindingError::Role("resident_expert_source_absent"))?;
if bank.banks.len() != BANKS || bank.report.bank_count != BANKS as u32 || bank.report.charged_bytes > SOURCE_CAP
{
if !bank_directory_ok(bank) {
return Err(BindingError::Geometry("resident_expert_directory"));
}
for (number, member) in bank.banks.iter().enumerate() {
@@ -42,6 +41,11 @@ impl Qwen4ExpArtifact {
Ok(ResidentExpertBankMember { descriptor: member.descriptor, tensor: Rc::clone(&member.tensor) })
}
}
/// The bank holds all 144 members and charged no more than the source cap.
fn bank_directory_ok(bank: &ResidentExpertBank) -> bool {
bank.banks.len() == BANKS && bank.report.bank_count == BANKS as u32 && bank.report.charged_bytes <= SOURCE_CAP
}
impl ResidentExpertBankSpan {
pub fn bytes(&self) -> &[u8] {
&self.member.bytes()[self.offset..self.offset + self.length]
@@ -21,17 +21,35 @@ pub(super) fn checked_descriptor(
role: TensorRole,
tensor: &ResolvedTensor,
) -> Result<BankDescriptor, ResidentExpertSourceError> {
use LayerRole as L;
let (columns, rows, kinds): (u64, u64, &[u32]) = match role {
TensorRole::Layer { layer, role: L::FfnGateExperts | L::FfnUpExperts } if layer < 48 => {
(2560, 640, &[18, 21, 22, 23])
}
TensorRole::Layer { layer, role: L::FfnDownExperts } if layer < 48 => (640, 2560, &[20, 42]),
_ => return Err(ResidentExpertSourceError::Geometry),
};
let (columns, rows, kinds) = expert_shape(role)?;
if tensor.shard != 0 || tensor.dimensions != [columns, rows, 512] || !kinds.contains(&tensor.kind) {
return Err(ResidentExpertSourceError::Geometry);
}
check_expert_strides(role, tensor, rows)?;
Ok(BankDescriptor {
role,
tensor_number: tensor.tensor_number,
raw_kind: tensor.kind,
absolute_start: tensor.absolute_start,
file_size: tensor.file_size,
bytes: usize::try_from(tensor.byte_length).map_err(|_| ResidentExpertSourceError::Geometry)?,
})
}
/// (columns, rows, admitted GGUF kinds) of the routed-expert tensor of a role.
fn expert_shape(role: TensorRole) -> Result<(u64, u64, &'static [u32]), ResidentExpertSourceError> {
use LayerRole as L;
match role {
TensorRole::Layer { layer, role: L::FfnGateExperts | L::FfnUpExperts } if layer < 48 => {
Ok((2560, 640, &[18, 21, 22, 23]))
}
TensorRole::Layer { layer, role: L::FfnDownExperts } if layer < 48 => Ok((640, 2560, &[20, 42])),
_ => Err(ResidentExpertSourceError::Geometry),
}
}
/// The 512 experts are equal, contiguous spans that fill the tensor exactly.
fn check_expert_strides(role: TensorRole, tensor: &ResolvedTensor, rows: u64) -> Result<(), ResidentExpertSourceError> {
let first = plan_stream_rows(tensor, role, 0, rows, Some(0)).map_err(|_| ResidentExpertSourceError::Geometry)?;
let last = plan_stream_rows(tensor, role, 0, rows, Some(511)).map_err(|_| ResidentExpertSourceError::Geometry)?;
if first.0 != 0
@@ -43,14 +61,7 @@ pub(super) fn checked_descriptor(
{
return Err(ResidentExpertSourceError::Geometry);
}
Ok(BankDescriptor {
role,
tensor_number: tensor.tensor_number,
raw_kind: tensor.kind,
absolute_start: tensor.absolute_start,
file_size: tensor.file_size,
bytes: usize::try_from(tensor.byte_length).map_err(|_| ResidentExpertSourceError::Geometry)?,
})
Ok(())
}
pub(super) fn slot(role: TensorRole) -> Result<usize, BindingError> {
let (layer, role) = match role {
@@ -67,61 +78,34 @@ pub(super) fn slot(role: TensorRole) -> Result<usize, BindingError> {
}
// Existing resident KAR and other owners are already reflected in MemAvailable.
// This is a snapshot, never an allocation reservation or a guarantee against races.
#[cfg(target_os = "linux")]
pub(super) fn memory_available() -> Result<usize, ResidentExpertSourceError> {
#[cfg(target_os = "linux")]
{
let mut text = String::new();
File::open("/proc/meminfo")
.map_err(|_| ResidentExpertSourceError::MemoryAdmission)?
.take(65537)
.read_to_string(&mut text)
.map_err(|_| ResidentExpertSourceError::MemoryAdmission)?;
if text.len() > 65536 {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
parse_memory_available(&text)
}
#[cfg(windows)]
{
let (total, available) =
leleka_libc_shim::physical_memory().ok_or(ResidentExpertSourceError::MemoryAdmission)?;
parse_memory_available(&format!(
"MemTotal: {} kB
MemAvailable: {} kB
",
total / 1024,
available / 1024
))
}
#[cfg(not(any(target_os = "linux", windows)))]
{
Err(ResidentExpertSourceError::MemoryAdmission)
let mut text = String::new();
File::open("/proc/meminfo")
.map_err(|_| ResidentExpertSourceError::MemoryAdmission)?
.take(65537)
.read_to_string(&mut text)
.map_err(|_| ResidentExpertSourceError::MemoryAdmission)?;
if text.len() > 65536 {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
parse_memory_available(&text)
}
#[cfg(windows)]
pub(super) fn memory_available() -> Result<usize, ResidentExpertSourceError> {
let (total, available) = leleka_libc_shim::physical_memory().ok_or(ResidentExpertSourceError::MemoryAdmission)?;
parse_memory_available(&format!("MemTotal: {} kB\nMemAvailable: {} kB\n", total / 1024, available / 1024))
}
#[cfg(not(any(target_os = "linux", windows)))]
pub(super) fn memory_available() -> Result<usize, ResidentExpertSourceError> {
Err(ResidentExpertSourceError::MemoryAdmission)
}
#[cfg(any(target_os = "linux", windows, test))]
pub(super) fn parse_memory_available(text: &str) -> Result<usize, ResidentExpertSourceError> {
let mut available = None;
let mut total = None;
for line in text.lines() {
let mut parts = line.split_ascii_whitespace();
let Some(key) = parts.next() else { continue };
let destination = match key {
"MemAvailable:" => &mut available,
"MemTotal:" => &mut total,
_ => continue,
};
if destination.is_some() {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
let value = parts
.next()
.ok_or(ResidentExpertSourceError::MemoryAdmission)?
.parse::<usize>()
.map_err(|_| ResidentExpertSourceError::MemoryAdmission)?;
if parts.next() != Some("kB") || parts.next().is_some() {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
*destination = Some(value.checked_mul(1024).ok_or(ResidentExpertSourceError::MemoryAdmission)?);
read_meminfo_line(line, &mut available, &mut total)?;
}
let available = available.ok_or(ResidentExpertSourceError::MemoryAdmission)?;
let total = total.ok_or(ResidentExpertSourceError::MemoryAdmission)?;
@@ -130,6 +114,34 @@ pub(super) fn parse_memory_available(text: &str) -> Result<usize, ResidentExpert
}
Ok(available)
}
/// One `MemAvailable:` or `MemTotal:` line (a value in kB, once) is recorded in bytes; other lines are ignored.
#[cfg(any(target_os = "linux", windows, test))]
fn read_meminfo_line(
line: &str,
available: &mut Option<usize>,
total: &mut Option<usize>,
) -> Result<(), ResidentExpertSourceError> {
let mut parts = line.split_ascii_whitespace();
let destination = match parts.next() {
Some("MemAvailable:") => available,
Some("MemTotal:") => total,
_ => return Ok(()),
};
if destination.is_some() {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
let value = parts
.next()
.ok_or(ResidentExpertSourceError::MemoryAdmission)?
.parse::<usize>()
.map_err(|_| ResidentExpertSourceError::MemoryAdmission)?;
if parts.next() != Some("kB") || parts.next().is_some() {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
*destination = Some(value.checked_mul(1024).ok_or(ResidentExpertSourceError::MemoryAdmission)?);
Ok(())
}
pub(super) fn admit(capacity: usize, available: usize) -> Result<(), ResidentExpertSourceError> {
if capacity as u64 > SOURCE_CAP
|| (capacity as u64).checked_add(FUTURE_HEADROOM).is_none_or(|n| n > available as u64)
@@ -70,25 +70,7 @@ impl Qwen4ExpArtifact {
}
for layer in 0..48u8 {
for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] {
let named = TensorRole::Layer { layer, role };
let tensor = self.roles.get(&named).ok_or(BindingError::Role("file_expert_role"))?;
// Reuse the actual routed bank shape/kind/domain admission; no wider stream geometry.
if tensor.shard != 0 || tensor.dimensions.len() != 3 || tensor.dimensions[2] != 512 {
return Err(BindingError::Geometry("file_expert_bank"));
}
let rows = if role == LayerRole::FfnDownExperts { 2560 } else { 640 };
let (offset, length) = plan_stream_rows(tensor, named, 0, rows, Some(0))?;
if offset != 0 || length.checked_mul(512) != Some(tensor.byte_length) {
return Err(BindingError::Geometry("file_expert_bank"));
}
self.shards[0].validate_empty_tensor_source(tensor.tensor_number).map_err(BindingError::Io)?;
members.push(FileExpertExtent {
role: named,
absolute: tensor.absolute_start,
bytes: tensor.byte_length,
expert_bytes: usize::try_from(length).map_err(|_| BindingError::Range("file_expert_bytes"))?,
kind: tensor.kind,
});
members.push(self.file_expert_extent(layer, role)?);
}
}
let file = self.shards[0].expert_file_owner().map_err(BindingError::Io)?;
@@ -102,6 +84,30 @@ impl Qwen4ExpArtifact {
}
Ok(FileExpertSourceLease { file, members, metadata_bytes })
}
/// The extent of one routed-expert bank in the file, after the bank shape and stride admission.
fn file_expert_extent(&self, layer: u8, role: LayerRole) -> Result<FileExpertExtent, BindingError> {
let named = TensorRole::Layer { layer, role };
let tensor = self.roles.get(&named).ok_or(BindingError::Role("file_expert_role"))?;
// Reuse the actual routed bank shape/kind/domain admission; no wider stream geometry.
if tensor.shard != 0 || tensor.dimensions.len() != 3 || tensor.dimensions[2] != 512 {
return Err(BindingError::Geometry("file_expert_bank"));
}
let rows = if role == LayerRole::FfnDownExperts { 2560 } else { 640 };
let (offset, length) = plan_stream_rows(tensor, named, 0, rows, Some(0))?;
if offset != 0 || length.checked_mul(512) != Some(tensor.byte_length) {
return Err(BindingError::Geometry("file_expert_bank"));
}
self.shards[0].validate_empty_tensor_source(tensor.tensor_number).map_err(BindingError::Io)?;
Ok(FileExpertExtent {
role: named,
absolute: tensor.absolute_start,
bytes: tensor.byte_length,
expert_bytes: usize::try_from(length).map_err(|_| BindingError::Range("file_expert_bytes"))?,
kind: tensor.kind,
})
}
pub fn validate_file_expert_source(&self, lease: &FileExpertSourceLease) -> Result<(), BindingError> {
lease.validate_current()?;
if self.shards[0].artifact_sha256() != lease.digest()
@@ -111,15 +117,7 @@ impl Qwen4ExpArtifact {
}
// Two dup'd file descriptors of the same actual admitted FD, not pathname identity.
let current = self.shards[0].expert_file_owner().map_err(BindingError::Io)?;
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
let a = current.file().metadata().map_err(|e| BindingError::Io(e.into()))?;
let b = lease.file().metadata().map_err(|e| BindingError::Io(e.into()))?;
if a.dev() != b.dev() || a.ino() != b.ino() {
return Err(BindingError::Identity(0));
}
}
check_same_file(&current, lease)?;
for member in &lease.members {
let tensor = self.roles.get(&member.role).ok_or(BindingError::Role("file_expert_role"))?;
if tensor.absolute_start != member.absolute
@@ -132,3 +130,20 @@ impl Qwen4ExpArtifact {
Ok(())
}
}
/// The current owner and the lease name the same device and inode.
#[cfg(unix)]
fn check_same_file(current: &gguf::ExpertFileOwner, lease: &FileExpertSourceLease) -> Result<(), BindingError> {
use std::os::unix::fs::MetadataExt;
let a = current.file().metadata().map_err(|e| BindingError::Io(e.into()))?;
let b = lease.file().metadata().map_err(|e| BindingError::Io(e.into()))?;
if a.dev() != b.dev() || a.ino() != b.ino() {
return Err(BindingError::Identity(0));
}
Ok(())
}
#[cfg(not(unix))]
fn check_same_file(_current: &gguf::ExpertFileOwner, _lease: &FileExpertSourceLease) -> Result<(), BindingError> {
Ok(())
}