STRA-338 size6 c01: group fields of OriginalServeStack, DenseWeightCache, QwenChunkTxn and Context so their constructors fit the limit

This commit is contained in:
Pavlo Ratushnyi
2026-11-07 17:23:32 +01:00
parent 08def7efea
commit 24b20f76e4
40 changed files with 690 additions and 543 deletions
@@ -181,8 +181,7 @@ impl<'driver> Context<'driver> {
qwen_kernels: qwen_dispatch::Cache::new(),
kar_levels: Cell::new(None),
experimental: std::array::from_fn(|_| Cell::new(None)),
window_modules: RefCell::new(Vec::new()),
deferred_frees: RefCell::new(Vec::new()),
retained: crate::prompt_sync_trace_types::Retained::default(),
}
}
}
+2 -2
View File
@@ -72,7 +72,7 @@ impl Context<'_> {
/// queued bytes pass `LELEKA_PREFILL_DEFER_FREE_MIB` (512) they are freed at once.
pub(super) fn defer_free(&self, handle: ffi::BufferHandle, bytes: usize) -> Result<()> {
let pending = {
let mut list = self.deferred_frees.borrow_mut();
let mut list = self.retained.deferred_frees.borrow_mut();
list.push((handle, bytes));
list.iter().map(|b| b.1).sum::<usize>()
};
@@ -88,7 +88,7 @@ impl Context<'_> {
}
/// Free every deferred buffer (one device synchronization).
pub(crate) fn flush_deferred_frees(&self) -> Result<()> {
let list = std::mem::take(&mut *self.deferred_frees.borrow_mut());
let list = std::mem::take(&mut *self.retained.deferred_frees.borrow_mut());
if list.is_empty() {
return Ok(());
}
+1 -1
View File
@@ -52,7 +52,7 @@ impl Context<'_> {
/// The shared verify-window modules: unloaded (current context) once no bank holds them; a module a live
/// bank still shares is left to that bank's own unload.
pub(super) fn unload_window_modules(&mut self) -> Result<()> {
let modules = std::mem::take(self.window_modules.get_mut());
let modules = std::mem::take(self.retained.window_modules.get_mut());
if modules.is_empty() {
return Ok(());
}
@@ -42,7 +42,7 @@ impl Physical<'_> {
let mut ready = Vec::new();
let mut unsealed: Result<()> = Ok(());
let mut loaded = self.window.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
let cache = self.context.window_modules.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
let cache = self.context.retained.window_modules.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
for (key, spec, entries) in groups {
if reuse_loaded(&mut loaded, &cache, key, &entries)? {
continue;
@@ -79,7 +79,7 @@ impl Physical<'_> {
fn load_module(&self, key: &'static str, ptx: &'static [u8], entries: Vec<&'static str>) -> Result<()> {
let m = Rc::new(Module::load(ptx, &entries)?);
{
let mut c = self.context.window_modules.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
let mut c = self.context.retained.window_modules.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
c.retain(|(n, _, _)| *n != key);
if c.try_reserve(1).is_ok() {
c.push((key, Rc::clone(&m), entries.clone()))
@@ -3,6 +3,9 @@
#[allow(unused_imports)]
use super::*;
mod retained;
pub(crate) use retained::Retained;
/// Bring-up: with `LELEKA_BRINGUP_TRACE` and `LELEKA_CUDA_TRACE_SYNC` set (Windows), every kernel launched while a
/// guard is alive is followed by a `cuStreamSynchronize`, so a device fault is named by the launch that caused it (the
/// non-blocking replacement of `CUDA_LAUNCH_BLOCKING`, scoped to the prompt forward because the decode windows would
@@ -110,12 +113,7 @@ pub struct Context<'driver> {
pub(super) qwen_kernels: qwen_dispatch::Cache,
pub(super) kar_levels: Cell<Option<kar_decode_levels::KarLevelsKernels>>,
pub(super) experimental: [Cell<Option<experimental::LoadedProgram>>; 6],
/// Sealed verify-window modules loaded under this context, shared by every verifier bank created later
/// (the serve path assembles one per request) and unloaded with the context.
pub(super) window_modules: RefCell<Vec<(&'static str, Rc<original_verify::abi::Module>, Vec<&'static str>)>>,
/// Buffers released while a prompt chunk's expert copies are in flight (cuMemFree synchronizes the whole
/// device and would wait for every queued copy): freed by `flush_deferred_frees`. They stay charged.
pub(super) deferred_frees: RefCell<Vec<(ffi::BufferHandle, usize)>>,
pub(super) retained: Retained,
}
#[derive(Clone, Copy)]
pub(super) struct FixedKernel {
@@ -0,0 +1,15 @@
//! The host-side lists a `Context` keeps for the verify-window modules and the deferred buffer frees.
#[allow(unused_imports)]
use super::*;
/// Lists that live and die with the context: both start empty.
#[derive(Default)]
pub(crate) struct Retained {
/// Sealed verify-window modules loaded under this context, shared by every verifier bank created later
/// (the serve path assembles one per request) and unloaded with the context.
pub(crate) window_modules: RefCell<Vec<(&'static str, Rc<original_verify::abi::Module>, Vec<&'static str>)>>,
/// Buffers released while a prompt chunk's expert copies are in flight (cuMemFree synchronizes the whole
/// device and would wait for every queued copy): freed by `flush_deferred_frees`. They stay charged.
pub(crate) deferred_frees: RefCell<Vec<(ffi::BufferHandle, usize)>>,
}
@@ -76,42 +76,9 @@ pub(crate) struct DenseWeightCache<'ctx> {
gdn_mirrors: Vec<Option<RefCell<GdnStateMirror<'ctx>>>>,
mirror_failed: Rc<Cell<bool>>,
gdn_four_borrow: bool,
gdn_input: Option<RefCell<GdnInputScratch<'ctx>>>,
gdn_qk_workspace: Option<Rc<QkScratch<'ctx>>>,
qsa_attention_workspace: Option<RefCell<QsaAttentionScratch<'ctx>>>,
gdn_verification: Option<Rc<RefCell<super::gdn::verification::Workspace<'ctx>>>>,
/// Idle GDN next-state finite guards (each owns a loaded module and a status word): a prompt chunk's GDN
/// layer borrows one and gives it back, instead of loading the module once per layer and chunk.
gdn_guards: RefCell<Vec<leleka_cuda_driver::GdnStateFiniteGuard<'ctx>>>,
/// Idle 3.1 MB GDN state buffers (`LELEKA_PREFILL_GDN_POOL`): the chunk device's ping-pong scratch and the mirror's
/// spare used to be a cuMemAlloc / cuMemFree pair each per GDN layer and chunk (4 driver calls x 36 layers, each
/// free a device-wide synchronization).
gdn_scratch: RefCell<Vec<DeviceBuffer<'ctx>>>,
gr_scratch: Option<RefCell<GrScratch<'ctx>>>,
qsa_input: Option<RefCell<QsaInputScratch<'ctx>>>,
qsa_keys: Option<RefCell<QsaIndexKeyCache<'ctx>>>,
qsa_selected: Option<RefCell<QsaSelectedCache<'ctx>>>,
router_scratch: Option<RefCell<RouterScratch<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
gr_batch_workspace: Option<RefCell<GrBatchInjectWorkspace<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
ple_queue: Option<RefCell<leleka_cuda_driver::PleClosedQueue<'ctx>>>,
workspaces: Workspaces<'ctx>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native_prompt_capacity: usize,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native_batch_workspace: Option<RefCell<leleka_cuda_driver::NativeBatchWorkspace<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
ple_batch_queue: Option<RefCell<leleka_cuda_driver::PleBatchQueue<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
gdn_batch_resources: Option<RefCell<super::gdn::prefill_batch::GdnBatchResources<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
qsa_native_workspace: Option<RefCell<leleka_cuda_driver::QsaNativeBatchWorkspace<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native_qsa: Option<RefCell<super::qsa_native_resources::NativeQsaResources<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native_gdn_fused: Option<Rc<RefCell<leleka_cuda_driver::GdnFusedT1<'ctx>>>>,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
gr_batch_completed: Cell<u64>,
qsa: Vec<Option<QsaResident>>,
gr: Vec<GrResident>,
router: Vec<usize>,
@@ -120,6 +87,8 @@ pub(crate) struct DenseWeightCache<'ctx> {
}
mod dense_slab_policy_fn;
mod workspaces;
use workspaces::Workspaces;
mod impl_denseweightcache;
#[allow(unused_imports)]
use dense_slab_policy_fn::dense_slab_policy;
@@ -15,7 +15,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
pub(crate) fn new_qsa_selected_router(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result<Self> {
let mut result = Self::new_qsa_selected(binding, context)?;
match RouterScratch::new(result.binding.clone(), context, result.mirror_failed.clone()) {
Ok(slot) => result.router_scratch = Some(RefCell::new(slot)),
Ok(slot) => result.workspaces.router_scratch = Some(RefCell::new(slot)),
Err(primary) => {
let _ = result.close();
return Err(primary);
@@ -31,7 +31,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
) -> Result<Self> {
let mut result = Self::new_qsa_selected_router(binding, context)?;
match context.gr_batch_inject_workspace() {
Ok(slot) => result.gr_batch_workspace = Some(RefCell::new(slot)),
Ok(slot) => result.workspaces.gr_batch_workspace = Some(RefCell::new(slot)),
Err(error) => {
let primary = driver_error(error);
let _ = result.close();
@@ -47,7 +47,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
) -> Result<Self> {
let mut result = Self::new_qsa_selected_router_gr_batch(binding, context)?;
match QkScratch::new(result.binding.clone(), context, result.mirror_failed.clone()) {
Ok(slot) => result.gdn_qk_workspace = Some(Rc::new(slot)),
Ok(slot) => result.workspaces.gdn_qk_workspace = Some(Rc::new(slot)),
Err(primary) => {
let _ = result.close();
return Err(primary);
@@ -93,7 +93,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
let _ = slot.close();
return Err(Error::InvalidDimension);
}
self.qsa_attention_workspace = Some(RefCell::new(slot));
self.workspaces.qsa_attention_workspace = Some(RefCell::new(slot));
self.attach_prompt_queues(context, capacity)?;
self.attach_prompt_resources(context, capacity)
}
@@ -101,11 +101,12 @@ impl<'ctx> DenseWeightCache<'ctx> {
fn attach_prompt_queues(&mut self, context: &'ctx Context<'ctx>, capacity: usize) -> Result<()> {
// This selected actor eagerly owns the actual PLE queue before any
// expert cache budget is admitted. Default actors retain their path.
self.ple_queue = Some(RefCell::new(context.ple_closed_queue().map_err(driver_error)?));
self.workspaces.ple_queue = Some(RefCell::new(context.ple_closed_queue().map_err(driver_error)?));
// Literal prefill GEMM has one model-lifetime vendor handle, stream and
// actual 32 MiB workspace. Each producer releases its exclusive loan
// after completion; a row bank never carries it across attention.
self.native_batch_workspace = Some(RefCell::new(context.native_batch_workspace().map_err(driver_error)?));
self.workspaces.native_batch_workspace =
Some(RefCell::new(context.native_batch_workspace().map_err(driver_error)?));
// Original selected mode17 profile has STRATA_PREFILL_BF16X2 absent.
// HighOnly is explicit. Hi+Lo is a separately qualified load profile.
let queue = if capacity == 64 {
@@ -114,7 +115,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
context.ple_batch_queue_for_prompt(leleka_cuda_driver::PleBf16Mode::HighOnly, capacity)
}
.map_err(driver_error)?;
self.ple_batch_queue = Some(RefCell::new(queue));
self.workspaces.ple_batch_queue = Some(RefCell::new(queue));
Ok(())
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -131,14 +132,14 @@ impl<'ctx> DenseWeightCache<'ctx> {
capacity,
)
}?;
self.gdn_batch_resources = Some(RefCell::new(resources));
self.workspaces.gdn_batch_resources = Some(RefCell::new(resources));
let owner = if capacity == 64 {
context.qsa_native_batch_workspace(leleka_cuda_driver::QsaNativePacking::HighOnly)
} else {
context.qsa_native_batch_workspace_for_prompt(leleka_cuda_driver::QsaNativePacking::HighOnly, capacity)
}
.map_err(driver_error)?;
self.qsa_native_workspace = Some(RefCell::new(owner));
self.workspaces.qsa_native_workspace = Some(RefCell::new(owner));
self.attach_native_qsa_resources(context, capacity)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -152,10 +153,10 @@ impl<'ctx> DenseWeightCache<'ctx> {
capacity,
)
}?;
self.native_qsa = Some(RefCell::new(owner));
self.workspaces.native_qsa = Some(RefCell::new(owner));
// The selected native target and verification journal share one actual
// closed fused program owner, charged before any routed PrefixPlan.
self.native_gdn_fused = Some(Rc::new(RefCell::new(context.gdn_fused_t1().map_err(driver_error)?)));
self.workspaces.native_gdn_fused = Some(Rc::new(RefCell::new(context.gdn_fused_t1().map_err(driver_error)?)));
Ok(())
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -165,14 +166,14 @@ impl<'ctx> DenseWeightCache<'ctx> {
context: &Context<'_>,
) -> Result<std::cell::RefMut<'_, super::super::super::qsa_native_resources::NativeQsaResources<'ctx>>> {
self.retained_context(binding, context)?;
let resource = self.native_qsa.as_ref().ok_or(Error::IdentityMismatch)?;
let resource = self.workspaces.native_qsa.as_ref().ok_or(Error::IdentityMismatch)?;
let owner = resource.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
owner.validate(context)?;
Ok(owner)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in super::super::super) fn has_native_qsa(&self) -> bool {
self.native_qsa.is_some()
self.workspaces.native_qsa.is_some()
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in crate::qwen_forward) fn native_gdn_fused(
@@ -181,7 +182,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
context: &Context<'_>,
) -> Result<Rc<RefCell<leleka_cuda_driver::GdnFusedT1<'ctx>>>> {
self.retained_context(binding, context)?;
let owner = self.native_gdn_fused.as_ref().ok_or(Error::IdentityMismatch)?;
let owner = self.workspaces.native_gdn_fused.as_ref().ok_or(Error::IdentityMismatch)?;
if owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.is_failed() {
self.mirror_failed.set(true);
return Err(Error::CudaExecution);
@@ -189,12 +190,13 @@ impl<'ctx> DenseWeightCache<'ctx> {
Ok(owner.clone())
}
pub(in super::super::super) fn qsa_attention_workspace(&self) -> Option<&RefCell<QsaAttentionScratch<'ctx>>> {
self.qsa_attention_workspace.as_ref()
self.workspaces.qsa_attention_workspace.as_ref()
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(crate) fn test_retained_scratch_witness(&self) -> Result<(usize, u64)> {
let qk = self.gdn_qk_workspace.as_ref().ok_or(Error::IdentityMismatch)?.test_slot_bytes()?;
let qk = self.workspaces.gdn_qk_workspace.as_ref().ok_or(Error::IdentityMismatch)?.test_slot_bytes()?;
let qsa = self
.workspaces
.qsa_attention_workspace
.as_ref()
.ok_or(Error::IdentityMismatch)?
@@ -213,7 +215,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
context,
cache.mirror_failed.clone(),
) {
Ok(workspace) => cache.gdn_verification = Some(Rc::new(RefCell::new(workspace))),
Ok(workspace) => cache.workspaces.gdn_verification = Some(Rc::new(RefCell::new(workspace))),
Err(primary) => {
let _ = cache.close();
return Err(primary);
@@ -38,18 +38,18 @@ impl<'ctx> DenseWeightCache<'ctx> {
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn load_prompt_workspaces(&mut self, context: &'ctx Context<'ctx>) -> Result<()> {
self.native_batch_workspace = Some(RefCell::new(
self.workspaces.native_batch_workspace = Some(RefCell::new(
startup_step("native_batch_workspace", context.native_batch_workspace()).map_err(driver_error)?,
));
self.ple_queue =
self.workspaces.ple_queue =
Some(RefCell::new(startup_step("ple_closed_queue", context.ple_closed_queue()).map_err(driver_error)?));
self.native_gdn_fused =
self.workspaces.native_gdn_fused =
Some(Rc::new(RefCell::new(startup_step("gdn_fused_t1", context.gdn_fused_t1()).map_err(driver_error)?)));
Ok(())
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn load_prompt_scratch(&mut self, context: &'ctx Context<'ctx>) -> Result<()> {
self.gdn_verification = Some(Rc::new(RefCell::new(startup_step(
self.workspaces.gdn_verification = Some(Rc::new(RefCell::new(startup_step(
"gdn verification workspace",
super::super::super::gdn::verification::Workspace::new(
self.binding.clone(),
@@ -57,15 +57,15 @@ impl<'ctx> DenseWeightCache<'ctx> {
self.mirror_failed.clone(),
),
)?)));
self.gdn_qk_workspace = Some(Rc::new(startup_step(
self.workspaces.gdn_qk_workspace = Some(Rc::new(startup_step(
"gdn qk scratch",
QkScratch::new(self.binding.clone(), context, self.mirror_failed.clone()),
)?));
self.router_scratch = Some(RefCell::new(startup_step(
self.workspaces.router_scratch = Some(RefCell::new(startup_step(
"router scratch",
RouterScratch::new(self.binding.clone(), context, self.mirror_failed.clone()),
)?));
self.gr_batch_workspace = Some(RefCell::new(
self.workspaces.gr_batch_workspace = Some(RefCell::new(
startup_step("gr_batch_inject_workspace", context.gr_batch_inject_workspace()).map_err(driver_error)?,
));
self.gdn_four_borrow = true;
@@ -97,7 +97,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
context: &Context<'_>,
) -> Result<usize> {
self.retained_context(binding, context)?;
if self.native_batch_workspace.is_none() || !(1..=8192).contains(&self.native_prompt_capacity) {
if self.workspaces.native_batch_workspace.is_none() || !(1..=8192).contains(&self.native_prompt_capacity) {
return Err(Error::IdentityMismatch);
}
Ok(self.native_prompt_capacity)
@@ -120,7 +120,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
context: &Context<'_>,
) -> Result<leleka_cuda_driver::GdnStateFiniteGuard<'ctx>> {
let context = self.retained_context(binding, context)?;
let idle = self.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.pop();
let idle = self.workspaces.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.pop();
match idle {
Some(guard) if !guard.is_failed() => Ok(guard),
Some(guard) => {
@@ -138,7 +138,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
bytes: usize,
) -> Result<DeviceBuffer<'ctx>> {
if super::super::super::gdn::pool_enabled() {
let idle = self.gdn_scratch.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.pop();
let idle = self.workspaces.gdn_scratch.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.pop();
if let Some(buffer) = idle {
if buffer.len() == bytes {
return Ok(buffer);
@@ -151,7 +151,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
/// Give a GDN state buffer back: pooled (at most 4) when the switch is on, else released as before.
pub(in crate::qwen_forward) fn return_gdn_scratch(&self, buffer: DeviceBuffer<'ctx>) -> Result<()> {
if super::super::super::gdn::pool_enabled() {
let mut idle = self.gdn_scratch.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
let mut idle = self.workspaces.gdn_scratch.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
if idle.len() < 4 {
idle.push(buffer);
return Ok(());
@@ -167,7 +167,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
if guard.is_failed() {
return guard.close().map_err(driver_error);
}
let mut idle = self.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
let mut idle = self.workspaces.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
if idle.len() >= 4 {
drop(idle);
return guard.close().map_err(driver_error);
@@ -176,7 +176,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
Ok(())
}
pub(in crate::qwen_forward) fn has_gdn_verification_workspace(&self) -> bool {
self.gdn_verification.is_some()
self.workspaces.gdn_verification.is_some()
}
pub(in crate::qwen_forward) fn gdn_verification_workspace(
&self,
@@ -187,6 +187,6 @@ impl<'ctx> DenseWeightCache<'ctx> {
if self.mirror_failed.get() {
return Err(Error::CudaExecution);
}
Ok(self.gdn_verification.clone())
Ok(self.workspaces.gdn_verification.clone())
}
}
@@ -43,37 +43,9 @@ impl<'ctx> DenseWeightCache<'ctx> {
gdn_mirrors: Vec::new(),
mirror_failed: Rc::new(Cell::new(false)),
gdn_four_borrow: false,
gdn_input: None,
gdn_qk_workspace: None,
qsa_attention_workspace: None,
gdn_verification: None,
gdn_guards: RefCell::new(Vec::new()),
gdn_scratch: RefCell::new(Vec::new()),
gr_scratch: None,
qsa_input: None,
qsa_keys: None,
qsa_selected: None,
router_scratch: None,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
gr_batch_workspace: None,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
ple_queue: None,
workspaces: Workspaces::default(),
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native_prompt_capacity: 64,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native_batch_workspace: None,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
ple_batch_queue: None,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
gdn_batch_resources: None,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
qsa_native_workspace: None,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native_qsa: None,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native_gdn_fused: None,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
gr_batch_completed: Cell::new(0),
qsa: Vec::new(),
gr: Vec::new(),
router: Vec::new(),
@@ -111,17 +83,17 @@ impl<'ctx> DenseWeightCache<'ctx> {
let context = self.context;
// Optional fixed byte workspace is eagerly charged before lazy MoE growth.
if selected {
self.qsa_selected =
self.workspaces.qsa_selected =
Some(RefCell::new(QsaSelectedCache::new(self.binding.clone(), context, self.mirror_failed.clone())?));
}
self.qsa_keys =
self.workspaces.qsa_keys =
Some(RefCell::new(QsaIndexKeyCache::new(self.binding.clone(), context, self.mirror_failed.clone())?));
self.qsa_input =
self.workspaces.qsa_input =
Some(RefCell::new(QsaInputScratch::new(self.binding.clone(), context, self.mirror_failed.clone())?));
// Fixed activation scratch is charged before any lazy MoE growth.
self.gdn_input =
self.workspaces.gdn_input =
Some(RefCell::new(GdnInputScratch::new(self.binding.clone(), context, self.mirror_failed.clone())?));
self.gr_scratch = Some(RefCell::new(GrScratch::new(binding, context, self.mirror_failed.clone())?));
self.workspaces.gr_scratch = Some(RefCell::new(GrScratch::new(binding, context, self.mirror_failed.clone())?));
Ok(())
}
fn add_layer(&mut self, binding: &ModelBinding, id: u32, kind: BoundLayerKind) -> Result<()> {
@@ -151,7 +151,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
source: &'loan super::super::super::gr::ResidualReady,
) -> Result<Option<RouterLease<'loan, 'ctx>>> {
self.retained_context(binding, context)?;
let Some(slot) = &self.router_scratch else {
let Some(slot) = &self.workspaces.router_scratch else {
return Ok(None);
};
// This matrix is an actual immutable buffer created by this cache on
@@ -162,7 +162,8 @@ impl<'ctx> DenseWeightCache<'ctx> {
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(crate) fn test_router_witness(&self) -> Result<u64> {
self.router_scratch
self.workspaces
.router_scratch
.as_ref()
.ok_or(Error::IdentityMismatch)?
.try_borrow()
@@ -175,7 +176,12 @@ impl<'ctx> DenseWeightCache<'ctx> {
context: &Context<'_>,
) -> Result<RefMut<'_, GrScratch<'ctx>>> {
self.retained_context(binding, context)?;
self.gr_scratch.as_ref().ok_or(Error::IdentityMismatch)?.try_borrow_mut().map_err(|_| Error::IdentityMismatch)
self.workspaces
.gr_scratch
.as_ref()
.ok_or(Error::IdentityMismatch)?
.try_borrow_mut()
.map_err(|_| Error::IdentityMismatch)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in super::super::super) fn gr_batch_workspace(
@@ -183,7 +189,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
binding: &ModelBinding,
context: &Context<'_>,
) -> Result<Option<RefMut<'_, GrBatchInjectWorkspace<'ctx>>>> {
let Some(slot) = &self.gr_batch_workspace else {
let Some(slot) = &self.workspaces.gr_batch_workspace else {
return Ok(None);
};
self.retained_context(binding, context)?;
@@ -196,7 +202,11 @@ impl<'ctx> DenseWeightCache<'ctx> {
context: &Context<'_>,
) -> Result<Option<RefMut<'_, leleka_cuda_driver::PleClosedQueue<'ctx>>>> {
self.retained_context(binding, context)?;
self.ple_queue.as_ref().map(|queue| queue.try_borrow_mut().map_err(|_| Error::IdentityMismatch)).transpose()
self.workspaces
.ple_queue
.as_ref()
.map(|queue| queue.try_borrow_mut().map_err(|_| Error::IdentityMismatch))
.transpose()
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in super::super::super) fn native_batch_workspace(
@@ -205,7 +215,8 @@ impl<'ctx> DenseWeightCache<'ctx> {
context: &Context<'_>,
) -> Result<Option<RefMut<'_, leleka_cuda_driver::NativeBatchWorkspace<'ctx>>>> {
self.retained_context(binding, context)?;
self.native_batch_workspace
self.workspaces
.native_batch_workspace
.as_ref()
.map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch))
.transpose()
@@ -217,6 +228,10 @@ impl<'ctx> DenseWeightCache<'ctx> {
context: &Context<'_>,
) -> Result<Option<RefMut<'_, leleka_cuda_driver::PleBatchQueue<'ctx>>>> {
self.retained_context(binding, context)?;
self.ple_batch_queue.as_ref().map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)).transpose()
self.workspaces
.ple_batch_queue
.as_ref()
.map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch))
.transpose()
}
}
@@ -14,7 +14,8 @@ impl<'ctx> DenseWeightCache<'ctx> {
if self.mirror_failed.get() {
return Err(Error::CudaExecution);
}
self.gdn_batch_resources
self.workspaces
.gdn_batch_resources
.as_ref()
.map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch))
.transpose()
@@ -29,7 +30,8 @@ impl<'ctx> DenseWeightCache<'ctx> {
if self.mirror_failed.get() {
return Err(Error::CudaExecution);
}
self.qsa_native_workspace
self.workspaces
.qsa_native_workspace
.as_ref()
.map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch))
.transpose()
@@ -41,19 +43,19 @@ impl<'ctx> DenseWeightCache<'ctx> {
context: &Context<'_>,
) -> Result<()> {
self.retained_context(binding, context)?;
if self.gr_batch_workspace.is_none() {
if self.workspaces.gr_batch_workspace.is_none() {
return Err(Error::IdentityMismatch);
}
let count = self.gr_batch_completed.get().checked_add(1).ok_or(Error::Overflow)?;
self.gr_batch_completed.set(count);
let count = self.workspaces.gr_batch_completed.get().checked_add(1).ok_or(Error::Overflow)?;
self.workspaces.gr_batch_completed.set(count);
Ok(())
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(crate) fn test_gr_batch_completions(&self) -> u64 {
self.gr_batch_completed.get()
self.workspaces.gr_batch_completed.get()
}
pub(in super::super::super) fn has_gdn_qk_workspace(&self) -> bool {
self.gdn_qk_workspace.is_some()
self.workspaces.gdn_qk_workspace.is_some()
}
pub(in super::super::super) fn gdn_qk_workspace(
&self,
@@ -70,7 +72,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
{
return Err(Error::IdentityMismatch);
}
self.gdn_qk_workspace.clone().ok_or(Error::IdentityMismatch)
self.workspaces.gdn_qk_workspace.clone().ok_or(Error::IdentityMismatch)
}
pub(in super::super::super) fn gdn_four_borrow(
&self,
@@ -101,6 +103,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
return Err(Error::IdentityMismatch);
}
let slot = self
.workspaces
.qsa_input
.as_ref()
.ok_or(Error::IdentityMismatch)?
@@ -109,7 +112,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
QsaInputScratch::lease(slot, &self.binding, context, layer, source)
}
pub(in super::super::super) fn has_qsa_selected(&self) -> bool {
self.qsa_selected.is_some()
self.workspaces.qsa_selected.is_some()
}
pub(in super::super::super) fn qsa_selected(
&self,
@@ -122,7 +125,11 @@ impl<'ctx> DenseWeightCache<'ctx> {
if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer {
return Err(Error::IdentityMismatch);
}
self.qsa_selected.as_ref().map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)).transpose()
self.workspaces
.qsa_selected
.as_ref()
.map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch))
.transpose()
}
pub(in super::super::super) fn qsa_select(
&self,
@@ -133,7 +140,8 @@ impl<'ctx> DenseWeightCache<'ctx> {
position: u32,
) -> Result<Box<[i32]>> {
self.retained_context(binding, context)?;
self.qsa_keys
self.workspaces
.qsa_keys
.as_ref()
.ok_or(Error::IdentityMismatch)?
.try_borrow_mut()
@@ -153,6 +161,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
return Err(Error::IdentityMismatch);
}
let slot = self
.workspaces
.gdn_input
.as_ref()
.ok_or(Error::IdentityMismatch)?
@@ -36,42 +36,48 @@ impl<'ctx> DenseWeightCache<'ctx> {
error.map_or(Ok(()), Err)
}
fn close_scratch_and_modules(&mut self, error: &mut Option<Error>) {
for guard in self.gdn_guards.take() {
for guard in self.workspaces.gdn_guards.take() {
close_into(error, Some(guard), |guard| guard.close().map_err(driver_error));
}
for buffer in self.gdn_scratch.take() {
for buffer in self.workspaces.gdn_scratch.take() {
close_into(error, Some(buffer), |buffer| buffer.release().map_err(driver_error));
}
close_into(error, self.modules.take(), |modules| modules.close());
close_into(error, self.qsa_selected.take(), |selected| selected.into_inner().close());
close_into(error, self.qsa_keys.take(), |keys| keys.into_inner().close());
close_into(error, self.gdn_verification.take(), |slot| {
close_into(error, self.workspaces.qsa_selected.take(), |selected| selected.into_inner().close());
close_into(error, self.workspaces.qsa_keys.take(), |keys| keys.into_inner().close());
close_into(error, self.workspaces.gdn_verification.take(), |slot| {
Rc::try_unwrap(slot).map_err(|_| Error::IdentityMismatch).and_then(|slot| slot.into_inner().close())
});
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
close_into(error, self.native_gdn_fused.take(), |owner| {
close_into(error, self.workspaces.native_gdn_fused.take(), |owner| {
Rc::try_unwrap(owner)
.map_err(|_| Error::IdentityMismatch)
.and_then(|owner| owner.into_inner().close().map_err(driver_error))
});
}
fn close_attention_scratch(&mut self, error: &mut Option<Error>) {
close_into(error, self.qsa_attention_workspace.take(), |slot| slot.into_inner().close());
close_into(error, self.qsa_input.take(), |slot| slot.into_inner().close());
close_into(error, self.gdn_qk_workspace.take(), QkScratch::close);
close_into(error, self.gdn_input.take(), |slot| slot.into_inner().close());
close_into(error, self.gr_scratch.take(), |slot| slot.into_inner().close());
close_into(error, self.router_scratch.take(), |slot| slot.into_inner().close());
close_into(error, self.workspaces.qsa_attention_workspace.take(), |slot| slot.into_inner().close());
close_into(error, self.workspaces.qsa_input.take(), |slot| slot.into_inner().close());
close_into(error, self.workspaces.gdn_qk_workspace.take(), QkScratch::close);
close_into(error, self.workspaces.gdn_input.take(), |slot| slot.into_inner().close());
close_into(error, self.workspaces.gr_scratch.take(), |slot| slot.into_inner().close());
close_into(error, self.workspaces.router_scratch.take(), |slot| slot.into_inner().close());
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn close_batch_workspaces(&mut self, error: &mut Option<Error>) {
close_into(error, self.gr_batch_workspace.take(), |slot| slot.into_inner().close().map_err(driver_error));
close_into(error, self.ple_queue.take(), |queue| queue.into_inner().close().map_err(driver_error));
close_into(error, self.ple_batch_queue.take(), |queue| queue.into_inner().close().map_err(driver_error));
close_into(error, self.gdn_batch_resources.take(), |resources| resources.into_inner().close());
close_into(error, self.native_qsa.take(), |owner| owner.into_inner().close());
close_into(error, self.qsa_native_workspace.take(), |owner| owner.into_inner().close().map_err(driver_error));
close_into(error, self.native_batch_workspace.take(), |workspace| {
close_into(error, self.workspaces.gr_batch_workspace.take(), |slot| {
slot.into_inner().close().map_err(driver_error)
});
close_into(error, self.workspaces.ple_queue.take(), |queue| queue.into_inner().close().map_err(driver_error));
close_into(error, self.workspaces.ple_batch_queue.take(), |queue| {
queue.into_inner().close().map_err(driver_error)
});
close_into(error, self.workspaces.gdn_batch_resources.take(), |resources| resources.into_inner().close());
close_into(error, self.workspaces.native_qsa.take(), |owner| owner.into_inner().close());
close_into(error, self.workspaces.qsa_native_workspace.take(), |owner| {
owner.into_inner().close().map_err(driver_error)
});
close_into(error, self.workspaces.native_batch_workspace.take(), |workspace| {
workspace.into_inner().close().map_err(driver_error)
});
}
@@ -0,0 +1,44 @@
//! The lazily created workspaces of the dense weight cache, moved out of it by STRA-338 (size): consecutive owners,
//! declared in the order the cache dropped them, so the drop order is unchanged.
#[allow(unused_imports)]
use super::*;
/// Every scratch owner of the cache that starts empty (`None` or an empty list) and is filled on first use.
#[derive(Default)]
pub(super) struct Workspaces<'ctx> {
pub(super) gdn_input: Option<RefCell<GdnInputScratch<'ctx>>>,
pub(super) gdn_qk_workspace: Option<Rc<QkScratch<'ctx>>>,
pub(super) qsa_attention_workspace: Option<RefCell<QsaAttentionScratch<'ctx>>>,
pub(super) gdn_verification: Option<Rc<RefCell<super::super::gdn::verification::Workspace<'ctx>>>>,
/// Idle GDN next-state finite guards (each owns a loaded module and a status word): a prompt chunk's GDN
/// layer borrows one and gives it back, instead of loading the module once per layer and chunk.
pub(super) gdn_guards: RefCell<Vec<leleka_cuda_driver::GdnStateFiniteGuard<'ctx>>>,
/// Idle 3.1 MB GDN state buffers (`LELEKA_PREFILL_GDN_POOL`): the chunk device's ping-pong scratch and the mirror's
/// spare used to be a cuMemAlloc / cuMemFree pair each per GDN layer and chunk (4 driver calls x 36 layers, each
/// free a device-wide synchronization).
pub(super) gdn_scratch: RefCell<Vec<DeviceBuffer<'ctx>>>,
pub(super) gr_scratch: Option<RefCell<GrScratch<'ctx>>>,
pub(super) qsa_input: Option<RefCell<QsaInputScratch<'ctx>>>,
pub(super) qsa_keys: Option<RefCell<QsaIndexKeyCache<'ctx>>>,
pub(super) qsa_selected: Option<RefCell<QsaSelectedCache<'ctx>>>,
pub(super) router_scratch: Option<RefCell<RouterScratch<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) gr_batch_workspace: Option<RefCell<GrBatchInjectWorkspace<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) ple_queue: Option<RefCell<leleka_cuda_driver::PleClosedQueue<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) native_batch_workspace: Option<RefCell<leleka_cuda_driver::NativeBatchWorkspace<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) ple_batch_queue: Option<RefCell<leleka_cuda_driver::PleBatchQueue<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) gdn_batch_resources: Option<RefCell<super::super::gdn::prefill_batch::GdnBatchResources<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) qsa_native_workspace: Option<RefCell<leleka_cuda_driver::QsaNativeBatchWorkspace<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) native_qsa: Option<RefCell<super::super::qsa_native_resources::NativeQsaResources<'ctx>>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) native_gdn_fused: Option<Rc<RefCell<leleka_cuda_driver::GdnFusedT1<'ctx>>>>,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) gr_batch_completed: Cell<u64>,
}
@@ -176,23 +176,7 @@ pub(crate) struct OriginalServeStack<'a, 'ctx> {
binding: &'a ModelBinding,
context: &'ctx Context<'ctx>,
config: StackConfig,
settings: OriginalServeSettings,
max_cells: usize,
rope: RopeConstants,
blobs: ExpertBlobSizes,
formats: OriginalVerifyExpertFormats,
full_policy: OriginalMtpFullPolicy,
scalar_policy: OriginalMtpScalarPolicy,
controller: OriginalSpecController,
/// Window policies other than the live one (`LELEKA_SPEC_ARMS`), parked with their controllers (each keeps its
/// learned
/// state across requests), and the live one's label. The verifier is built for `verifier_max_t`, the widest arm.
parked: Vec<(String, OriginalServeSettings, OriginalSpecController)>,
arm_label: String,
arm_order: Vec<String>,
verifier_max_t: usize,
/// Why the stack can serve no more (a lost physical owner); `None` while healthy.
broken: Option<Error>,
policy: ServePolicy,
// The empty-prompt lineage taken at load: the reset target of every request.
empty_session: OriginalSessionCheckpoint<'ctx>,
empty_draft: OriginalDraftCheckpoint,
@@ -200,48 +184,16 @@ pub(crate) struct OriginalServeStack<'a, 'ctx> {
conversation: Option<ServeConversation<StackPoint<'ctx>>>,
/// The prefix cache (`StackConfig::prefix`); replaces `conversation` when set.
prefix: Option<PrefixServe<StackState, StackBlock>>,
/// The tokens the session holds at the end of a decode that left it settled with the draft ring in step
/// (`TailMode::Reply`).
tail_consumed: Option<Vec<i32>>,
/// Prompt tokens the last request did not read again.
reused: usize,
/// Where the conversation cache placed the last request (`reused`, or the re-read checkpoint's length).
resume_point: usize,
state: RequestState,
// Owners, dependents first (fields drop in declaration order).
history: OriginalNativePenaltyHistory<'ctx>,
ple_history: DeviceBuffer<'ctx>,
ple_scratch: DeviceBuffer<'ctx>,
/// The prompt path's own buffers; `None` while it borrows the expert cache's last slots instead.
arena: Option<OriginalPrefillArena<'ctx, 'ctx>>,
layout: PrefillLayoutOptions,
/// The VRAM expert tier (`None`: off), the slots the prompt path borrows per chunk, the adaptive counts
/// that survive requests.
/// The VRAM expert tier (`None`: off).
expert_cache: Option<OriginalExpertCache<'ctx>>,
loan: Option<usize>,
/// Smaller loans for smaller chunks, ascending by rows (empty unless `LELEKA_PREFILL_LOAN_TIERS=1`: only `loan`):
/// a chunk of at most
/// `rows` rows borrows `slots` slots instead of the full loan, so a request that reads a few hundred tokens
/// refills a few
/// hundred slots, not the 1.9 GB of an 8192-row arena.
loan_tiers: Vec<LoanTier>,
residency: ResidencyState,
/// The (layer, expert) pairs the tier held right after the profile fill (`reset_expert_tier`).
initial_owners: Vec<Option<(usize, usize)>>,
/// The last request's prompt-routing seed (`LELEKA_ORIGINAL_SERVE_SEED`), if one was made.
seed_report: Option<SeedReport>,
/// The prompt counts of the last seed (kept for the `LELEKA_SEED_TRACE` coverage line).
seed_counts: Option<Vec<f32>>,
/// Lent-slot refill copies are queued and not yet waited (`LELEKA_REFILL_DEFER`): the decode phase waits before any
/// window reads the cache; every other user of the cache waits inside its own entry points.
refill_pending: bool,
/// The lent slots still have to be refilled: the decode phase queues the copies right after its host-side intake
/// uploads (so they overlap the graph capture instead of queueing small uploads behind 1.4 GB of DMA).
refill_due: bool,
/// Wall-clock milliseconds of the last request's prompt and decode phases (operator measurements).
timing: (f64, f64),
/// Milliseconds since the request entered `serve` at which each stage of the time to first token ended
/// (`ttft_marks`).
marks: TtftMarks,
tier: TierState,
executor: OriginalPromptExecutor<'ctx>,
draft: super::session::original_prompt::draft::OriginalDraftSession<'ctx>,
session: QwenSession<'ctx>,
@@ -275,6 +227,8 @@ mod tests;
#[cfg(test)]
pub(crate) mod lifecycle_fake;
mod stack_groups;
use stack_groups::{RequestState, ServePolicy, TierState};
mod impl_default_for_ttftmarks;
#[allow(unused_imports)]
use impl_default_for_ttftmarks::at;
@@ -6,6 +6,8 @@ use super::*;
#[path = "impl_originalservestack_2/open_phases.rs"]
mod open_phases;
use open_phases::{OpenCtx, load_buffers, load_core, open_tier};
mod assemble;
use assemble::{Assembly, prepare};
impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// `generate.cpp` startup over the binding: embedding table, native head + embedding, dense weights at
@@ -19,68 +21,13 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
config: StackConfig,
) -> std::result::Result<Self, ServeFailure> {
check_open(binding, context, &shared, &config)?;
let max_cells =
usize::try_from(super::super::super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?;
let Policies { settings, arm_label, arm_order, parked, verifier_max_t, controller } = serve_policies(&config)?;
let rope = RopeConstants::from_serving_context();
let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?;
let formats = expert_formats(binding).map_err(at("expert_formats"))?;
let layout = prefill_layout_options(config.capacity, max_cells, &blobs);
let ctx = OpenCtx { binding, context, config: &config, layout };
let mut core = load_core(&ctx, shared, (verifier_max_t, settings.coupled))?;
let prepared = prepare(binding, &config)?;
let ctx = OpenCtx { binding, context, config: &config, layout: prepared.layout };
let verifier = (prepared.policies.verifier_max_t, prepared.policies.settings.coupled);
let mut core = load_core(&ctx, shared, verifier)?;
let mut buffers = load_buffers(&ctx, &mut core)?;
let tier = open_tier(&ctx, &core.moe, &mut buffers.arena)?;
let this = Self {
binding,
context,
conversation: tier.conversation,
prefix: tier.prefix,
tail_consumed: None,
reused: 0,
resume_point: 0,
full_policy: mtp_full_policy(&rope),
scalar_policy: mtp_scalar_policy(&rope),
config,
settings,
max_cells,
rope,
blobs,
formats,
controller,
parked,
arm_label,
arm_order,
verifier_max_t,
broken: None,
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: 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: 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,
};
let this = Self::assemble(Assembly { binding, context, config, prepared, core, buffers, tier });
this.register_memory_classes();
crate::memory_governor::post_open();
log_open_inventory();
@@ -0,0 +1,94 @@
//! The start and the end of `OriginalServeStack::open`, moved out of it by STRA-338 (size): the config-derived values
//! computed before any allocation and the final assembly of the stack from the opened parts.
#[allow(unused_imports)]
use super::open_phases::{Buffers, Core, TierParts};
use super::*;
use crate::qwen_forward::original_serve_stack::stack_groups::{RequestState, ServePolicy, TierState};
/// What `open` derives from the binding and the config before it allocates anything.
pub(super) struct Prepared {
pub(super) max_cells: usize,
pub(super) policies: Policies,
pub(super) rope: RopeConstants,
pub(super) blobs: ExpertBlobSizes,
pub(super) formats: OriginalVerifyExpertFormats,
pub(super) layout: PrefillLayoutOptions,
}
/// Every part `open` assembled, to move into the stack.
pub(super) struct Assembly<'a, 'ctx> {
pub(super) binding: &'a ModelBinding,
pub(super) context: &'ctx Context<'ctx>,
pub(super) config: StackConfig,
pub(super) prepared: Prepared,
pub(super) core: Core<'ctx>,
pub(super) buffers: Buffers<'a, 'ctx>,
pub(super) tier: TierParts<'ctx>,
}
/// The cell count, the window policies, the RoPE constants, the expert blob sizes and formats and the prefill layout,
/// in the order `open` computed them.
pub(super) fn prepare(binding: &ModelBinding, config: &StackConfig) -> std::result::Result<Prepared, ServeFailure> {
let max_cells =
usize::try_from(crate::qwen_forward::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?;
let policies = serve_policies(config)?;
let rope = RopeConstants::from_serving_context();
let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?;
let formats = expert_formats(binding).map_err(at("expert_formats"))?;
let layout = prefill_layout_options(config.capacity, max_cells, &blobs);
Ok(Prepared { max_cells, policies, rope, blobs, formats, layout })
}
/// The policy group of the stack: the MTP policies are derived from the RoPE constants before they move in.
fn serve_policy(prepared: Prepared) -> ServePolicy {
let Prepared { max_cells, policies, rope, blobs, formats, .. } = prepared;
ServePolicy {
settings: policies.settings,
max_cells,
full_policy: mtp_full_policy(&rope),
scalar_policy: mtp_scalar_policy(&rope),
rope,
blobs,
formats,
controller: policies.controller,
parked: policies.parked,
arm_label: policies.arm_label,
arm_order: policies.arm_order,
verifier_max_t: policies.verifier_max_t,
}
}
impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// Moves the opened parts into the stack: nothing is computed here but the two MTP policies.
pub(super) fn assemble(parts: Assembly<'a, 'ctx>) -> Self {
let Assembly { binding, context, config, prepared, core, buffers, tier } = parts;
let layout = prepared.layout;
Self {
binding,
context,
config,
policy: serve_policy(prepared),
empty_session: buffers.empty_session,
empty_draft: buffers.empty_draft,
conversation: tier.conversation,
prefix: tier.prefix,
state: RequestState::default(),
history: buffers.history,
ple_history: buffers.ple_history,
ple_scratch: buffers.ple_scratch,
arena: buffers.arena,
expert_cache: tier.expert_cache,
tier: TierState::new(layout, tier.loan, tier.loan_tiers, tier.residency, tier.initial_owners),
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,
}
}
}
@@ -6,7 +6,7 @@ use super::*;
impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// `Some` once a physical owner was lost: the stack must be closed and rebuilt.
pub(crate) fn health(&self) -> Option<Error> {
self.broken
self.state.broken
}
/// One request. Admission, reset, prompt conditioning and decode in order; see `run_request`.
@@ -17,7 +17,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
cancel: &mut dyn FnMut() -> bool,
) -> std::result::Result<ServeOutcome, ServeError> {
self.apply_memory_directive();
self.marks = TtftMarks::start(&self.config.clock);
self.state.marks = TtftMarks::start(&self.config.clock);
let max_context = self.config.max_context;
let result = run_request(self, request, max_context, emit, cancel);
self.note_memory();
@@ -114,18 +114,18 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
}
fn register_device_classes(&self) {
use leleka_memory::{Space, When};
if let Ok(bytes) = prefill_bytes(self.layout) {
if let Ok(bytes) = prefill_bytes(self.tier.layout) {
crate::memory_governor::account(
"prefill",
if self.loan.is_some() { "arena_borrowed" } else { "arena" },
if self.tier.loan.is_some() { "arena_borrowed" } else { "arena" },
Space::Device,
When::Startup,
if self.loan.is_some() {
if self.tier.loan.is_some() {
"carve of the prefill arena, borrowed from the last slots of the expert cache (not additional)"
} else {
"carve of the prefill arena at the chunk capacity"
},
if self.loan.is_some() { 0 } else { bytes as u64 },
if self.tier.loan.is_some() { 0 } else { bytes as u64 },
);
}
}
@@ -187,37 +187,37 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// included.
#[allow(dead_code)]
pub(crate) fn spec_arms(&self) -> Vec<String> {
self.arm_order.clone()
self.policy.arm_order.clone()
}
/// Make `label` the window policy of the following requests (between requests only). Returns false for an unknown
/// label.
#[allow(dead_code)]
pub(crate) fn select_spec_arm(&mut self, label: &str) -> bool {
if self.arm_label == label {
if self.policy.arm_label == label {
return true;
}
let Some(at) = self.parked.iter().position(|(l, _, _)| l == label) else { return false };
let (new_label, new_settings, new_controller) = self.parked.swap_remove(at);
let old_label = std::mem::replace(&mut self.arm_label, new_label);
let old_settings = std::mem::replace(&mut self.settings, new_settings);
let old_controller = std::mem::replace(&mut self.controller, new_controller);
self.parked.push((old_label, old_settings, old_controller));
let Some(at) = self.policy.parked.iter().position(|(l, _, _)| l == label) else { return false };
let (new_label, new_settings, new_controller) = self.policy.parked.swap_remove(at);
let old_label = std::mem::replace(&mut self.policy.arm_label, new_label);
let old_settings = std::mem::replace(&mut self.policy.settings, new_settings);
let old_controller = std::mem::replace(&mut self.policy.controller, new_controller);
self.policy.parked.push((old_label, old_settings, old_controller));
true
}
/// The live arm's own request floor, if its label pinned one (`fixed4@0`).
#[allow(dead_code)]
pub(crate) fn spec_arm_min_p(&self) -> Option<f32> {
self.settings.request_min_p
self.policy.settings.request_min_p
}
#[allow(dead_code)]
pub(crate) fn spec_arm(&self) -> &str {
&self.arm_label
&self.policy.arm_label
}
/// Wall-clock milliseconds of the last request's prompt phase and decode phase.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn last_timing(&self) -> (f64, f64) {
self.timing
self.state.timing
}
/// Where the last request's time to first token went: `(resumed, prefilled, assembled, first_round)`, each the
@@ -226,13 +226,13 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// state upload); `first_round`: the first verified round was emitted). NaN for a stage the request did not reach.
#[allow(dead_code)]
pub(crate) fn ttft_marks(&self) -> [f64; 4] {
self.marks.as_array()
self.state.marks.as_array()
}
/// The VRAM expert tier's counters (`None` when the tier is off).
pub(crate) fn expert_tier_stats(&self) -> Option<original_serve_residency::ResidencyStats> {
self.expert_cache.as_ref().map(|cache| {
let mut stats = self.residency.stats;
let mut stats = self.tier.residency.stats;
stats.swaps = cache.swaps();
stats
})
@@ -248,32 +248,32 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// The last request's seed from the prompt's routing (`None`: seed off, or no prompt rows were read).
#[allow(dead_code)]
pub(crate) fn last_seed(&self) -> Option<SeedReport> {
self.seed_report
self.state.seed_report
}
/// Cumulative (vram, pcie, cpu) window entries after each verified round of the last request.
#[allow(dead_code)]
pub(crate) fn round_marks(&self) -> Vec<[u64; 3]> {
self.residency.round_marks()
self.tier.residency.round_marks()
}
/// A first-request state for an experiment: the tier back on the starting profile's set, the adaptive counts and
/// the draft/adaptation controller as in a new process. Returns the swaps the restore needed.
#[allow(dead_code)]
pub(crate) fn reset_expert_tier(&mut self) -> Result<usize> {
if let Some(error) = self.broken {
if let Some(error) = self.state.broken {
return Err(error);
}
self.residency.clear_usage();
self.controller = self.settings.controller()?;
self.tier.residency.clear_usage();
self.policy.controller = self.policy.settings.controller()?;
match self.expert_cache.as_mut() {
Some(cache) => original_serve_seed::restore_placement(
self.binding,
&self.moe,
cache,
&mut self.pool,
&mut self.residency.spans,
&self.initial_owners,
&mut self.tier.residency.spans,
&self.tier.initial_owners,
),
None => Ok(0),
}
@@ -281,14 +281,14 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// Prompt tokens the last request reused from the conversation cache (generate.cpp `REUSED`).
pub(crate) fn reused_tokens(&self) -> usize {
self.reused
self.state.reused
}
/// The position the conversation cache resumed the last request at (equals `reused_tokens` unless
/// `STRATA_CKPT_REREAD` re-read that prefix from 0).
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn resume_point(&self) -> usize {
self.resume_point
self.state.resume_point
}
/// Drop every conversation checkpoint and the live state: the next request reads its whole prompt.
@@ -26,7 +26,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
pub(crate) fn close(self) -> Result<()> {
drop(self.conversation);
// the span cache retains registered-source spans of the bank `moe` closes below
drop(self.residency);
drop(self.tier.residency);
let mut first: Option<Error> = None;
let mut note = |result: Result<()>| {
if let Err(error) = result {
@@ -52,6 +52,6 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
}
pub(in super::super) fn mark_broken(&mut self, error: Error) {
self.broken.get_or_insert(error);
self.state.broken.get_or_insert(error);
}
}
@@ -31,7 +31,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
&mut self,
request: &ServeRequest,
) -> std::result::Result<(RequestSampling, Staged<'ctx>), SpecError> {
let Self { binding, config, settings, blobs, controller, ple_history, expert_cache, moe, session, .. } = self;
let Self { binding, config, policy, ple_history, expert_cache, moe, session, .. } = self;
let (settings, blobs, controller) = (&policy.settings, &policy.blobs, &mut policy.controller);
let binding: &ModelBinding = *binding;
if controller.is_failed() {
// a failed restore/finish poisoned the controller; its adaptive cadence is the only thing lost
@@ -98,22 +98,28 @@ pub(super) struct DecodeView<'s, 'a, 'ctx> {
impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// Borrow the fields of a decode, each by itself. `shared` is the shared-expert key table the stage loaded.
pub(super) fn decode_view<'s>(&'s mut self, shared: &'s SharedKeys) -> DecodeView<'s, 'a, 'ctx> {
let (policy, state, tier) = (&mut self.policy, &mut self.state, &mut self.tier);
DecodeView {
ids: Ids { binding: self.binding, context: self.context, max_cells: self.max_cells, shared },
reads: Reads { dense: &self.dense, moe: &self.moe, formats: &self.formats, ple_scratch: &self.ple_scratch },
consts: Consts { output: &self.output, rope: &self.rope, blobs: &self.blobs },
ids: Ids { binding: self.binding, context: self.context, max_cells: policy.max_cells, shared },
reads: Reads {
dense: &self.dense,
moe: &self.moe,
formats: &policy.formats,
ple_scratch: &self.ple_scratch,
},
consts: Consts { output: &self.output, rope: &policy.rope, blobs: &policy.blobs },
owners: Owners { session: &mut self.session, draft: &mut self.draft, executor: &mut self.executor },
extra: Extra { history: &mut self.history, kar: self.kar.as_mut(), policy: &self.full_policy },
tier: Tier { expert_cache: &mut self.expert_cache, pool: &mut self.pool, residency: &mut self.residency },
refill: Refill { pending: &mut self.refill_pending, due: &mut self.refill_due },
policy: Policy { config: &self.config, settings: &mut self.settings, controller: &mut self.controller },
arms: Arms { parked: &mut self.parked, verifier_max_t: &mut self.verifier_max_t },
extra: Extra { history: &mut self.history, kar: self.kar.as_mut(), policy: &policy.full_policy },
tier: Tier { expert_cache: &mut self.expert_cache, pool: &mut self.pool, residency: &mut tier.residency },
refill: Refill { pending: &mut state.refill_pending, due: &mut state.refill_due },
policy: Policy { config: &self.config, settings: &mut policy.settings, controller: &mut policy.controller },
arms: Arms { parked: &mut policy.parked, verifier_max_t: &mut policy.verifier_max_t },
book: Book {
conversation: &mut self.conversation,
tail_consumed: &mut self.tail_consumed,
marks: &mut self.marks,
broken: &mut self.broken,
arm_label: &self.arm_label,
tail_consumed: &mut state.tail_consumed,
marks: &mut state.marks,
broken: &mut state.broken,
arm_label: &policy.arm_label,
prefix_live: self.prefix.is_some(),
},
ple_history: &self.ple_history,
@@ -27,7 +27,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
let refilled = self.refill_after_read(defer);
let routing = if seeding { self.moe.take_prompt_routing() } else { None };
let seeded = self.seed_after_read((&read, &refilled), routing, defer);
self.refill_due = defer;
self.state.refill_due = defer;
match (read, refilled, seeded) {
(Ok(()), Err(error), _) | (Ok(()), Ok(()), Err(error)) => {
self.mark_broken(error);
@@ -43,14 +43,14 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
read_ok
&& !seeding
&& original_serve_residency::refill_defer_enabled()
&& self.loan.is_some()
&& self.tier.loan.is_some()
&& self.expert_cache.is_some()
}
/// The start of a request's prompt phase: swaps in flight land first, and the MoE stage starts counting routes
/// when the prompt seeds the placement. Returns whether it does.
fn begin_prefill(&mut self) -> std::result::Result<bool, SpecError> {
self.residency.begin_request();
self.seed_report = None;
self.tier.residency.begin_request();
self.state.seed_report = None;
if let Some(cache) = self.expert_cache.as_mut() {
let _p = profile::span("prefill.wait_swaps");
cache
@@ -66,11 +66,15 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
}
/// The lent slots' refill after the read, unless it is deferred into the decode phase.
fn refill_after_read(&mut self, defer: bool) -> Result<()> {
match (self.loan, self.expert_cache.as_mut()) {
(Some(_), Some(cache)) if !defer => {
original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false)
.map(|_| ())
}
match (self.tier.loan, self.expert_cache.as_mut()) {
(Some(_), Some(cache)) if !defer => original_serve_residency::refill_lent(
self.binding,
&self.moe,
cache,
&mut self.tier.residency.spans,
false,
)
.map(|_| ()),
_ => Ok(()),
}
}
@@ -106,16 +110,16 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
&self.moe,
cache,
&mut self.pool,
&mut self.residency.spans,
&mut self.tier.residency.spans,
&swaps,
)?;
report.plan_ms = planned.as_secs_f64() * 1e3;
report.queue_ms = (self.config.clock.since(started) - planned).as_secs_f64() * 1e3;
self.residency.add_usage(counts, usage);
self.tier.residency.add_usage(counts, usage);
trace_seed_report(&report);
self.seed_report = Some(report);
self.state.seed_report = Some(report);
if crate::settings::process().diagnostics.seed_trace {
self.seed_counts = Some(counts.to_vec());
self.state.seed_counts = Some(counts.to_vec());
}
Ok(())
}
@@ -124,14 +128,14 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// resident set covers: the starting profile's set, the prompt's top experts (what the seed installs, per layer
/// slot counts of the profile) and the best any static set could do (the decode's own top experts).
pub(in super::super) fn seed_coverage_trace(&mut self) {
let Some(prompt) = self.seed_counts.take() else { return };
let usage = self.residency.usage();
let Some(prompt) = self.state.seed_counts.take() else { return };
let usage = self.tier.residency.usage();
if usage.len() != prompt.len() || self.config.expert_tier.adapt_every != 0 {
return;
}
let mut slots = [0usize; 48];
let mut initial = vec![false; 48 * 512];
for &(layer, expert) in self.initial_owners.iter().flatten() {
for &(layer, expert) in self.tier.initial_owners.iter().flatten() {
slots[layer] += 1;
initial[layer * 512 + expert] = true;
}
@@ -186,8 +190,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
let binding: &ModelBinding = self.binding;
let mtp_setup_span = profile::span("prefill.mtp_setup");
self.executor.set_mtp_prompt_len(binding, n as i64)?;
self.executor
.set_mtp_max_drafts(binding, i32::try_from(self.settings.max_drafts()).map_err(|_| Error::Overflow)?)?;
self.executor.set_mtp_max_drafts(
binding,
i32::try_from(self.policy.settings.max_drafts()).map_err(|_| Error::Overflow)?,
)?;
self.executor.set_mtp_draft_sampling(binding, &request.params)?;
drop(mtp_setup_span);
Ok(())
@@ -23,12 +23,12 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
moe: &mut self.moe,
draft: &mut self.draft,
embedding: &self.embedding,
scalar_policy: &self.scalar_policy,
scalar_policy: &self.policy.scalar_policy,
};
let first = chunk.session.target_origin().map(|o| o.next_position()).unwrap_or(0);
super::super::super::prefill_profile::begin_chunk();
let ran = match (self.loan, self.expert_cache.as_mut(), self.arena.as_mut()) {
(Some(slots), Some(cache), _) => match lend_tail(cache, &self.loan_tiers, self.layout, slots, count) {
let ran = match (self.tier.loan, self.expert_cache.as_mut(), self.arena.as_mut()) {
(Some(slots), Some(cache), _) => match lend_tail(cache, &self.tier, slots, count) {
Ok(mut lent) => chunk.run(count, &mut lent, cancel),
Err(e) => Err(SpecError::Forward(super::super::super::original_serve_verifier::driver_error(&e))),
},
@@ -153,12 +153,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// The chunk's loan from the expert cache: the smallest rung of the ladder that holds `count` rows, else the full loan.
fn lend_tail<'l, 'ctx>(
cache: &'l mut OriginalExpertCache<'ctx>,
tiers: &[LoanTier],
layout: PrefillLayoutOptions,
tier: &TierState,
slots: usize,
count: usize,
) -> std::result::Result<OriginalPrefillArena<'l, 'ctx>, leleka_cuda_driver::Error> {
let _span = super::super::super::prefill_profile::span(super::super::super::prefill_profile::Stage::Lend, None);
let (slots, options) = tier_for(tiers, count).map_or((slots, layout), |t| (t.slots, t.layout));
let (slots, options) = tier_for(&tier.loan_tiers, count).map_or((slots, tier.layout), |t| (t.slots, t.layout));
cache.lend_prefill_tail(slots, options)
}
@@ -15,7 +15,7 @@ impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> {
(PARKED_STATE_ESTIMATE, block_tokens * PARKED_BYTES_PER_TOKEN)
}
fn park_state(&mut self) -> Result<StackState> {
if let Some(error) = self.broken {
if let Some(error) = self.state.broken {
return Err(error);
}
let _p = profile::span("prefix.park_state");
@@ -24,21 +24,21 @@ impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> {
Ok(StackState { session, draft })
}
fn park_block(&mut self, first: usize, tokens: usize) -> Result<StackBlock> {
if let Some(error) = self.broken {
if let Some(error) = self.state.broken {
return Err(error);
}
let _p = profile::span("prefix.park_block");
self.executor.park_block(&self.session, first, tokens).map(StackBlock)
}
fn park_tail(&mut self, first: usize, tokens: usize) -> Result<StackBlock> {
if let Some(error) = self.broken {
if let Some(error) = self.state.broken {
return Err(error);
}
let _p = profile::span("prefix.park_tail");
self.executor.park_block(&self.session, first, tokens).map(StackBlock)
}
fn import(&mut self, state: &StackState, blocks: &[(usize, &StackBlock)]) -> Result<()> {
if let Some(error) = self.broken {
if let Some(error) = self.state.broken {
return Err(error);
}
let blocks: Vec<&ParkedBlock> = blocks.iter().map(|(_, block)| &block.0).collect();
@@ -52,7 +52,7 @@ impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> {
imported
}
fn restore_draft(&mut self, state: &StackState, resume: usize) -> Result<()> {
if let Some(error) = self.broken {
if let Some(error) = self.state.broken {
return Err(error);
}
let result = (|| {
@@ -73,12 +73,12 @@ impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> {
impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> {
fn is_fresh(&self) -> bool {
self.broken.is_none()
self.state.broken.is_none()
&& self.session.original_state_lag().is_none()
&& self.session.target_origin().is_ok_and(|origin| origin.next_position() == 0)
}
fn reset(&mut self) -> std::result::Result<(), Error> {
if let Some(error) = self.broken {
if let Some(error) = self.state.broken {
return Err(error);
}
let _p = profile::span("request.reset");
@@ -93,21 +93,21 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> {
result
}
fn resume(&mut self, request: &ServeRequest) -> Option<usize> {
self.reused = 0;
self.resume_point = 0;
self.state.reused = 0;
self.state.resume_point = 0;
if self.prefix.is_some() {
return self.prefix_resume(request);
}
let mut conversation = self.conversation.take()?;
let _resume_span = profile::span("request.resume");
let resume = if self.broken.is_some() {
let resume = if self.state.broken.is_some() {
conversation.invalidate();
None
} else {
match conversation.begin(self, &request.prompt) {
Ok(start) => {
self.reused = start.read_from;
self.resume_point = start.resume;
self.state.reused = start.read_from;
self.state.resume_point = start.resume;
Some(start.resume)
}
Err(error) => {
@@ -128,14 +128,14 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> {
cancel: &mut dyn FnMut() -> bool,
) -> std::result::Result<(), SpecError> {
let started = self.config.clock.now();
self.timing = (0.0, 0.0);
self.marks.resumed = self.marks.since(&self.config.clock);
self.state.timing = (0.0, 0.0);
self.state.marks.resumed = self.state.marks.since(&self.config.clock);
let result = self.prefill_phase(request, resume, cancel);
if matches!(result, Err(SpecError::Cancelled)) {
self.keep_conversation_after_cancelled_prefill(request);
}
self.marks.prefilled = self.marks.since(&self.config.clock);
self.timing.0 = self.config.clock.since(started).as_secs_f64() * 1e3;
self.state.marks.prefilled = self.state.marks.since(&self.config.clock);
self.state.timing.0 = self.config.clock.since(started).as_secs_f64() * 1e3;
result
}
fn decode(
@@ -145,21 +145,21 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> {
cancel: &mut dyn FnMut() -> bool,
) -> std::result::Result<ServeOutcome, SpecError> {
let started = self.config.clock.now();
let tier0 = self.residency.stats;
let tier0 = self.tier.residency.stats;
let result = self.decode_phase(request, emit, cancel);
match (result.is_ok(), self.tail_consumed.take()) {
(true, Some(consumed)) if self.broken.is_none() => self.prefix_after_decode(&consumed),
match (result.is_ok(), self.state.tail_consumed.take()) {
(true, Some(consumed)) if self.state.broken.is_none() => self.prefix_after_decode(&consumed),
_ => {}
}
self.settle_lent_refills();
self.timing.1 = self.config.clock.since(started).as_secs_f64() * 1e3;
profile::add("decode.phase", self.timing.1);
self.state.timing.1 = self.config.clock.since(started).as_secs_f64() * 1e3;
profile::add("decode.phase", self.state.timing.1);
self.report_tier_request(tier0);
self.report_request_profile();
result
}
fn finish(&mut self, ended: std::result::Result<(), ServeError>) {
let completed = self.broken.is_none() && matches!(ended, Ok(()) | Err(ServeError::Cancelled));
let completed = self.state.broken.is_none() && matches!(ended, Ok(()) | Err(ServeError::Cancelled));
if let Some(conversation) = self.conversation.as_mut() {
conversation.finish(completed);
}
@@ -202,20 +202,20 @@ impl<'a, 'ctx> ServeDevice for OriginalServeStack<'a, 'ctx> {
impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
/// An exit before the decode phase queued the refill still refills now; one before it waited still waits.
fn settle_lent_refills(&mut self) {
if std::mem::take(&mut self.refill_due) {
if std::mem::take(&mut self.state.refill_due) {
if let Some(cache) = self.expert_cache.as_mut() {
if let Err(error) = original_serve_residency::refill_lent(
self.binding,
&self.moe,
cache,
&mut self.residency.spans,
&mut self.tier.residency.spans,
false,
) {
self.mark_broken(error);
}
}
}
if std::mem::take(&mut self.refill_pending) {
if std::mem::take(&mut self.state.refill_pending) {
if let Some(cache) = self.expert_cache.as_mut() {
if let Err(error) = original_serve_residency::settle_refill(cache) {
self.mark_broken(error);
@@ -225,7 +225,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
}
fn report_tier_request(&self, tier0: original_serve_residency::ResidencyStats) {
if profile::enabled() {
let t1 = self.residency.stats;
let t1 = self.tier.residency.stats;
let (v, p, c) = (
t1.vram_entries - tier0.vram_entries,
t1.pcie_entries - tier0.pcie_entries,
@@ -247,11 +247,12 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
}
}
fn pcie_num_for_report(&self) -> u32 {
self.residency
self.tier
.residency
.pcie_lag
.as_ref()
.map(|l| l.pcie_num())
.or_else(|| self.residency.pcie_auto.as_ref().map(|a| a.pcie_num()))
.or_else(|| self.tier.residency.pcie_auto.as_ref().map(|a| a.pcie_num()))
.unwrap_or(self.config.expert_tier.pcie_num())
}
fn report_request_profile(&mut self) {
@@ -259,9 +260,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
let (capture_ms, instantiate_ms, _) = leleka_cuda_driver::original_capture_timing::take();
profile::add("mtp.capture", capture_ms);
profile::add("mtp.instantiate", instantiate_ms);
profile::add("prefill.phase", self.timing.0);
profile::add("prefill.phase", self.state.timing.0);
profile::report("request");
self.residency.flush_routing();
self.tier.residency.flush_routing();
self.seed_coverage_trace();
}
}
@@ -112,7 +112,7 @@ impl<'a, 'ctx> ResumeDevice for OriginalServeStack<'a, 'ctx> {
Ok(self.session.target_origin()?.next_position())
}
fn save(&mut self) -> Result<StackPoint<'ctx>> {
if let Some(error) = self.broken {
if let Some(error) = self.state.broken {
return Err(error);
}
let session = self.executor.checkpoint_session(self.binding, &mut self.session)?;
@@ -123,7 +123,7 @@ impl<'a, 'ctx> ResumeDevice for OriginalServeStack<'a, 'ctx> {
point.session.next_position()
}
fn restore(&mut self, point: &StackPoint<'ctx>) -> Result<()> {
if let Some(error) = self.broken {
if let Some(error) = self.state.broken {
return Err(error);
}
// a refused re-stamp touches nothing; a failed physical restore poisons the executor
@@ -135,7 +135,7 @@ impl<'a, 'ctx> ResumeDevice for OriginalServeStack<'a, 'ctx> {
restored
}
fn restore_draft(&mut self, point: &StackPoint<'ctx>, resume: usize) -> Result<()> {
if let Some(error) = self.broken {
if let Some(error) = self.state.broken {
return Err(error);
}
let result = (|| {
@@ -149,7 +149,7 @@ impl<'a, 'ctx> ResumeDevice for OriginalServeStack<'a, 'ctx> {
result
}
fn live_in_step(&self) -> bool {
self.broken.is_none()
self.state.broken.is_none()
&& self.session.original_state_lag().is_none()
&& self.draft.in_step(self.binding, &self.session)
}
@@ -160,7 +160,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
pub(super) fn prefix_resume(&mut self, request: &ServeRequest) -> Option<usize> {
let mut prefix = self.prefix.take()?;
let _resume_span = profile::span("request.resume");
let resume = if self.broken.is_some() {
let resume = if self.state.broken.is_some() {
prefix.invalidate();
None
} else {
@@ -177,8 +177,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
let n = request.prompt.len();
match prefix.begin(self, &request.prompt) {
Ok(Some(start)) => {
self.reused = start.resume;
self.resume_point = start.resume;
self.state.reused = start.resume;
self.state.resume_point = start.resume;
operator_text(&prefix_hit_text(n, &start, prefix));
Some(start.resume)
}
@@ -0,0 +1,81 @@
//! Groups of cohesive plain-data fields of `OriginalServeStack`, moved out of it by STRA-338 (size). None owns a
//! device resource; each is declared at the position of its first member, so the stack's drop order is unchanged.
#[allow(unused_imports)]
use super::*;
/// The per-request state the last request left behind; every field starts empty.
#[derive(Default)]
pub(super) struct RequestState {
/// The tokens the session holds at the end of a decode that left it settled with the draft ring in step
/// (`TailMode::Reply`).
pub(super) tail_consumed: Option<Vec<i32>>,
/// Prompt tokens the last request did not read again.
pub(super) reused: usize,
/// Where the conversation cache placed the last request (`reused`, or the re-read checkpoint's length).
pub(super) resume_point: usize,
/// Why the stack can serve no more (a lost physical owner); `None` while healthy.
pub(super) broken: Option<Error>,
/// The last request's prompt-routing seed (`LELEKA_ORIGINAL_SERVE_SEED`), if one was made.
pub(super) seed_report: Option<SeedReport>,
/// The prompt counts of the last seed (kept for the `LELEKA_SEED_TRACE` coverage line).
pub(super) seed_counts: Option<Vec<f32>>,
/// Lent-slot refill copies are queued and not yet waited (`LELEKA_REFILL_DEFER`): the decode phase waits before any
/// window reads the cache; every other user of the cache waits inside its own entry points.
pub(super) refill_pending: bool,
/// The lent slots still have to be refilled: the decode phase queues the copies right after its host-side intake
/// uploads (so they overlap the graph capture instead of queueing small uploads behind 1.4 GB of DMA).
pub(super) refill_due: bool,
/// Wall-clock milliseconds of the last request's prompt and decode phases (operator measurements).
pub(super) timing: (f64, f64),
/// Milliseconds since the request entered `serve` at which each stage of the time to first token ended
/// (`ttft_marks`).
pub(super) marks: TtftMarks,
}
/// The settings, constants and window policies the stack was opened with.
pub(super) struct ServePolicy {
pub(super) settings: OriginalServeSettings,
pub(super) max_cells: usize,
pub(super) rope: RopeConstants,
pub(super) blobs: ExpertBlobSizes,
pub(super) formats: OriginalVerifyExpertFormats,
pub(super) full_policy: OriginalMtpFullPolicy,
pub(super) scalar_policy: OriginalMtpScalarPolicy,
pub(super) controller: OriginalSpecController,
/// Window policies other than the live one (`LELEKA_SPEC_ARMS`), parked with their controllers (each keeps its
/// learned state across requests), and the live one's label. The verifier is built for `verifier_max_t`, the
/// widest arm.
pub(super) parked: Vec<(String, OriginalServeSettings, OriginalSpecController)>,
pub(super) arm_label: String,
pub(super) arm_order: Vec<String>,
pub(super) verifier_max_t: usize,
}
/// The prompt layout, the loan ladder of the VRAM expert tier and what survives requests (`expert_cache` itself stays
/// a field of the stack: it owns device memory).
pub(super) struct TierState {
pub(super) layout: PrefillLayoutOptions,
/// The slots the prompt path borrows per chunk, the adaptive counts that survive requests.
pub(super) loan: Option<usize>,
/// Smaller loans for smaller chunks, ascending by rows (empty unless `LELEKA_PREFILL_LOAN_TIERS=1`: only `loan`):
/// a chunk of at most `rows` rows borrows `slots` slots instead of the full loan, so a request that reads a few
/// hundred tokens refills a few hundred slots, not the 1.9 GB of an 8192-row arena.
pub(super) loan_tiers: Vec<LoanTier>,
pub(super) residency: ResidencyState,
/// The (layer, expert) pairs the tier held right after the profile fill (`reset_expert_tier`).
pub(super) initial_owners: Vec<Option<(usize, usize)>>,
}
impl TierState {
/// The prompt layout with the tier's loan ladder and its persistent counts.
pub(super) fn new(
layout: PrefillLayoutOptions,
loan: Option<usize>,
loan_tiers: Vec<LoanTier>,
residency: ResidencyState,
initial_owners: Vec<Option<(usize, usize)>>,
) -> Self {
Self { layout, loan, loan_tiers, residency, initial_owners }
}
}
@@ -2,8 +2,11 @@
#![allow(dead_code)]
use super::*;
#[path = "session_chunk/txn_groups.rs"]
mod txn_groups;
#[path = "session_chunk_verify.rs"]
mod verify;
use txn_groups::{AttentionProgress, BatchProgress, MicroProgress};
pub(in crate::qwen_forward) use verify::{VerifiedDraftPublication, VerifiedTargetPrefix};
// Genuine chunk/layer anchor; ordinary GdnPrior stays at the canonical boundary.
@@ -143,27 +146,15 @@ pub(in crate::qwen_forward) struct QwenChunkTxn<'session, 'driver> {
next_qsa: [Option<QsaIndexPrior>; STATE_CAPACITY],
next_layer: u32,
next_row: usize,
batch_layer: Option<LayerId>,
batch_rows: Vec<Option<Rc<()>>>,
batch_completed: usize,
attention_layer: Option<LayerId>,
attention_next: usize,
attention_sources: Vec<Option<AttentionSource>>,
attention_authorized: Option<usize>,
batch: BatchProgress,
attention: AttentionProgress,
known_next: Option<TokenId>,
output: Option<TokenId>,
finished: bool,
aborted: bool,
end: u64,
windowed: bool,
micro_cursor: usize,
active_micro: Option<ActiveMicroWindow>,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_micro_width: usize,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_window_journal: Vec<(u32, usize, usize)>,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_partial_words: usize,
micro: MicroProgress,
}
#[cfg(test)]
@@ -219,7 +210,7 @@ mod refusal_tests {
txn.read_attention_column(1, layer, |_| panic!("wrong row must not execute")),
Err(Error::IdentityMismatch)
));
txn.attention_layer = Some(layer);
txn.attention.layer = Some(layer);
assert!(matches!(
txn.prepare_layer_batch::<()>(0, layer, |_| panic!("unsealed phase must not execute")),
Err(Error::IdentityMismatch)
@@ -284,10 +275,10 @@ mod refusal_tests {
));
// A synthetic phase flag is a negative challenge only, never a
// fabricated actual pending producer or completed residual.
txn.batch_layer = Some(layer);
txn.batch.layer = Some(layer);
assert!(matches!(txn.layer(0, layer, |_| panic!("mixed scalar completes")), Err(Error::IdentityMismatch)));
txn.next_row = 1;
txn.batch_rows = vec![None];
txn.batch.rows = vec![None];
assert!(matches!(
txn.batch_outputs(|_| -> Result<()> { panic!("missing proof executes") }),
Err(Error::IdentityMismatch)
@@ -64,7 +64,6 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
init: PromptInit,
(known_next, end, windowed): (Option<TokenId>, u64, bool),
) -> Self {
let PromptInit { origin, rows, witnesses } = init;
Self {
verification: None,
next_ple: session.ple_state.clone(),
@@ -72,33 +71,21 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
gdn_chunk: None,
next_qsa: session.qsa_states.clone(),
session,
origin,
origin: init.origin,
chunk: Rc::new(()),
rows,
witnesses,
rows: init.rows,
witnesses: init.witnesses,
next_layer: 0,
next_row: 0,
batch_layer: None,
batch_rows: Vec::new(),
batch_completed: 0,
attention_layer: None,
attention_next: 0,
attention_sources: Vec::new(),
attention_authorized: None,
batch: BatchProgress::default(),
attention: AttentionProgress::default(),
known_next,
output: None,
finished: false,
aborted: false,
end,
windowed,
micro_cursor: 0,
active_micro: None,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_micro_width: 64,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_window_journal: Vec::new(),
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_partial_words: 0,
micro: MicroProgress::new(),
}
}
pub(in super::super) fn check(&self) -> Result<()> {
@@ -119,9 +106,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
if !self.windowed {
return Ok((0, self.rows.len()));
}
let active = self.active_micro.as_ref().ok_or(Error::IdentityMismatch)?;
let active = self.micro.active.as_ref().ok_or(Error::IdentityMismatch)?;
if active.layer.get() != self.next_layer
|| active.first != self.micro_cursor
|| active.first != self.micro.cursor
|| active.end <= active.first
|| active.end - active.first > 64
|| active.end > self.rows.len()
@@ -131,11 +118,11 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
Ok((active.first, active.end))
}
pub(in super::super) fn window_proof(&self) -> Option<Rc<()>> {
self.active_micro.as_ref().map(|a| Rc::clone(&a.proof))
self.micro.active.as_ref().map(|a| Rc::clone(&a.proof))
}
pub(in super::super) fn validate_window_proof(&self, proof: &Option<Rc<()>>) -> Result<()> {
self.phase_span()?;
match (self.active_micro.as_ref(), proof) {
match (self.micro.active.as_ref(), proof) {
(None, None) if !self.windowed => Ok(()),
(Some(active), Some(proof)) if Rc::ptr_eq(&active.proof, proof) => Ok(()),
_ => Err(Error::IdentityMismatch),
@@ -18,32 +18,32 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
fn micro_misaligned(&self, layer: LayerId) -> bool {
!self.windowed
|| self.finished
|| self.active_micro.is_some()
|| self.micro.active.is_some()
|| self.next_layer != layer.get()
|| layer.get() >= 48
|| self.micro_cursor >= self.rows.len()
|| self.next_row != self.micro_cursor
|| self.attention_next != self.micro_cursor
|| self.micro.cursor >= self.rows.len()
|| self.next_row != self.micro.cursor
|| self.attention.next != self.micro.cursor
}
/// A batch or attention phase is still holding rows, sources or authorization.
fn phase_in_flight(&self) -> bool {
self.batch_layer.is_some()
|| self.attention_layer.is_some()
|| !self.batch_rows.is_empty()
|| !self.attention_sources.is_empty()
|| self.attention_authorized.is_some()
self.batch.layer.is_some()
|| self.attention.layer.is_some()
|| !self.batch.rows.is_empty()
|| !self.attention.sources.is_empty()
|| self.attention.authorized.is_some()
}
fn micro_width(&self) -> usize {
#[cfg(not(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
let width = 64;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let width = self.test_micro_width;
let width = self.micro.test_width;
width
}
pub(in crate::qwen_forward) fn open_micro_window(&mut self, layer: LayerId) -> Result<ChunkMicroWindow> {
self.check()?;
self.check_micro_open(layer)?;
let first = self.micro_cursor;
let first = self.micro.cursor;
let width = self.micro_width();
if !(1..=64).contains(&width) {
return Err(Error::IdentityMismatch);
@@ -53,12 +53,12 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
return Err(Error::IdentityMismatch);
}
let proof = Rc::new(());
self.active_micro = Some(ActiveMicroWindow { proof: Rc::clone(&proof), layer, first, end });
self.micro.active = Some(ActiveMicroWindow { proof: Rc::clone(&proof), layer, first, end });
Ok(ChunkMicroWindow { chunk: Rc::clone(&self.chunk), proof, layer, first, end })
}
/// The window is exactly the minted capability, the range is fully computed and no phase is in flight.
fn check_micro_close(&self, window: &ChunkMicroWindow, first: usize, end: usize) -> Result<()> {
let active = self.active_micro.as_ref().ok_or(Error::IdentityMismatch)?;
let active = self.micro.active.as_ref().ok_or(Error::IdentityMismatch)?;
if !self.is_minted_window(active, window, (first, end)) || !self.window_fully_computed(first, end) {
return Err(Error::IdentityMismatch);
}
@@ -76,19 +76,19 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
/// Every row of the range is computed through the current layer and no phase is in flight.
fn window_fully_computed(&self, first: usize, end: usize) -> bool {
self.next_row == end
&& self.attention_next == end
&& self.attention.next == end
&& !self.phase_in_flight()
&& self.rows[first..end].iter().all(|r| r.completed == self.next_layer + 1)
}
/// The infallible cursor transition after a window closed; the last window moves to the next layer.
fn advance_micro(&mut self, end: usize) {
self.active_micro = None;
self.micro_cursor = end;
self.micro.active = None;
self.micro.cursor = end;
if end == self.rows.len() {
self.next_layer += 1;
self.micro_cursor = 0;
self.micro.cursor = 0;
self.next_row = 0;
self.attention_next = 0;
self.attention.next = 0;
}
}
/// Consumes the exact minted capability; no next range can open early.
@@ -108,10 +108,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
{
self.test_window_journal.try_reserve(1).map_err(|_| Error::InputAllocation)?;
self.micro.test_window_journal.try_reserve(1).map_err(|_| Error::InputAllocation)?;
// The tuple is observed only after genuine finite completion and
// all capability checks, before the infallible cursor transition.
self.test_window_journal.push((self.next_layer, first, end));
self.micro.test_window_journal.push((self.next_layer, first, end));
}
self.advance_micro(end);
Ok(())
@@ -123,17 +123,17 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|| self.len() != 4
|| self.next_layer != 0
|| self.next_row != 0
|| self.active_micro.is_some()
|| self.micro.active.is_some()
|| self.rows.iter().any(|r| r.input.is_some())
{
return Err(Error::IdentityMismatch);
}
self.test_micro_width = 2;
self.micro.test_width = 2;
Ok(())
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in crate::qwen_forward) fn test_window_journal(&self) -> &[(u32, usize, usize)] {
&self.test_window_journal
&self.micro.test_window_journal
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn check_first_layer(&self, residuals: &[Option<InjectedResidual>]) -> Result<()> {
@@ -142,7 +142,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|| self.next_row != 0
|| self.finished
|| !self.witnesses.is_empty()
|| self.active_micro.is_some()
|| self.micro.active.is_some()
|| residuals.len() != self.len()
|| self.rows.iter().any(|r| r.completed != 1)
{
@@ -197,12 +197,12 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
let words = self.first_layer_words(residuals, layer)?;
let end = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?;
self.validate_first_layer_prior(layer, end)?;
self.test_partial_words = words;
self.micro.test_partial_words = words;
Ok(())
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in crate::qwen_forward) fn test_partial_words(&self) -> usize {
self.test_partial_words
self.micro.test_partial_words
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in crate::qwen_forward) fn test_publication_preflight_refused(&self) -> bool {
@@ -221,10 +221,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|| !self.session.qsa_layers[slot]
|| self.next_layer != layer.get()
|| self.next_row != first
|| self.attention_layer != Some(layer)
|| self.attention_next != end
|| self.batch_layer.is_some()
|| self.attention_authorized.is_some()
|| self.attention.layer != Some(layer)
|| self.attention.next != end
|| self.batch.layer.is_some()
|| self.attention.authorized.is_some()
{
return Err(Error::IdentityMismatch);
}
@@ -13,10 +13,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|| !self.session.qsa_layers[slot]
|| self.next_layer != layer.get()
|| self.next_row != first
|| self.attention_layer != Some(layer)
|| self.attention_next != end
|| self.batch_layer.is_some()
|| self.attention_authorized.is_some()
|| self.attention.layer != Some(layer)
|| self.attention.next != end
|| self.batch.layer.is_some()
|| self.attention.authorized.is_some()
|| self.next_qsa[slot].as_ref().is_none_or(|actual| !actual.same_state(prior))
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -116,10 +116,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
let slot = layer.get() as usize;
if !self.windowed
|| self.gdn_chunk.is_some()
|| self.active_micro.is_some()
|| self.micro.active.is_some()
|| self.next_layer != layer.get()
|| self.next_row != 0
|| self.micro_cursor != 0
|| self.micro.cursor != 0
|| slot >= 48
|| !self.session.gdn_layers[slot]
|| self.rows.iter().any(|row| row.completed != layer.get())
@@ -159,14 +159,14 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
/// Every row of the chunk completed the layer and no phase is in flight.
fn gdn_finish_ready(&self, journal: &GdnChunkJournal, layer: LayerId) -> bool {
Rc::ptr_eq(&self.chunk, &journal.start.0.chunk)
&& self.active_micro.is_none()
&& self.micro_cursor == 0
&& self.micro.active.is_none()
&& self.micro.cursor == 0
&& self.next_row == 0
&& self.next_layer == layer.get() + 1
&& journal.accepted == self.rows.len()
&& self.batch_layer.is_none()
&& self.attention_layer.is_none()
&& self.attention_authorized.is_none()
&& self.batch.layer.is_none()
&& self.attention.layer.is_none()
&& self.attention.authorized.is_none()
&& self.rows.iter().all(|row| row.completed == layer.get() + 1)
}
/// The seal of the journaled chunk once every row completed the layer; otherwise the transaction aborts.
@@ -43,9 +43,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
layer.get() != 1
|| self.next_layer != 1
|| self.next_row != first
|| self.attention_next != first
|| self.batch_layer.is_some()
|| self.attention_layer.is_some()
|| self.attention.next != first
|| self.batch.layer.is_some()
|| self.attention.layer.is_some()
}
/// The layer-one PLE window is complete, idle and has no device GDN lease.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -116,9 +116,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
if layer.get() != self.next_layer
|| layer.get() >= 48
|| self.next_row != first
|| self.attention_next != first
|| self.batch_layer.is_some()
|| self.attention_layer.is_some_and(|old| old != layer)
|| self.attention.next != first
|| self.batch.layer.is_some()
|| self.attention.layer.is_some_and(|old| old != layer)
|| !(1..=64).contains(&(end - first))
|| self.rows[first..end].iter().any(|row| row.completed != layer.get())
{
@@ -130,8 +130,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn admit_attention_sources(&mut self, layer: LayerId, first: usize, end: usize) -> Result<()> {
self.open_attention_sources(layer)?;
if self.attention_sources.len() != self.rows.len()
|| self.attention_sources[first..end].iter().any(Option::is_some)
if self.attention.sources.len() != self.rows.len()
|| self.attention.sources[first..end].iter().any(Option::is_some)
{
return Err(Error::IdentityMismatch);
}
@@ -144,7 +144,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
index: usize,
prepare: &mut impl FnMut(usize, &mut QwenStepTxn<'_, 'driver>) -> Result<GrMicroInput>,
) -> Result<GrMicroInput> {
if self.attention_next != index {
if self.attention.next != index {
return Err(Error::IdentityMismatch);
}
let mut view = self.stage_view(index)?;
@@ -158,7 +158,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
input.validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?;
input.identity().validate(token, position, layer)?;
self.admit_row_ple(&mut step, layer, (index, position))?;
self.attention_next += 1;
self.attention.next += 1;
Ok(input)
}
/// Every row of the window is prepared chronologically; the device batch has not run yet.
@@ -185,7 +185,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
(first, end): (usize, usize),
reads: &[DetachedGrRead],
) -> Result<()> {
if reads.len() != end - first || self.attention_next != end {
if reads.len() != end - first || self.attention.next != end {
return Err(Error::IdentityMismatch);
}
for (row, read) in self.rows[first..end].iter().zip(reads) {
@@ -16,9 +16,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|| self.next_row != first
|| index < first
|| index >= end
|| self.batch_layer.is_some()
|| index != self.attention_next
|| self.attention_layer.is_some_and(|old| old != layer)
|| self.batch.layer.is_some()
|| index != self.attention.next
|| self.attention.layer.is_some_and(|old| old != layer)
|| self.rows.get(index).is_none_or(|row| row.completed != layer.get())
{
return Err(Error::IdentityMismatch);
@@ -27,10 +27,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
}
/// Allocate the per-row source slots on the first read of the layer.
pub(super) fn open_attention_sources(&mut self, layer: LayerId) -> Result<()> {
if self.attention_layer.is_none() {
self.attention_sources.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
self.attention_sources.resize_with(self.rows.len(), || None);
self.attention_layer = Some(layer);
if self.attention.layer.is_none() {
self.attention.sources.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
self.attention.sources.resize_with(self.rows.len(), || None);
self.attention.layer = Some(layer);
}
Ok(())
}
@@ -65,7 +65,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
) -> ChunkAttentionRow {
let proof = Rc::new(());
let read = Rc::new(read);
self.attention_sources[index] = Some(AttentionSource { proof: Rc::clone(&proof), read: Rc::clone(&read) });
self.attention.sources[index] = Some(AttentionSource { proof: Rc::clone(&proof), read: Rc::clone(&read) });
ChunkAttentionRow { chunk: Rc::clone(&self.chunk), proof, index, layer, read, window: self.window_proof() }
}
pub(in crate::qwen_forward) fn read_attention_column(
@@ -90,7 +90,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
});
let result = result.map(|read| {
let row = self.publish_attention_source(layer, index, read);
self.attention_next += 1;
self.attention.next += 1;
row
});
self.settle_failure(&result);
@@ -103,10 +103,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
ready: &super::super::super::super::gr::ResidualReady,
) -> Result<()> {
let (first, end) = self.phase_span()?;
if index < first || index >= end || self.attention_layer != Some(layer) || self.attention_next != end {
if index < first || index >= end || self.attention.layer != Some(layer) || self.attention.next != end {
return Err(Error::IdentityMismatch);
}
let source = self.attention_sources.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?;
let source = self.attention.sources.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?;
if !std::ptr::eq(source.read.ready(), ready) {
return Err(Error::IdentityMismatch);
}
@@ -122,7 +122,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
) -> Result<()> {
self.validate_attention_input(index, layer, read.ready())?;
self.validate_window_proof(&read.window)?;
let source = self.attention_sources[index].as_ref().ok_or(Error::IdentityMismatch)?;
let source = self.attention.sources[index].as_ref().ok_or(Error::IdentityMismatch)?;
if !Rc::ptr_eq(&self.chunk, &read.chunk)
|| !Rc::ptr_eq(&source.proof, &read.proof)
|| !Rc::ptr_eq(&source.read, &read.read)
@@ -155,15 +155,15 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
) -> Result<(T, PreparedLayerRow)> {
self.validate_attention_input(index, layer, read.ready())?;
self.validate_window_proof(&read.window)?;
let source = self.attention_sources[index].as_ref().ok_or(Error::IdentityMismatch)?;
if !self.read_is_source(source, read, (index, layer)) || self.attention_authorized.is_some() {
let source = self.attention.sources[index].as_ref().ok_or(Error::IdentityMismatch)?;
if !self.read_is_source(source, read, (index, layer)) || self.attention.authorized.is_some() {
return Err(Error::IdentityMismatch);
}
self.attention_authorized = Some(index);
self.attention.authorized = Some(index);
let result = self.prepare_layer_batch(index, layer, |step| execute(step, &read.read));
self.attention_authorized = None;
self.attention.authorized = None;
if result.is_ok() {
self.attention_sources[index] = None;
self.attention.sources[index] = None;
}
result
}
@@ -183,10 +183,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
}
/// The read is the live source of `index` and the GDN journal stands at that row: mint its chunk row.
pub(super) fn gdn_ffn_row(&self, index: usize, layer: LayerId, read: &ChunkAttentionRow) -> Result<GdnChunkRow> {
let source = self.attention_sources[index].as_ref().ok_or(Error::IdentityMismatch)?;
let source = self.attention.sources[index].as_ref().ok_or(Error::IdentityMismatch)?;
let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?;
if !self.read_is_source(source, read, (index, layer))
|| self.attention_authorized.is_some()
|| self.attention.authorized.is_some()
|| journal.accepted != index
{
return Err(Error::IdentityMismatch);
@@ -213,13 +213,13 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
self.validate_attention_input(index, layer, read.ready())?;
self.validate_window_proof(&read.window)?;
let row = self.gdn_ffn_row(index, layer, read)?;
self.attention_authorized = Some(index);
self.attention.authorized = Some(index);
let result = self.prepare_layer_batch_internal(index, layer, |step| {
execute(step, &read.read, row).map(|(v, e)| (v, Some(e)))
});
self.attention_authorized = None;
self.attention.authorized = None;
let (row, proof) = result?;
self.attention_sources[index] = None;
self.attention.sources[index] = None;
row.validate(&self.session.binding, self.rows[index].token, self.rows[index].position, layer)?;
Ok(ChunkFfnRow { proof, row })
}
@@ -19,13 +19,13 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
self.validate_attention_input(index, layer, read.ready())?;
self.validate_window_proof(&read.window)?;
let row = self.gdn_ffn_row(index, layer, read)?;
self.attention_authorized = Some(index);
self.attention.authorized = Some(index);
let result = self.prepare_layer_batch_internal(index, layer, |step| {
execute(step, &read.read, row).map(|(value, edge)| (value, Some(edge)))
});
self.attention_authorized = None;
self.attention.authorized = None;
if result.is_ok() {
self.attention_sources[index] = None;
self.attention.sources[index] = None;
}
result
}
@@ -35,10 +35,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
fn gdn_micro_cursors_off(&self, layer: LayerId, (first, end): (usize, usize), accepted: usize) -> bool {
self.next_layer != layer.get()
|| self.next_row != first
|| self.attention_next != end
|| self.batch_layer.is_some()
|| self.attention_layer != Some(layer)
|| self.attention_authorized.is_some()
|| self.attention.next != end
|| self.batch.layer.is_some()
|| self.attention.layer != Some(layer)
|| self.attention.authorized.is_some()
|| accepted != first
}
/// The GDN journal stands at the window's first row, the attention reads of the window are complete and
@@ -95,13 +95,13 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
if self.gdn_chunk.as_ref().is_none_or(|journal| journal.accepted != index) {
return Err(Error::IdentityMismatch);
}
self.attention_authorized = Some(index);
self.attention.authorized = Some(index);
let prepared = self.prepare_layer_batch_internal(index, layer, |step| {
consume(local, step, &read.read, product).map(|(value, edge)| (value, Some(edge)))
});
self.attention_authorized = None;
self.attention.authorized = None;
let prepared = prepared?;
self.attention_sources[index] = None;
self.attention.sources[index] = None;
Ok(prepared)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -148,13 +148,14 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
pub(super) fn check_prepared_row(&self, proof: &PreparedLayerRow, (first, end): (usize, usize)) -> Result<()> {
if proof.index < first
|| proof.index >= end
|| self.batch_layer != Some(proof.layer)
|| self.batch.layer != Some(proof.layer)
|| self.next_layer != proof.layer.get()
|| self.next_row != end
|| self.batch_completed != first
|| self.batch.completed != first
|| !Rc::ptr_eq(&self.chunk, &proof.chunk)
|| self
.batch_rows
.batch
.rows
.get(proof.index)
.and_then(Option::as_ref)
.is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof))
@@ -54,7 +54,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
if step.ple_pending.is_some()
|| step.gdn_pending.iter().any(Option::is_some)
|| step.qsa_pending.iter().any(Option::is_some)
|| self.attention_authorized != Some(index)
|| self.attention.authorized != Some(index)
{
return Err(Error::IdentityMismatch);
}
@@ -65,7 +65,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?;
row.validate(&journal.start, journal.accepted, &self.session.binding)?;
let actual = self.rows.get(index).ok_or(Error::IdentityMismatch)?;
let source = self.attention_sources.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?;
let source = self.attention.sources.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?;
if row.index != index
|| row.identity != TokenLayer::new(actual.token, actual.position, layer)
|| !Rc::ptr_eq(&source.proof, &row.proof)
@@ -103,11 +103,11 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
stored: &Rc<()>,
) -> bool {
let proof = &row.proof;
self.batch_layer != Some(layer)
self.batch.layer != Some(layer)
|| index < first
|| index >= end
|| self.next_row != end
|| self.batch_completed != first
|| self.batch.completed != first
|| proof.index != index
|| proof.layer != layer
|| !Rc::ptr_eq(&self.chunk, &proof.chunk)
@@ -121,7 +121,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
) -> Result<()> {
let span = self.phase_span()?;
self.validate_window_proof(&row.proof.window)?;
let stored = self.batch_rows.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?;
let stored = self.batch.rows.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?;
if self.ffn_row_mismatch(span, (index, layer), row, stored) {
return Err(Error::IdentityMismatch);
}
@@ -159,8 +159,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
}
/// A source-owned attention row holds no PLE history of its own.
fn check_source_owned_ple(&self, step: &QwenStepTxn<'_, 'driver>) -> Result<()> {
let index = self.attention_authorized.ok_or(Error::IdentityMismatch)?;
if self.attention_sources.get(index).and_then(Option::as_ref).is_none() || step.ple_pending.is_some() {
let index = self.attention.authorized.ok_or(Error::IdentityMismatch)?;
if self.attention.sources.get(index).and_then(Option::as_ref).is_none() || step.ple_pending.is_some() {
return Err(Error::IdentityMismatch);
}
Ok(())
@@ -185,7 +185,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
layer: LayerId,
(position, next_position): (Position, u64),
) -> Result<()> {
if self.attention_layer == Some(layer) {
if self.attention.layer == Some(layer) {
self.check_source_owned_ple(step)?;
} else if layer.get() == 1 && self.session.ple_required {
self.roll_ple_layer_one(step, (position, next_position))?;
@@ -19,7 +19,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
}
/// The unwindowed layer pass runs the next row of the current layer with no batch or attention phase open.
fn check_layer_row(&self, index: usize, layer: LayerId) -> Result<()> {
if self.windowed || self.batch_layer.is_some() || self.attention_layer.is_some() {
if self.windowed || self.batch.layer.is_some() || self.attention.layer.is_some() {
return Err(Error::IdentityMismatch);
}
if layer.get() != self.next_layer
@@ -68,8 +68,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
}
/// The attention phase does not authorise this row for a batch.
fn batch_gate_closed(&self, index: usize) -> bool {
(self.windowed && self.attention_layer.is_none())
|| (self.attention_layer.is_some() && self.attention_authorized != Some(index))
(self.windowed && self.attention.layer.is_none())
|| (self.attention.layer.is_some() && self.attention.authorized != Some(index))
}
/// The row is not the next row of `layer`, or the open batch belongs to another layer.
fn batch_cursor_off(&self, index: usize, layer: LayerId) -> bool {
@@ -77,7 +77,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|| index != self.next_row
|| layer.get() >= 48
|| self.rows.get(index).is_none_or(|r| r.completed != layer.get())
|| self.batch_layer.is_some_and(|current| current != layer)
|| self.batch.layer.is_some_and(|current| current != layer)
}
/// The row is inside the active phase and is the next one of `layer`, whose batch it may open or continue.
fn check_batch_row(&self, index: usize, layer: LayerId, (first, end): (usize, usize)) -> Result<()> {
@@ -94,14 +94,14 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
}
/// The first row of a layer opens its batch.
fn open_batch(&mut self, index: usize, layer: LayerId, first: usize) -> Result<()> {
if self.batch_layer.is_none() {
if self.batch.layer.is_none() {
if index != first {
return Err(Error::IdentityMismatch);
}
self.batch_rows.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
self.batch_rows.resize_with(self.rows.len(), || None);
self.batch_layer = Some(layer);
self.batch_completed = first;
self.batch.rows.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
self.batch.rows.resize_with(self.rows.len(), || None);
self.batch.layer = Some(layer);
self.batch.completed = first;
}
Ok(())
}
@@ -123,7 +123,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
/// Record the prepared row in its batch and mint its capability.
fn mint_batch_row(&mut self, index: usize, layer: LayerId) -> PreparedLayerRow {
let proof = Rc::new(());
self.batch_rows[index] = Some(Rc::clone(&proof));
self.batch.rows[index] = Some(Rc::clone(&proof));
self.next_row += 1;
PreparedLayerRow {
chunk: Rc::clone(&self.chunk),
@@ -132,7 +132,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
layer,
window: self.window_proof(),
attention_source: self
.attention_sources
.attention
.sources
.get(index)
.and_then(Option::as_ref)
.map(|source| Rc::clone(&source.read)),
@@ -162,9 +163,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
execute: impl FnOnce(&Context<'driver>) -> Result<T>,
) -> Result<T> {
let (first, end) = self.phase_span()?;
if self.batch_layer.is_none()
if self.batch.layer.is_none()
|| self.next_row != end
|| self.batch_rows.get(first..end).is_none_or(|rows| rows.iter().any(Option::is_none))
|| self.batch.rows.get(first..end).is_none_or(|rows| rows.iter().any(Option::is_none))
{
return Err(Error::IdentityMismatch);
}
@@ -208,11 +209,11 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
fn check_complete_row(&self, proof: &PreparedLayerRow, (first, end): (usize, usize)) -> Result<()> {
if proof.index < first
|| proof.index >= end
|| self.batch_layer != Some(proof.layer)
|| self.batch.layer != Some(proof.layer)
|| !Rc::ptr_eq(&self.chunk, &proof.chunk)
|| proof.index != self.batch_completed
|| proof.index != self.batch.completed
|| self.next_row != end
|| self.batch_rows.get(proof.index).and_then(Option::as_ref).is_none_or(|p| !Rc::ptr_eq(p, &proof.proof))
|| self.batch.rows.get(proof.index).and_then(Option::as_ref).is_none_or(|p| !Rc::ptr_eq(p, &proof.proof))
{
return Err(Error::IdentityMismatch);
}
@@ -226,13 +227,13 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
self.next_row = 0;
self.next_layer += 1;
}
self.batch_layer = None;
self.batch_rows.clear();
self.batch_completed = 0;
self.attention_layer = None;
self.attention_next = if self.windowed { end } else { 0 };
self.attention_sources.clear();
self.attention_authorized = None;
self.batch.layer = None;
self.batch.rows.clear();
self.batch.completed = 0;
self.attention.layer = None;
self.attention.next = if self.windowed { end } else { 0 };
self.attention.sources.clear();
self.attention.authorized = None;
}
pub(in crate::qwen_forward) fn complete_layer_batch(
&mut self,
@@ -249,9 +250,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
self.settle_failure(&marked);
marked?;
self.rows[proof.index].completed += 1;
self.batch_rows[proof.index] = None;
self.batch_completed += 1;
if self.batch_completed == span.1 {
self.batch.rows[proof.index] = None;
self.batch.completed += 1;
if self.batch.completed == span.1 {
self.close_batch(span.1);
}
Ok(residual)
@@ -18,8 +18,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
if self.finished
|| self.next_layer != 48
|| self.next_row != 0
|| self.active_micro.is_some()
|| self.micro_cursor != 0
|| self.micro.active.is_some()
|| self.micro.cursor != 0
|| residuals.len() != self.rows.len()
{
return Err(Error::IdentityMismatch);
@@ -93,8 +93,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
/// The transaction finished every row and holds one validated witness per row.
fn check_publishable(&self) -> Result<()> {
if !self.finished
|| self.active_micro.is_some()
|| self.micro_cursor != 0
|| self.micro.active.is_some()
|| self.micro.cursor != 0
|| self.next_layer != 48
|| self.next_row != 0
|| self.witnesses.len() != self.rows.len()
@@ -0,0 +1,49 @@
//! Groups of cohesive fields of `QwenChunkTxn`, moved out of it by STRA-338 (size): the fields keep their declaration
//! order inside the transaction, so the drop order is unchanged.
#[allow(unused_imports)]
use super::*;
/// The layer whose batched rows are staged, the rows' identity tokens and how many are completed.
#[derive(Default)]
pub(super) struct BatchProgress {
pub(super) layer: Option<LayerId>,
pub(super) rows: Vec<Option<Rc<()>>>,
pub(super) completed: usize,
}
/// The attention layer in flight: the next row, the sources taken so far and the authorized row.
#[derive(Default)]
pub(super) struct AttentionProgress {
pub(super) layer: Option<LayerId>,
pub(super) next: usize,
pub(super) sources: Vec<Option<AttentionSource>>,
pub(super) authorized: Option<usize>,
}
/// The micro-window cursor and the active window (plus the test-only probes).
pub(super) struct MicroProgress {
pub(super) cursor: usize,
pub(super) active: Option<ActiveMicroWindow>,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) test_width: usize,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) test_window_journal: Vec<(u32, usize, usize)>,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) test_partial_words: usize,
}
impl MicroProgress {
pub(super) fn new() -> Self {
Self {
cursor: 0,
active: None,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_width: 64,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_window_journal: Vec::new(),
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_partial_words: 0,
}
}
}
@@ -327,10 +327,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
/// The cursors and the journal stand at the first row of the window, with no batch or authorisation open.
fn ple_cursors_at(&self, journal: &GdnChunkJournal, (first, index): (usize, usize)) -> bool {
self.next_row == first
&& self.attention_layer == Some(journal.start.0.layer)
&& self.attention_next == index
&& self.batch_layer.is_none()
&& self.attention_authorized.is_none()
&& self.attention.layer == Some(journal.start.0.layer)
&& self.attention.next == index
&& self.batch.layer.is_none()
&& self.attention.authorized.is_none()
&& journal.accepted == first
}
/// The row is the next PLE row of the layer-one GDN chunk: same chunk, extent and position, none ahead of it.
@@ -150,8 +150,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|| self.verification.as_ref().is_none_or(|j| j.states.len() != self.rows.len())
|| self.next_layer != 48
|| self.next_row != 0
|| self.active_micro.is_some()
|| self.micro_cursor != 0
|| self.micro.active.is_some()
|| self.micro.cursor != 0
|| residuals.len() != self.rows.len()
|| !self.witnesses.is_empty()
{
@@ -119,8 +119,8 @@ fn break_phase_state(txn: &mut Txn<'_>, refusal: u32, start: &GdnChunkStart) {
match refusal {
0 => txn.chunk = Rc::new(()),
1 | 2 | 3 => replace_anchor(txn, start, refusal),
4 => txn.attention_layer = None,
5 => txn.attention_next = 1,
4 => txn.attention.layer = None,
5 => txn.attention.next = 1,
6 => txn.rows[0].completed = 0,
7 => txn.next_row = 1,
_ => unreachable!(),
@@ -141,9 +141,9 @@ fn break_authority(txn: &mut Txn<'_>, refusal: u32, layer: LayerId, position: Po
}
11 => txn.aborted = true,
12 => txn.session.reset().unwrap(),
13 => txn.active_micro = None,
14 => txn.batch_layer = Some(layer),
15 => txn.attention_authorized = Some(0),
13 => txn.micro.active = None,
14 => txn.batch.layer = Some(layer),
15 => txn.attention.authorized = Some(0),
_ => unreachable!(),
}
}
@@ -156,7 +156,7 @@ fn refuse_with(refusal: u32) {
// Production constructors mint this actual session's anchor/window.
let start = txn.begin_gdn_chunk(layer).unwrap();
let window = txn.open_micro_window(layer).unwrap();
txn.attention_layer = Some(layer);
txn.attention.layer = Some(layer);
let next = stage_next_ple(&mut txn, layer, position);
assert_ple_recorded_without_gdn_prior(&mut txn, layer, position, &next);
// Restore the empty private PLE journal slot before each refusal.