feat(driver): the verify window's GPU expert plan, PCIe DMA and adaptive slot swaps

The pool callback can now publish the literal GpuPlanSink block of its group
(VRAM groups over completed expert-cache slots, PCIe groups staged by DMA on
the verifier's copy stream with a cuLaunchHostFunc flag-B raise, as
Verifier::fetch_dma), checked against the doorbell's mapped ids. The expert
cache gains the residency test of host_res, the adaptive tier's slot swaps on
their own non-blocking stream with event polling (apply_pending), and a
probe-only slot fill. OriginalExpertTierProbe runs one window group's post
phase eagerly for model-free device proofs (feature expert-tier-probe).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-16 10:39:30 +02:00
co-authored by Claude Opus 5.5
parent 64f117f84b
commit 90a73bf2cf
10 changed files with 928 additions and 6 deletions
+2
View File
@@ -14,6 +14,8 @@ leleka-experimental-ref = { path = "../experimental-ref" }
[features]
default = []
cuda-driver = []
# Model-free GPU probes of the Original expert tier (slot fill from caller bytes); never a production path.
expert-tier-probe = []
[target.'cfg(all(target_os = "linux", target_pointer_width = "64"))'.dependencies]
libc = "=0.2.190"
+8
View File
@@ -3262,6 +3262,7 @@ pub(crate) mod original_verify;
target_pointer_width = "64"
))]
pub use original_verify::{
MAX_PCIE_FETCHES as ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalVerifyGpuPlan, OriginalVerifyPcieSource,
OriginalVerifier, OriginalVerifyBank, OriginalVerifyCanonicalGdn, OriginalVerifyCpuRows,
OriginalVerifyCpuSink, OriginalVerifyGdnJournal, OriginalVerifyGdnStage,
OriginalVerifyGdnWeights, OriginalVerifyGeometry, OriginalVerifyGraphResources,
@@ -3303,6 +3304,13 @@ pub use original_verify::{
target_pointer_width = "64"
))]
pub use qsa_prompt_index::{OriginalVerifyQsaJournal, OriginalVerifyRope};
#[cfg(all(
feature = "cuda-driver",
feature = "expert-tier-probe",
target_os = "linux",
target_pointer_width = "64"
))]
pub use original_verify::{OriginalExpertTierProbe, expert_probe_geometry};
// Which compiled assets the Original serve stack needs, and which of them are sealed in this build.
#[cfg(all(
+227 -1
View File
@@ -59,6 +59,15 @@ pub struct OriginalExpertCache<'ctx> {
fills: u64,
attempted: bool,
failed: bool,
/// The adaptive tier's own non-blocking stream (generate.cpp `adapt_stream`) and the completion event of
/// its last batch (`adapt_ev`); created on the first swap.
swap_stream: Option<api::Stream>,
swap_event: Option<api::Event>,
/// Slots whose swap copy is queued on `swap_stream`, with the retained sources they read.
swapping: Vec<usize>,
swap_sources: Vec<RetainedFill<'ctx>>,
swap_armed: bool,
swaps: u64,
}
impl<'ctx> Context<'ctx> {
@@ -151,6 +160,12 @@ impl<'ctx> OriginalExpertCache<'ctx> {
fills: 0,
attempted: false,
failed: false,
swap_stream: None,
swap_event: None,
swapping: Vec::new(),
swap_sources: Vec::new(),
swap_armed: false,
swaps: 0,
};
let guard = context.enter()?;
let operation = (|| {
@@ -227,6 +242,202 @@ impl<'ctx> OriginalExpertCache<'ctx> {
pub fn slot_of(&self, layer: usize, expert: usize) -> i32 {
self.table.slot_of(layer, expert)
}
/// The verify window's residency test (`host_res[l * n_expert + e] >= 0`): the slot holding the expert,
/// only once its bytes were genuinely copied and fenced. A lent, queued or swapped-out slot is a miss.
pub fn resident_slot(&self, layer: usize, expert: usize) -> Option<usize> {
let slot = usize::try_from(self.table.slot_of(layer, expert)).ok()?;
(self.states.get(slot) == Some(&State::Filled)
&& self.owners.get(slot).copied().flatten() == Some((layer, expert)))
.then_some(slot)
}
/// The (layer, expert) a slot was admitted for (or swapped to).
pub fn slot_owner(&self, slot: usize) -> Option<(usize, usize)> {
self.owners.get(slot).copied().flatten()
}
/// Per-layer slot range `[lo, hi)` of `--expert-cache-per-layer` (R4.2g).
pub fn layer_slot_range(&self, layer: usize) -> (usize, usize) {
self.table.layer_slot_range(layer)
}
/// Adaptive swaps issued since open.
pub fn swaps(&self) -> u64 {
self.swaps
}
/// generate.cpp `adapt` (one swap): the slot of `out` (resident, same layer) is given to the expert of
/// `spans` and its bytes are copied on the adaptive tier's own stream. `out` is a miss from now on and
/// the new expert becomes resident only when `poll_swaps` sees the batch's event complete.
pub fn swap_slot_queued(
&mut self,
slot: usize,
bank: Rc<MappedExpertBank<'ctx>>,
spans: [ResidentExpertBankSpan; 3],
) -> Result<()> {
self.ensure_live()?;
if self.file_source_digest.is_some() || !bank.cache_context_matches(self.context) || !bank.eligible(&spans) {
return Err(Error::InvalidSize);
}
let layer = match spans[0].role() {
TensorRole::Layer { layer, .. } => usize::from(layer),
_ => return Err(Error::InvalidSize),
};
let to = (layer, spans[0].expert() as usize);
let from = self.owners.get(slot).copied().flatten().ok_or(Error::InvalidSize)?;
if !matches!(self.states.get(slot), Some(State::Filled) | Some(State::NeedsRefill)) || self.swap_armed {
return Err(Error::InvalidSize);
}
let (handle, capacity) = self.slot_handle(slot)?;
let mut total = 0usize;
for span in &spans {
bank.cache_source(span)?;
total = total.checked_add(span.bytes().len()).ok_or(Error::InvalidSize)?;
}
if total > capacity {
return Err(Error::ShapeMismatch { expected: capacity, actual: total });
}
self.swapping.try_reserve(1).map_err(|_| Error::HostAllocation)?;
self.swap_sources.try_reserve(1).map_err(|_| Error::HostAllocation)?;
self.table.reassign(slot, from, to)?;
self.owners[slot] = Some(to);
// From here the slot holds neither expert until the copy is fenced.
self.states[slot] = State::NeedsRefill;
self.swap_sources.push(RetainedFill::Mapped { bank, spans });
let guard = self.context.enter()?;
let operation = (|| {
let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?;
if self.swap_stream.is_none() {
self.swap_stream = Some(api.create_stream()?);
}
let stream = self.swap_stream.ok_or(Error::ContextPoisoned)?;
let RetainedFill::Mapped { bank, spans } = self.swap_sources.last().ok_or(Error::ContextPoisoned)? else {
return Err(Error::InvalidSize);
};
let mut offset = 0usize;
for span in spans {
let source = bank.cache_source(span)?;
let destination = handle.checked_subspan(capacity, offset, source.len())?;
api.copy(destination.qwen_address(), source, stream)?;
offset += source.len();
}
Ok(())
})();
let result = combine(operation, guard.finish());
if result.is_err() {
self.poison();
return result;
}
self.states[slot] = State::Queued;
self.swapping.push(slot);
self.swaps = self.swaps.checked_add(1).ok_or(Error::InvalidSize)?;
self.fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?;
Ok(())
}
/// `cudaEventRecord(adapt_ev, adapt_stream)` after a batch of swaps; nothing to do without swaps.
pub fn arm_swaps(&mut self) -> Result<()> {
self.ensure_live()?;
if self.swapping.is_empty() || self.swap_armed {
return Ok(());
}
let guard = self.context.enter()?;
let operation = (|| {
let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?;
if self.swap_event.is_none() {
self.swap_event = Some(api.create_event()?);
}
api.record(self.swap_event.ok_or(Error::ContextPoisoned)?, self.swap_stream.ok_or(Error::ContextPoisoned)?)
})();
let result = combine(operation, guard.finish());
if result.is_err() {
self.poison();
return result;
}
self.swap_armed = true;
Ok(())
}
/// True while swaps are queued and not yet published (`!pending.empty()`).
pub fn swaps_pending(&self) -> bool {
!self.swapping.is_empty()
}
/// generate.cpp `apply_pending(false)`: when the batch's event has completed, every swapped slot becomes
/// resident (`host_res[in] = slot`) and its sources are released. NOT_READY publishes nothing.
pub fn poll_swaps(&mut self) -> Result<bool> {
self.ensure_live()?;
if self.swapping.is_empty() {
return Ok(true);
}
if !self.swap_armed {
return Ok(false);
}
let guard = self.context.enter()?;
let query = self
.api
.as_ref()
.ok_or(Error::ContextPoisoned)
.and_then(|api| api.query(self.swap_event.ok_or(Error::ContextPoisoned)?));
match combine(query, guard.finish()) {
Err(error) => {
self.poison();
Err(error)
}
Ok(false) => Ok(false),
Ok(true) => {
self.complete_swaps();
Ok(true)
}
}
}
fn complete_swaps(&mut self) {
for &slot in &self.swapping {
if self.states[slot] == State::Queued {
self.states[slot] = State::Filled;
}
}
self.swapping.clear();
self.swap_sources.clear();
self.swap_armed = false;
}
/// generate.cpp `apply_pending(true)`: wait for the swaps in flight, then publish them.
pub fn wait_swaps(&mut self) -> Result<()> {
self.ensure_live()?;
if self.swapping.is_empty() {
return Ok(());
}
let guard = self.context.enter()?;
let wait = self
.api
.as_ref()
.ok_or(Error::ContextPoisoned)
.and_then(|api| api.synchronize_stream(self.swap_stream.ok_or(Error::ContextPoisoned)?));
let result = combine(wait, guard.finish());
if result.is_err() {
self.poison();
return result;
}
self.complete_swaps();
Ok(())
}
/// Model-free probes only (feature `expert-tier-probe`): fill an admitted slot from caller bytes with a
/// blocking copy. Production fills come from the registered model bank or the pinned file source only.
#[cfg(any(test, feature = "expert-tier-probe"))]
pub fn probe_fill_slot(&mut self, slot: usize, bytes: &[u8]) -> Result<()> {
self.ensure_live()?;
if self.owners.get(slot).copied().flatten().is_none() || !self.pending.is_empty() || !self.swapping.is_empty() {
return Err(Error::InvalidSize);
}
let (handle, capacity) = self.slot_handle(slot)?;
if bytes.is_empty() || bytes.len() > capacity {
return Err(Error::InvalidSize);
}
let handle = handle.checked_subspan(capacity, 0, bytes.len())?;
let guard = self.context.enter()?;
let copy = self.context.driver.api.copy_from(handle, bytes);
let result = combine(copy, guard.finish());
if result.is_err() {
self.poison();
return result;
}
self.states[slot] = State::Filled;
self.fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?;
Ok(())
}
pub fn admit(&mut self, layer: usize, expert: usize) -> Result<i32> {
self.ensure_live()?;
let slot = self.table.admit(layer, expert);
@@ -504,6 +715,7 @@ impl<'ctx> OriginalExpertCache<'ctx> {
/// Exactly one default-stream fence for all preceding startup/refill copies.
/// NOT_READY/transport errors never publish the table as usable GPU weights.
pub fn sync_queued(&mut self) -> Result<()> {
self.wait_swaps()?;
self.ensure_live()?;
if !self.attempted {
return Ok(());
@@ -666,6 +878,7 @@ impl<'ctx> OriginalExpertCache<'ctx> {
if drain.is_err() || self.context.is_poisoned() {
self.poison();
std::mem::forget(std::mem::take(&mut self.pending));
std::mem::forget(std::mem::take(&mut self.swap_sources));
if let Some(buffer) = self.buffer.take() {
std::mem::forget(buffer);
}
@@ -676,7 +889,20 @@ impl<'ctx> OriginalExpertCache<'ctx> {
}
self.failed = true;
self.pending.clear();
let released = self.buffer.take().ok_or(Error::ContextPoisoned)?.release();
let mut released = Ok(());
if self.swap_event.is_some() || self.swap_stream.is_some() {
let guard = self.context.enter()?;
if let Some(api) = self.api.as_ref() {
if let Some(event) = self.swap_event.take() {
released = combine(released, api.destroy_event(event));
}
if let Some(stream) = self.swap_stream.take() {
released = combine(released, api.destroy_stream(stream));
}
}
released = combine(released, guard.finish());
}
let released = combine(released, self.buffer.take().ok_or(Error::ContextPoisoned)?.release());
self.api.take();
released
}
@@ -156,6 +156,26 @@ impl OriginalExpertSlots {
self.residency[at] = slot as i32;
slot as i32
}
/// generate.cpp's adaptive tier: `in` takes the slot `out` held, in the same layer (`host_res[out] =
/// kNotResident`, `host_res[in] = slot` once the copy landed). Only the residency moves; admission
/// cursors are unchanged, so the slot stays inside its layer's range.
pub(crate) fn reassign(&mut self, slot: usize, from: (usize, usize), to: (usize, usize)) -> Result<()> {
if from.0 != to.0
|| from.0 >= self.n_layers
|| from.1 >= self.n_expert
|| to.1 >= self.n_expert
|| slot >= self.slots
{
return Err(Error::InvalidSize);
}
let (old, new) = (from.0 * self.n_expert + from.1, to.0 * self.n_expert + to.1);
if self.residency[old] != slot as i32 || self.residency[new] != -1 {
return Err(Error::InvalidSize);
}
self.residency[old] = -1;
self.residency[new] = slot as i32;
Ok(())
}
pub(crate) fn slot_span(&self, slot: usize) -> Result<(usize, usize)> {
if slot >= self.slots {
return Err(Error::InvalidSize);
@@ -243,6 +243,24 @@ impl<'ctx> OriginalGpuStream<'ctx> {
}
self.inner.run(|a, h| a.stream_sync(h))
}
/// `fetch_dma`'s `cudaMemcpyAsync` of one registered source span into device staging. The caller retains
/// the registered source and the destination allocation until this stream's next fence.
pub(crate) fn enqueue_copy_h2d(&mut self, destination: u64, source: &[u8]) -> Result<()> {
if self.inner.capture.get() || source.is_empty() || destination == 0 {
return Err(Error::InvalidQwenShape);
}
self.inner.bump()?;
self.inner.run(|a, h| a.copy_h2d(destination, source, h))
}
/// `fetch_dma`'s `cudaLaunchHostFunc(raise_flag)`: the mapped host word rises to `value` after every
/// earlier operation of this stream. The word's owner must outlive this stream's next fence.
pub(crate) fn enqueue_raise_u32(&mut self, word: usize, value: u32) -> Result<()> {
if self.inner.capture.get() {
return Err(Error::InvalidQwenShape);
}
self.inner.bump()?;
self.inner.run(|a, h| a.raise_u32_after(h, word, value))
}
/// Only closed typed driver producers may enqueue via this private validated handle.
/// Their stable ABI/device/mapped owners MUST live in capture resources R.
pub(crate) fn with_enqueue<T>(&mut self, f: impl FnOnce(usize) -> Result<T>) -> Result<T> {
@@ -43,6 +43,23 @@ mod platform {
type Instantiate = unsafe extern "C" fn(*mut Handle, Handle, u64) -> i32;
type GraphCall = unsafe extern "C" fn(Handle) -> i32;
type GraphStream = unsafe extern "C" fn(Handle, Handle) -> i32;
type CopyH2d = unsafe extern "C" fn(u64, *const c_void, usize, Handle) -> i32;
type HostFn = unsafe extern "C" fn(*mut c_void);
type LaunchHostFn = unsafe extern "C" fn(Handle, HostFn, *mut c_void) -> i32;
/// One `fetch_dma` flag raise: the mapped host word and the ring value it must reach.
struct Raise {
word: usize,
value: u32,
}
/// `cudaLaunchHostFunc` body of `Verifier::fetch_dma`: `raise_flag(flag, value)` (only rises).
unsafe extern "C" fn raise_after_copies(data: *mut c_void) {
// SAFETY: `data` is the Box leaked by `raise_u32_after` for exactly this one call.
let raise = unsafe { Box::from_raw(data.cast::<Raise>()) };
// SAFETY: the word is a 4-byte-aligned mapped host allocation the verifier bank keeps alive until the
// context is synchronized at its close, after every host function of its streams has run.
let word = unsafe { &*(raise.word as *const std::sync::atomic::AtomicU32) };
word.fetch_max(raise.value, std::sync::atomic::Ordering::SeqCst);
}
pub(crate) struct Api {
_library: Library,
create: StreamCreate,
@@ -65,6 +82,8 @@ mod platform {
exec_destroy: GraphCall,
upload: GraphStream,
launch: GraphStream,
copy_h2d: CopyH2d,
host_fn: LaunchHostFn,
}
impl Api {
pub(crate) fn load() -> Result<Self> {
@@ -110,6 +129,8 @@ mod platform {
exec_destroy: sym!(c"cuGraphExecDestroy", GraphCall),
upload: sym!(c"cuGraphUpload", GraphStream),
launch: sym!(c"cuGraphLaunch", GraphStream),
copy_h2d: sym!(c"cuMemcpyHtoDAsync_v2", CopyH2d),
host_fn: sym!(c"cuLaunchHostFunc", LaunchHostFn),
_library: l,
})
}
@@ -244,6 +265,29 @@ mod platform {
(self.launch)(e as Handle, s as Handle)
})
}
/// `cudaMemcpyAsync(H2D)` of `fetch_dma`. The caller keeps `src` (a registered bank) and `dst` alive
/// until the stream's fence.
pub(crate) fn copy_h2d(&self, dst: u64, src: &[u8], s: usize) -> Result<()> {
check("cuMemcpyHtoDAsync_v2", unsafe {
(self.copy_h2d)(dst, src.as_ptr().cast(), src.len(), s as Handle)
})
}
/// `cudaLaunchHostFunc(raise_flag)` of `fetch_dma`: `word` rises to at least `value` once every earlier
/// operation of the stream completed. `word` must be a live 4-byte-aligned mapped host word.
pub(crate) fn raise_u32_after(&self, s: usize, word: usize, value: u32) -> Result<()> {
if word == 0 || word % 4 != 0 {
return Err(Error::InvalidSize);
}
let data = Box::into_raw(Box::new(Raise { word, value }));
let launched = check("cuLaunchHostFunc", unsafe {
(self.host_fn)(s as Handle, raise_after_copies, data.cast())
});
if launched.is_err() {
// SAFETY: the driver refused the launch, so the callback will never take this Box.
drop(unsafe { Box::from_raw(data) });
}
launched
}
}
}
#[cfg(all(
@@ -327,4 +371,10 @@ impl Api {
pub(crate) fn launch(&self, _: usize, _: usize) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy_h2d(&self, _: u64, _: &[u8], _: usize) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn raise_u32_after(&self, _: usize, _: usize, _: u32) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
}
+12 -3
View File
@@ -130,7 +130,9 @@ impl Physical<'_>{
impl Drop for Physical<'_>{fn drop(&mut self){let _=self.close();}}
/// One genuine fixed max-T bank. Root keeps this in every captured graph's
/// resource aggregate; commands retain the stable ABI through final graph drain.
pub struct OriginalVerifyBank<'ctx>{physical:Rc<Physical<'ctx>>,last_t:usize,last_position:usize,last_tokens:[i32;8],generation:u64,last_keep:usize,released:bool}
pub struct OriginalVerifyBank<'ctx>{physical:Rc<Physical<'ctx>>,last_t:usize,last_position:usize,last_tokens:[i32;8],generation:u64,last_keep:usize,released:bool,
/// Registered expert banks a window's PCIe DMA reads (`publish_gpu_plan`), held until the copy-stream fence.
pcie_sources:Vec<Rc<crate::MappedExpertBank<'ctx>>>}
impl<'ctx> OriginalVerifyBank<'ctx>{
fn new(context:&'ctx Context<'ctx>,geometry:OriginalVerifyGeometry)->Result<Self>{
let layout=OriginalVerifyLayout::new(geometry)?;let asset=sealed_asset(ASSET,ASSET_SHA)?;let qsa_asset=sealed_asset(QSA_ASSET,QSA_ASSET_SHA)?;admission(context,layout.bytes)?;
@@ -147,7 +149,7 @@ impl<'ctx> OriginalVerifyBank<'ctx>{
if std::env::var_os("STRATA_VERIFY_PROFILE").is_some(){let bytes=profile::profile_stamp_words(48)*8;if let Ok(b)=context.allocate(bytes){let zeroed=handle(&b).and_then(|h|context.driver.api.zero(h.qwen_address(),bytes));if zeroed.is_ok(){owner.prof=Some(b)}else{let _=b.release();}}}
Ok(())
})();let sync=context.driver.api.synchronize();let pop=guard.finish();if loaded.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){poison(context)}combine(combine(loaded,sync),pop)
})();if let Err(primary)=operation{return combine(Err(primary),owner.close())}Ok(Self{physical:Rc::new(owner),last_t:0,last_position:0,last_tokens:[0;8],generation:0,last_keep:0,released:false})
})();if let Err(primary)=operation{return combine(Err(primary),owner.close())}Ok(Self{physical:Rc::new(owner),last_t:0,last_position:0,last_tokens:[0;8],generation:0,last_keep:0,released:false,pcie_sources:Vec::new()})
}
pub(crate) fn staged_window(&self)->Result<(u64,usize,usize)>{self.validate_context(self.physical.context)?;if self.last_t==0||self.released{return Err(Error::InvalidQwenShape)}Ok((self.generation,self.last_position,self.last_t))}
pub(crate) fn staged_keep(&self)->Result<usize>{self.staged_window()?;if !(1..=self.last_t).contains(&self.last_keep){return Err(Error::InvalidQwenShape)}Ok(self.last_keep)}
@@ -187,7 +189,10 @@ impl<'ctx> OriginalVerifyBank<'ctx>{
}
pub fn doorbell_sequence(&self)->Result<u32>{self.physical.mapped[9].try_borrow().map_err(|_|Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)}
pub(crate) fn publish_empty_plan(&mut self,group:usize,ring:u32)->Result<()>{if group>1||ring==0||ring>96{return Err(Error::InvalidQwenShape)}let m=&self.physical.mapped;let mut slot=m[14].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let p=slot.as_mut().ok_or(Error::ContextPoisoned)?;let base=group*self.physical.layout.plan_i32*4;for o in [0,4,8,16,(self.physical.layout.plan_i32-self.geometry().max_t*self.geometry().k-2)*4]{p.write(base+o,&0i32.to_le_bytes())?}m[11].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0,ring)?;m[12].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.raise_u32(0,ring)}
pub fn close(self)->Result<()>{match Rc::try_unwrap(self.physical){Ok(mut owner)=>owner.close(),Err(_)=>Err(Error::InvalidQwenShape)}}
pub(crate) fn retain_pcie_source(&mut self,bank:Rc<crate::MappedExpertBank<'ctx>>)->Result<()>{if !self.pcie_sources.iter().any(|b|Rc::ptr_eq(b,&bank)){self.pcie_sources.try_reserve(1).map_err(|_|Error::HostAllocation)?;self.pcie_sources.push(bank)}Ok(())}
/// Only after the copy stream drained (the window's own fence).
pub(crate) fn release_pcie_sources(&mut self){self.pcie_sources.clear()}
pub fn close(self)->Result<()>{let Self{physical,pcie_sources,..}=self;let closed=match Rc::try_unwrap(physical){Ok(mut owner)=>owner.close(),Err(_)=>Err(Error::InvalidQwenShape)};drop(pcie_sources);closed}
/// Fixed real layer operands and borrowed source weights remain alive inside
/// the graph aggregate. No host-made readiness or arbitrary handles enter.
pub fn gdn_journal<'a>(&self,canonical:&mut OriginalVerifyCanonicalGdn<'ctx>,weights:[OriginalVerifyGdnWeights<'a,'ctx>;36],ple:Option<&'a DeviceBuffer<'ctx>>)->Result<OriginalVerifyGdnJournal<'a,'ctx>>{
@@ -377,6 +382,10 @@ impl OriginalVerifyGdnJournal<'_, '_>{
pub fn validate_bank(&self,bank:&OriginalVerifyBank<'_>)->Result<()>{if !Rc::ptr_eq(&self.physical,&bank.physical){return Err(Error::InvalidQwenShape)}self.validate_context(self.physical.context)}
}
#[path="original_verify_schedule.rs"] mod schedule;
#[path="original_verify_gpu_plan.rs"] mod gpu_plan;
pub use gpu_plan::{MAX_PCIE_FETCHES,OriginalVerifyGpuPlan,OriginalVerifyPcieSource};
#[cfg(any(test,feature="expert-tier-probe"))] #[path="original_verify_expert_probe.rs"] mod expert_probe;
#[cfg(any(test,feature="expert-tier-probe"))] pub use expert_probe::{OriginalExpertTierProbe,expert_probe_geometry};
pub use schedule::{OriginalVerifier,OriginalVerifyWindowResult,OriginalVerifyCpuRows,OriginalVerifyCpuSink};
#[path="original_verify_window_ops.rs"] mod window_ops;
pub use window_ops::{OriginalVerifyExpertLayout,OriginalVerifyWindowResources,UNBOUND_PRODUCERS,unsealed_window_assets};
@@ -0,0 +1,291 @@
//! Model-free device probe of the verify window's expert tier (feature `expert-tier-probe`; never a serving
//! path). One layer group of the window's `post` phase runs eagerly on a real verifier bank, with the very
//! launches the recorded graph makes (`moe` planners and the bank's own flag/plan/row kernels) and the very
//! host protocol `OriginalVerifier::run` follows around the pool callback:
//!
//! ```text
//! compute: quantize_expert_input | wait A | plan copy | VRAM groups | wait B | PCIe groups | wait M
//! | copy cpu rows (only the CPU's) | hit add
//! host : pool(rows, sink, copy) [publishes the GPU plan (A), stages PCIe (B), writes its CPU rows]
//! | empty plan unless published | M
//! ```
//!
//! The result is the group's `parts` rows (`rows * k * n` floats): what `combine` would weight. A runtime test
//! drives it with synthetic expert blobs and the real CPU pool to prove placement, the hit/miss split and the
//! GPU-vs-CPU rounding bound without a model.
use super::kernels::ArenaMap;
use super::moe::{self, MoeKnobs, OriginalVerifyExpertFormats};
use super::window_plan::PlanLayout;
use super::window_record::{ExpertTier, Rows};
use super::*;
use crate::{OriginalGpuStream, OriginalStreamKind};
struct ProbeArena<'p, 'ctx>(&'p Physical<'ctx>);
impl ArenaMap for ProbeArena<'_, '_> {
fn span(&self, name: &str, offset: usize, bytes: usize) -> Result<u64> {
self.0.span(name, offset, bytes)
}
}
/// A verifier bank, its two streams and the window's MoE modules, for eager single-group runs.
pub struct OriginalExpertTierProbe<'ctx> {
bank: Option<OriginalVerifyBank<'ctx>>,
compute: Option<OriginalGpuStream<'ctx>>,
copy: Option<OriginalGpuStream<'ctx>>,
formats: OriginalVerifyExpertFormats,
}
/// The probe geometry: the model's MoE shape with a small context and vocabulary (no head runs here).
pub fn expert_probe_geometry(max_t: usize, max_expert_blob: usize) -> OriginalVerifyGeometry {
OriginalVerifyGeometry {
max_t,
n: 2560,
hc: 4,
lr: 320,
ff: 640,
experts: 512,
k: 10,
channels: 10240,
value_heads: 48,
key_heads: 16,
heads: 24,
kv_heads: 2,
head_dim: 256,
index_heads: 4,
index_dim: 128,
index_block: 4,
selection: 2051,
max_cells: 256,
vocabulary: 1024,
max_expert_blob,
}
}
impl<'ctx> Context<'ctx> {
pub fn original_expert_tier_probe(
&'ctx self,
max_t: usize,
max_expert_blob: usize,
formats: OriginalVerifyExpertFormats,
) -> Result<OriginalExpertTierProbe<'ctx>> {
let bank = self.original_verify_bank(expert_probe_geometry(max_t, max_expert_blob))?;
let mut probe = OriginalExpertTierProbe { bank: Some(bank), compute: None, copy: None, formats };
let opened = (|| {
probe.bank()?.physical.ensure_window_assets(&moe::assets())?;
probe.copy = Some(self.original_gpu_stream(OriginalStreamKind::NonBlocking)?);
probe.compute = Some(self.original_gpu_stream(OriginalStreamKind::NonBlocking)?);
Ok(())
})();
match opened {
Ok(()) => Ok(probe),
Err(primary) => combine(Err(primary), probe.close_inner()),
}
}
}
impl<'ctx> OriginalExpertTierProbe<'ctx> {
fn bank(&self) -> Result<&OriginalVerifyBank<'ctx>> {
self.bank.as_ref().ok_or(Error::ContextPoisoned)
}
fn launch_window(&mut self, launches: Vec<kernels::Launch>) -> Result<()> {
let physical = self.bank()?.physical.clone();
let modules = physical.window.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
let compute = self.compute.as_mut().ok_or(Error::ContextPoisoned)?;
for launch in launches {
let mut command = launch.command()?;
let module = modules
.iter()
.find(|(n, _, _)| *n == launch.asset.key())
.ok_or(Error::InvalidDriverValue(launch.asset.unsealed))?;
compute.with_enqueue(|h| module.1.launch(h, &mut command))?;
}
Ok(())
}
fn launch_bank(&mut self, mut commands: Vec<Command>) -> Result<()> {
let physical = self.bank()?.physical.clone();
let module = physical.module.as_ref().ok_or(Error::ContextPoisoned)?;
let compute = self.compute.as_mut().ok_or(Error::ContextPoisoned)?;
for command in &mut commands {
compute.with_enqueue(|h| module.launch(h, command))?;
}
Ok(())
}
fn write_mapped(&self, index: usize, offset: usize, bytes: &[u8]) -> Result<()> {
let physical = &self.bank()?.physical;
let mut slot = physical.mapped[index].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
slot.as_mut().ok_or(Error::ContextPoisoned)?.write(offset, bytes)
}
fn flag(&self, index: usize, value: u32) -> Result<()> {
let physical = &self.bank()?.physical;
let mut slot = physical.mapped[index].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
slot.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0, value)
}
fn arena_handle(&self, name: &str, offset: usize, bytes: usize) -> Result<crate::ffi::BufferHandle> {
let physical = &self.bank()?.physical;
let span = physical.layout.span(name)?;
if offset.checked_add(bytes).is_none_or(|end| end > span.bytes) {
return Err(Error::InvalidSize);
}
let arena = physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;
handle(arena)?.checked_subspan(arena.len(), span.offset + offset, bytes)
}
/// Run one window group of `rows = ids.len() / k` rows (group 0, layer `layer`): `activation` is the FFN
/// input `mixed` (`rows * n`), `ids` the router's top-k per row. `pool` is called exactly like the
/// verifier's pool callback (its rows, the sink, the copy stream). Returns the group's `parts`.
pub fn run_group(
&mut self,
layer: usize,
activation: &[f32],
ids: &[i32],
pool: impl FnOnce(OriginalVerifyCpuRows<'_>, &mut OriginalVerifyCpuSink<'_, 'ctx>, &mut OriginalGpuStream<'ctx>) -> Result<()>,
) -> Result<Vec<f32>> {
let g = self.bank()?.geometry();
let (n, k) = (g.n, g.k);
let rows = ids.len() / k;
if rows == 0 || rows > g.max_t || ids.len() != rows * k || activation.len() != rows * n || layer >= 48 {
return Err(Error::InvalidQwenShape);
}
let context = self.bank()?.physical.context;
let ring = 1u32;
let group = Rows { begin: 0, end: rows, group: 0 };
// the doorbell's publication and the device FFN input
for flag in 9..=12 {
self.flag(flag, 0)?;
}
let as_bytes = |v: &[f32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
self.write_mapped(6, 0, &as_bytes(activation))?;
self.write_mapped(7, 0, &ids.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>())?;
self.write_mapped(8, 0, &as_bytes(&vec![1.0 / k as f32; rows * k]))?;
{
let mixed = self.arena_handle("mixed", 0, rows * n * 4)?;
let guard = context.enter()?;
let copy = context.driver.api.copy_from(mixed, &as_bytes(activation));
combine(copy, guard.finish())?;
// parts / hit_out start from a known state, as a reused window would not guarantee
let zero = (|| {
for name in ["parts", "hit_out"] {
let h = self.arena_handle(name, 0, rows * k * n * 4)?;
let guard = context.enter()?;
let z = context.driver.api.zero(h.qwen_address(), rows * k * n * 4);
combine(z, guard.finish())?;
}
Ok(())
})();
zero?;
}
// compute side, in the recorded order of `post`
let knobs = MoeKnobs::mode17();
let layout = PlanLayout::new(g.max_t * k);
let (quantize, vram, pcie, hit_add) = {
let arena = ProbeArena(&self.bank()?.physical);
(
moe::plan_quantize_expert_input(&arena, &g, &knobs, group)?,
moe::plan_expert_groups(&arena, &g, &knobs, &self.formats, layer, group, ExpertTier::Vram)?,
moe::plan_expert_groups(&arena, &g, &knobs, &self.formats, layer, group, ExpertTier::Pcie)?,
moe::plan_hit_add(&arena, &g, group)?,
)
};
let physical = self.bank()?.physical.clone();
let wait = |index: usize| -> Result<Command> {
command("verify_wait_flag_ge_kernel", [1, 1, 1], [1, 1, 1], vec![Arg::Address(physical.mapped_address(index, 0, 4)?), Arg::I32(ring as i32)])
};
let plan_copy = command(
"verify_copy_i32_from_mapped_kernel",
[1, 1, 1],
[128, 1, 1],
vec![
Arg::Address(physical.span("plan", 0, layout.words * 4)?),
Arg::Address(physical.mapped_address(14, 0, layout.words * 4)?),
Arg::I32(layout.words as i32),
],
)?;
let plan_word = |word: usize| physical.span("plan", word * 4, 4);
let copy_rows = command(
"verify_copy_rows_from_mapped_kernel",
[(rows * k) as u32, 1, 1],
[128, 1, 1],
vec![
Arg::Address(physical.span("parts", 0, rows * k * n * 4)?),
Arg::Address(physical.mapped_address(13, 0, rows * k * n * 4)?),
Arg::I64((n / 4) as i64),
Arg::Address(plan_word(layout.dst)?),
Arg::Address(plan_word(layout.counts + 1)?),
],
)?;
let enqueued = (|| {
self.launch_window(quantize)?;
self.launch_bank(vec![wait(11)?, plan_copy])?;
self.launch_window(vram)?;
self.launch_bank(vec![wait(12)?])?;
self.launch_window(pcie)?;
self.launch_bank(vec![wait(10)?, copy_rows])?;
self.launch_window(hit_add)
})();
// host side: the pool callback, then the run loop's empty plan and M
let served = enqueued.and_then(|()| {
let bank = self.bank.as_mut().ok_or(Error::ContextPoisoned)?;
let copy = self.copy.as_mut().ok_or(Error::ContextPoisoned)?;
let x = physical.mapped[6].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
let ids_m = physical.mapped[7].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
let w = physical.mapped[8].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
MappedAllocation::with_cpu_rows(
x.as_ref().ok_or(Error::ContextPoisoned)?,
ids_m.as_ref().ok_or(Error::ContextPoisoned)?,
w.as_ref().ok_or(Error::ContextPoisoned)?,
0,
rows,
n,
k,
|activation, ids, route_weights| {
pool(
OriginalVerifyCpuRows { layer, group: 0, first_row: 0, activation, ids, route_weights },
&mut OriginalVerifyCpuSink { bank, first: 0, rows, layer, group: 0, groups: 1, ring },
copy,
)
},
)
});
let finished = served.and_then(|()| {
let a = physical.mapped[11].try_borrow().map_err(|_| Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)?;
if a != ring {
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(0, ring)?;
}
self.flag(10, ring)?;
self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.release_pcie_sources();
let parts = self.arena_handle("parts", 0, rows * k * n * 4)?;
let mut bytes = vec![0u8; rows * k * n * 4];
let guard = context.enter()?;
let read = context.driver.api.copy_to(parts, &mut bytes);
combine(read, guard.finish())?;
Ok(bytes.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap_or([0; 4]))).collect())
});
if finished.is_err() {
// no spin kernel may outlive a failed probe: raise every flag and drain both streams
let _ = self.bank.as_mut().map(OriginalVerifyBank::release_gpu_waits);
let _ = self.compute.as_ref().map(OriginalGpuStream::synchronize);
let _ = self.copy.as_ref().map(OriginalGpuStream::synchronize);
}
finished
}
fn close_inner(&mut self) -> Result<()> {
let mut result = Ok(());
for stream in [self.compute.take(), self.copy.take()].into_iter().flatten() {
result = combine(result, stream.close());
}
if let Some(bank) = self.bank.take() {
result = combine(result, bank.close());
}
result
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
}
impl Drop for OriginalExpertTierProbe<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
@@ -0,0 +1,294 @@
//! The pool's GPU half of a verify-window layer group (expert_source.cpp `expert_pool_dispatch_multi`, plan
//! v0.3 P6, and verify.cpp `Verifier::publish_plan` / `Verifier::fetch_dma`).
//!
//! The pool decides, on THIS layer's routed ids, which distinct experts the GPU computes: the ones resident
//! in the VRAM tier (`OriginalExpertCache` slots) and a PCIe share of the missed ones (staged into the
//! window's `staging` span by DMA on the verifier's copy stream). The plan block it publishes is the literal
//! `GpuPlanSink` layout (`PlanLayout`): `counts = [vram groups, gpu entries, pcie groups, 0]`, `start`,
//! `dst`, `tok`, the u64 `ptr` / `ptr2` arrays and `start2`. Flag A is raised once the block is written (the
//! graph then copies it to the device and runs the VRAM groups while the CPU computes its misses); flag B
//! rises once the PCIe blobs have landed (a host function on the copy stream after the copies, the
//! `cudaLaunchHostFunc` of `fetch_dma`), or at once when nothing is staged.
//!
//! Every pointer comes from an owner, never from the caller: a VRAM group names a cache slot whose fill has
//! completed and whose owner is the routed expert of every entry of the group (checked against the mapped ids
//! the doorbell published), a PCIe group names the three registered bank spans of that same expert.
use super::*;
use super::window_plan::{PlanLayout, staging_blobs_per_group};
use crate::{MappedExpertBank, OriginalExpertCache, OriginalGpuStream};
use leleka_model_format::qwen4exp::{ResidentExpertBankSpan, TensorRole};
/// `dma_src[64]` / `pcie_i0[64]`: the most PCIe groups one layer group may stage.
pub const MAX_PCIE_FETCHES: usize = 64;
/// One window group's GPU share: the VRAM groups (a cache slot and the entries `row * k + j` that routed to
/// its expert, ascending) in routing order, then the PCIe groups (staging slot `q` = position) likewise.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct OriginalVerifyGpuPlan {
vram: Vec<(usize, Vec<u16>)>,
pcie: Vec<Vec<u16>>,
}
impl OriginalVerifyGpuPlan {
pub fn new() -> Self {
Self::default()
}
pub fn push_vram(&mut self, slot: usize, entries: Vec<u16>) {
self.vram.push((slot, entries));
}
pub fn push_pcie(&mut self, entries: Vec<u16>) {
self.pcie.push(entries);
}
pub fn vram(&self) -> &[(usize, Vec<u16>)] {
&self.vram
}
pub fn pcie(&self) -> &[Vec<u16>] {
&self.pcie
}
/// Entries the GPU computes (`counts[1]`).
pub fn entries(&self) -> usize {
self.vram.iter().map(|(_, e)| e.len()).sum::<usize>() + self.pcie.iter().map(Vec::len).sum::<usize>()
}
pub fn is_empty(&self) -> bool {
self.vram.is_empty() && self.pcie.is_empty()
}
}
/// The registered source of the plan's PCIe groups: `spans[q]` are the gate/up/down spans of PCIe group `q`'s
/// expert. `Some` also routes flag B through the copy stream even when nothing is staged, so the flag only
/// ever rises in copy-stream order once a window stages anything.
pub struct OriginalVerifyPcieSource<'s, 'ctx> {
pub bank: &'s Rc<MappedExpertBank<'ctx>>,
pub spans: &'s [[ResidentExpertBankSpan; 3]],
}
/// The literal `GpuPlanSink` writes of one group into a `layout.words` int32 block (little-endian bytes):
/// VRAM groups first (`ptr`, `start`), `start[groups] = entries`, then the PCIe groups (`ptr2`, `start2`),
/// `start2[fetches] = entries`, and the counts. `dst[e] = i`, `tok[e] = i / k`. Refuses an entry outside the
/// group's `n_entries`, a repeated entry, an empty group, and more groups or entries than the block holds.
pub(crate) fn encode_plan_block(
layout: &PlanLayout,
cap: usize,
k: usize,
n_entries: usize,
vram: &[(u64, &[u16])],
pcie: &[(u64, &[u16])],
) -> Result<Vec<u8>> {
if k == 0 || n_entries > cap || n_entries > 128 || vram.len() > cap || pcie.len() > cap.min(MAX_PCIE_FETCHES) {
return Err(Error::InvalidQwenShape);
}
let mut words = vec![0i32; layout.words];
let mut seen = [false; 128];
let mut entries = 0usize;
let put_u64 = |words: &mut Vec<i32>, at: usize, value: u64| {
words[at] = value as u32 as i32;
words[at + 1] = (value >> 32) as u32 as i32;
};
let mut add_entries = |words: &mut Vec<i32>, list: &[u16], entries: &mut usize| -> Result<()> {
if list.is_empty() {
return Err(Error::InvalidQwenShape);
}
for &i in list {
let i = usize::from(i);
if i >= n_entries || std::mem::replace(&mut seen[i], true) || *entries >= cap {
return Err(Error::InvalidQwenShape);
}
words[layout.dst + *entries] = i as i32;
words[layout.tok + *entries] = (i / k) as i32;
*entries += 1;
}
Ok(())
};
for (g, (ptr, list)) in vram.iter().enumerate() {
if *ptr == 0 {
return Err(Error::InvalidQwenShape);
}
put_u64(&mut words, layout.ptr + 2 * g, *ptr);
words[layout.start + g] = entries as i32;
add_entries(&mut words, list, &mut entries)?;
}
words[layout.start + vram.len()] = entries as i32;
for (q, (ptr, list)) in pcie.iter().enumerate() {
if *ptr == 0 {
return Err(Error::InvalidQwenShape);
}
put_u64(&mut words, layout.ptr2 + 2 * q, *ptr);
words[layout.start2 + q] = entries as i32;
add_entries(&mut words, list, &mut entries)?;
}
words[layout.start2 + pcie.len()] = entries as i32;
words[layout.counts] = vram.len() as i32;
words[layout.counts + 1] = entries as i32;
words[layout.counts + 2] = pcie.len() as i32;
Ok(words.iter().flat_map(|w| w.to_le_bytes()).collect())
}
fn span_layer(span: &ResidentExpertBankSpan) -> Option<usize> {
match span.role() {
TensorRole::Layer { layer, .. } => Some(usize::from(layer)),
_ => None,
}
}
impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> {
/// The routed ids of this group's rows (`rows * k`), as the doorbell published them.
fn group_ids(&self) -> Result<Vec<i32>> {
let g = self.bank.geometry();
let mapped = self.bank.physical.mapped[7].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
let mapped = mapped.as_ref().ok_or(Error::ContextPoisoned)?;
let mut ids = Vec::new();
ids.try_reserve_exact(self.rows * g.k).map_err(|_| Error::HostAllocation)?;
for i in 0..self.rows * g.k {
ids.push(mapped.read_u32((self.first * g.k + i) * 4)? as i32);
}
Ok(ids)
}
/// Publish this group's GPU plan and raise flag A; stage its PCIe share by DMA on `copy` and raise flag B
/// after it (or at once). Call at most once per group, before the CPU's own share is written; the run loop
/// then skips its empty plan. A refusal publishes nothing (the run loop's empty plan follows, and the pool
/// must then fail the group).
pub fn publish_gpu_plan(
&mut self,
plan: &OriginalVerifyGpuPlan,
cache: &OriginalExpertCache<'ctx>,
pcie: Option<OriginalVerifyPcieSource<'_, 'ctx>>,
copy: &mut OriginalGpuStream<'ctx>,
) -> Result<()> {
let context = self.bank.physical.context;
self.bank.validate_context(context)?;
cache.validate_file_source_context(context)?;
copy.validate_context(context)?;
let g = self.bank.geometry();
let layout = PlanLayout::new(g.max_t * g.k);
let cap = g.max_t * g.k;
let a = self.bank.physical.mapped[11].try_borrow().map_err(|_| Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)?;
if a >= self.ring {
return Err(Error::InvalidQwenShape);
}
let ids = self.group_ids()?;
// VRAM groups: a completed slot owned by the routed expert of every entry, in this layer.
let mut vram = Vec::new();
vram.try_reserve_exact(plan.vram.len()).map_err(|_| Error::HostAllocation)?;
for (slot, entries) in &plan.vram {
let (layer, expert) = cache.slot_owner(*slot).ok_or(Error::InvalidQwenShape)?;
if layer != self.layer || entries.iter().any(|&i| ids.get(usize::from(i)).copied() != Some(expert as i32)) {
return Err(Error::InvalidQwenShape);
}
let (handle, _) = cache.completed_slot(*slot)?;
vram.push((handle.qwen_address(), entries.as_slice()));
}
// PCIe groups: staging slot q of this group's half, each the bank spans of that entry's expert.
let per = staging_blobs_per_group(self.groups);
let mut stride = 0usize;
let spans = match &pcie {
Some(source) => source.spans,
None => &[],
};
if spans.len() != plan.pcie.len() || plan.pcie.len() > per.min(MAX_PCIE_FETCHES) {
return Err(Error::InvalidQwenShape);
}
for (q, entries) in plan.pcie.iter().enumerate() {
let s = &spans[q];
let source = pcie.as_ref().ok_or(Error::InvalidQwenShape)?;
if !source.bank.cache_context_matches(context)
|| !source.bank.eligible(s)
|| span_layer(&s[0]) != Some(self.layer)
|| entries.iter().any(|&i| ids.get(usize::from(i)).copied() != Some(s[0].expert() as i32))
{
return Err(Error::InvalidQwenShape);
}
let bytes = s.iter().try_fold(0usize, |n, x| n.checked_add(x.bytes().len()).ok_or(Error::InvalidSize))?;
if bytes == 0 || bytes > g.max_expert_blob || (stride != 0 && bytes != stride) {
return Err(Error::InvalidQwenShape);
}
stride = bytes;
}
let staging = if plan.pcie.is_empty() {
0
} else {
self.bank.physical.span("staging", self.group * per * g.max_expert_blob, per * g.max_expert_blob)?
};
let pcie_ptrs: Vec<(u64, &[u16])> =
plan.pcie.iter().enumerate().map(|(q, e)| (staging + (q * stride) as u64, e.as_slice())).collect();
let block = encode_plan_block(&layout, cap, g.k, self.rows * g.k, &vram, &pcie_ptrs)?;
{
let m = &self.bank.physical.mapped;
let mut slot = m[14].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
slot.as_mut().ok_or(Error::ContextPoisoned)?.write(self.group * layout.mapped_stride() * 4, &block)?;
m[11].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0, self.ring)?;
}
let flag_b = self.bank.physical.mapped[12].try_borrow().map_err(|_| Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.host_address(0, 4)?;
match pcie {
None => self.bank.physical.mapped[12]
.try_borrow_mut()
.map_err(|_| Error::InvalidQwenShape)?
.as_mut()
.ok_or(Error::ContextPoisoned)?
.raise_u32(0, self.ring),
Some(source) => {
if !plan.pcie.is_empty() {
// The bank's registered bytes are read by the copy engine after this call returns: the bank
// stays retained by the verifier until the window's copy-stream fence.
self.bank.retain_pcie_source(Rc::clone(source.bank))?;
}
for (q, s) in spans.iter().enumerate() {
let mut offset = staging + (q * stride) as u64;
for part in s {
let bytes = source.bank.cache_source(part)?;
copy.enqueue_copy_h2d(offset, bytes)?;
offset += bytes.len() as u64;
}
}
copy.enqueue_raise_u32(flag_b, self.ring)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn words(bytes: &[u8]) -> Vec<i32> {
bytes.chunks_exact(4).map(|c| i32::from_le_bytes(c.try_into().unwrap())).collect()
}
#[test]
fn the_block_is_the_literal_gpu_plan_sink_carve() {
// a 3-row group of a max_t = 4 window: cap = 40, 30 entries
let layout = PlanLayout::new(40);
let vram: Vec<(u64, &[u16])> = vec![(0x1000, &[0, 13]), (0x2000, &[5])];
let pcie: Vec<(u64, &[u16])> = vec![(0x9000, &[2, 21, 27]), (0x9800, &[29])];
let w = words(&encode_plan_block(&layout, 40, 10, 30, &vram, &pcie).unwrap());
assert_eq!(w.len(), layout.words);
assert_eq!(&w[..4], &[2, 7, 2, 0], "vram groups, gpu entries, pcie groups");
assert_eq!(&w[layout.start..layout.start + 3], &[0, 2, 3]);
assert_eq!(&w[layout.dst..layout.dst + 7], &[0, 13, 5, 2, 21, 27, 29]);
assert_eq!(&w[layout.tok..layout.tok + 7], &[0, 1, 0, 0, 2, 2, 2]);
let u64_at = |at: usize| (w[at] as u32 as u64) | ((w[at + 1] as u32 as u64) << 32);
assert_eq!((u64_at(layout.ptr), u64_at(layout.ptr + 2)), (0x1000, 0x2000));
assert_eq!((u64_at(layout.ptr2), u64_at(layout.ptr2 + 2)), (0x9000, 0x9800));
assert_eq!(&w[layout.start2..layout.start2 + 3], &[3, 6, 7]);
}
#[test]
fn an_empty_plan_is_the_run_loops_empty_plan() {
let layout = PlanLayout::new(80);
let w = words(&encode_plan_block(&layout, 80, 10, 80, &[], &[]).unwrap());
assert!(w.iter().all(|&x| x == 0));
}
#[test]
fn a_corrupt_plan_is_refused_not_repaired() {
let layout = PlanLayout::new(40);
let one = |e: &'static [u16]| vec![(0x1000u64, e)];
// entry outside the group's rows, repeated within and across groups, empty group, null pointer
assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[20]), &[]).is_err());
assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[3, 3]), &[]).is_err());
assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[3]), &one(&[3])).is_err());
assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[]), &[]).is_err());
assert!(encode_plan_block(&layout, 40, 10, 20, &[(0, &[1])], &[]).is_err());
// more entries than the block holds
assert!(encode_plan_block(&layout, 40, 10, 50, &[], &[]).is_err());
}
}
@@ -11,7 +11,9 @@ use std::io::Write;
pub struct OriginalVerifyCpuRows<'a>{pub layer:usize,pub group:usize,pub first_row:usize,pub activation:&'a [f32],pub ids:&'a [i32],pub route_weights:&'a [f32]}
/// Borrowed real mapped destination; CPU writes it directly before M publication.
/// This cannot escape the actual group callback or publish flags independently.
pub struct OriginalVerifyCpuSink<'a,'ctx>{bank:&'a mut OriginalVerifyBank<'ctx>,first:usize,rows:usize}
/// `layer`, `group`, `groups` and `ring` name the doorbell this callback serves; the GPU plan of the group
/// (`publish_gpu_plan`, original_verify_gpu_plan.rs) is published through the same sink.
pub struct OriginalVerifyCpuSink<'a,'ctx>{pub(super) bank:&'a mut OriginalVerifyBank<'ctx>,pub(super) first:usize,pub(super) rows:usize,pub(super) layer:usize,pub(super) group:usize,pub(super) groups:usize,pub(super) ring:u32}
impl OriginalVerifyCpuSink<'_, '_>{pub fn with_output<R>(&mut self,produce:impl FnOnce(&mut [f32])->Result<R>)->Result<R>{let g=self.bank.geometry();let mut m=self.bank.physical.mapped[13].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;m.as_mut().ok_or(Error::ContextPoisoned)?.with_cpu_output(self.first*g.k*g.n*4,self.rows*g.k*g.n,produce)}}
pub struct OriginalVerifyWindowResult{pub selection:NativeHeadSelection,pub generation:u64,pub first_position:usize,pub rows:usize}
pub struct OriginalVerifier<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>>{
@@ -76,7 +78,7 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<
let x=physical.mapped[6].try_borrow().map_err(|_|Error::InvalidQwenShape)?;
let ids=physical.mapped[7].try_borrow().map_err(|_|Error::InvalidQwenShape)?;
let w=physical.mapped[8].try_borrow().map_err(|_|Error::InvalidQwenShape)?;
MappedAllocation::with_cpu_rows(x.as_ref().ok_or(Error::ContextPoisoned)?,ids.as_ref().ok_or(Error::ContextPoisoned)?,w.as_ref().ok_or(Error::ContextPoisoned)?,begin,rows,g.n,g.k,|activation,ids,route_weights|pool(OriginalVerifyCpuRows{layer,group,first_row:begin,activation,ids,route_weights},&mut OriginalVerifyCpuSink{bank:self.bank.as_mut().ok_or(Error::ContextPoisoned)?,first:begin,rows},self.copy.as_mut().ok_or(Error::ContextPoisoned)?))?;
MappedAllocation::with_cpu_rows(x.as_ref().ok_or(Error::ContextPoisoned)?,ids.as_ref().ok_or(Error::ContextPoisoned)?,w.as_ref().ok_or(Error::ContextPoisoned)?,begin,rows,g.n,g.k,|activation,ids,route_weights|pool(OriginalVerifyCpuRows{layer,group,first_row:begin,activation,ids,route_weights},&mut OriginalVerifyCpuSink{bank:self.bank.as_mut().ok_or(Error::ContextPoisoned)?,first:begin,rows,layer,group,groups,ring:want},self.copy.as_mut().ok_or(Error::ContextPoisoned)?))?;
drop((x,ids,w));
// A pool with no GPU plan publishes the literal empty plan; actual DMA
// producers publish A and raise B only from completed host callbacks.
@@ -89,6 +91,8 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<
// then request sampling with Philox counter tied to actual position.
let receipt=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?;
self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
// Every PCIe copy of the window has landed: the registered sources it read may go.
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.release_pcie_sources();
// The window's GPU stage stamps (single-group windows only, as in Original).
if groups==1&&self.bank()?.profile_enabled(){let stamps=self.bank()?.read_profile()?;self.profile.add_window(&stamps,48,|l|l%4==3);}
self.window[t-1].as_mut().ok_or(Error::ContextPoisoned)?.verifier_head_after_drain(self.compute.as_mut().ok_or(Error::ContextPoisoned)?,&receipt,sampling)