STRA-338 size3 en4: WIP of the slice (unverified, committed by the new integrator)

This commit is contained in:
Pavlo Ratushnyi
2026-11-07 09:21:31 +01:00
parent 758f72b2a9
commit d7d6fbc52e
27 changed files with 543 additions and 319 deletions
@@ -58,16 +58,10 @@ pub(super) fn exact(left: &[f32], right: &[f32]) {
pub(super) fn bounded_gate_up(kind: MoeMatrixKind, variant: usize) -> Vec<u8> {
let mut values = encoded(kind, FF, N, variant);
let block_bytes = match kind {
MoeMatrixKind::Iq3Xxs => 98,
MoeMatrixKind::Iq3S => 110,
MoeMatrixKind::Iq2S => 82,
MoeMatrixKind::RoutedIq4Xs | MoeMatrixKind::DenseIq4Xs => 136,
MoeMatrixKind::Q4K => 144,
MoeMatrixKind::Q5K => 176,
MoeMatrixKind::Q6K => 210,
_ => panic!("bounded fixture admits only Gate/Up formats"),
};
if matches!(kind, MoeMatrixKind::RoutedIq4Nl | MoeMatrixKind::Q8_0) {
panic!("bounded fixture admits only Gate/Up formats");
}
let (_, block_bytes) = block_geometry(kind);
for block in values.chunks_exact_mut(block_bytes) {
let scale_offset = if kind == MoeMatrixKind::Q6K { 208 } else { 0 };
// Literal F16 2^-12; affine minima use 2^-13. Packed patterns stay
@@ -117,7 +117,8 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
#[cfg(test)]
fn trace_reserve_failure(&self, first_row: usize, allocated_before: usize, extra: usize, _error: &Error) {
eprintln!(
"PUBLIC MMQ allocation stage=reserve-transient layer={} first={} rows={} allocated_before={} allocated_after={} extra={} reserve={} budget={} error={_error:?}",
"PUBLIC MMQ allocation stage=reserve-transient layer={} first={} rows={} allocated_before={} \
allocated_after={} extra={} reserve={} budget={} error={_error:?}",
self.layer.get(),
first_row,
self.rows.len(),
@@ -132,7 +133,8 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
#[cfg(test)]
fn trace_guard_failure(&self, extra: usize) -> Result<()> {
eprintln!(
"PUBLIC MMQ allocation stage=post-reservation-guard layer={} first={} rows={} allocated={} extra={} reserve={} budget={}",
"PUBLIC MMQ allocation stage=post-reservation-guard layer={} first={} rows={} allocated={} \
extra={} reserve={} budget={}",
self.layer.get(),
self.txn.micro_row_index(0)?,
self.rows.len(),
@@ -47,19 +47,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
if !self.main.is_empty() || self.main_bytes != 0 || self.mtp_input_workspace.is_some() {
return Err(Error::IdentityMismatch);
}
let supported =
[MtpRole::FcEmbedding, MtpRole::FcHidden].into_iter().all(|role| {
self.dense.iter().any(|entry| {
entry.role == role && (entry.kind, entry.rows, entry.columns) == (MtpKind::Q8_0, 2560, 2560)
})
}) && [(MtpRole::EmbeddingNorm, 2560), (MtpRole::HiddenNorm, 10240)].into_iter().all(|(role, words)| {
self.dense.iter().any(|entry| {
entry.role == role
&& entry.kind == MtpKind::F32
&& entry.f32.as_ref().is_some_and(|values| values.len() == words)
})
});
if !supported {
if !self.mtp_input_workspace_supported() {
return Ok(());
}
// Actual Context charge is counted once. Both admission predicates leave
@@ -69,6 +57,23 @@ impl<'ctx> MoeWeightCache<'ctx> {
self.room(0)?;
self.validate(binding, self.context)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn mtp_input_workspace_supported(&self) -> bool {
let fc_present = |role: MtpRole| {
self.dense.iter().any(|entry| {
entry.role == role && (entry.kind, entry.rows, entry.columns) == (MtpKind::Q8_0, 2560, 2560)
})
};
let norm_present = |(role, words): (MtpRole, usize)| {
self.dense.iter().any(|entry| {
entry.role == role
&& entry.kind == MtpKind::F32
&& entry.f32.as_ref().is_some_and(|values| values.len() == words)
})
};
[MtpRole::FcEmbedding, MtpRole::FcHidden].into_iter().all(fc_present)
&& [(MtpRole::EmbeddingNorm, 2560), (MtpRole::HiddenNorm, 10240)].into_iter().all(norm_present)
}
#[cfg(test)]
pub(in super::super::super) fn note_mtp_input_completed(&self) {
self.mtp_input_completions.set(self.mtp_input_completions.get().saturating_add(1));
@@ -33,23 +33,32 @@ pub(super) fn dual_layout(key: MoeWeightDescriptor) -> Result<Option<(MmqFormat,
if key.expert.is_none() {
return Ok(None);
}
let (format, raw, tail) = match key.raw_kind {
18 if matches!(key.role, 0 | 1) && key.rows == 640 && key.columns == 2560 => {
(MmqFormat::Iq3XxsGateUp, 627_200, 0)
}
22 if matches!(key.role, 0 | 1) && key.rows == 640 && key.columns == 2560 => {
(MmqFormat::Iq2SGateUp, 524_800, 0)
}
20 if key.role == 2 && key.rows == 2560 && key.columns == 640 => (MmqFormat::Iq4NlDown, 921_600, 216),
42 if key.role == 2 && key.rows == 2560 && key.columns == 640 => (MmqFormat::Q2Down, 460_800, 108),
18 | 22 | 20 | 42 => return Err(Error::InvalidDimension),
_ => return Ok(None),
let Some((format, raw, tail)) = routed_dual_spec(key)? else {
return Ok(None);
};
if key.bytes != raw {
return Err(Error::InvalidDimension);
}
Ok(Some((format, raw + tail)))
}
fn is_gate_up_shape(key: &MoeWeightDescriptor) -> bool {
matches!(key.role, 0 | 1) && key.rows == 640 && key.columns == 2560
}
fn is_down_shape(key: &MoeWeightDescriptor) -> bool {
key.role == 2 && key.rows == 2560 && key.columns == 640
}
// (format, raw bytes, padded tail bytes) of a routed fixed format with the expected geometry.
fn routed_dual_spec(key: MoeWeightDescriptor) -> Result<Option<(MmqFormat, usize, usize)>> {
let spec = match (key.raw_kind, is_gate_up_shape(&key), is_down_shape(&key)) {
(18, true, _) => (MmqFormat::Iq3XxsGateUp, 627_200, 0),
(22, true, _) => (MmqFormat::Iq2SGateUp, 524_800, 0),
(20, _, true) => (MmqFormat::Iq4NlDown, 921_600, 216),
(42, _, true) => (MmqFormat::Q2Down, 460_800, 108),
(18 | 22 | 20 | 42, _, _) => return Err(Error::InvalidDimension),
_ => return Ok(None),
};
Ok(Some(spec))
}
/// Literal Original prompt MMQ formats, from actual bound descriptor geometry.
/// This adds no fabricated device view and never expands the ordinary policy.
pub(in crate::qwen_forward) fn original_dual_layout(key: MoeWeightDescriptor) -> Result<Option<(MmqFormat, usize)>> {
@@ -72,14 +81,8 @@ pub(in crate::qwen_forward) fn original_dual_layout(key: MoeWeightDescriptor) ->
}
pub(super) fn original_mmq_triplet(keys: &[MoeWeightDescriptor; 3]) -> Result<bool> {
let [gate, up, down] = *keys;
if gate.role != 0
|| up.role != 1
|| down.role != 2
|| gate.expert.is_none_or(|e| e >= 512)
|| gate.expert != up.expert
|| gate.expert != down.expert
|| gate.layer != up.layer
|| gate.layer != down.layer
if triplet_roles_mismatch(&gate, &up, &down)
|| triplet_ids_mismatch(&gate, &up, &down)
|| gate.raw_kind != up.raw_kind
{
return Err(Error::IdentityMismatch);
@@ -87,6 +90,20 @@ pub(super) fn original_mmq_triplet(keys: &[MoeWeightDescriptor; 3]) -> Result<bo
let layouts = [original_dual_layout(gate)?, original_dual_layout(up)?, original_dual_layout(down)?];
Ok(layouts.iter().all(Option::is_some))
}
fn triplet_roles_mismatch(gate: &MoeWeightDescriptor, up: &MoeWeightDescriptor, down: &MoeWeightDescriptor) -> bool {
gate.role != 0 || up.role != 1 || down.role != 2 || gate.expert.is_none_or(|e| e >= 512)
}
fn triplet_ids_mismatch(gate: &MoeWeightDescriptor, up: &MoeWeightDescriptor, down: &MoeWeightDescriptor) -> bool {
gate.expert != up.expert || gate.expert != down.expert || gate.layer != up.layer || gate.layer != down.layer
}
fn gate_up_geometry_mismatch(gate: &MoeWeightDescriptor, up: &MoeWeightDescriptor) -> bool {
gate.rows != 640
|| up.rows != 640
|| gate.columns != 2560
|| up.columns != 2560
|| gate.bytes != 627_200
|| up.bytes != 627_200
}
pub(super) fn integer_iq3_triplet(keys: &[MoeWeightDescriptor; 3]) -> Result<bool> {
let [gate, up, down] = *keys;
// Legal other GU formats make the whole layer take actual native execution.
@@ -94,20 +111,9 @@ pub(super) fn integer_iq3_triplet(keys: &[MoeWeightDescriptor; 3]) -> Result<boo
if gate.raw_kind != 18 || up.raw_kind != 18 {
return Ok(false);
}
if gate.role != 0
|| up.role != 1
|| down.role != 2
|| gate.expert.is_none_or(|e| e >= 512)
|| gate.expert != up.expert
|| gate.expert != down.expert
|| gate.layer != up.layer
|| gate.layer != down.layer
|| gate.rows != 640
|| up.rows != 640
|| gate.columns != 2560
|| up.columns != 2560
|| gate.bytes != 627_200
|| up.bytes != 627_200
if triplet_roles_mismatch(&gate, &up, &down)
|| triplet_ids_mismatch(&gate, &up, &down)
|| gate_up_geometry_mismatch(&gate, &up)
{
return Err(Error::InvalidDimension);
}
@@ -13,6 +13,12 @@ impl Role {
Self::SharedUp => Slot::SharedUp,
Self::SharedHidden => Slot::SharedHidden,
Self::SharedDown => Slot::SharedDown,
other => other.output_slot(),
}
}
// The roles that are neither routed nor a shared expert projection.
fn output_slot(self) -> Slot {
match self {
Self::Scalar => Slot::Scalar,
Self::Scaled => Slot::Scaled,
Self::Combined => Slot::Combined,
@@ -22,6 +28,13 @@ impl Role {
Self::InputScales => Slot::InputScales,
#[cfg(test)]
Self::HiddenScales => Slot::HiddenScales,
Self::RoutedGu(..)
| Self::RoutedHidden(..)
| Self::RoutedDown(..)
| Self::SharedGate
| Self::SharedUp
| Self::SharedHidden
| Self::SharedDown => unreachable!("routed and shared roles map in slot"),
}
}
pub(super) fn count(self) -> usize {
@@ -179,31 +192,37 @@ impl<'lease, 'ctx> Transport<'lease, 'ctx> {
pub(super) fn quantize(&mut self, input: usize, hidden: bool) -> Result<(usize, usize)> {
let q = self.allocate(if hidden { Slot::HiddenQ } else { Slot::InputQ })?;
let scales = self.allocate(if hidden { Slot::HiddenScales } else { Slot::InputScales })?;
let (inputs, outputs) = self.buffers.split_at_mut(q);
let (quant, scale) = outputs.split_at_mut(1);
let result = if hidden {
self.context.mtp_quantize_scaled_640(
at(inputs, input)?,
quant[0].as_mut().ok_or(Error::IdentityMismatch)?,
scale[0].as_mut().ok_or(Error::IdentityMismatch)?,
)
} else {
self.context.mtp_quantize_scaled_2560(
at(inputs, input)?,
quant[0].as_mut().ok_or(Error::IdentityMismatch)?,
scale[0].as_mut().ok_or(Error::IdentityMismatch)?,
)
}
.map_err(moe_driver_error)
.and_then(|()| {
let values = download(at(&self.buffers, scales)?, if hidden { 20 } else { 80 })?;
#[cfg(test)]
self.observe(if hidden { Role::HiddenScales } else { Role::InputScales }, &values)?;
let _ = values;
Ok(())
});
let launched = self.launch_quantize(input, q, hidden)?;
let result = launched.map_err(moe_driver_error).and_then(|()| self.read_scales(scales, hidden));
self.note(&result);
result?;
Ok((q, scales))
}
// Operand lookups fail before the launch; only the launch's own driver error is returned inside.
fn launch_quantize(
&mut self,
input: usize,
q: usize,
hidden: bool,
) -> Result<std::result::Result<(), leleka_cuda_driver::Error>> {
let (inputs, outputs) = self.buffers.split_at_mut(q);
let (quant, scale) = outputs.split_at_mut(1);
let operands = (
at(inputs, input)?,
quant[0].as_mut().ok_or(Error::IdentityMismatch)?,
scale[0].as_mut().ok_or(Error::IdentityMismatch)?,
);
Ok(if hidden {
self.context.mtp_quantize_scaled_640(operands.0, operands.1, operands.2)
} else {
self.context.mtp_quantize_scaled_2560(operands.0, operands.1, operands.2)
})
}
fn read_scales(&mut self, scales: usize, hidden: bool) -> Result<()> {
let values = download(at(&self.buffers, scales)?, if hidden { 20 } else { 80 })?;
#[cfg(test)]
self.observe(if hidden { Role::HiddenScales } else { Role::InputScales }, &values)?;
let _ = values;
Ok(())
}
}
@@ -7,18 +7,23 @@ pub(super) fn route(context: &Context<'_>, logits: &[f32]) -> Result<([u32; K],
let x = upload(context, logits)?;
let mut ids = context.allocate(K * 4).map_err(moe_driver_error)?;
let mut weights = allocate(context, K)?;
let result: Result<([u32; K], [f32; K])> = (|| {
context.qwen_route_top10(&x, &mut ids, &mut weights).map_err(moe_driver_error)?;
let raw = download_bytes(&ids, K * 4)?;
let ids = std::array::from_fn(|i| i32::from_le_bytes(raw[i * 4..(i + 1) * 4].try_into().expect("fixed IDs")));
let weights: [f32; K] = download(&weights, K)?.as_ref().try_into().map_err(|_| Error::InvalidDimension)?;
Ok((validate_route(ids, &weights)?, weights))
})();
let result = route_on_device(context, &x, (&mut ids, &mut weights));
let cleanup = release([x, ids, weights]);
let value = result?;
cleanup?;
Ok(value)
}
fn route_on_device(
context: &Context<'_>,
x: &DeviceBuffer<'_>,
(ids, weights): (&mut DeviceBuffer<'_>, &mut DeviceBuffer<'_>),
) -> Result<([u32; K], [f32; K])> {
context.qwen_route_top10(x, ids, weights).map_err(moe_driver_error)?;
let raw = download_bytes(ids, K * 4)?;
let ids = std::array::from_fn(|i| i32::from_le_bytes(raw[i * 4..(i + 1) * 4].try_into().expect("fixed IDs")));
let weights: [f32; K] = download(weights, K)?.as_ref().try_into().map_err(|_| Error::InvalidDimension)?;
Ok((validate_route(ids, &weights)?, weights))
}
pub(super) fn compose(
context: &Context<'_>,
binding: &ModelBinding,
@@ -40,15 +40,9 @@ pub(in crate::qwen_forward) fn produce_chunk_kv_only(
if frame.position != position || frame.token != next || !frame.origin.same_prefix(&origin) {
return Err(Error::IdentityMismatch);
}
let result = (|| {
let input = MtpInput::compute(binding, target, frame.clone(), streams, cache)?;
let read = super::super::mtp_gr::attention_read(binding, &input, target, cache)?;
let (key, value) = super::super::mtp_attention::produce_kv_cell(binding, &read, target, cache)?;
target.finish_mtp_device()?;
frame.validate(binding, target)?;
product = Some(MtpKvOnlyProduct { frame: frame.clone(), key, value });
Ok(())
})();
let result = compute_kv_product(binding, target, (frame, streams), cache).map(|computed| {
product = Some(computed);
});
if let Err(error) = &result {
target.note_mtp_failure(error);
}
@@ -57,6 +51,20 @@ pub(in crate::qwen_forward) fn produce_chunk_kv_only(
product.ok_or(Error::IdentityMismatch)
}
fn compute_kv_product(
binding: &ModelBinding,
target: &mut QwenSession<'_>,
(frame, streams): (&MtpFrame, &[f32]),
cache: &MoeWeightCache<'_>,
) -> Result<MtpKvOnlyProduct> {
let input = MtpInput::compute(binding, target, frame.clone(), streams, cache)?;
let read = super::super::mtp_gr::attention_read(binding, &input, target, cache)?;
let (key, value) = super::super::mtp_attention::produce_kv_cell(binding, &read, target, cache)?;
target.finish_mtp_device()?;
frame.validate(binding, target)?;
Ok(MtpKvOnlyProduct { frame: frame.clone(), key, value })
}
/// Changed-boundary numerical seam for a real loaded row. Original full
/// attention is the reference; only this row's genuine half K/V is compared.
/// No metadata-only ready state or model-quality claim is constructed.
@@ -34,13 +34,7 @@ impl DenseKv {
// Closed mirror admission. Authoritative append() already validated each
// immutable cell; reload still calls window() for complete finite validation.
pub(in crate::qwen_forward) fn ring_validate(&self, frame: &MtpFrame) -> Result<()> {
if !self.binding.matches(&frame.binding)
|| !Rc::ptr_eq(&self.owner, &frame.epoch)
|| frame.generation != frame.epoch.get()
|| self.next_position != frame.position.get() + 1
|| self.cells.len() != usize::try_from(self.next_position).map_err(|_| Error::Overflow)?.min(WINDOW)
|| self.produced.as_ref().is_none_or(|source| !source.same(frame))
{
if self.window_header_mismatch(frame) || self.window_cells_mismatch(frame)? {
return Err(Error::IdentityMismatch);
}
Ok(())
@@ -72,14 +66,18 @@ impl DenseKv {
validate_half(&cell.value)?;
Ok((&cell.key, &cell.value))
}
pub(in crate::qwen_forward) fn window(&self, frame: &MtpFrame) -> Result<HalfWindow> {
if !self.binding.matches(&frame.binding)
fn window_header_mismatch(&self, frame: &MtpFrame) -> bool {
!self.binding.matches(&frame.binding)
|| !Rc::ptr_eq(&self.owner, &frame.epoch)
|| frame.generation != frame.epoch.get()
|| self.next_position != frame.position.get() + 1
|| self.cells.len() != usize::try_from(self.next_position).map_err(|_| Error::Overflow)?.min(WINDOW)
|| self.produced.as_ref().is_none_or(|source| !source.same(frame))
{
}
fn window_cells_mismatch(&self, frame: &MtpFrame) -> Result<bool> {
Ok(self.cells.len() != usize::try_from(self.next_position).map_err(|_| Error::Overflow)?.min(WINDOW)
|| self.produced.as_ref().is_none_or(|source| !source.same(frame)))
}
pub(in crate::qwen_forward) fn window(&self, frame: &MtpFrame) -> Result<HalfWindow> {
if self.window_header_mismatch(frame) || self.window_cells_mismatch(frame)? {
return Err(Error::IdentityMismatch);
}
let bytes = self.cells.len().checked_mul(HALF_ROW).ok_or(Error::Overflow)?;
@@ -136,19 +136,25 @@ impl MtpChunkStage<'_> {
target: &QwenSession<'_>,
) -> Result<()> {
self.anchor.validate(target)?;
if !self.original.binding.matches(&binding.identity())
if self.lineage_mismatch(binding) || self.position_mismatch() {
return Err(Error::IdentityMismatch);
}
Ok(())
}
fn lineage_mismatch(&self, binding: &ModelBinding) -> bool {
!self.original.binding.matches(&binding.identity())
|| !self.candidate.binding.matches(&self.original.binding)
|| self.original.epoch.get() != self.generation
|| !Rc::ptr_eq(&self.original.epoch, &self.candidate.epoch)
|| !Rc::ptr_eq(&self.original.retained, &self.candidate.retained)
|| self.original.next_position != self.start_position
}
fn position_mismatch(&self) -> bool {
self.original.next_position != self.start_position
|| self.original.kv.next_position != self.start_position
|| self.candidate.next_position < self.start_position
|| self.candidate.next_position > self.max_position
{
return Err(Error::IdentityMismatch);
}
Ok(())
}
// Only the enclosing actual chunk warmer may compute a new candidate.
@@ -84,25 +84,34 @@ impl MtpKvPrefill {
let origin = target.target_origin()?;
origin.validate(target)?;
if self.complete
|| !self.binding.matches(&binding.identity())
|| !original.binding.matches(&self.binding)
|| !self.anchor.same_branch(&origin)
|| !Rc::ptr_eq(&self.epoch, &original.epoch)
|| self.epoch.get() != self.generation
|| original.next_position != 0
|| original.kv.next_position != 0
|| !original.kv.binding.matches(&self.binding)
|| !Rc::ptr_eq(&original.kv.owner, &self.epoch)
|| !Rc::ptr_eq(&original.kv.cells, &self.original_cells)
|| !original.kv.cells.is_empty()
|| original.kv.produced.is_some()
|| original.residual.is_some()
|| original.target_owner.is_some()
|| self.owner_foreign(binding, original, &origin)
|| self.original_not_fresh(original)
|| self.original_kv_foreign(original)
{
return Err(Error::IdentityMismatch);
}
Ok(())
}
fn owner_foreign(&self, binding: &ModelBinding, original: &MtpSession, origin: &TargetStepOrigin) -> bool {
!self.binding.matches(&binding.identity())
|| !original.binding.matches(&self.binding)
|| !self.anchor.same_branch(origin)
|| !Rc::ptr_eq(&self.epoch, &original.epoch)
|| self.epoch.get() != self.generation
}
fn original_not_fresh(&self, original: &MtpSession) -> bool {
original.next_position != 0
|| original.kv.next_position != 0
|| original.residual.is_some()
|| original.target_owner.is_some()
}
fn original_kv_foreign(&self, original: &MtpSession) -> bool {
!original.kv.binding.matches(&self.binding)
|| !Rc::ptr_eq(&original.kv.owner, &self.epoch)
|| !Rc::ptr_eq(&original.kv.cells, &self.original_cells)
|| !original.kv.cells.is_empty()
|| original.kv.produced.is_some()
}
/// Actual final publication certificate; positions/booleans alone cannot
/// admit a replacement draft with numerically equal but unrelated cells.
pub(in crate::qwen_forward) fn validate_ready(
@@ -14,26 +14,11 @@ impl OriginalRankedExperts {
/// and duplicate pairs. A different topology is refused before any fill.
pub(crate) fn read(path: &Path, binding: &ModelBinding) -> Result<Self> {
let mut file = File::open(path).map_err(|_| Error::InputRead)?;
let mut header = [0u8; 24];
file.read_exact(&mut header).map_err(|_| Error::InputRead)?;
if &header[..4] != b"STRP" {
return Err(Error::IdentityMismatch);
}
let word = |at| u32::from_le_bytes(header[at..at + 4].try_into().unwrap());
let (layers, experts, want, count) = (word(8), word(12), word(16), word(20));
if layers != binding.layer_count() || experts != 512 || count > want {
return Err(Error::InvalidDimension);
}
let (layers, experts, want, count) = read_header(&mut file, binding)?;
let mut pairs = Vec::new();
pairs.try_reserve_exact(count as usize).map_err(|_| Error::InputAllocation)?;
for _ in 0..count {
let mut raw = [0u8; 4];
file.read_exact(&mut raw).map_err(|_| Error::InputRead)?;
let pair = (u16::from_le_bytes([raw[0], raw[1]]), u16::from_le_bytes([raw[2], raw[3]]));
if u32::from(pair.0) >= layers || u32::from(pair.1) >= experts {
return Err(Error::InvalidDimension);
}
pairs.push(pair);
pairs.push(read_pair(&mut file, layers, experts)?);
}
Ok(Self { pairs, requested_slots: want })
}
@@ -48,6 +33,30 @@ impl OriginalRankedExperts {
}
}
// (layers, experts, requested slots, pair count) of a STRP header that matches the binding.
fn read_header(file: &mut File, binding: &ModelBinding) -> Result<(u32, u32, u32, u32)> {
let mut header = [0u8; 24];
file.read_exact(&mut header).map_err(|_| Error::InputRead)?;
if &header[..4] != b"STRP" {
return Err(Error::IdentityMismatch);
}
let word = |at| u32::from_le_bytes(header[at..at + 4].try_into().unwrap());
let (layers, experts, want, count) = (word(8), word(12), word(16), word(20));
if layers != binding.layer_count() || experts != 512 || count > want {
return Err(Error::InvalidDimension);
}
Ok((layers, experts, want, count))
}
fn read_pair(file: &mut File, layers: u32, experts: u32) -> Result<(u16, u16)> {
let mut raw = [0u8; 4];
file.read_exact(&mut raw).map_err(|_| Error::InputRead)?;
let pair = (u16::from_le_bytes([raw[0], raw[1]]), u16::from_le_bytes([raw[2], raw[3]]));
if u32::from(pair.0) >= layers || u32::from(pair.1) >= experts {
return Err(Error::InvalidDimension);
}
Ok(pair)
}
#[derive(Clone, Copy)]
pub(crate) struct OriginalCacheOptions {
/// -1=auto, 0=off, positive=explicit slots, as in Original.
@@ -58,6 +58,17 @@ impl<'ctx> OriginalVerifiedMtpReceipt<'ctx> {
}
Ok(Self { binding: binding.identity(), context, window, selection, before, first, accepted_row })
}
fn commit_origin_foreign(
&self,
binding: &ModelBinding,
session: &QwenSession<'ctx>,
(committed, source_origin): (&TargetStepOrigin, &TargetStepOrigin),
) -> Result<bool> {
Ok(!self.binding.matches(&binding.identity())
|| !std::ptr::eq(self.context, session.mtp_context()?)
|| !self.before.same_session(committed)
|| !source_origin.same_prefix(committed))
}
/// Must be called after the genuine verifier has committed exactly the
/// source accept count through `QwenChunkTxn::publish_verified_joint`.
/// The resulting `TargetStepProduct` rejects skipped, extra, manually
@@ -71,14 +82,9 @@ impl<'ctx> OriginalVerifiedMtpReceipt<'ctx> {
let committed = session.target_origin()?;
let (_, source_position, _, source_origin) = committed_source.mtp_source(binding, session)?;
self.before.validate_projection_branch(session)?;
let expected =
self.first.checked_add(self.accepted_row).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?;
if !self.binding.matches(&binding.identity())
|| !std::ptr::eq(self.context, session.mtp_context()?)
|| !self.before.same_session(&committed)
|| !source_origin.same_prefix(&committed)
|| source_position.get().checked_add(1).ok_or(Error::Overflow)? != committed.next_position()
|| usize::try_from(committed.next_position()).map_err(|_| Error::Overflow)? != expected
let expected = window_end_row(self.first, self.accepted_row)?;
if self.commit_origin_foreign(binding, session, (&committed, &source_origin))?
|| committed_position_foreign(source_position.get(), &committed, expected)?
{
return Err(Error::IdentityMismatch);
}
@@ -112,15 +118,11 @@ impl<'ctx> OriginalCommittedMtpReceipt<'ctx> {
accepted_row: usize,
) -> Result<Self> {
let committed = session.target_origin()?;
window.validate_context(context).map_err(driver_error)?;
window.validate_selection(&selection).map_err(driver_error)?;
let first = u64::try_from(window.first_position()).map_err(|_| Error::Overflow)?;
let expected = first.checked_add(accepted_row as u64).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?;
check_window(&window, context, &selection)?;
let (first, expected) = published_bounds(&window, accepted_row)?;
if !std::ptr::eq(context, session.mtp_context()?)
|| accepted_row >= window.rows()
|| !before.same_session(&committed)
|| before.next_position() != first
|| committed.next_position() != expected
|| published_origins_foreign(&before, &committed, (first, expected))
{
return Err(Error::IdentityMismatch);
}
@@ -133,25 +135,55 @@ impl<'ctx> OriginalCommittedMtpReceipt<'ctx> {
session: &QwenSession<'ctx>,
context: &Context<'ctx>,
) -> Result<()> {
self.window.validate_context(context).map_err(driver_error)?;
self.window.validate_selection(&self.selection).map_err(driver_error)?;
let expected = self
.window
.first_position()
.checked_add(self.accepted_row)
.and_then(|n| n.checked_add(1))
.ok_or(Error::Overflow)?;
let expected = self.checked_window_end(context)?;
self.before.validate_projection_branch(session)?;
self.committed.validate(session)?;
if !self.binding.matches(&binding.identity())
|| !std::ptr::eq(self.context, context)
|| !std::ptr::eq(context, session.mtp_context()?)
|| !self.before.same_session(&self.committed)
|| usize::try_from(self.committed.next_position()).map_err(|_| Error::Overflow)? != expected
|| self.accepted_row >= self.window.rows()
|| self.committed_foreign(expected)?
{
return Err(Error::IdentityMismatch);
}
Ok(())
}
fn checked_window_end(&self, context: &Context<'ctx>) -> Result<usize> {
check_window(&self.window, context, &self.selection)?;
window_end_row(self.window.first_position(), self.accepted_row)
}
fn committed_foreign(&self, expected: usize) -> Result<bool> {
Ok(!self.before.same_session(&self.committed)
|| usize::try_from(self.committed.next_position()).map_err(|_| Error::Overflow)? != expected
|| self.accepted_row >= self.window.rows())
}
}
fn check_window(
window: &OriginalVerifyWindow<'_>,
context: &Context<'_>,
selection: &NativeHeadSelection,
) -> Result<()> {
window.validate_context(context).map_err(driver_error)?;
window.validate_selection(selection).map_err(driver_error)?;
Ok(())
}
// The row count after `accepted_row` more rows from `first`, and one past it.
fn window_end_row(first: usize, accepted_row: usize) -> Result<usize> {
first.checked_add(accepted_row).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)
}
fn published_origins_foreign(
before: &TargetStepOrigin,
committed: &TargetStepOrigin,
(first, expected): (u64, u64),
) -> bool {
!before.same_session(committed) || before.next_position() != first || committed.next_position() != expected
}
fn published_bounds(window: &OriginalVerifyWindow<'_>, accepted_row: usize) -> Result<(u64, u64)> {
let first = u64::try_from(window.first_position()).map_err(|_| Error::Overflow)?;
let expected = first.checked_add(accepted_row as u64).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?;
Ok((first, expected))
}
fn committed_position_foreign(source_position: u64, committed: &TargetStepOrigin, expected: usize) -> Result<bool> {
Ok(source_position.checked_add(1).ok_or(Error::Overflow)? != committed.next_position()
|| usize::try_from(committed.next_position()).map_err(|_| Error::Overflow)? != expected)
}
@@ -248,8 +248,8 @@ impl<P> ServeConversation<P> {
/// next request of the conversation read from its last checkpoint. Returns whether the claim was kept.
pub(super) fn note_cancelled_prefill(&mut self, prompt: &[i32], reached: u64, in_step: bool) -> bool {
let Ok(reached) = usize::try_from(reached) else { return false };
// the cells below `reached` are this prompt's (a restored point is a prefix of it and every published chunk wrote the
// next ones); the last prompt token always starts the first verify window
// the cells below `reached` are this prompt's (a restored point is a prefix of it and every published chunk
// wrote the next ones); the last prompt token always starts the first verify window
if !in_step || self.start.is_none() || reached == 0 || reached >= prompt.len() {
return false;
}
@@ -108,7 +108,8 @@ impl<P: OriginalServePort> OriginalSpecEngine for OriginalServeEngine<P> {
Ok(())
}
fn discard_window(&mut self) -> Result<()> {
// after the drain of the refused window, before the checkpoints' round starts again: no window may be alive, no commit outstanding
// after the drain of the refused window, before the checkpoints' round starts again: no window may be
// alive, no commit outstanding
if self.live_windows != 0 || self.commit_pending {
return Err(Error::IdentityMismatch);
}
@@ -84,9 +84,10 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> {
fn begin_adaptation(&mut self, next_round: u64) -> Result<()> {
// generate.cpp `adapt()` when `(rounds + 1) % adapt_every == 0`, issued before the commit; its copies
// run on the tier's own stream beside the commit and the draft (no work for the all-CPU tier).
// The planning and the queueing are host work (0.6 ms on an adaptation round) that sat between the window and the commit/draft
// launch; with the deferral they run once the draft is launched (`run_deferred_adaptation`) or, at the latest, at the join,
// always before the next round's `apply_pending`. LELEKA_SERVE_ADAPT_DEFER=off runs them here as before.
// The planning and the queueing are host work (0.6 ms on an adaptation round) that sat between the window
// and the commit/draft launch; with the deferral they run once the draft is launched
// (`run_deferred_adaptation`) or, at the latest, at the join, always before the next round's
// `apply_pending`. LELEKA_SERVE_ADAPT_DEFER=off runs them here as before.
if adapt_defer() {
if self.deferred_adaptation.is_some() {
return Err(Error::IdentityMismatch);
@@ -84,16 +84,7 @@ where
// A capture-only or already-superseded window cannot pass: the driver mints
// `completed_window` only for the genuinely completed current generation.
let completed = self.verifier.completed_window().map_err(|_| Error::IdentityMismatch)?;
if completed.generation() != window.generation
|| completed.rows() != window.rows
|| completed.first_position() != usize::try_from(position).map_err(|_| Error::InvalidPosition)?
{
return Err(Error::IdentityMismatch);
}
if let Some(selection) = window.selection.borrow().as_ref() {
completed.validate_selection(selection).map_err(|_| Error::IdentityMismatch)?;
}
Ok(())
check_completed(&completed, window, position)
}
fn window_outputs<'a>(&self, window: &'a NativeWindow) -> &'a [i32] {
&window.ids
@@ -125,7 +116,8 @@ where
Ok(())
}
fn discard_window(&mut self) -> Result<()> {
// an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears `pending_publish`)
// an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears
// `pending_publish`)
if self.pending_publish.is_some() {
self.failed = true;
return Err(Error::IdentityMismatch);
@@ -197,3 +189,19 @@ where
self.host.drain_first()
}
}
fn start_foreign(first: usize, position: i64) -> Result<bool> {
Ok(first != usize::try_from(position).map_err(|_| Error::InvalidPosition)?)
}
// The completed window is the one `window` stands for, started at `position`, with the same head selection.
fn check_completed(completed: &OriginalVerifyWindow<'_>, window: &NativeWindow, position: i64) -> Result<()> {
if completed.generation() != window.generation
|| completed.rows() != window.rows
|| start_foreign(completed.first_position(), position)?
{
return Err(Error::IdentityMismatch);
}
if let Some(selection) = window.selection.borrow().as_ref() {
completed.validate_selection(selection).map_err(|_| Error::IdentityMismatch)?;
}
Ok(())
}
@@ -181,7 +181,8 @@ impl DirectTier {
match self.start_lookahead(binding) {
Ok(lookahead) => {
eprintln!(
"leleka-serve cpu expert pool: router lookahead on (mapped experts, LELEKA_CPU_POOL_LOOKAHEAD=on)"
"leleka-serve cpu expert pool: router lookahead on \
(mapped experts, LELEKA_CPU_POOL_LOOKAHEAD=on)"
);
self.lookahead = Some(lookahead);
}
@@ -103,22 +103,30 @@ pub(super) fn open_job(
held: &Option<[ResidentExpertBankSpan; 3]>,
) -> Result<Opened> {
source.validate_binding(binding).map_err(binding_error)?;
let keys = [
source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?,
source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?,
source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?,
];
let keys = job_descriptors(source)?;
if keys.iter().any(|k| k.layer != layer || k.expert != Some(expert)) {
return Err(Error::IdentityMismatch);
}
let format = validate_triplet(keys).map_err(runtime_error)?;
let spans = [
let spans = job_bank_spans(source)?;
let ready = held.as_ref().is_some_and(|h| same_spans(h, &spans));
Ok((spans, format, ready))
}
fn job_descriptors(
source: &mut MoeRoutedSourceScope<'_, '_>,
) -> Result<[crate::model_binding::qwen4exp_input::MoeWeightDescriptor; 3]> {
Ok([
source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?,
source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?,
source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?,
])
}
fn job_bank_spans(source: &mut MoeRoutedSourceScope<'_, '_>) -> Result<[ResidentExpertBankSpan; 3]> {
Ok([
source.bank_span(0, MoeMatrixRole::Gate).map_err(binding_error)?,
source.bank_span(0, MoeMatrixRole::Up).map_err(binding_error)?,
source.bank_span(0, MoeMatrixRole::Down).map_err(binding_error)?,
];
let ready = held.as_ref().is_some_and(|h| same_spans(h, &spans));
Ok((spans, format, ready))
])
}
/// First use (or a different span): admit every row of the job's actual matrices and retain them.
@@ -12,8 +12,8 @@ impl PrefixConfig {
max_nodes: 1024,
memory_floor: 3 << 30,
policy: {
// LELEKA_PREFIX_RETENTION_S: session retention in seconds (default 3600 = 60 minutes; 0 = no time limit); a
// diagnostic knob so the expiry path can be exercised in minutes
// LELEKA_PREFIX_RETENTION_S: session retention in seconds (default 3600 = 60 minutes; 0 = no time
// limit); a diagnostic knob so the expiry path can be exercised in minutes
let mut policy = PolicyParams::default();
if let Some(seconds) = crate::settings::process().kv.prefix_retention_s {
policy.retention_ms = seconds.saturating_mul(1000);
@@ -177,8 +177,8 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
if self.cfg.tail != TailMode::Reply || self.bypass || self.req.is_none() {
return Ok(ChunkOutcome::Nothing);
}
// the prompt-end checkpoint of this request stays: a client that resends the history without the reasoning of the reply
// continues from the prompt, not from the decode end
// the prompt-end checkpoint of this request stays: a client that resends the history without the reasoning
// of the reply continues from the prompt, not from the decode end
let keep = self.req.as_ref().map(|r| r.limit);
let outcome = self.admit_tail(device, consumed, keep)?;
if matches!(outcome, ChunkOutcome::Admitted { .. } | ChunkOutcome::Exists) {
@@ -287,7 +287,9 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
pub(in super::super::super) fn describe(&self) -> String {
let s = self.store.stats();
format!(
"prefix stats: nodes={} blocks={} used_mib={} budget_mib={} requests={} hits={} shared_hits={} misses={} reused_tokens={} prompt_tokens={} admitted={} rejected={} evicted={} expired={} already_cached={} live_tokens={}",
"prefix stats: nodes={} blocks={} used_mib={} budget_mib={} requests={} hits={} shared_hits={} \
misses={} reused_tokens={} prompt_tokens={} admitted={} rejected={} evicted={} expired={} \
already_cached={} live_tokens={}",
self.store.node_count(),
self.store.block_count(),
self.store.bytes() >> 20,
@@ -311,7 +311,8 @@ impl ResidencyStats {
String::new()
};
format!(
"expert tier: {} layer groups, entries vram {} ({:.1}%) pcie {} ({:.1}%) cpu {} ({:.1}%), {} adaptations, {} swaps{}",
"expert tier: {} layer groups, entries vram {} ({:.1}%) pcie {} ({:.1}%) cpu {} ({:.1}%), \
{} adaptations, {} swaps{}",
self.groups,
self.vram_entries,
100.0 * self.vram_entries as f64 / all,
@@ -33,11 +33,14 @@ pub(crate) fn effective_tail_rank(cache: &OriginalExpertCache<'_>) -> u32 {
if ANNOUNCED.swap(effective, Ordering::Relaxed) != effective {
if effective == 0 {
eprintln!(
"leleka-serve: route tail skip {rank} is OFF: {percent:.1}% of the experts are in VRAM (limit {limit:.0}%)"
"leleka-serve: route tail skip {rank} is OFF: {percent:.1}% of the experts are in VRAM \
(limit {limit:.0}%)"
);
} else {
eprintln!(
"leleka-serve: EXPERIMENTAL route tail skip is ON (LELEKA_ROUTE_TAIL_SKIP={rank}, {percent:.1}% of the experts in VRAM): a missed expert every token of a window routes at rank {rank} or lower is skipped; the OUTPUT CHANGES"
"leleka-serve: EXPERIMENTAL route tail skip is ON (LELEKA_ROUTE_TAIL_SKIP={rank}, {percent:.1}% of \
the experts in VRAM): a missed expert every token of a window routes at rank {rank} or lower is \
skipped; the OUTPUT CHANGES"
);
}
}
@@ -67,14 +70,16 @@ impl ExpertTierConfig {
per_layer: false,
profile: None,
reserve_mib: 700,
// measured (jobs 989/990/988): the per-request verifier needs ~450 MiB, so 1024 left ~550 MiB idle (180k smoke
// included); 300 gives the auto-sized cache ~+330 slots. 5090, 5 x 245k session (speedtrain-ab): with 300 the card
// never had less than 563 MiB free (vanilla runs down to 315), so 130 would be safe on the card (E: +87 slots),
// but the first slots-footprint A/B showed the Context BUDGET is a second ceiling the planner now respects
// (`usable_room`); 130 stays an opt-in (`LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130`) until its own arm measures it.
// measured (jobs 989/990/988): the per-request verifier needs ~450 MiB, so 1024 left ~550 MiB idle
// (180k smoke included); 300 gives the auto-sized cache ~+330 slots. 5090, 5 x 245k session
// (speedtrain-ab): with 300 the card never had less than 563 MiB free (vanilla runs down to 315), so
// 130 would be safe on the card (E: +87 slots), but the first slots-footprint A/B showed the Context
// BUDGET is a second ceiling the planner now respects (`usable_room`); 130 stays an opt-in
// (`LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130`) until its own arm measures it.
decode_reserve_mib: 300,
// the PCIe share that equalises the legs when the CPU pool and the DMA share the host's memory ceiling
// (P/(P+C) = 0.45, job 987-b/909; 0.45 vs 0.55: +0.5 % / +4.7 % at the auto-sized cache, equal at 2048 slots)
// (P/(P+C) = 0.45, job 987-b/909; 0.45 vs 0.55: +0.5 % / +4.7 % at the auto-sized cache, equal at
// 2048 slots)
pcie_frac: 0.45,
pcie_frac_set: false,
pcie_mode: PcieMode::Auto,
@@ -98,22 +103,26 @@ impl ExpertTierConfig {
if self.slots == 0 && self.profile.is_some() { -1 } else { self.slots }
}
pub(crate) fn validate(&self) -> Result<()> {
if self.slots < -1
if self.cache_shape_invalid() || self.seed_invalid() {
return Err(Error::InvalidDimension);
}
Ok(())
}
fn cache_shape_invalid(&self) -> bool {
self.slots < -1
|| !self.pcie_frac.is_finite()
|| !(0.0..=1.0).contains(&self.pcie_frac)
|| self.adapt_swaps > 4096
|| !self.resident_budget_gib.is_finite()
|| self.resident_budget_gib < 0.0
|| !self.seed_keep.is_finite()
}
fn seed_invalid(&self) -> bool {
!self.seed_keep.is_finite()
|| self.seed_keep < 0.0
|| !self.seed_usage.is_finite()
|| self.seed_usage < 0.0
|| !(0.0..=1.0).contains(&self.seed_decay)
|| self.seed_swaps > LAYERS * EXPERTS
{
return Err(Error::InvalidDimension);
}
Ok(())
}
/// `pcie_num = clamp(round(pcie_frac * 256), 0, 256)`.
pub(crate) fn pcie_num(&self) -> u32 {
@@ -34,8 +34,9 @@ impl StackConfig {
rt_directory: None,
coupled: crate::settings::process().decode.coupled,
// LELEKA_ORIGINAL_SERVE_CPU_WORKERS: experiment knob (the Original's default on this host is 15)
// LELEKA_CPU_POOL_PLAN=on: when the count is not set, the plan of `native-cpu-expert::pool_plan` (physical cores but the host's, hybrid and quota aware;
// docs/upstream-port-plan.md row 2.3) instead of the constant 15 (opt-in: the same 15 on the server's 16-core CPU, not measured on any other)
// LELEKA_CPU_POOL_PLAN=on: when the count is not set, the plan of `native-cpu-expert::pool_plan`
// (physical cores but the host's, hybrid and quota aware; docs/upstream-port-plan.md row 2.3) instead
// of the constant 15 (opt-in: the same 15 on the server's 16-core CPU, not measured on any other)
cpu_workers: serve.cpu_workers.unwrap_or_else(|| {
if serve.cpu_pool_plan { leleka_native_cpu_expert::pool_plan::default_workers() } else { CPU_WORKERS }
}),
@@ -53,17 +54,19 @@ impl StackConfig {
pub(crate) fn kv_footprint(&self) -> Option<leleka_context::geometry::KvStreamFootprint> {
leleka_cuda_driver::serving_context().geometry.kv_stream_footprint(self.kv_resident).ok()
}
fn capacity_invalid(&self) -> bool {
!ADMITTED_CAPACITIES.contains(&self.capacity) || self.kv_footprint().is_none() || self.capacity > 8192
}
fn context_invalid(&self) -> bool {
self.max_context < 1
|| self.max_context as u64 > super::super::contract::serving_cells()
|| !(1..=64).contains(&self.cpu_workers)
}
pub(crate) fn validate(&self) -> Result<()> {
if self.kv_format != KvFormat::Int8 {
return Err(Error::Unsupported(super::super::contract::Stage::Session));
}
if !ADMITTED_CAPACITIES.contains(&self.capacity)
|| self.kv_footprint().is_none()
|| self.capacity > 8192
|| self.max_context < 1
|| self.max_context as u64 > super::super::contract::serving_cells()
|| !(1..=64).contains(&self.cpu_workers)
{
if self.capacity_invalid() || self.context_invalid() {
return Err(Error::InvalidDimension);
}
if let Some(conversation) = &self.conversation {
@@ -51,7 +51,8 @@ impl<'ctx> RefillOwners<'_, 'ctx> {
fn note_window_retry(failed: usize, next: usize) {
operator_text(&format!(
"decode window graphs: out of device memory recording windows up to T={failed}; retrying with windows up to T={next}"
"decode window graphs: out of device memory recording windows up to T={failed}; \
retrying with windows up to T={next}"
))
}
@@ -164,7 +165,8 @@ pub(super) fn narrow_window_policy(
) -> Result<()> {
let (settings, controller, verifier_max_t) = stack;
operator_text(&format!(
"decode window graphs: windows limited to T<={used_max_t} (were T<={}): the policy, its arms and the MTP draft cap follow",
"decode window graphs: windows limited to T<={used_max_t} (were T<={}): the policy, its arms and the \
MTP draft cap follow",
*verifier_max_t
));
*verifier_max_t = used_max_t;
@@ -3,6 +3,10 @@
#[allow(unused_imports)]
use super::*;
#[path = "impl_originalservestack_2/open_phases.rs"]
mod open_phases;
use open_phases::{OpenCtx, load_buffers, load_core, open_tier};
impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// `generate.cpp` startup over the binding: embedding table, native head + embedding, dense weights at
/// the prompt capacity, the MoE arena cache, the target session, the prompt executor with the MTP
@@ -23,76 +27,15 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
let formats = expert_formats(binding).map_err(at("expert_formats"))?;
let layout = prefill_layout_options(config.capacity, max_cells, &blobs);
let weights = load_weights(binding, context, &config, layout)?;
let mut session = QwenSession::for_binding_on_shared_device(binding, shared);
let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context));
let opened =
open_executor(binding, context, &config, &weights, &mut session, verifier_max_t, settings.coupled)?;
let (mut executor, draft) = opened;
let Weights { output, embedding, kar, dense, mut moe } = weights;
share_rt_dense_roles(&config, &executor, &mut moe)?;
vram_note(context, "after prompt executor and draft");
crate::memory_governor::end(executor_stage, Some(context));
// generate.cpp: the expert cache is sized after everything else, and the prompt path's own buffers
// after the cache when it cannot borrow them; without the tier the order is unchanged.
let tier = config.expert_tier.enabled();
let mut arena = staged!(
"prefill arena",
context,
if tier {
None
} else {
Some(context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?)
}
);
vram_note(context, "before cache");
let history = staged!(
"penalty history",
context,
OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))?
);
let ple_history = context.allocate(PLE_HISTORY_BYTES).map_err(at("ple_history"))?;
let ple_scratch = context.allocate(PLE_SCRATCH_BYTES).map_err(at("ple_scratch"))?;
let pool = staged!(
"CPU expert pool",
context,
CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))?
);
let empty_session = staged!(
"empty-prompt session checkpoint",
context,
executor.checkpoint_session(binding, &mut session).map_err(at("checkpoint_session"))?
);
let empty_draft = staged!(
"empty-prompt draft checkpoint",
context,
draft.checkpoint(binding, &session).map_err(at("draft.checkpoint"))?
);
let prefix = open_prefix(&config);
let conversation =
if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) };
let residency = ResidencyState::new(&config.expert_tier);
report_kernel_selection();
vram_note(context, "before expert tier");
let (expert_cache, loan) = open_expert_cache(binding, context, &moe, &config, layout)?;
vram_note(context, "after expert tier");
let loan_tiers = loan_ladder(&config, layout, loan, expert_cache.as_ref())?;
let initial_owners: Vec<Option<(usize, usize)>> = expert_cache
.as_ref()
.map(|cache| (0..cache.slots()).map(|slot| cache.slot_owner(slot)).collect())
.unwrap_or_default();
if arena.is_none() && loan.is_none() {
arena = Some(staged!(
"prefill arena (after the expert tier)",
context,
context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?
));
}
let ctx = OpenCtx { binding, context, config: &config, layout };
let mut core = load_core(&ctx, shared, (verifier_max_t, settings.coupled))?;
let mut buffers = load_buffers(&ctx, &mut core)?;
let tier = open_tier(&ctx, &core.moe, &mut buffers.arena)?;
let this = Self {
binding,
context,
conversation,
prefix,
conversation: tier.conversation,
prefix: tier.prefix,
tail_consumed: None,
reused: 0,
resume_point: 0,
@@ -110,33 +53,33 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
arm_order,
verifier_max_t,
broken: None,
empty_session,
empty_draft,
history,
ple_history,
ple_scratch,
arena,
empty_session: buffers.empty_session,
empty_draft: buffers.empty_draft,
history: buffers.history,
ple_history: buffers.ple_history,
ple_scratch: buffers.ple_scratch,
arena: buffers.arena,
layout,
expert_cache,
loan,
loan_tiers,
residency,
initial_owners,
expert_cache: tier.expert_cache,
loan: tier.loan,
loan_tiers: tier.loan_tiers,
residency: tier.residency,
initial_owners: tier.initial_owners,
seed_report: None,
seed_counts: None,
refill_pending: false,
refill_due: false,
timing: (0.0, 0.0),
marks: TtftMarks::default(),
executor,
draft,
session,
pool,
kar,
moe,
dense,
output,
embedding,
executor: core.executor,
draft: core.draft,
session: core.session,
pool: buffers.pool,
kar: core.kar,
moe: core.moe,
dense: core.dense,
output: core.output,
embedding: core.embedding,
};
this.register_memory_classes();
crate::memory_governor::post_open();
@@ -0,0 +1,150 @@
//! Phases of `OriginalServeStack::open`, moved out of it by STRA-338 (size): each helper runs one step of the startup
//! in the order `open` called it, with the same stage marks, notes and error context.
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::session::original_prompt::draft::OriginalDraftSession;
/// What every phase of the startup reads: the binding, the context, the configuration and the prompt layout.
pub(super) struct OpenCtx<'x, 'a, 'ctx> {
pub(super) binding: &'a ModelBinding,
pub(super) context: &'ctx Context<'ctx>,
pub(super) config: &'x StackConfig,
pub(super) layout: PrefillLayoutOptions,
}
/// The session, the prompt executor with its MTP drafter and the weights they run over.
pub(super) struct Core<'ctx> {
pub(super) executor: OriginalPromptExecutor<'ctx>,
pub(super) draft: OriginalDraftSession<'ctx>,
pub(super) session: QwenSession<'ctx>,
pub(super) kar: Option<KarPleCache<'ctx>>,
pub(super) moe: MoeWeightCache<'ctx>,
pub(super) dense: DenseWeightCache<'ctx>,
pub(super) output: OriginalNativeOutput<'ctx>,
pub(super) embedding: OriginalPromptEmbedding<'ctx>,
}
/// The prefill arena, the history and scratch buffers, the CPU expert pool and the empty-prompt checkpoints.
pub(super) struct Buffers<'a, 'ctx> {
pub(super) arena: Option<OriginalPrefillArena<'ctx, 'ctx>>,
pub(super) history: OriginalNativePenaltyHistory<'ctx>,
pub(super) ple_history: DeviceBuffer<'ctx>,
pub(super) ple_scratch: DeviceBuffer<'ctx>,
pub(super) pool: CpuExpertPool<'a>,
pub(super) empty_session: OriginalSessionCheckpoint<'ctx>,
pub(super) empty_draft: OriginalDraftCheckpoint,
}
/// The conversation or prefix cache and the VRAM expert tier with its loan ladder.
pub(super) struct TierParts<'ctx> {
pub(super) conversation: Option<ServeConversation<StackPoint<'ctx>>>,
pub(super) prefix: Option<PrefixServe<StackState, StackBlock>>,
pub(super) residency: ResidencyState,
pub(super) expert_cache: Option<OriginalExpertCache<'ctx>>,
pub(super) loan: Option<usize>,
pub(super) loan_tiers: Vec<LoanTier>,
pub(super) initial_owners: Vec<Option<(usize, usize)>>,
}
/// The weights, the target session and the prompt executor with the MTP drafter; `verifier` is the widest window
/// and whether the policy is coupled.
pub(super) fn load_core<'a, 'ctx>(
ctx: &OpenCtx<'_, 'a, 'ctx>,
shared: Rc<Context<'ctx>>,
verifier: (usize, bool),
) -> std::result::Result<Core<'ctx>, ServeFailure> {
let (binding, context, config) = (ctx.binding, ctx.context, ctx.config);
let weights = load_weights(binding, context, config, ctx.layout)?;
let mut session = QwenSession::for_binding_on_shared_device(binding, shared);
let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context));
let opened = open_executor(binding, context, config, &weights, &mut session, verifier.0, verifier.1)?;
let (executor, draft) = opened;
let Weights { output, embedding, kar, dense, mut moe } = weights;
share_rt_dense_roles(config, &executor, &mut moe)?;
vram_note(context, "after prompt executor and draft");
crate::memory_governor::end(executor_stage, Some(context));
Ok(Core { executor, draft, session, kar, moe, dense, output, embedding })
}
/// The expert cache is sized after everything else, and the prompt path's own buffers after the cache when it cannot
/// borrow them; without the tier the order is unchanged.
pub(super) fn load_buffers<'a, 'ctx>(
ctx: &OpenCtx<'_, 'a, 'ctx>,
core: &mut Core<'ctx>,
) -> std::result::Result<Buffers<'a, 'ctx>, ServeFailure> {
let (binding, context, config) = (ctx.binding, ctx.context, ctx.config);
let tier = config.expert_tier.enabled();
let arena = staged!(
"prefill arena",
context,
if tier {
None
} else {
Some(context.original_prefill_arena(ctx.layout).map_err(at("original_prefill_arena"))?)
}
);
vram_note(context, "before cache");
let history = staged!(
"penalty history",
context,
OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))?
);
let ple_history = context.allocate(PLE_HISTORY_BYTES).map_err(at("ple_history"))?;
let ple_scratch = context.allocate(PLE_SCRATCH_BYTES).map_err(at("ple_scratch"))?;
let pool = staged!(
"CPU expert pool",
context,
CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))?
);
let (empty_session, empty_draft) = empty_checkpoints(ctx, core)?;
Ok(Buffers { arena, history, ple_history, ple_scratch, pool, empty_session, empty_draft })
}
fn empty_checkpoints<'ctx>(
ctx: &OpenCtx<'_, '_, 'ctx>,
core: &mut Core<'ctx>,
) -> std::result::Result<(OriginalSessionCheckpoint<'ctx>, OriginalDraftCheckpoint), ServeFailure> {
let (binding, context) = (ctx.binding, ctx.context);
let empty_session = staged!(
"empty-prompt session checkpoint",
context,
core.executor.checkpoint_session(binding, &mut core.session).map_err(at("checkpoint_session"))?
);
let empty_draft = staged!(
"empty-prompt draft checkpoint",
context,
core.draft.checkpoint(binding, &core.session).map_err(at("draft.checkpoint"))?
);
Ok((empty_session, empty_draft))
}
/// The prefix or conversation cache, then the VRAM expert tier; the prefill arena is opened here when the tier left it
/// unopened and no loan stands in for it.
pub(super) fn open_tier<'ctx>(
ctx: &OpenCtx<'_, '_, 'ctx>,
moe: &MoeWeightCache<'ctx>,
arena: &mut Option<OriginalPrefillArena<'ctx, 'ctx>>,
) -> std::result::Result<TierParts<'ctx>, ServeFailure> {
let (binding, context, config, layout) = (ctx.binding, ctx.context, ctx.config, ctx.layout);
let prefix = open_prefix(config);
let conversation = if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) };
let residency = ResidencyState::new(&config.expert_tier);
report_kernel_selection();
vram_note(context, "before expert tier");
let (expert_cache, loan) = open_expert_cache(binding, context, moe, config, layout)?;
vram_note(context, "after expert tier");
let loan_tiers = loan_ladder(config, layout, loan, expert_cache.as_ref())?;
let initial_owners: Vec<Option<(usize, usize)>> = expert_cache
.as_ref()
.map(|cache| (0..cache.slots()).map(|slot| cache.slot_owner(slot)).collect())
.unwrap_or_default();
if arena.is_none() && loan.is_none() {
*arena = Some(staged!(
"prefill arena (after the expert tier)",
context,
context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?
));
}
Ok(TierParts { conversation, prefix, residency, expert_cache, loan, loan_tiers, initial_owners })
}
@@ -46,7 +46,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
match prefix.after_prefill(self, prompt) {
Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => {
operator_text(&format!(
"prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}",
"prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} \
park_ms={park_ms:.1}",
bytes >> 20
));
}
@@ -69,7 +70,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
match prefix.after_decode(self, consumed) {
Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => {
operator_text(&format!(
"prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}",
"prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} \
park_ms={park_ms:.1}",
bytes >> 20
));
}