STRA-338 size: cuda-driver original_verify_schedule: run split into check/stage/ring/doorbell/pool/publish/finish/settle phases (fn_lines 207 -> 19)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 14:05:35 +01:00
parent df2464a9db
commit 526eb70386
3 changed files with 347 additions and 190 deletions
@@ -72,3 +72,5 @@ mod impl_originalverifier_2;
mod impl_originalverifier_3;
#[path = "original_verify_schedule/impl_originalverifier_4.rs"]
mod impl_originalverifier_4;
#[path = "original_verify_schedule/window_phases.rs"]
mod window_phases;
@@ -19,200 +19,15 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
&mut OriginalGpuStream<'ctx>,
) -> Result<()>,
) -> Result<OriginalVerifyWindowResult> {
// #267: a released verifier (a window the GPU never finished) refuses every later window.
if self.released || self.registration.as_ref().is_some_and(diag::Registration::is_released) {
return Err(Error::InvalidDriverValue(
"Verifier released: an earlier window never finished on the GPU (#267)",
));
}
if self.failed || self.active || self.window_ready || self.commit.is_none() {
return Err(Error::InvalidQwenShape);
}
if sampling.position != position as u64 {
return Err(Error::InvalidQwenShape);
}
self.check_run_inputs(tokens, position, ple, sampling.position)?;
let t = tokens.len();
if !(1..=self.bank()?.geometry().max_t).contains(&t) || self.window[t - 1].is_none() {
return Err(Error::InvalidQwenShape);
}
let wants_ple = self.window[t - 1].as_ref().ok_or(Error::InvalidQwenShape)?.verifier_uses_ple()?;
if wants_ple != ple.is_some() {
return Err(Error::InvalidQwenShape);
}
// The preceding asynchronous commit has the same compute stream. Its actual
// mapped records are overwritten only after that completed receipt/window.
let span_wait = crate::host_profile::span("drv.run_wait_commit");
self.wait_commit()?;
drop(span_wait);
let span_stage = crate::host_profile::span("drv.stage");
let generation = self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage(tokens, position)?;
if let Some(ple) = ple {
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_ple(ple)?
}
drop(span_stage);
let span_begin = crate::host_profile::span("drv.begin_window");
self.window[t - 1].as_ref().ok_or(Error::ContextPoisoned)?.verifier_begin_window(self.bank()?)?;
drop(span_begin);
self.active = true;
if let Some(r) = &self.registration {
r.begin_window(t, position as u64)
}
let operation = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<NativeHeadSelection> {
let span_launch = crate::host_profile::span("drv.launch");
self.window[t - 1]
.as_mut()
.ok_or(Error::ContextPoisoned)?
.enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;
let _ = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?;
drop(span_launch);
let groups = self.groups[t - 1];
for k in 0..window_plan::window_rings(groups) {
let layer = k / groups;
let group = k % groups;
let want = window_plan::ring(layer, groups, group);
let start = Instant::now();
let mut last_flush = start;
let mut spins = 0u32;
if let Some(r) = &self.registration {
r.layer_step(want)
}
let span_bell = crate::host_profile::span("drv.doorbell_wait");
loop {
if self.bank()?.doorbell_sequence()? >= want {
break;
}
std::hint::spin_loop();
spins = spins.wrapping_add(1);
if spins & 1023 != 0 {
continue;
}
let now = Instant::now();
if self.registration.as_ref().is_some_and(diag::Registration::is_released) {
return Err(Error::InvalidDriverValue(
"Verifier window released while waiting for a layer (#267)",
));
}
if now.duration_since(last_flush) > Duration::from_micros(2000) {
last_flush = now;
let q = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?;
if q && self.bank()?.doorbell_sequence()? < want {
return Err(Error::InvalidDriverValue("Verifier layer never rang"));
}
}
if now.duration_since(start) > Duration::from_secs(20) {
return Err(Error::InvalidDriverValue("Verifier layer doorbell timeout"));
}
}
drop(span_bell);
let (begin, end) = window_plan::group_rows(t, groups, group);
let rows = end - begin;
let g = self.bank()?.geometry();
let physical = self.bank()?.physical.clone();
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,
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.
let span_flag = crate::host_profile::span("drv.group_publish");
let flag = self.bank()?.physical.mapped[11]
.try_borrow()
.map_err(|_| Error::InvalidQwenShape)?
.as_ref()
.ok_or(Error::ContextPoisoned)?
.read_u32(0)?;
if flag != want {
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(group, want)?
}
let stalled = self.test_stall > 0
&& self.windows + 1 == self.test_stall
&& k + 1 == window_plan::window_rings(groups);
if !stalled {
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.physical.mapped[10]
.try_borrow_mut()
.map_err(|_| Error::InvalidQwenShape)?
.as_mut()
.ok_or(Error::ContextPoisoned)?
.publish_u32(0, want)?;
}
drop(span_flag);
}
// Original order: compute fence, then copy-stream fence (no late flag B),
// then request sampling with Philox counter tied to actual position.
let span_sync = crate::host_profile::span("drv.sync_compute");
let receipt = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?;
drop(span_sync);
let span_copy = crate::host_profile::span("drv.sync_copy");
self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
drop(span_copy);
// 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);
}
let _span_head = crate::host_profile::span("drv.head");
self.window[t - 1].as_mut().ok_or(Error::ContextPoisoned)?.verifier_head_after_drain(
self.compute.as_mut().ok_or(Error::ContextPoisoned)?,
&receipt,
sampling,
)
}));
let generation = self.stage_window(tokens, position, ple)?;
let operation =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.run_window(t, sampling, &mut pool)));
if let Some(r) = &self.registration {
r.end_window()
}
match operation {
Ok(Ok(selection)) => {
if selection.ids().len() != t
|| selection.position() != position as u64
|| selection.vocabulary() != self.bank()?.geometry().vocabulary
{
self.failed = true;
return combine(Err(Error::InvalidQwenShape), self.abort_gpu_waits());
}
self.completed_ids[..t].copy_from_slice(selection.ids());
self.active = false;
self.window_ready = true;
self.completed_generation = Some(generation);
self.windows = self.windows.checked_add(1).ok_or(Error::InvalidSize)?;
Ok(OriginalVerifyWindowResult { selection, generation, first_position: position, rows: t })
}
Ok(Err(primary)) => {
self.failed = true;
let cleanup = self.abort_gpu_waits();
combine(Err(primary), cleanup)
}
Err(panic) => {
self.failed = true;
let _ = self.abort_gpu_waits();
std::panic::resume_unwind(panic)
}
}
self.settle_window(operation, (t, position, generation))
}
/// n_keep is meaningful only after the actual preceding window completes.
/// Root prepares all genuine accepted-prefix publication permits AFTER this
@@ -0,0 +1,340 @@
//! STRA-338 size: the phases of `OriginalVerifier::run`, extracted in call order.
#[allow(unused_imports)]
use super::*;
impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx, R> {
/// Refuses a released or busy verifier, a mismatched position or row count and a PLE mismatch.
pub(super) fn check_run_inputs(
&self,
tokens: &[i32],
position: usize,
ple: Option<&[f32]>,
sampling_position: u64,
) -> Result<()> {
// #267: a released verifier (a window the GPU never finished) refuses every later window.
if self.released || self.registration.as_ref().is_some_and(diag::Registration::is_released) {
return Err(Error::InvalidDriverValue(
"Verifier released: an earlier window never finished on the GPU (#267)",
));
}
if self.failed || self.active || self.window_ready || self.commit.is_none() {
return Err(Error::InvalidQwenShape);
}
self.check_window_shape(tokens, position, ple, sampling_position)
}
fn check_window_shape(
&self,
tokens: &[i32],
position: usize,
ple: Option<&[f32]>,
sampling_position: u64,
) -> Result<()> {
if sampling_position != position as u64 {
return Err(Error::InvalidQwenShape);
}
let t = tokens.len();
if !(1..=self.bank()?.geometry().max_t).contains(&t) || self.window[t - 1].is_none() {
return Err(Error::InvalidQwenShape);
}
let wants_ple = self.window[t - 1].as_ref().ok_or(Error::InvalidQwenShape)?.verifier_uses_ple()?;
if wants_ple != ple.is_some() {
return Err(Error::InvalidQwenShape);
}
Ok(())
}
/// Waits for the previous commit, stages tokens and PLE and begins the window; returns its generation.
pub(super) fn stage_window(&mut self, tokens: &[i32], position: usize, ple: Option<&[f32]>) -> Result<u64> {
let t = tokens.len();
// The preceding asynchronous commit has the same compute stream. Its actual
// mapped records are overwritten only after that completed receipt/window.
let span_wait = crate::host_profile::span("drv.run_wait_commit");
self.wait_commit()?;
drop(span_wait);
let span_stage = crate::host_profile::span("drv.stage");
let generation = self.stage_bank(tokens, position, ple)?;
drop(span_stage);
let span_begin = crate::host_profile::span("drv.begin_window");
self.window[t - 1].as_ref().ok_or(Error::ContextPoisoned)?.verifier_begin_window(self.bank()?)?;
drop(span_begin);
self.active = true;
if let Some(r) = &self.registration {
r.begin_window(t, position as u64)
}
Ok(generation)
}
fn stage_bank(&mut self, tokens: &[i32], position: usize, ple: Option<&[f32]>) -> Result<u64> {
let generation = self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage(tokens, position)?;
if let Some(ple) = ple {
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_ple(ple)?
}
Ok(generation)
}
/// Launches the window graph, serves every ring through `pool`, then drains both streams and samples.
pub(super) fn run_window<P>(
&mut self,
t: usize,
sampling: NativeHeadSampling<'_, 'ctx>,
pool: &mut P,
) -> Result<NativeHeadSelection>
where
P: FnMut(
OriginalVerifyCpuRows<'_>,
&mut OriginalVerifyCpuSink<'_, 'ctx>,
&mut OriginalGpuStream<'ctx>,
) -> Result<()>,
{
let span_launch = crate::host_profile::span("drv.launch");
self.window[t - 1]
.as_mut()
.ok_or(Error::ContextPoisoned)?
.enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;
let _ = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?;
drop(span_launch);
let groups = self.groups[t - 1];
for k in 0..window_plan::window_rings(groups) {
self.run_ring(t, groups, k, pool)?;
}
self.finish_window(t, groups, sampling)
}
fn run_ring<P>(&mut self, t: usize, groups: usize, k: usize, pool: &mut P) -> Result<()>
where
P: FnMut(
OriginalVerifyCpuRows<'_>,
&mut OriginalVerifyCpuSink<'_, 'ctx>,
&mut OriginalGpuStream<'ctx>,
) -> Result<()>,
{
let layer = k / groups;
let group = k % groups;
let want = window_plan::ring(layer, groups, group);
let start = Instant::now();
if let Some(r) = &self.registration {
r.layer_step(want)
}
let span_bell = crate::host_profile::span("drv.doorbell_wait");
self.wait_doorbell(want, start)?;
drop(span_bell);
self.pool_group(t, groups, (layer, group), want, pool)?;
self.publish_group(k, groups, group, want)
}
/// Spins on the mapped doorbell until ring `want` rings; checks release, a finished-but-silent stream and 20 s.
fn wait_doorbell(&self, want: u32, start: Instant) -> Result<()> {
let mut last_flush = start;
let mut spins = 0u32;
loop {
if self.bank()?.doorbell_sequence()? >= want {
break;
}
std::hint::spin_loop();
spins = spins.wrapping_add(1);
if spins & 1023 != 0 {
continue;
}
last_flush = self.doorbell_poll(want, (start, last_flush))?;
}
Ok(())
}
/// One slow-path check of the doorbell wait; returns the time of the last stream query.
fn doorbell_poll(&self, want: u32, (start, mut last_flush): (Instant, Instant)) -> Result<Instant> {
let now = Instant::now();
if self.registration.as_ref().is_some_and(diag::Registration::is_released) {
return Err(Error::InvalidDriverValue("Verifier window released while waiting for a layer (#267)"));
}
if now.duration_since(last_flush) > Duration::from_micros(2000) {
last_flush = now;
let q = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?;
if q && self.bank()?.doorbell_sequence()? < want {
return Err(Error::InvalidDriverValue("Verifier layer never rang"));
}
}
if now.duration_since(start) > Duration::from_secs(20) {
return Err(Error::InvalidDriverValue("Verifier layer doorbell timeout"));
}
Ok(last_flush)
}
/// Hands the group's mapped CPU rows to the caller's pool together with the plan sink.
fn pool_group<P>(
&mut self,
t: usize,
groups: usize,
(layer, group): (usize, usize),
want: u32,
pool: &mut P,
) -> Result<()>
where
P: FnMut(
OriginalVerifyCpuRows<'_>,
&mut OriginalVerifyCpuSink<'_, 'ctx>,
&mut OriginalGpuStream<'ctx>,
) -> Result<()>,
{
let (begin, end) = window_plan::group_rows(t, groups, group);
let rows = end - begin;
let g = self.bank()?.geometry();
let physical = self.bank()?.physical.clone();
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| {
let cpu = OriginalVerifyCpuRows { layer, group, first_row: begin, activation, ids, route_weights };
self.invoke_pool(pool, cpu, (begin, rows, groups, want))
},
)?;
drop((x, ids, w));
Ok(())
}
fn invoke_pool<P>(
&mut self,
pool: &mut P,
cpu: OriginalVerifyCpuRows<'_>,
(first, rows, groups, ring): (usize, usize, usize, u32),
) -> Result<()>
where
P: FnMut(
OriginalVerifyCpuRows<'_>,
&mut OriginalVerifyCpuSink<'_, 'ctx>,
&mut OriginalGpuStream<'ctx>,
) -> Result<()>,
{
let (layer, group) = (cpu.layer, cpu.group);
pool(
cpu,
&mut OriginalVerifyCpuSink {
bank: self.bank.as_mut().ok_or(Error::ContextPoisoned)?,
first,
rows,
layer,
group,
groups,
ring,
},
self.copy.as_mut().ok_or(Error::ContextPoisoned)?,
)
}
/// A pool with no GPU plan publishes the literal empty plan; actual DMA
/// producers publish A and raise B only from completed host callbacks.
fn publish_group(&mut self, k: usize, groups: usize, group: usize, want: u32) -> Result<()> {
let span_flag = crate::host_profile::span("drv.group_publish");
let flag = self.bank()?.physical.mapped[11]
.try_borrow()
.map_err(|_| Error::InvalidQwenShape)?
.as_ref()
.ok_or(Error::ContextPoisoned)?
.read_u32(0)?;
if flag != want {
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(group, want)?
}
self.raise_group_flag(k, groups, want)?;
drop(span_flag);
Ok(())
}
/// Raises flag B for the ring unless the test stall hook holds back the last ring of its window.
fn raise_group_flag(&mut self, k: usize, groups: usize, want: u32) -> Result<()> {
let stalled =
self.test_stall > 0 && self.windows + 1 == self.test_stall && k + 1 == window_plan::window_rings(groups);
if !stalled {
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.physical.mapped[10]
.try_borrow_mut()
.map_err(|_| Error::InvalidQwenShape)?
.as_mut()
.ok_or(Error::ContextPoisoned)?
.publish_u32(0, want)?;
}
Ok(())
}
/// Original order: compute fence, then copy-stream fence (no late flag B),
/// then request sampling with Philox counter tied to actual position.
fn finish_window(
&mut self,
t: usize,
groups: usize,
sampling: NativeHeadSampling<'_, 'ctx>,
) -> Result<NativeHeadSelection> {
let span_sync = crate::host_profile::span("drv.sync_compute");
let receipt = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?;
drop(span_sync);
let span_copy = crate::host_profile::span("drv.sync_copy");
self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
drop(span_copy);
// 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();
self.record_window_profile(groups)?;
let _span_head = crate::host_profile::span("drv.head");
self.window[t - 1].as_mut().ok_or(Error::ContextPoisoned)?.verifier_head_after_drain(
self.compute.as_mut().ok_or(Error::ContextPoisoned)?,
&receipt,
sampling,
)
}
/// The window's GPU stage stamps (single-group windows only, as in Original).
fn record_window_profile(&mut self, groups: usize) -> Result<()> {
if groups == 1 && self.bank()?.profile_enabled() {
let stamps = self.bank()?.read_profile()?;
self.profile.add_window(&stamps, 48, |l| l % 4 == 3);
}
Ok(())
}
fn complete_window(
&mut self,
selection: NativeHeadSelection,
(t, position, generation): (usize, usize, u64),
) -> Result<OriginalVerifyWindowResult> {
if selection.ids().len() != t
|| selection.position() != position as u64
|| selection.vocabulary() != self.bank()?.geometry().vocabulary
{
self.failed = true;
return combine(Err(Error::InvalidQwenShape), self.abort_gpu_waits());
}
self.completed_ids[..t].copy_from_slice(selection.ids());
self.active = false;
self.window_ready = true;
self.completed_generation = Some(generation);
self.windows = self.windows.checked_add(1).ok_or(Error::InvalidSize)?;
Ok(OriginalVerifyWindowResult { selection, generation, first_position: position, rows: t })
}
/// Records the outcome of a window: validates and completes it, or fails the verifier and releases the waits.
pub(super) fn settle_window(
&mut self,
operation: std::thread::Result<Result<NativeHeadSelection>>,
(t, position, generation): (usize, usize, u64),
) -> Result<OriginalVerifyWindowResult> {
match operation {
Ok(Ok(selection)) => self.complete_window(selection, (t, position, generation)),
Ok(Err(primary)) => {
self.failed = true;
let cleanup = self.abort_gpu_waits();
combine(Err(primary), cleanup)
}
Err(panic) => {
self.failed = true;
let _ = self.abort_gpu_waits();
std::panic::resume_unwind(panic)
}
}
}
}