decode: a verifier graph that runs out of device memory costs the widest windows, not the engine
cuGraphInstantiateWithFlags answering out of memory used to poison the whole CUDA context (every call after it failed, so the engine was lost; upstream a8c1d4b7 / 2a9a67c1). The refusal is not sticky and changes no state, so now:
- the instantiate step does not poison the context on that one code (every other failure still does), the half-built graph is destroyed, and a line is logged;
- a failed cuGraphUpload (a warm-up) is skipped with a line;
- OriginalVerifier::record_all names the graph that did not fit (Error::GraphOutOfMemory { window }, 0 = commit graph);
- the serve stack repeats the assembly with the windows that fit (assemble_with_window_fallback; owners come back from each failure), logs each step, and narrows the settings, controllers and MTP draft cap of every arm to the window it ended with, for the later requests too. No cap below T=2: a failure with nothing left is returned as before, but with the context intact.
Test hook for a card with room: LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT=N fails the N-th window instantiation once.
CPU tests: poison decision, error classification, cap computation, retry loop (terminates, stops at the floor, no retry on other errors), settings cap. Not verified on a GPU.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
58305a193d
commit
b5d5b24faa
+3507
-3495
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,368 +1,476 @@
|
||||
//! Assembly and teardown of the native Original verifier for one decode phase.
|
||||
//!
|
||||
//! The verifier owns, for the whole phase, a canonical GDN image seeded from the session's published
|
||||
//! recurrent priors, the PLE history seeded from the session's PLE prior, and the twelve resident QSA
|
||||
//! index images and mapped K/V journals handed over from the prompt executor. It records the T = 1..=max_t
|
||||
//! window graphs and the accepted-prefix commit graph over those owners (`record_all`) and is then ready to
|
||||
//! `run`. Teardown closes the graphs, which releases every aggregate's reference to the QSA journal, and
|
||||
//! returns the physical QSA owners so the executor can take them back at the session's lineage.
|
||||
//!
|
||||
//! Any producer the driver cannot capture yet fails `record_all` with its name
|
||||
//! (`UNBOUND_PRODUCERS`); that refusal surfaces here untouched, never as a substituted arithmetic.
|
||||
use super::{
|
||||
contract::{Error, Result, Stage},
|
||||
dense_weight_cache::DenseWeightCache,
|
||||
gdn::GdnPrior,
|
||||
moe_weight_cache::{MoeWeightCache, SharedKeys},
|
||||
original_serve_config::{ExpertBlobSizes, RopeConstants, verify_geometry},
|
||||
output_native::OriginalNativeOutput,
|
||||
session::original_verified::OriginalVerifiedBase,
|
||||
};
|
||||
use crate::model_binding::qwen4exp_input::{BoundLayerKind, ModelBinding};
|
||||
use leleka_cuda_driver::{
|
||||
Context, DeviceBuffer, OriginalQsaMappedJournal, OriginalQsaResidentIndex, OriginalVerifier, OriginalVerifyExpertFormats,
|
||||
OriginalVerifyQsaJournal, OriginalVerifyResources, OriginalVerifyWindowPolicy, OriginalVerifyWindowResources,
|
||||
};
|
||||
use std::rc::Rc;
|
||||
|
||||
const PLE_HISTORY_VALUES: usize = 9 * 10240;
|
||||
pub(in crate::qwen_forward) const PLE_HISTORY_BYTES: usize = PLE_HISTORY_VALUES * 4;
|
||||
|
||||
/// Default of `LELEKA_QSA_CLUSTER` (the cluster top-k of the decode window; flipped after its gates, docs/upstream-port-plan.md row 2.5).
|
||||
const QSA_CLUSTER_DEFAULT: bool = true;
|
||||
|
||||
/// A refusal with the driver's own words when it has them (an unbound producer, an unsealed asset).
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct ServeFailure {
|
||||
pub(crate) error: Error,
|
||||
pub(crate) detail: Option<String>,
|
||||
}
|
||||
impl From<Error> for ServeFailure {
|
||||
fn from(error: Error) -> Self {
|
||||
Self { error, detail: None }
|
||||
}
|
||||
}
|
||||
impl From<leleka_cuda_driver::Error> for ServeFailure {
|
||||
fn from(driver: leleka_cuda_driver::Error) -> Self {
|
||||
let error = driver_error(&driver);
|
||||
let detail = match &driver {
|
||||
leleka_cuda_driver::Error::InvalidDriverValue(message) => Some((*message).to_owned()),
|
||||
leleka_cuda_driver::Error::UnsupportedQwenOperation => {
|
||||
Some("a compiled asset is unsealed or the operation is not supported by this build".to_owned())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
Self { error, detail }
|
||||
}
|
||||
}
|
||||
impl ServeFailure {
|
||||
/// `class=... detail=...` for the operator diagnostic line (the detail text is a fixed driver string).
|
||||
pub(crate) fn describe(&self) -> String {
|
||||
match &self.detail {
|
||||
Some(detail) => format!("{:?}: {detail}", self.error),
|
||||
None => format!("{:?}", self.error),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The runtime error class of a driver error (the same mapping every Original owner uses).
|
||||
pub(in crate::qwen_forward) fn driver_error(error: &leleka_cuda_driver::Error) -> Error {
|
||||
use leleka_cuda_driver::Error as D;
|
||||
match error {
|
||||
D::NonFiniteMmqOutput(_) => Error::NonFinite,
|
||||
D::BudgetExceeded | D::HostAllocation => Error::InputAllocation,
|
||||
D::ContextMismatch | D::UnexpectedContext => Error::IdentityMismatch,
|
||||
D::InvalidQwenShape | D::InvalidSize | D::InvalidProjectionShape => Error::InvalidDimension,
|
||||
D::UnsupportedQwenOperation => Error::Unsupported(Stage::Session),
|
||||
D::InvalidDriverValue(_) => Error::Unsupported(Stage::Executor),
|
||||
_ => Error::CudaExecution,
|
||||
}
|
||||
}
|
||||
|
||||
type QsaOwners<'ctx> = [Option<(OriginalQsaResidentIndex<'ctx>, OriginalQsaMappedJournal<'ctx>)>; 48];
|
||||
|
||||
/// The verifier plus the one extra reference to the QSA journal that lets the owners be recovered.
|
||||
pub(in crate::qwen_forward) struct DecodeResources<'a, 'ctx> {
|
||||
pub(in crate::qwen_forward) verifier: OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>>,
|
||||
pub(in crate::qwen_forward) qsa: Rc<OriginalVerifyQsaJournal<'a, 'ctx>>,
|
||||
/// Model layer index of journal layer `i` (the owners were handed over in ascending slot order).
|
||||
pub(in crate::qwen_forward) slots: [usize; 12],
|
||||
}
|
||||
|
||||
/// Why an assembly failed and whether the physical QSA owners survived it.
|
||||
pub(in crate::qwen_forward) struct AssembleFailure<'ctx> {
|
||||
pub(in crate::qwen_forward) failure: ServeFailure,
|
||||
/// The owners, when they could be recovered; `None` means the stack must be rebuilt.
|
||||
pub(in crate::qwen_forward) owners: Option<QsaOwners<'ctx>>,
|
||||
}
|
||||
impl<'ctx> AssembleFailure<'ctx> {
|
||||
fn lost(failure: impl Into<ServeFailure>) -> Self {
|
||||
Self { failure: failure.into(), owners: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// The GDN priors of the thirty-six recurrent layers in layer order, as the canonical image takes them.
|
||||
fn gdn_layer_priors<'p>(binding: &ModelBinding, base: &'p OriginalVerifiedBase<'_>) -> Result<Vec<&'p GdnPrior>> {
|
||||
let mut priors = Vec::new();
|
||||
priors.try_reserve_exact(36).map_err(|_| Error::InputAllocation)?;
|
||||
for layer in binding.ordered_layers() {
|
||||
if layer.kind() == BoundLayerKind::Gdn {
|
||||
priors.push(base.gdn[layer.index() as usize].as_ref().ok_or(Error::IdentityMismatch)?);
|
||||
}
|
||||
}
|
||||
if priors.len() != 36 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(priors)
|
||||
}
|
||||
|
||||
/// Upload the session's PLE prior into the device history image the commit graph keeps current.
|
||||
pub(in crate::qwen_forward) fn seed_ple_history<'ctx>(
|
||||
base: &OriginalVerifiedBase<'_>,
|
||||
ple_history: &mut DeviceBuffer<'ctx>,
|
||||
) -> std::result::Result<(), ServeFailure> {
|
||||
let ple = base.ple.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
if ple.history().len() != PLE_HISTORY_VALUES || ple_history.len() != PLE_HISTORY_BYTES {
|
||||
return Err(Error::InvalidDimension.into());
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(PLE_HISTORY_BYTES).map_err(|_| Error::InputAllocation)?;
|
||||
for value in ple.history() {
|
||||
bytes.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
ple_history.copy_from(&bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The PLE history image as the commit graph left it (after the last committed window).
|
||||
pub(in crate::qwen_forward) fn read_ple_history(ple_history: &DeviceBuffer<'_>) -> Result<Box<[f32]>> {
|
||||
if ple_history.len() != PLE_HISTORY_BYTES {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let bytes = ple_history.copy_to_owned(PLE_HISTORY_BYTES).map_err(|e| driver_error(&e))?;
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(PLE_HISTORY_VALUES).map_err(|_| Error::InputAllocation)?;
|
||||
values.extend(bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)));
|
||||
Ok(values.into_boxed_slice())
|
||||
}
|
||||
|
||||
/// The model weights the window graphs read in place for the whole phase, all borrowed from the caches that
|
||||
/// own them: projections, hyper-connection / PLE and QSA operands from the dense cache, router and shared
|
||||
/// experts from the MoE cache, and the PLE scratch the stack owns.
|
||||
pub(in crate::qwen_forward) struct VerifyWeights<'a, 'ctx> {
|
||||
pub(in crate::qwen_forward) dense: &'a DenseWeightCache<'ctx>,
|
||||
pub(in crate::qwen_forward) moe: &'a MoeWeightCache<'ctx>,
|
||||
pub(in crate::qwen_forward) shared: &'a SharedKeys,
|
||||
pub(in crate::qwen_forward) formats: &'a OriginalVerifyExpertFormats,
|
||||
pub(in crate::qwen_forward) ple_scratch: &'a DeviceBuffer<'ctx>,
|
||||
}
|
||||
|
||||
/// Build the canonical GDN image from the GDN priors, the QSA journal over the handed-over owners, and
|
||||
/// record every window graph and the commit graph. `ple_history` must already hold the seeded image
|
||||
/// (`seed_ple_history`) and outlive the phase; the caller keeps its own shared reference to read it back.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::qwen_forward) fn assemble<'a, 'ctx>(
|
||||
binding: &ModelBinding,
|
||||
weights: &VerifyWeights<'a, 'ctx>,
|
||||
context: &'ctx Context<'ctx>,
|
||||
output: &OriginalNativeOutput<'ctx>,
|
||||
base: &OriginalVerifiedBase<'ctx>,
|
||||
mut owners: QsaOwners<'ctx>,
|
||||
ple_history: &'a DeviceBuffer<'ctx>,
|
||||
rope: &RopeConstants,
|
||||
blobs: &ExpertBlobSizes,
|
||||
max_t: usize,
|
||||
max_cells: usize,
|
||||
pcie_mode: u8,
|
||||
after_prepare: &mut dyn FnMut() -> std::result::Result<(), Error>,
|
||||
) -> std::result::Result<DecodeResources<'a, 'ctx>, AssembleFailure<'ctx>> {
|
||||
let dense = weights.dense;
|
||||
// The window graphs bind each layer's streamed-KV resolver. The prompt path initialises it lazily on its
|
||||
// first append, so a ONE-token prompt on a fresh stack reaches the capture with none: initialise it here
|
||||
// (never through `reset`, which would change the epoch and orphan every prefix the session holds).
|
||||
if let Err(failure) = ensure_resolvers(binding, dense, context, &mut owners) {
|
||||
return Err(AssembleFailure { failure, owners: Some(owners) });
|
||||
}
|
||||
// Everything that can be refused WITHOUT consuming the owners is checked first.
|
||||
let p = super::original_serve_profile::span("assemble.prepare");
|
||||
let prepare = (|| -> std::result::Result<_, ServeFailure> {
|
||||
let geometry = verify_geometry(max_t, max_cells, blobs)?;
|
||||
blobs.layout()?;
|
||||
let priors = gdn_layer_priors(binding, base)?;
|
||||
let states: [&[f32]; 36] = std::array::from_fn(|i| priors[i].values());
|
||||
let histories: [&[f32]; 36] = std::array::from_fn(|i| priors[i].history());
|
||||
let canonical = context.original_verify_canonical_gdn(states, histories)?;
|
||||
// PLE history: the seeded device image the commit graph keeps current.
|
||||
if base.ple.is_none() || ple_history.len() != PLE_HISTORY_BYTES {
|
||||
return Err(Error::InvalidDimension.into());
|
||||
}
|
||||
let gamma = dense.original_verify_qsa_gamma(binding)?;
|
||||
Ok((geometry, canonical, gamma))
|
||||
})();
|
||||
drop(p);
|
||||
let (geometry, mut canonical, gamma) = match prepare {
|
||||
Ok(parts) => parts,
|
||||
Err(failure) => return Err(AssembleFailure { failure, owners: Some(owners) }),
|
||||
};
|
||||
// The caller's work that wants the intake uploads done and the graph capture still ahead (the lent-slot refill copies).
|
||||
if let Err(error) = after_prepare() {
|
||||
drop(canonical);
|
||||
return Err(AssembleFailure { failure: error.into(), owners: Some(owners) });
|
||||
}
|
||||
// ---- from here the owners move into the journal
|
||||
let mut slots = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
let mut mapped = Vec::new();
|
||||
for (slot, owner) in owners.into_iter().enumerate() {
|
||||
if let Some((index, kv)) = owner {
|
||||
slots.push(slot);
|
||||
indices.push(index);
|
||||
mapped.push(kv);
|
||||
}
|
||||
}
|
||||
let slots: [usize; 12] = slots.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?;
|
||||
let indices: [OriginalQsaResidentIndex<'ctx>; 12] =
|
||||
indices.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?;
|
||||
let mapped: [OriginalQsaMappedJournal<'ctx>; 12] =
|
||||
mapped.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?;
|
||||
let p = super::original_serve_profile::span("assemble.qsa_journal");
|
||||
let qsa = OriginalVerifyQsaJournal::new(context, indices, mapped, gamma, rope.verify_rope())
|
||||
.map_err(AssembleFailure::lost)?;
|
||||
drop(p);
|
||||
let recorded = (|| -> std::result::Result<_, ServeFailure> {
|
||||
let p = super::original_serve_profile::span("assemble.verifier_new");
|
||||
let mut verifier = OriginalVerifier::<'ctx, OriginalVerifyWindowResources<'a, 'ctx>>::new(context, geometry)?;
|
||||
drop(p);
|
||||
let p = super::original_serve_profile::span("assemble.aggregates");
|
||||
let built = (|| -> std::result::Result<(Vec<Option<OriginalVerifyWindowResources<'a, 'ctx>>>, OriginalVerifyWindowResources<'a, 'ctx>), ServeFailure> {
|
||||
let mut windows = Vec::new();
|
||||
windows.try_reserve_exact(max_t).map_err(|_| Error::InputAllocation)?;
|
||||
let mut aggregate = |t: usize| -> std::result::Result<OriginalVerifyWindowResources<'a, 'ctx>, ServeFailure> {
|
||||
let gdn_weights = dense.original_verify_gdn_weights(binding)?;
|
||||
let journal = verifier.bank()?.gdn_journal(&mut canonical, gdn_weights, Some(ple_history))?;
|
||||
let head = output.rows(binding, t)?;
|
||||
let resources = OriginalVerifyResources::new(context, journal, Rc::clone(&qsa), head)?;
|
||||
let embed = output.embedding(binding)?.rows(t)?;
|
||||
let window = OriginalVerifyWindowResources::new(context, resources, embed, blobs.layout()?, t)?
|
||||
.with_projections(dense.original_verify_projections(binding, &geometry)?)?
|
||||
.with_gr(dense.original_verify_gr(binding, weights.ple_scratch, ple_history)?)?
|
||||
.with_qsa(dense.original_verify_qsa(binding, &geometry)?)?
|
||||
.with_moe(weights.moe.original_verify_moe(binding, dense, &geometry, weights.shared, weights.formats.clone())?)?;
|
||||
Ok(window)
|
||||
};
|
||||
for t in 1..=max_t {
|
||||
windows.push(Some(aggregate(t)?));
|
||||
}
|
||||
let commit = aggregate(max_t)?;
|
||||
Ok((windows, commit))
|
||||
})();
|
||||
drop(p);
|
||||
let (mut windows, commit) = match built {
|
||||
Ok(parts) => parts,
|
||||
Err(failure) => {
|
||||
let _ = verifier.close();
|
||||
return Err(failure);
|
||||
}
|
||||
};
|
||||
let _ = leleka_cuda_driver::original_capture_timing::take();
|
||||
let _p = super::original_serve_profile::span("assemble.record_all");
|
||||
// `Verifier::set_pcie_mode`: the copy kernel stages the PCIe share inside the graph (2), or DMA (0).
|
||||
let mut policy = OriginalVerifyWindowPolicy::mode17();
|
||||
policy.pcie_mode = pcie_mode;
|
||||
// docs/upstream-port-plan.md row 2.5: the decode top-k as a thread-block cluster (same ids as qsa_topk_ref; sm_90+, the driver
|
||||
// turns it off again on an older card). `LELEKA_QSA_CLUSTER=1` / `0`; unset: QSA_CLUSTER_DEFAULT.
|
||||
policy.qsa.cluster_topk = leleka_cuda_driver::qsa_cluster_requested(QSA_CLUSTER_DEFAULT);
|
||||
let recorded = verifier.record_all(
|
||||
policy,
|
||||
|t| windows.get_mut(t - 1).and_then(Option::take).ok_or(leleka_cuda_driver::Error::InvalidQwenShape),
|
||||
commit,
|
||||
);
|
||||
let (capture_ms, instantiate_ms, modules_ms) = leleka_cuda_driver::original_capture_timing::take();
|
||||
super::original_serve_profile::add("record.capture", capture_ms);
|
||||
super::original_serve_profile::add("record.instantiate", instantiate_ms);
|
||||
super::original_serve_profile::add("record.modules", modules_ms);
|
||||
if let Err(error) = recorded {
|
||||
// dropping the unused aggregates and closing the verifier releases every journal reference
|
||||
drop(windows);
|
||||
let _ = verifier.close();
|
||||
return Err(error.into());
|
||||
}
|
||||
Ok(verifier)
|
||||
})();
|
||||
drop(canonical);
|
||||
match recorded {
|
||||
Ok(verifier) => Ok(DecodeResources { verifier, qsa, slots }),
|
||||
Err(failure) => {
|
||||
// every aggregate is gone: the journal can give the owners back
|
||||
let owners = recover(qsa, slots);
|
||||
Err(AssembleFailure { failure, owners })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `OriginalQsaMappedJournal::ensure_resolver` on every handed-over layer (a no-op for a layer the prompt
|
||||
/// already appended to).
|
||||
fn ensure_resolvers<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
context: &'ctx Context<'ctx>,
|
||||
owners: &mut QsaOwners<'ctx>,
|
||||
) -> std::result::Result<(), ServeFailure> {
|
||||
if owners.iter().flatten().all(|(_, kv)| kv.resolver_ready()) {
|
||||
return Ok(());
|
||||
}
|
||||
let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
|
||||
for (_, kv) in owners.iter_mut().flatten() {
|
||||
kv.ensure_resolver(&mut workspace)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close the verifier (drains both streams, drops every graph and aggregate) and take the physical QSA
|
||||
/// owners back from the journal.
|
||||
pub(in crate::qwen_forward) fn disassemble<'a, 'ctx>(
|
||||
resources: DecodeResources<'a, 'ctx>,
|
||||
) -> std::result::Result<QsaOwners<'ctx>, ServeFailure> {
|
||||
let DecodeResources { verifier, qsa, slots } = resources;
|
||||
let closed = verifier.close();
|
||||
let recovered = recover(qsa, slots);
|
||||
match (closed, recovered) {
|
||||
(Ok(()), Some(owners)) => Ok(owners),
|
||||
(Err(error), _) => Err(error.into()),
|
||||
(Ok(()), None) => Err(Error::IdentityMismatch.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn recover<'a, 'ctx>(qsa: Rc<OriginalVerifyQsaJournal<'a, 'ctx>>, slots: [usize; 12]) -> Option<QsaOwners<'ctx>> {
|
||||
let (indices, mapped) = OriginalVerifyQsaJournal::into_owners(qsa).ok()?;
|
||||
let mut owners: QsaOwners<'ctx> = std::array::from_fn(|_| None);
|
||||
for ((slot, index), kv) in slots.into_iter().zip(indices).zip(mapped) {
|
||||
*owners.get_mut(slot)? = Some((index, kv));
|
||||
}
|
||||
Some(owners)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn driver_refusals_keep_their_words_and_a_stable_class() {
|
||||
let unbound = leleka_cuda_driver::Error::InvalidDriverValue("Original verifier producer unbound: router");
|
||||
let failure = ServeFailure::from(unbound);
|
||||
assert_eq!(failure.error, Error::Unsupported(Stage::Executor));
|
||||
assert_eq!(failure.detail.as_deref(), Some("Original verifier producer unbound: router"));
|
||||
assert!(failure.describe().contains("router"));
|
||||
let sealed = ServeFailure::from(leleka_cuda_driver::Error::UnsupportedQwenOperation);
|
||||
assert_eq!(sealed.error, Error::Unsupported(Stage::Session));
|
||||
assert!(sealed.detail.as_deref().is_some_and(|d| d.contains("unsealed")));
|
||||
let plain = ServeFailure::from(leleka_cuda_driver::Error::ContextMismatch);
|
||||
assert_eq!((plain.error, plain.detail), (Error::IdentityMismatch, None));
|
||||
assert_eq!(ServeFailure::from(Error::NonFinite).describe(), "NonFinite");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ple_history_image_is_nine_slots_of_the_channel_width() {
|
||||
assert_eq!(PLE_HISTORY_VALUES, 92_160);
|
||||
assert_eq!(PLE_HISTORY_BYTES, 368_640);
|
||||
}
|
||||
}
|
||||
//! Assembly and teardown of the native Original verifier for one decode phase.
|
||||
//!
|
||||
//! The verifier owns, for the whole phase, a canonical GDN image seeded from the session's published
|
||||
//! recurrent priors, the PLE history seeded from the session's PLE prior, and the twelve resident QSA
|
||||
//! index images and mapped K/V journals handed over from the prompt executor. It records the T = 1..=max_t
|
||||
//! window graphs and the accepted-prefix commit graph over those owners (`record_all`) and is then ready to
|
||||
//! `run`. Teardown closes the graphs, which releases every aggregate's reference to the QSA journal, and
|
||||
//! returns the physical QSA owners so the executor can take them back at the session's lineage.
|
||||
//!
|
||||
//! Any producer the driver cannot capture yet fails `record_all` with its name
|
||||
//! (`UNBOUND_PRODUCERS`); that refusal surfaces here untouched, never as a substituted arithmetic.
|
||||
use super::{
|
||||
contract::{Error, Result, Stage},
|
||||
dense_weight_cache::DenseWeightCache,
|
||||
gdn::GdnPrior,
|
||||
moe_weight_cache::{MoeWeightCache, SharedKeys},
|
||||
original_serve_config::{ExpertBlobSizes, RopeConstants, verify_geometry},
|
||||
output_native::OriginalNativeOutput,
|
||||
session::original_verified::OriginalVerifiedBase,
|
||||
};
|
||||
use crate::model_binding::qwen4exp_input::{BoundLayerKind, ModelBinding};
|
||||
use leleka_cuda_driver::{
|
||||
Context, DeviceBuffer, OriginalQsaMappedJournal, OriginalQsaResidentIndex, OriginalVerifier, OriginalVerifyExpertFormats,
|
||||
OriginalVerifyQsaJournal, OriginalVerifyResources, OriginalVerifyWindowPolicy, OriginalVerifyWindowResources,
|
||||
};
|
||||
use std::rc::Rc;
|
||||
|
||||
const PLE_HISTORY_VALUES: usize = 9 * 10240;
|
||||
pub(in crate::qwen_forward) const PLE_HISTORY_BYTES: usize = PLE_HISTORY_VALUES * 4;
|
||||
|
||||
/// Default of `LELEKA_QSA_CLUSTER` (the cluster top-k of the decode window; flipped after its gates, docs/upstream-port-plan.md row 2.5).
|
||||
const QSA_CLUSTER_DEFAULT: bool = true;
|
||||
|
||||
/// A refusal with the driver's own words when it has them (an unbound producer, an unsealed asset).
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct ServeFailure {
|
||||
pub(crate) error: Error,
|
||||
pub(crate) detail: Option<String>,
|
||||
}
|
||||
impl From<Error> for ServeFailure {
|
||||
fn from(error: Error) -> Self {
|
||||
Self { error, detail: None }
|
||||
}
|
||||
}
|
||||
impl From<leleka_cuda_driver::Error> for ServeFailure {
|
||||
fn from(driver: leleka_cuda_driver::Error) -> Self {
|
||||
let error = driver_error(&driver);
|
||||
let detail = match &driver {
|
||||
leleka_cuda_driver::Error::InvalidDriverValue(message) => Some((*message).to_owned()),
|
||||
leleka_cuda_driver::Error::UnsupportedQwenOperation => {
|
||||
Some("a compiled asset is unsealed or the operation is not supported by this build".to_owned())
|
||||
}
|
||||
leleka_cuda_driver::Error::GraphOutOfMemory { .. } => Some(driver.to_string()),
|
||||
_ => None,
|
||||
};
|
||||
Self { error, detail }
|
||||
}
|
||||
}
|
||||
impl ServeFailure {
|
||||
/// `class=... detail=...` for the operator diagnostic line (the detail text is a fixed driver string).
|
||||
pub(crate) fn describe(&self) -> String {
|
||||
match &self.detail {
|
||||
Some(detail) => format!("{:?}: {detail}", self.error),
|
||||
None => format!("{:?}", self.error),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The runtime error class of a driver error (the same mapping every Original owner uses).
|
||||
pub(in crate::qwen_forward) fn driver_error(error: &leleka_cuda_driver::Error) -> Error {
|
||||
use leleka_cuda_driver::Error as D;
|
||||
match error {
|
||||
D::NonFiniteMmqOutput(_) => Error::NonFinite,
|
||||
D::BudgetExceeded | D::HostAllocation => Error::InputAllocation,
|
||||
D::ContextMismatch | D::UnexpectedContext => Error::IdentityMismatch,
|
||||
D::InvalidQwenShape | D::InvalidSize | D::InvalidProjectionShape => Error::InvalidDimension,
|
||||
D::UnsupportedQwenOperation => Error::Unsupported(Stage::Session),
|
||||
D::InvalidDriverValue(_) => Error::Unsupported(Stage::Executor),
|
||||
_ => Error::CudaExecution,
|
||||
}
|
||||
}
|
||||
|
||||
type QsaOwners<'ctx> = [Option<(OriginalQsaResidentIndex<'ctx>, OriginalQsaMappedJournal<'ctx>)>; 48];
|
||||
|
||||
/// The verifier plus the one extra reference to the QSA journal that lets the owners be recovered.
|
||||
pub(in crate::qwen_forward) struct DecodeResources<'a, 'ctx> {
|
||||
pub(in crate::qwen_forward) verifier: OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>>,
|
||||
pub(in crate::qwen_forward) qsa: Rc<OriginalVerifyQsaJournal<'a, 'ctx>>,
|
||||
/// Model layer index of journal layer `i` (the owners were handed over in ascending slot order).
|
||||
pub(in crate::qwen_forward) slots: [usize; 12],
|
||||
}
|
||||
|
||||
/// Why an assembly failed and whether the physical QSA owners survived it.
|
||||
pub(in crate::qwen_forward) struct AssembleFailure<'ctx> {
|
||||
pub(in crate::qwen_forward) failure: ServeFailure,
|
||||
/// The owners, when they could be recovered; `None` means the stack must be rebuilt.
|
||||
pub(in crate::qwen_forward) owners: Option<QsaOwners<'ctx>>,
|
||||
/// Set when a window or commit graph did not fit in device memory (the context is intact): the widest window T that is still
|
||||
/// worth recording (`window_cap_after`), so the assembly can be repeated with `max_t` = this. `None` for every other failure.
|
||||
pub(in crate::qwen_forward) window_cap: Option<usize>,
|
||||
}
|
||||
impl<'ctx> AssembleFailure<'ctx> {
|
||||
fn lost(failure: impl Into<ServeFailure>) -> Self {
|
||||
Self { failure: failure.into(), owners: None, window_cap: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// The narrowest verify window worth running: a width of one is plain decoding, so a fallback below it is no fallback.
|
||||
pub(in crate::qwen_forward) const MIN_FALLBACK_WINDOW: usize = 2;
|
||||
|
||||
/// After a graph instantiate that ran out of device memory while `max_t` windows were being recorded: the widest window width to
|
||||
/// record instead, or `None` when the error is anything else or nothing wide enough is left. The graph that did not fit and every
|
||||
/// wider one are given up; windows below it were recorded, so they fit (the commit graph, `window` = 0, costs the widest window).
|
||||
pub(in crate::qwen_forward) fn window_cap_after(error: &leleka_cuda_driver::Error, max_t: usize) -> Option<usize> {
|
||||
let leleka_cuda_driver::Error::GraphOutOfMemory { window } = error else { return None };
|
||||
let failed = if *window == 0 { max_t } else { (*window).min(max_t) };
|
||||
let cap = failed - 1;
|
||||
(cap >= MIN_FALLBACK_WINDOW).then_some(cap)
|
||||
}
|
||||
|
||||
/// Repeat an assembly with narrower windows while it fails only because a window graph did not fit in device memory.
|
||||
/// `attempt(max_t)` returns the assembly or the failure with the cap `window_cap_after` named (`None` = not retryable); every
|
||||
/// retry is strictly narrower, so this ends. `note(failed, next)` reports each step. Returns the `max_t` of the last attempt with
|
||||
/// its outcome.
|
||||
pub(in crate::qwen_forward) fn assemble_with_window_fallback<T, E>(
|
||||
max_t: usize,
|
||||
mut attempt: impl FnMut(usize) -> std::result::Result<T, (E, Option<usize>)>,
|
||||
mut note: impl FnMut(usize, usize),
|
||||
) -> (usize, std::result::Result<T, E>) {
|
||||
let mut current = max_t;
|
||||
loop {
|
||||
match attempt(current) {
|
||||
Ok(done) => return (current, Ok(done)),
|
||||
Err((_, Some(next))) if next < current && next >= MIN_FALLBACK_WINDOW => {
|
||||
note(current, next);
|
||||
current = next;
|
||||
}
|
||||
Err((error, _)) => return (current, Err(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The GDN priors of the thirty-six recurrent layers in layer order, as the canonical image takes them.
|
||||
fn gdn_layer_priors<'p>(binding: &ModelBinding, base: &'p OriginalVerifiedBase<'_>) -> Result<Vec<&'p GdnPrior>> {
|
||||
let mut priors = Vec::new();
|
||||
priors.try_reserve_exact(36).map_err(|_| Error::InputAllocation)?;
|
||||
for layer in binding.ordered_layers() {
|
||||
if layer.kind() == BoundLayerKind::Gdn {
|
||||
priors.push(base.gdn[layer.index() as usize].as_ref().ok_or(Error::IdentityMismatch)?);
|
||||
}
|
||||
}
|
||||
if priors.len() != 36 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(priors)
|
||||
}
|
||||
|
||||
/// Upload the session's PLE prior into the device history image the commit graph keeps current.
|
||||
pub(in crate::qwen_forward) fn seed_ple_history<'ctx>(
|
||||
base: &OriginalVerifiedBase<'_>,
|
||||
ple_history: &mut DeviceBuffer<'ctx>,
|
||||
) -> std::result::Result<(), ServeFailure> {
|
||||
let ple = base.ple.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
if ple.history().len() != PLE_HISTORY_VALUES || ple_history.len() != PLE_HISTORY_BYTES {
|
||||
return Err(Error::InvalidDimension.into());
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(PLE_HISTORY_BYTES).map_err(|_| Error::InputAllocation)?;
|
||||
for value in ple.history() {
|
||||
bytes.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
ple_history.copy_from(&bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The PLE history image as the commit graph left it (after the last committed window).
|
||||
pub(in crate::qwen_forward) fn read_ple_history(ple_history: &DeviceBuffer<'_>) -> Result<Box<[f32]>> {
|
||||
if ple_history.len() != PLE_HISTORY_BYTES {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let bytes = ple_history.copy_to_owned(PLE_HISTORY_BYTES).map_err(|e| driver_error(&e))?;
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(PLE_HISTORY_VALUES).map_err(|_| Error::InputAllocation)?;
|
||||
values.extend(bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)));
|
||||
Ok(values.into_boxed_slice())
|
||||
}
|
||||
|
||||
/// The model weights the window graphs read in place for the whole phase, all borrowed from the caches that
|
||||
/// own them: projections, hyper-connection / PLE and QSA operands from the dense cache, router and shared
|
||||
/// experts from the MoE cache, and the PLE scratch the stack owns.
|
||||
pub(in crate::qwen_forward) struct VerifyWeights<'a, 'ctx> {
|
||||
pub(in crate::qwen_forward) dense: &'a DenseWeightCache<'ctx>,
|
||||
pub(in crate::qwen_forward) moe: &'a MoeWeightCache<'ctx>,
|
||||
pub(in crate::qwen_forward) shared: &'a SharedKeys,
|
||||
pub(in crate::qwen_forward) formats: &'a OriginalVerifyExpertFormats,
|
||||
pub(in crate::qwen_forward) ple_scratch: &'a DeviceBuffer<'ctx>,
|
||||
}
|
||||
|
||||
/// Build the canonical GDN image from the GDN priors, the QSA journal over the handed-over owners, and
|
||||
/// record every window graph and the commit graph. `ple_history` must already hold the seeded image
|
||||
/// (`seed_ple_history`) and outlive the phase; the caller keeps its own shared reference to read it back.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::qwen_forward) fn assemble<'a, 'ctx>(
|
||||
binding: &ModelBinding,
|
||||
weights: &VerifyWeights<'a, 'ctx>,
|
||||
context: &'ctx Context<'ctx>,
|
||||
output: &OriginalNativeOutput<'ctx>,
|
||||
base: &OriginalVerifiedBase<'ctx>,
|
||||
mut owners: QsaOwners<'ctx>,
|
||||
ple_history: &'a DeviceBuffer<'ctx>,
|
||||
rope: &RopeConstants,
|
||||
blobs: &ExpertBlobSizes,
|
||||
max_t: usize,
|
||||
max_cells: usize,
|
||||
pcie_mode: u8,
|
||||
after_prepare: &mut dyn FnMut() -> std::result::Result<(), Error>,
|
||||
) -> std::result::Result<DecodeResources<'a, 'ctx>, AssembleFailure<'ctx>> {
|
||||
let dense = weights.dense;
|
||||
// The window graphs bind each layer's streamed-KV resolver. The prompt path initialises it lazily on its
|
||||
// first append, so a ONE-token prompt on a fresh stack reaches the capture with none: initialise it here
|
||||
// (never through `reset`, which would change the epoch and orphan every prefix the session holds).
|
||||
if let Err(failure) = ensure_resolvers(binding, dense, context, &mut owners) {
|
||||
return Err(AssembleFailure { failure, owners: Some(owners), window_cap: None });
|
||||
}
|
||||
// Everything that can be refused WITHOUT consuming the owners is checked first.
|
||||
let p = super::original_serve_profile::span("assemble.prepare");
|
||||
let prepare = (|| -> std::result::Result<_, ServeFailure> {
|
||||
let geometry = verify_geometry(max_t, max_cells, blobs)?;
|
||||
blobs.layout()?;
|
||||
let priors = gdn_layer_priors(binding, base)?;
|
||||
let states: [&[f32]; 36] = std::array::from_fn(|i| priors[i].values());
|
||||
let histories: [&[f32]; 36] = std::array::from_fn(|i| priors[i].history());
|
||||
let canonical = context.original_verify_canonical_gdn(states, histories)?;
|
||||
// PLE history: the seeded device image the commit graph keeps current.
|
||||
if base.ple.is_none() || ple_history.len() != PLE_HISTORY_BYTES {
|
||||
return Err(Error::InvalidDimension.into());
|
||||
}
|
||||
let gamma = dense.original_verify_qsa_gamma(binding)?;
|
||||
Ok((geometry, canonical, gamma))
|
||||
})();
|
||||
drop(p);
|
||||
let (geometry, mut canonical, gamma) = match prepare {
|
||||
Ok(parts) => parts,
|
||||
Err(failure) => return Err(AssembleFailure { failure, owners: Some(owners), window_cap: None }),
|
||||
};
|
||||
// The caller's work that wants the intake uploads done and the graph capture still ahead (the lent-slot refill copies).
|
||||
if let Err(error) = after_prepare() {
|
||||
drop(canonical);
|
||||
return Err(AssembleFailure { failure: error.into(), owners: Some(owners), window_cap: None });
|
||||
}
|
||||
// ---- from here the owners move into the journal
|
||||
let mut slots = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
let mut mapped = Vec::new();
|
||||
for (slot, owner) in owners.into_iter().enumerate() {
|
||||
if let Some((index, kv)) = owner {
|
||||
slots.push(slot);
|
||||
indices.push(index);
|
||||
mapped.push(kv);
|
||||
}
|
||||
}
|
||||
let slots: [usize; 12] = slots.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?;
|
||||
let indices: [OriginalQsaResidentIndex<'ctx>; 12] =
|
||||
indices.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?;
|
||||
let mapped: [OriginalQsaMappedJournal<'ctx>; 12] =
|
||||
mapped.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?;
|
||||
let p = super::original_serve_profile::span("assemble.qsa_journal");
|
||||
let qsa = OriginalVerifyQsaJournal::new(context, indices, mapped, gamma, rope.verify_rope())
|
||||
.map_err(AssembleFailure::lost)?;
|
||||
drop(p);
|
||||
let mut window_cap = None;
|
||||
let recorded = (|| -> std::result::Result<_, ServeFailure> {
|
||||
let p = super::original_serve_profile::span("assemble.verifier_new");
|
||||
let mut verifier = OriginalVerifier::<'ctx, OriginalVerifyWindowResources<'a, 'ctx>>::new(context, geometry)?;
|
||||
drop(p);
|
||||
let p = super::original_serve_profile::span("assemble.aggregates");
|
||||
let built = (|| -> std::result::Result<(Vec<Option<OriginalVerifyWindowResources<'a, 'ctx>>>, OriginalVerifyWindowResources<'a, 'ctx>), ServeFailure> {
|
||||
let mut windows = Vec::new();
|
||||
windows.try_reserve_exact(max_t).map_err(|_| Error::InputAllocation)?;
|
||||
let mut aggregate = |t: usize| -> std::result::Result<OriginalVerifyWindowResources<'a, 'ctx>, ServeFailure> {
|
||||
let gdn_weights = dense.original_verify_gdn_weights(binding)?;
|
||||
let journal = verifier.bank()?.gdn_journal(&mut canonical, gdn_weights, Some(ple_history))?;
|
||||
let head = output.rows(binding, t)?;
|
||||
let resources = OriginalVerifyResources::new(context, journal, Rc::clone(&qsa), head)?;
|
||||
let embed = output.embedding(binding)?.rows(t)?;
|
||||
let window = OriginalVerifyWindowResources::new(context, resources, embed, blobs.layout()?, t)?
|
||||
.with_projections(dense.original_verify_projections(binding, &geometry)?)?
|
||||
.with_gr(dense.original_verify_gr(binding, weights.ple_scratch, ple_history)?)?
|
||||
.with_qsa(dense.original_verify_qsa(binding, &geometry)?)?
|
||||
.with_moe(weights.moe.original_verify_moe(binding, dense, &geometry, weights.shared, weights.formats.clone())?)?;
|
||||
Ok(window)
|
||||
};
|
||||
for t in 1..=max_t {
|
||||
windows.push(Some(aggregate(t)?));
|
||||
}
|
||||
let commit = aggregate(max_t)?;
|
||||
Ok((windows, commit))
|
||||
})();
|
||||
drop(p);
|
||||
let (mut windows, commit) = match built {
|
||||
Ok(parts) => parts,
|
||||
Err(failure) => {
|
||||
let _ = verifier.close();
|
||||
return Err(failure);
|
||||
}
|
||||
};
|
||||
let _ = leleka_cuda_driver::original_capture_timing::take();
|
||||
let _p = super::original_serve_profile::span("assemble.record_all");
|
||||
// `Verifier::set_pcie_mode`: the copy kernel stages the PCIe share inside the graph (2), or DMA (0).
|
||||
let mut policy = OriginalVerifyWindowPolicy::mode17();
|
||||
policy.pcie_mode = pcie_mode;
|
||||
// docs/upstream-port-plan.md row 2.5: the decode top-k as a thread-block cluster (same ids as qsa_topk_ref; sm_90+, the driver
|
||||
// turns it off again on an older card). `LELEKA_QSA_CLUSTER=1` / `0`; unset: QSA_CLUSTER_DEFAULT.
|
||||
policy.qsa.cluster_topk = leleka_cuda_driver::qsa_cluster_requested(QSA_CLUSTER_DEFAULT);
|
||||
let recorded = verifier.record_all(
|
||||
policy,
|
||||
|t| windows.get_mut(t - 1).and_then(Option::take).ok_or(leleka_cuda_driver::Error::InvalidQwenShape),
|
||||
commit,
|
||||
);
|
||||
let (capture_ms, instantiate_ms, modules_ms) = leleka_cuda_driver::original_capture_timing::take();
|
||||
super::original_serve_profile::add("record.capture", capture_ms);
|
||||
super::original_serve_profile::add("record.instantiate", instantiate_ms);
|
||||
super::original_serve_profile::add("record.modules", modules_ms);
|
||||
if let Err(error) = recorded {
|
||||
// dropping the unused aggregates and closing the verifier releases every journal reference
|
||||
drop(windows);
|
||||
let _ = verifier.close();
|
||||
window_cap = window_cap_after(&error, max_t);
|
||||
return Err(error.into());
|
||||
}
|
||||
Ok(verifier)
|
||||
})();
|
||||
drop(canonical);
|
||||
match recorded {
|
||||
Ok(verifier) => Ok(DecodeResources { verifier, qsa, slots }),
|
||||
Err(failure) => {
|
||||
// every aggregate is gone: the journal can give the owners back
|
||||
let owners = recover(qsa, slots);
|
||||
// a retry needs the owners back
|
||||
let window_cap = window_cap.filter(|_| owners.is_some());
|
||||
Err(AssembleFailure { failure, owners, window_cap })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `OriginalQsaMappedJournal::ensure_resolver` on every handed-over layer (a no-op for a layer the prompt
|
||||
/// already appended to).
|
||||
fn ensure_resolvers<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
context: &'ctx Context<'ctx>,
|
||||
owners: &mut QsaOwners<'ctx>,
|
||||
) -> std::result::Result<(), ServeFailure> {
|
||||
if owners.iter().flatten().all(|(_, kv)| kv.resolver_ready()) {
|
||||
return Ok(());
|
||||
}
|
||||
let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
|
||||
for (_, kv) in owners.iter_mut().flatten() {
|
||||
kv.ensure_resolver(&mut workspace)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close the verifier (drains both streams, drops every graph and aggregate) and take the physical QSA
|
||||
/// owners back from the journal.
|
||||
pub(in crate::qwen_forward) fn disassemble<'a, 'ctx>(
|
||||
resources: DecodeResources<'a, 'ctx>,
|
||||
) -> std::result::Result<QsaOwners<'ctx>, ServeFailure> {
|
||||
let DecodeResources { verifier, qsa, slots } = resources;
|
||||
let closed = verifier.close();
|
||||
let recovered = recover(qsa, slots);
|
||||
match (closed, recovered) {
|
||||
(Ok(()), Some(owners)) => Ok(owners),
|
||||
(Err(error), _) => Err(error.into()),
|
||||
(Ok(()), None) => Err(Error::IdentityMismatch.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn recover<'a, 'ctx>(qsa: Rc<OriginalVerifyQsaJournal<'a, 'ctx>>, slots: [usize; 12]) -> Option<QsaOwners<'ctx>> {
|
||||
let (indices, mapped) = OriginalVerifyQsaJournal::into_owners(qsa).ok()?;
|
||||
let mut owners: QsaOwners<'ctx> = std::array::from_fn(|_| None);
|
||||
for ((slot, index), kv) in slots.into_iter().zip(indices).zip(mapped) {
|
||||
*owners.get_mut(slot)? = Some((index, kv));
|
||||
}
|
||||
Some(owners)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use leleka_cuda_driver::Error as D;
|
||||
|
||||
#[test]
|
||||
fn a_graph_out_of_memory_names_the_widest_window_worth_recording() {
|
||||
// window T=6 of 8 did not fit: 1..=5 were recorded and fit
|
||||
assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 6 }, 8), Some(5));
|
||||
assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 3 }, 8), Some(2));
|
||||
// the commit graph (window 0) is recorded after every window: the widest window goes
|
||||
assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 8), Some(7));
|
||||
assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 4), Some(3));
|
||||
// nothing wide enough is left (a width of one is no speculation), and a window past max_t is clamped
|
||||
assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 2 }, 8), None);
|
||||
assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 1 }, 8), None);
|
||||
assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 2), None);
|
||||
assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 9 }, 4), Some(3));
|
||||
// every other failure, including a plain out-of-memory the driver did not classify, is not retried
|
||||
for other in [D::HostAllocation, D::ContextPoisoned, D::InvalidQwenShape, D::Driver { operation: "cuGraphInstantiateWithFlags", code: 2 }] {
|
||||
assert_eq!(window_cap_after(&other, 8), None, "{other:?}");
|
||||
}
|
||||
assert!(ServeFailure::from(D::GraphOutOfMemory { window: 6 }).describe().contains("T=6"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_assembly_is_repeated_with_narrower_windows_until_one_fits() {
|
||||
// 8 and 6 do not fit, 5 does
|
||||
let mut tried = Vec::new();
|
||||
let mut notes = Vec::new();
|
||||
let (used, outcome) = assemble_with_window_fallback(
|
||||
8,
|
||||
|t| {
|
||||
tried.push(t);
|
||||
match t {
|
||||
8 => Err(("oom at 8", window_cap_after(&D::GraphOutOfMemory { window: 7 }, t))),
|
||||
6 => Err(("oom at 6", window_cap_after(&D::GraphOutOfMemory { window: 0 }, t))),
|
||||
t => Ok(t * 10),
|
||||
}
|
||||
},
|
||||
|failed, next| notes.push((failed, next)),
|
||||
);
|
||||
assert_eq!((used, outcome), (5, Ok(50)));
|
||||
assert_eq!(tried, [8, 6, 5]);
|
||||
assert_eq!(notes, [(8, 6), (6, 5)]);
|
||||
// it fits at once: one attempt, nothing noted
|
||||
let mut calls = 0;
|
||||
let (used, outcome) = assemble_with_window_fallback::<_, &str>(8, |t| { calls += 1; Ok(t) }, |_, _| panic!("no retry"));
|
||||
assert_eq!((used, outcome, calls), (8, Ok(8), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fallback_stops_at_the_floor_on_any_other_failure_and_never_loops() {
|
||||
// nothing fits down to the floor: the last failure comes back, with the width it was tried at
|
||||
let (used, outcome) = assemble_with_window_fallback::<(), _>(
|
||||
8,
|
||||
|t| Err((format!("oom at {t}"), window_cap_after(&D::GraphOutOfMemory { window: t }, t))),
|
||||
|_, _| {},
|
||||
);
|
||||
assert_eq!((used, outcome), (2, Err("oom at 2".to_string())));
|
||||
// a failure that is not an out-of-memory is returned at once, with no retry
|
||||
let mut calls = 0;
|
||||
let (used, outcome) = assemble_with_window_fallback::<(), _>(8, |_| { calls += 1; Err(("broken", None)) }, |_, _| panic!("no retry"));
|
||||
assert_eq!((used, outcome, calls), (8, Err("broken"), 1));
|
||||
// a cap that does not narrow the window (a bug somewhere) is not followed
|
||||
let (used, outcome) = assemble_with_window_fallback::<(), _>(4, |_| Err(("same", Some(4))), |_, _| panic!("no retry"));
|
||||
assert_eq!((used, outcome), (4, Err("same")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn driver_refusals_keep_their_words_and_a_stable_class() {
|
||||
let unbound = leleka_cuda_driver::Error::InvalidDriverValue("Original verifier producer unbound: router");
|
||||
let failure = ServeFailure::from(unbound);
|
||||
assert_eq!(failure.error, Error::Unsupported(Stage::Executor));
|
||||
assert_eq!(failure.detail.as_deref(), Some("Original verifier producer unbound: router"));
|
||||
assert!(failure.describe().contains("router"));
|
||||
let sealed = ServeFailure::from(leleka_cuda_driver::Error::UnsupportedQwenOperation);
|
||||
assert_eq!(sealed.error, Error::Unsupported(Stage::Session));
|
||||
assert!(sealed.detail.as_deref().is_some_and(|d| d.contains("unsealed")));
|
||||
let plain = ServeFailure::from(leleka_cuda_driver::Error::ContextMismatch);
|
||||
assert_eq!((plain.error, plain.detail), (Error::IdentityMismatch, None));
|
||||
assert_eq!(ServeFailure::from(Error::NonFinite).describe(), "NonFinite");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ple_history_image_is_nine_slots_of_the_channel_width() {
|
||||
assert_eq!(PLE_HISTORY_VALUES, 92_160);
|
||||
assert_eq!(PLE_HISTORY_BYTES, 368_640);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user