STRA-338 size2 en7: session, chunk, verify, original-prompt/draft and serve-meta functions cut to the limits
This commit is contained in:
@@ -3,6 +3,13 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Which of the bound layers (by position) are of `kind`.
|
||||
fn layers_of_kind<const N: usize>(binding: &ModelBinding, kind: BoundLayerKind) -> [bool; N] {
|
||||
std::array::from_fn(|index| {
|
||||
let layers = binding.ordered_layers();
|
||||
layers.get(index).is_some_and(|d| d.index() as usize == index && d.kind() == kind)
|
||||
})
|
||||
}
|
||||
impl<'driver> QwenSession<'driver> {
|
||||
pub(in crate::qwen_forward) fn note_mtp_failure(&mut self, error: &Error) {
|
||||
if *error == Error::CudaExecution {
|
||||
@@ -38,20 +45,10 @@ impl<'driver> QwenSession<'driver> {
|
||||
ple_required: binding.ordered_layers().get(1).is_some_and(|d| d.index() == 1),
|
||||
ple_owner: PleOwner::new(),
|
||||
ple_state: None,
|
||||
gdn_layers: std::array::from_fn(|index| {
|
||||
binding
|
||||
.ordered_layers()
|
||||
.get(index)
|
||||
.is_some_and(|d| d.index() as usize == index && d.kind() == BoundLayerKind::Gdn)
|
||||
}),
|
||||
gdn_layers: layers_of_kind(binding, BoundLayerKind::Gdn),
|
||||
gdn_owner: GdnOwner::new(),
|
||||
gdn_states: std::array::from_fn(|_| None),
|
||||
qsa_layers: std::array::from_fn(|index| {
|
||||
binding
|
||||
.ordered_layers()
|
||||
.get(index)
|
||||
.is_some_and(|d| d.index() as usize == index && d.kind() == BoundLayerKind::Qsa)
|
||||
}),
|
||||
qsa_layers: layers_of_kind(binding, BoundLayerKind::Qsa),
|
||||
qsa_owner: QsaOwner::new(),
|
||||
qsa_states: std::array::from_fn(|_| None),
|
||||
state_lag: None,
|
||||
@@ -81,7 +78,8 @@ impl<'driver> QwenSession<'driver> {
|
||||
session
|
||||
}
|
||||
|
||||
pub(super) fn begin(&mut self, token: TokenId, position: Position) -> Result<QwenStepTxn<'_, 'driver>> {
|
||||
/// The guards of `begin`: the owning thread, a healthy device, a bound layer count and the next position.
|
||||
fn admit_step(&self, position: Position) -> Result<()> {
|
||||
if self.owner_thread != std::thread::current().id() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
@@ -94,6 +92,10 @@ impl<'driver> QwenSession<'driver> {
|
||||
if position.get() != self.next_position {
|
||||
return Err(Error::InvalidPosition);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn begin(&mut self, token: TokenId, position: Position) -> Result<QwenStepTxn<'_, 'driver>> {
|
||||
self.admit_step(position)?;
|
||||
Ok(QwenStepTxn {
|
||||
binding: self.binding.clone(),
|
||||
_owner: self.owner.clone(),
|
||||
|
||||
+85
-51
@@ -128,57 +128,15 @@ impl<'driver> QwenStepTxn<'_, 'driver> {
|
||||
}
|
||||
let next_position = self.position.get().checked_add(1).ok_or(Error::Overflow)?;
|
||||
let token = i32::try_from(self.token.get()).map_err(|_| Error::InvalidToken)?;
|
||||
let next_ple = if self.session.ple_required {
|
||||
let next = self.ple_pending.ok_or(Error::Unsupported(Stage::Input))?.into_prior();
|
||||
if next.next_position() != next_position {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Some(next)
|
||||
} else {
|
||||
if self.ple_pending.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
None
|
||||
};
|
||||
let mut next_states = self.session.gdn_states.clone();
|
||||
for (index, pending) in self.gdn_pending.into_iter().enumerate() {
|
||||
if self.session.gdn_layers[index] {
|
||||
let next = pending.ok_or(Error::Unsupported(Stage::Gdn))?.into_prior();
|
||||
if next.layer().get() as usize != index || next.next_position() != next_position {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
next_states[index] = Some(next);
|
||||
} else if pending.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
let mut next_qsa = self.session.qsa_states.clone();
|
||||
for (index, pending) in self.qsa_pending.into_iter().enumerate() {
|
||||
if self.session.qsa_layers[index] {
|
||||
let next = pending.ok_or(Error::Unsupported(Stage::QsaIndex))?.into_prior();
|
||||
if next.layer().get() as usize != index || next.next_position() != next_position {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
next_qsa[index] = Some(next);
|
||||
} else if pending.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
if self.session.layer_count > 0 {
|
||||
if self.completed_layers != self.session.layer_count {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
match output {
|
||||
// A token callback without a produced logits/argmax is a skipped
|
||||
// forward (Unsupported), distinct from a wrong callback token.
|
||||
Some(_) if !self.prefill_finished && self.forward_output.is_none() => {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
Some(value) if !self.prefill_finished && self.forward_output == Some(value) => {}
|
||||
None if self.prefill_finished && self.forward_output.is_none() => {}
|
||||
_ => return Err(Error::IdentityMismatch),
|
||||
}
|
||||
}
|
||||
let next_ple = next_ple(self.session.ple_required, self.ple_pending, next_position)?;
|
||||
let next_states = next_gdn(self.session, self.gdn_pending, next_position)?;
|
||||
let next_qsa = next_qsa(self.session, self.qsa_pending, next_position)?;
|
||||
check_forward_output(
|
||||
self.session,
|
||||
self.completed_layers,
|
||||
(self.prefill_finished, self.forward_output),
|
||||
output,
|
||||
)?;
|
||||
let session = self.session;
|
||||
session.complete_cuda()?;
|
||||
session.ple_state = next_ple;
|
||||
@@ -196,3 +154,79 @@ impl<'driver> QwenStepTxn<'_, 'driver> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The PLE prior after this step: required exactly when the session carries PLE, and at the next position.
|
||||
fn next_ple(required: bool, pending: Option<PlePending>, next_position: u64) -> Result<Option<PlePrior>> {
|
||||
if !required {
|
||||
return if pending.is_some() { Err(Error::IdentityMismatch) } else { Ok(None) };
|
||||
}
|
||||
let next = pending.ok_or(Error::Unsupported(Stage::Input))?.into_prior();
|
||||
if next.next_position() != next_position {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(Some(next))
|
||||
}
|
||||
/// The GDN priors after this step: one per GDN layer at the next position, none for any other layer.
|
||||
fn next_gdn(
|
||||
session: &QwenSession<'_>,
|
||||
pending: [Option<GdnPending>; STATE_CAPACITY],
|
||||
next_position: u64,
|
||||
) -> Result<[Option<GdnPrior>; STATE_CAPACITY]> {
|
||||
let mut next_states = session.gdn_states.clone();
|
||||
for (index, pending) in pending.into_iter().enumerate() {
|
||||
if session.gdn_layers[index] {
|
||||
let next = pending.ok_or(Error::Unsupported(Stage::Gdn))?.into_prior();
|
||||
if next.layer().get() as usize != index || next.next_position() != next_position {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
next_states[index] = Some(next);
|
||||
} else if pending.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
Ok(next_states)
|
||||
}
|
||||
/// The QSA index priors after this step: one per QSA layer at the next position, none for any other layer.
|
||||
fn next_qsa(
|
||||
session: &QwenSession<'_>,
|
||||
pending: [Option<QsaPending>; STATE_CAPACITY],
|
||||
next_position: u64,
|
||||
) -> Result<[Option<QsaIndexPrior>; STATE_CAPACITY]> {
|
||||
let mut next_qsa = session.qsa_states.clone();
|
||||
for (index, pending) in pending.into_iter().enumerate() {
|
||||
if session.qsa_layers[index] {
|
||||
let next = pending.ok_or(Error::Unsupported(Stage::QsaIndex))?.into_prior();
|
||||
if next.layer().get() as usize != index || next.next_position() != next_position {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
next_qsa[index] = Some(next);
|
||||
} else if pending.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
Ok(next_qsa)
|
||||
}
|
||||
/// A bound session must have completed every layer, and the callback token must match the forward output.
|
||||
fn check_forward_output(
|
||||
session: &QwenSession<'_>,
|
||||
completed_layers: u32,
|
||||
(prefill_finished, forward_output): (bool, Option<TokenId>),
|
||||
output: Option<TokenId>,
|
||||
) -> Result<()> {
|
||||
if session.layer_count > 0 {
|
||||
if completed_layers != session.layer_count {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
match output {
|
||||
// A token callback without a produced logits/argmax is a skipped
|
||||
// forward (Unsupported), distinct from a wrong callback token.
|
||||
Some(_) if !prefill_finished && forward_output.is_none() => {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
Some(value) if !prefill_finished && forward_output == Some(value) => {}
|
||||
None if prefill_finished && forward_output.is_none() => {}
|
||||
_ => return Err(Error::IdentityMismatch),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -51,6 +51,88 @@ impl ResetReplaySnapshot {
|
||||
}
|
||||
}
|
||||
|
||||
/// The host products one oracle capture gathers over the 36 GDN and 12 QSA layers.
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
struct OracleParts {
|
||||
gdn: Vec<f32>,
|
||||
tails: Vec<f32>,
|
||||
dead: Vec<f32>,
|
||||
blocks: Vec<[u8; 4]>,
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn capture_gdn(s: &ResetReplaySnapshot, index: usize, gdn: &mut Vec<f32>) -> Result<()> {
|
||||
if !s.gdn_layers[index] || s.qsa_layers[index] {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let state = s.gdn[index].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
if state.values().len() != 786432 || state.history().len() != 30720 {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
gdn.extend_from_slice(state.values());
|
||||
gdn.extend_from_slice(state.history());
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn capture_qsa(s: &ResetReplaySnapshot, index: usize, parts: &mut OracleParts) -> Result<()> {
|
||||
if !s.qsa_layers[index] || s.gdn_layers[index] {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let state = s.qsa[index].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let (k, v, pooled, tail, d) = state.oracle_capture_parts()?;
|
||||
super::super::oracle_capture::file_bytes(&format!("layer{index}.k.f16"), &k)?;
|
||||
super::super::oracle_capture::file_bytes(&format!("layer{index}.v.f16"), &v)?;
|
||||
super::super::oracle_capture::file_f32(&format!("layer{index}.pooled.f32"), &pooled)?;
|
||||
parts.tails.extend_from_slice(&tail);
|
||||
parts.dead.extend_from_slice(&d);
|
||||
// Original native append changes initialized -1 only upon completed block (pos 3).
|
||||
// Fixed prefixes 1/2 have no independent candidate block-pos storage; normalize metadata only.
|
||||
parts.blocks.push((-1i32).to_le_bytes());
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn capture_layers(s: &ResetReplaySnapshot) -> Result<OracleParts> {
|
||||
let mut gdn = Vec::new();
|
||||
gdn.try_reserve_exact(36 * (786432 + 30720)).map_err(|_| Error::InputAllocation)?;
|
||||
let mut parts = OracleParts { gdn, tails: Vec::new(), dead: Vec::new(), blocks: Vec::new() };
|
||||
let mut gc = 0;
|
||||
let mut qc = 0;
|
||||
for index in 0..48 {
|
||||
if index % 4 != 3 {
|
||||
capture_gdn(s, index, &mut parts.gdn)?;
|
||||
gc += 1;
|
||||
} else {
|
||||
capture_qsa(s, index, &mut parts)?;
|
||||
qc += 1;
|
||||
}
|
||||
}
|
||||
if gc != 36 || qc != 12 {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
Ok(parts)
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn write_oracle_files(s: &ResetReplaySnapshot, position: u64, parts: &OracleParts) -> Result<()> {
|
||||
super::super::oracle_capture::file_f32("gdn_recurrence_conv.f32", &parts.gdn)?;
|
||||
super::super::oracle_capture::file_f32(
|
||||
"ple_history.f32",
|
||||
s.ple.as_ref().ok_or(Error::IdentityMismatch)?.oracle_history(),
|
||||
)?;
|
||||
super::super::oracle_capture::file_f32("qsa_tail.f32", &parts.tails)?;
|
||||
super::super::oracle_capture::file_f32("qsa_dead.f32", &parts.dead)?;
|
||||
super::super::oracle_capture::file_bytes("qsa_block_pos.i32", &parts.blocks.concat())?;
|
||||
super::super::oracle_capture::file_bytes("next_position.i64", &s.next_position.to_le_bytes())?;
|
||||
let tokens: [i32; 2] = [0, 1];
|
||||
super::super::oracle_capture::file_bytes(
|
||||
"tokens.i32",
|
||||
&tokens[..(position + 1) as usize].iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<_>>(),
|
||||
)?;
|
||||
super::super::oracle_capture::file_bytes(
|
||||
"ple_prev.i32",
|
||||
&s.predecessors.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<_>>(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
impl QwenSession<'_> {
|
||||
pub(in super::super) fn oracle_capture_committed(&self, binding: &ModelBinding, position: u64) -> Result<()> {
|
||||
@@ -59,78 +141,11 @@ impl QwenSession<'_> {
|
||||
if position > 1 || !s.has_prefix(position + 1, prior) || s.layer_count != 48 || !s.ple_required {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut gdn = Vec::new();
|
||||
gdn.try_reserve_exact(36 * (786432 + 30720)).map_err(|_| Error::InputAllocation)?;
|
||||
let mut tails = Vec::new();
|
||||
let mut dead = Vec::new();
|
||||
let mut blocks = Vec::new();
|
||||
let mut gc = 0;
|
||||
let mut qc = 0;
|
||||
for index in 0..48 {
|
||||
if index % 4 != 3 {
|
||||
if !s.gdn_layers[index] || s.qsa_layers[index] {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let state = s.gdn[index].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
if state.values().len() != 786432 || state.history().len() != 30720 {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
gdn.extend_from_slice(state.values());
|
||||
gdn.extend_from_slice(state.history());
|
||||
gc += 1;
|
||||
} else {
|
||||
if !s.qsa_layers[index] || s.gdn_layers[index] {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let state = s.qsa[index].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let (k, v, pooled, tail, d) = state.oracle_capture_parts()?;
|
||||
super::super::oracle_capture::file_bytes(&format!("layer{index}.k.f16"), &k)?;
|
||||
super::super::oracle_capture::file_bytes(&format!("layer{index}.v.f16"), &v)?;
|
||||
super::super::oracle_capture::file_f32(&format!("layer{index}.pooled.f32"), &pooled)?;
|
||||
tails.extend_from_slice(&tail);
|
||||
dead.extend_from_slice(&d);
|
||||
// Original native append changes initialized -1 only upon completed block (pos 3).
|
||||
// Fixed prefixes 1/2 have no independent candidate block-pos storage; normalize metadata only.
|
||||
blocks.push((-1i32).to_le_bytes());
|
||||
qc += 1;
|
||||
}
|
||||
}
|
||||
if gc != 36 || qc != 12 {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
super::super::oracle_capture::file_f32("gdn_recurrence_conv.f32", &gdn)?;
|
||||
super::super::oracle_capture::file_f32(
|
||||
"ple_history.f32",
|
||||
s.ple.as_ref().ok_or(Error::IdentityMismatch)?.oracle_history(),
|
||||
)?;
|
||||
super::super::oracle_capture::file_f32("qsa_tail.f32", &tails)?;
|
||||
super::super::oracle_capture::file_f32("qsa_dead.f32", &dead)?;
|
||||
super::super::oracle_capture::file_bytes("qsa_block_pos.i32", &blocks.concat())?;
|
||||
super::super::oracle_capture::file_bytes("next_position.i64", &s.next_position.to_le_bytes())?;
|
||||
let tokens: [i32; 2] = [0, 1];
|
||||
super::super::oracle_capture::file_bytes(
|
||||
"tokens.i32",
|
||||
&tokens[..(position + 1) as usize].iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<_>>(),
|
||||
)?;
|
||||
super::super::oracle_capture::file_bytes(
|
||||
"ple_prev.i32",
|
||||
&s.predecessors.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<_>>(),
|
||||
)?;
|
||||
Ok(())
|
||||
let parts = capture_layers(&s)?;
|
||||
write_oracle_files(&s, position, &parts)
|
||||
}
|
||||
pub(crate) fn test_reset_replay_snapshot(&self, binding: &ModelBinding) -> Result<ResetReplaySnapshot> {
|
||||
if self.owner_thread != std::thread::current().id()
|
||||
|| !self.binding.matches(&binding.identity())
|
||||
|| self.layer_count != binding.layer_count()
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if self.cuda_failed {
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
let position =
|
||||
Position::new(self.next_position, Dimension::new(u64::from(binding.input_constants().context_length()))?)?;
|
||||
let layers = Dimension::new(u64::from(self.layer_count))?;
|
||||
/// Every retained prior validates against the session lineage at the next position, or is absent.
|
||||
fn validate_reset_states(&self, position: Position, layers: Dimension) -> Result<()> {
|
||||
match &self.ple_state {
|
||||
Some(state) if self.ple_required && self.next_position > 0 => {
|
||||
state.validate(&self.binding, &self.ple_owner, position)?;
|
||||
@@ -154,6 +169,22 @@ impl QwenSession<'_> {
|
||||
_ => return Err(Error::IdentityMismatch),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn test_reset_replay_snapshot(&self, binding: &ModelBinding) -> Result<ResetReplaySnapshot> {
|
||||
if self.owner_thread != std::thread::current().id()
|
||||
|| !self.binding.matches(&binding.identity())
|
||||
|| self.layer_count != binding.layer_count()
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if self.cuda_failed {
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
let position =
|
||||
Position::new(self.next_position, Dimension::new(u64::from(binding.input_constants().context_length()))?)?;
|
||||
let layers = Dimension::new(u64::from(self.layer_count))?;
|
||||
self.validate_reset_states(position, layers)?;
|
||||
Ok(ResetReplaySnapshot {
|
||||
binding: self.binding.clone(),
|
||||
predecessors: self.predecessors,
|
||||
|
||||
@@ -142,7 +142,7 @@ impl GdnChunkStart {
|
||||
let owner = phase.journal_owner();
|
||||
let start = Self(Rc::new(GdnChunkAnchor {
|
||||
binding: txn.original_session().binding.clone(),
|
||||
chunk: Rc::clone(&owner),
|
||||
chunk: owner,
|
||||
prior: prior.clone(),
|
||||
layer,
|
||||
first: Position::new(txn.start_position(), crate::qwen_forward::contract::position_dimension())?,
|
||||
@@ -150,6 +150,15 @@ impl GdnChunkStart {
|
||||
count: txn.len(),
|
||||
}));
|
||||
start.validate_binding(&txn.original_session().binding)?;
|
||||
let rows = start.prompt_rows(txn, layer)?;
|
||||
Ok((start, rows))
|
||||
}
|
||||
/// One row per prompt position, each keyed and validated against the Original prompt transaction.
|
||||
fn prompt_rows(
|
||||
&self,
|
||||
txn: &super::super::original_prompt::OriginalPromptTxn<'_, '_>,
|
||||
layer: LayerId,
|
||||
) -> Result<Vec<GdnChunkRow>> {
|
||||
let mut rows = Vec::new();
|
||||
rows.try_reserve_exact(txn.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for index in 0..txn.len() {
|
||||
@@ -157,16 +166,10 @@ impl GdnChunkStart {
|
||||
let key = txn.row_key(index)?;
|
||||
let identity =
|
||||
key.validate(&txn.original_session().binding, &input, GrRole::Attention(layer.get()), true)?;
|
||||
rows.push(GdnChunkRow {
|
||||
start: start.clone(),
|
||||
index,
|
||||
identity,
|
||||
proof: Rc::clone(&owner),
|
||||
window: None,
|
||||
key: Rc::new(()),
|
||||
});
|
||||
let proof = Rc::clone(&self.0.chunk);
|
||||
rows.push(GdnChunkRow { start: self.clone(), index, identity, proof, window: None, key: Rc::new(()) });
|
||||
}
|
||||
Ok((start, rows))
|
||||
Ok(rows)
|
||||
}
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
|
||||
+85
-41
@@ -53,46 +53,19 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
host_remaining: usize,
|
||||
windowed: bool,
|
||||
) -> Result<Self> {
|
||||
let limit = if windowed { 256 } else { 64 };
|
||||
let origin = session.target_origin()?;
|
||||
if !session.binding.matches(&binding.identity())
|
||||
|| session.layer_count != 48
|
||||
|| tokens.is_empty()
|
||||
|| tokens.len() > limit
|
||||
{
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let end = session.next_position.checked_add(tokens.len() as u64).ok_or(Error::Overflow)?;
|
||||
let context_bound = Dimension::new(u64::from(binding.input_constants().context_length()))?;
|
||||
if end >= u64::from(context_bound.get()) || end >= crate::qwen_forward::contract::serving_cells() {
|
||||
return Err(Error::InvalidPosition);
|
||||
}
|
||||
let vocab = Dimension::new(248320)?;
|
||||
for token in tokens.iter().copied().chain(known_next) {
|
||||
if token != TokenId::new(u64::from(token.get()), vocab)? {
|
||||
return Err(Error::InvalidToken);
|
||||
}
|
||||
}
|
||||
let charge =
|
||||
if windowed { host_charge_bounded(tokens.len(), end, 256)? } else { host_charge(tokens.len(), end)? };
|
||||
if charge > host_remaining {
|
||||
return Err(Error::InputAllocation);
|
||||
}
|
||||
let context = session.mtp_context()?;
|
||||
if context.allocated_bytes().checked_add(128 * 1024 * 1024).is_none_or(|n| n > context.budget_bytes()) {
|
||||
return Err(Error::InputAllocation);
|
||||
}
|
||||
let mut rows = Vec::new();
|
||||
rows.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut witnesses = Vec::new();
|
||||
witnesses.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut predecessors = session.predecessors;
|
||||
for (index, token) in tokens.iter().copied().enumerate() {
|
||||
let position = Position::new(session.next_position + index as u64, context_bound)?;
|
||||
rows.push(Row { token, position, predecessors, input: None, completed: 0 });
|
||||
predecessors = [predecessors[1], i32::try_from(token.get()).map_err(|_| Error::InvalidToken)?];
|
||||
}
|
||||
Ok(Self {
|
||||
let origin = prompt_origin(session, binding, tokens.len(), windowed)?;
|
||||
let (end, context_bound) = prompt_end(session, binding, tokens.len())?;
|
||||
admit_prompt_host(session, tokens, known_next, (end, host_remaining, windowed))?;
|
||||
let (rows, witnesses) = prompt_rows(session, tokens, context_bound)?;
|
||||
Ok(Self::fresh(session, PromptInit { origin, rows, witnesses }, (known_next, end, windowed)))
|
||||
}
|
||||
fn fresh(
|
||||
session: &'session mut QwenSession<'driver>,
|
||||
init: PromptInit,
|
||||
(known_next, end, windowed): (Option<TokenId>, u64, bool),
|
||||
) -> Self {
|
||||
let PromptInit { origin, rows, witnesses } = init;
|
||||
Self {
|
||||
verification: None,
|
||||
next_ple: session.ple_state.clone(),
|
||||
next_gdn: session.gdn_states.clone(),
|
||||
@@ -126,7 +99,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
test_window_journal: Vec::new(),
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
test_partial_words: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
pub(in super::super) fn check(&self) -> Result<()> {
|
||||
self.origin.validate(self.session)?;
|
||||
@@ -186,3 +159,74 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
if self.windowed { 256 } else { 64 }
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows, witnesses and step origin a fresh chunk transaction starts from.
|
||||
struct PromptInit {
|
||||
origin: TargetStepOrigin,
|
||||
rows: Vec<Row>,
|
||||
witnesses: Vec<ChunkRowResidual>,
|
||||
}
|
||||
/// The step origin of a prompt of `count` tokens, which must fit the bound session (64 rows, 256 windowed).
|
||||
fn prompt_origin(
|
||||
session: &QwenSession<'_>,
|
||||
binding: &ModelBinding,
|
||||
count: usize,
|
||||
windowed: bool,
|
||||
) -> Result<TargetStepOrigin> {
|
||||
let limit = if windowed { 256 } else { 64 };
|
||||
let origin = session.target_origin()?;
|
||||
if !session.binding.matches(&binding.identity()) || session.layer_count != 48 || count == 0 || count > limit {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
Ok(origin)
|
||||
}
|
||||
/// The end position of the prompt, which must stay below the model context and the served cells.
|
||||
fn prompt_end(session: &QwenSession<'_>, binding: &ModelBinding, count: usize) -> Result<(u64, Dimension)> {
|
||||
let end = session.next_position.checked_add(count as u64).ok_or(Error::Overflow)?;
|
||||
let context_bound = Dimension::new(u64::from(binding.input_constants().context_length()))?;
|
||||
if end >= u64::from(context_bound.get()) || end >= crate::qwen_forward::contract::serving_cells() {
|
||||
return Err(Error::InvalidPosition);
|
||||
}
|
||||
Ok((end, context_bound))
|
||||
}
|
||||
/// Every token is in the vocabulary, the host charge fits what remains, and the device budget keeps its reserve.
|
||||
fn admit_prompt_host(
|
||||
session: &QwenSession<'_>,
|
||||
tokens: &[TokenId],
|
||||
known_next: Option<TokenId>,
|
||||
(end, host_remaining, windowed): (u64, usize, bool),
|
||||
) -> Result<()> {
|
||||
let vocab = Dimension::new(248320)?;
|
||||
for token in tokens.iter().copied().chain(known_next) {
|
||||
if token != TokenId::new(u64::from(token.get()), vocab)? {
|
||||
return Err(Error::InvalidToken);
|
||||
}
|
||||
}
|
||||
let charge = if windowed { host_charge_bounded(tokens.len(), end, 256)? } else { host_charge(tokens.len(), end)? };
|
||||
if charge > host_remaining {
|
||||
return Err(Error::InputAllocation);
|
||||
}
|
||||
let context = session.mtp_context()?;
|
||||
if context.allocated_bytes().checked_add(128 * 1024 * 1024).is_none_or(|n| n > context.budget_bytes()) {
|
||||
return Err(Error::InputAllocation);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// One row per token with its position and the two tokens before it; the witnesses start empty.
|
||||
fn prompt_rows(
|
||||
session: &QwenSession<'_>,
|
||||
tokens: &[TokenId],
|
||||
context_bound: Dimension,
|
||||
) -> Result<(Vec<Row>, Vec<ChunkRowResidual>)> {
|
||||
let mut rows = Vec::new();
|
||||
rows.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut witnesses = Vec::new();
|
||||
witnesses.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut predecessors = session.predecessors;
|
||||
for (index, token) in tokens.iter().copied().enumerate() {
|
||||
let position = Position::new(session.next_position + index as u64, context_bound)?;
|
||||
rows.push(Row { token, position, predecessors, input: None, completed: 0 });
|
||||
predecessors = [predecessors[1], i32::try_from(token.get()).map_err(|_| Error::InvalidToken)?];
|
||||
}
|
||||
Ok((rows, witnesses))
|
||||
}
|
||||
|
||||
+69
-41
@@ -4,8 +4,8 @@
|
||||
use super::*;
|
||||
|
||||
impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
pub(in crate::qwen_forward) fn open_micro_window(&mut self, layer: LayerId) -> Result<ChunkMicroWindow> {
|
||||
self.check()?;
|
||||
/// A micro window opens only on an idle windowed transaction, at the cursor, for the current layer.
|
||||
fn check_micro_open(&self, layer: LayerId) -> Result<()> {
|
||||
if self.gdn_chunk.as_ref().is_some_and(|journal| journal.start.0.layer != layer) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
@@ -26,10 +26,20 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let first = self.micro_cursor;
|
||||
Ok(())
|
||||
}
|
||||
fn micro_width(&self) -> usize {
|
||||
#[cfg(not(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
|
||||
let width = 64;
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
let width = self.test_micro_width;
|
||||
width
|
||||
}
|
||||
pub(in crate::qwen_forward) fn open_micro_window(&mut self, layer: LayerId) -> Result<ChunkMicroWindow> {
|
||||
self.check()?;
|
||||
self.check_micro_open(layer)?;
|
||||
let first = self.micro_cursor;
|
||||
let width = self.micro_width();
|
||||
if !(1..=64).contains(&width) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
@@ -41,9 +51,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
self.active_micro = Some(ActiveMicroWindow { proof: Rc::clone(&proof), layer, first, end });
|
||||
Ok(ChunkMicroWindow { chunk: Rc::clone(&self.chunk), proof, layer, first, end })
|
||||
}
|
||||
/// Consumes the exact minted capability; no next range can open early.
|
||||
pub(in crate::qwen_forward) fn close_micro_window(&mut self, window: ChunkMicroWindow) -> Result<()> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
/// The window is exactly the minted capability, the range is fully computed and no phase is in flight.
|
||||
fn check_micro_close(&self, window: &ChunkMicroWindow, first: usize, end: usize) -> Result<()> {
|
||||
let active = self.active_micro.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
if !Rc::ptr_eq(&self.chunk, &window.chunk)
|
||||
|| !Rc::ptr_eq(&active.proof, &window.proof)
|
||||
@@ -61,6 +70,23 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The infallible cursor transition after a window closed; the last window moves to the next layer.
|
||||
fn advance_micro(&mut self, end: usize) {
|
||||
self.active_micro = None;
|
||||
self.micro_cursor = end;
|
||||
if end == self.rows.len() {
|
||||
self.next_layer += 1;
|
||||
self.micro_cursor = 0;
|
||||
self.next_row = 0;
|
||||
self.attention_next = 0;
|
||||
}
|
||||
}
|
||||
/// Consumes the exact minted capability; no next range can open early.
|
||||
pub(in crate::qwen_forward) fn close_micro_window(&mut self, window: ChunkMicroWindow) -> Result<()> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
self.check_micro_close(&window, first, end)?;
|
||||
if let Some(journal) = &self.gdn_chunk
|
||||
&& (journal.start.0.layer != window.layer || journal.accepted != end)
|
||||
{
|
||||
@@ -79,14 +105,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
// all capability checks, before the infallible cursor transition.
|
||||
self.test_window_journal.push((self.next_layer, first, end));
|
||||
}
|
||||
self.active_micro = None;
|
||||
self.micro_cursor = end;
|
||||
if end == self.rows.len() {
|
||||
self.next_layer += 1;
|
||||
self.micro_cursor = 0;
|
||||
self.next_row = 0;
|
||||
self.attention_next = 0;
|
||||
}
|
||||
self.advance_micro(end);
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
@@ -109,11 +128,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
&self.test_window_journal
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn test_observe_first_layer(
|
||||
&mut self,
|
||||
residuals: &[Option<InjectedResidual>],
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
fn check_first_layer(&self, residuals: &[Option<InjectedResidual>]) -> Result<()> {
|
||||
if !self.windowed
|
||||
|| self.next_layer != 1
|
||||
|| self.next_row != 0
|
||||
@@ -125,7 +140,11 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let layer = LayerId::new(0, Dimension::new(48)?)?;
|
||||
Ok(())
|
||||
}
|
||||
/// Every first-layer residual carries the row identity and finite streams; returns their total word count.
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn first_layer_words(&self, residuals: &[Option<InjectedResidual>], layer: LayerId) -> Result<usize> {
|
||||
let mut words = 0usize;
|
||||
for (index, residual) in residuals.iter().enumerate() {
|
||||
let residual = residual.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
@@ -137,24 +156,39 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
}
|
||||
words = words.checked_add(residual.streams().len()).ok_or(Error::Overflow)?;
|
||||
}
|
||||
let end = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?;
|
||||
Ok(words)
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn validate_first_layer_prior(&self, layer: LayerId, end: Position) -> Result<()> {
|
||||
if self.session.gdn_layers[0] {
|
||||
self.next_gdn[0].as_ref().ok_or(Error::IdentityMismatch)?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.gdn_owner,
|
||||
layer,
|
||||
end,
|
||||
)?;
|
||||
)
|
||||
} else if self.session.qsa_layers[0] {
|
||||
self.next_qsa[0].as_ref().ok_or(Error::IdentityMismatch)?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.qsa_owner,
|
||||
layer,
|
||||
end,
|
||||
)?;
|
||||
)
|
||||
} else {
|
||||
return Err(Error::InvalidLayer);
|
||||
Err(Error::InvalidLayer)
|
||||
}
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn test_observe_first_layer(
|
||||
&mut self,
|
||||
residuals: &[Option<InjectedResidual>],
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
self.check_first_layer(residuals)?;
|
||||
let layer = LayerId::new(0, Dimension::new(48)?)?;
|
||||
let words = self.first_layer_words(residuals, layer)?;
|
||||
let end = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?;
|
||||
self.validate_first_layer_prior(layer, end)?;
|
||||
self.test_partial_words = words;
|
||||
Ok(())
|
||||
}
|
||||
@@ -170,11 +204,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
self.check()?;
|
||||
self.session.mtp_context()
|
||||
}
|
||||
/// The genuine rolling state at this prompt micro's first causal row.
|
||||
/// Store an actual initial empty owner once; later validation compares the
|
||||
/// same Rc state, not a reconstructed position or a batch's final state.
|
||||
/// The QSA slot of `layer` and the first row of the active micro window, once every phase cursor agrees.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn prompt_qsa_prior(&mut self, layer: LayerId) -> Result<QsaIndexPrior> {
|
||||
fn prompt_qsa_slot(&self, layer: LayerId) -> Result<(usize, usize)> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
let slot = layer.get() as usize;
|
||||
if slot >= STATE_CAPACITY
|
||||
@@ -188,6 +220,14 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok((slot, first))
|
||||
}
|
||||
/// The genuine rolling state at this prompt micro's first causal row.
|
||||
/// Store an actual initial empty owner once; later validation compares the
|
||||
/// same Rc state, not a reconstructed position or a batch's final state.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn prompt_qsa_prior(&mut self, layer: LayerId) -> Result<QsaIndexPrior> {
|
||||
let (slot, first) = self.prompt_qsa_slot(layer)?;
|
||||
let position = self.rows.get(first).ok_or(Error::InvalidPosition)?.position;
|
||||
if self.next_qsa[slot].is_none() {
|
||||
if position.get() != 0 {
|
||||
@@ -208,19 +248,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
layer: LayerId,
|
||||
kv: &leleka_cuda_driver::QsaPromptKv<'_>,
|
||||
) -> Result<QsaIndexPrior> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
let slot = layer.get() as usize;
|
||||
if slot >= STATE_CAPACITY
|
||||
|| !self.session.qsa_layers[slot]
|
||||
|| self.next_layer != layer.get()
|
||||
|| self.next_row != first
|
||||
|| self.attention_layer != Some(layer)
|
||||
|| self.attention_next != end
|
||||
|| self.batch_layer.is_some()
|
||||
|| self.attention_authorized.is_some()
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let (slot, first) = self.prompt_qsa_slot(layer)?;
|
||||
kv.validate_context(self.session.mtp_context()?)
|
||||
.map_err(super::super::super::super::qsa_index::driver_error)?;
|
||||
let position = self.rows.get(first).ok_or(Error::InvalidPosition)?.position;
|
||||
|
||||
+63
-57
@@ -57,11 +57,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
self.validate_row(witness)?;
|
||||
Ok(())
|
||||
}
|
||||
pub(in crate::qwen_forward) fn validate_row<'a>(
|
||||
&self,
|
||||
witness: &'a ChunkRowResidual,
|
||||
) -> Result<(TokenId, Position, Option<TokenId>, &'a [f32])> {
|
||||
self.check()?;
|
||||
/// The witness belongs to this finished, non-GDN-chunk transaction and its step origin is still live.
|
||||
fn check_witness(&self, witness: &ChunkRowResidual) -> Result<()> {
|
||||
if self.gdn_chunk.is_some()
|
||||
|| !self.finished
|
||||
|| !witness.binding.matches(&self.session.binding)
|
||||
@@ -70,7 +67,14 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
witness.origin.validate(self.session)?;
|
||||
witness.origin.validate(self.session)
|
||||
}
|
||||
pub(in crate::qwen_forward) fn validate_row<'a>(
|
||||
&self,
|
||||
witness: &'a ChunkRowResidual,
|
||||
) -> Result<(TokenId, Position, Option<TokenId>, &'a [f32])> {
|
||||
self.check()?;
|
||||
self.check_witness(witness)?;
|
||||
let index = usize::try_from(
|
||||
witness.position.get().checked_sub(self.session.next_position).ok_or(Error::InvalidPosition)?,
|
||||
)
|
||||
@@ -97,8 +101,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
self.rows.len()
|
||||
}
|
||||
|
||||
pub(in crate::qwen_forward) fn begin_gdn_chunk(&mut self, layer: LayerId) -> Result<GdnChunkStart> {
|
||||
self.check()?;
|
||||
/// A GDN chunk begins on an idle windowed transaction at row 0 of a GDN layer; returns the layer slot.
|
||||
fn gdn_begin_slot(&self, layer: LayerId) -> Result<usize> {
|
||||
let slot = layer.get() as usize;
|
||||
if !self.windowed
|
||||
|| self.gdn_chunk.is_some()
|
||||
@@ -112,13 +116,23 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let first = self.rows.first().ok_or(Error::InvalidPosition)?.position;
|
||||
Ok(slot)
|
||||
}
|
||||
/// The rolling GDN state at the first row: the retained prior, or the zero state at position 0.
|
||||
fn gdn_begin_prior(&self, slot: usize, layer: LayerId, first: Position) -> Result<GdnPrior> {
|
||||
let prior = match &self.next_gdn[slot] {
|
||||
Some(prior) => prior.clone(),
|
||||
None if first.get() == 0 => GdnPrior::zero(self.session.binding.clone(), &self.session.gdn_owner, layer)?,
|
||||
None => return Err(Error::IdentityMismatch),
|
||||
};
|
||||
prior.validate(&self.session.binding, &self.session.gdn_owner, layer, first)?;
|
||||
Ok(prior)
|
||||
}
|
||||
pub(in crate::qwen_forward) fn begin_gdn_chunk(&mut self, layer: LayerId) -> Result<GdnChunkStart> {
|
||||
self.check()?;
|
||||
let slot = self.gdn_begin_slot(layer)?;
|
||||
let first = self.rows.first().ok_or(Error::InvalidPosition)?.position;
|
||||
let prior = self.gdn_begin_prior(slot, layer, first)?;
|
||||
let start = GdnChunkStart(Rc::new(GdnChunkAnchor {
|
||||
binding: self.session.binding.clone(),
|
||||
chunk: self.chunk.clone(),
|
||||
@@ -132,61 +146,53 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
self.gdn_chunk = Some(GdnChunkJournal { start: start.clone(), accepted: 0 });
|
||||
Ok(start)
|
||||
}
|
||||
/// Every row of the chunk completed the layer and no phase is in flight.
|
||||
fn gdn_finish_ready(&self, journal: &GdnChunkJournal, layer: LayerId) -> bool {
|
||||
Rc::ptr_eq(&self.chunk, &journal.start.0.chunk)
|
||||
&& self.active_micro.is_none()
|
||||
&& self.micro_cursor == 0
|
||||
&& self.next_row == 0
|
||||
&& self.next_layer == layer.get() + 1
|
||||
&& journal.accepted == self.rows.len()
|
||||
&& self.batch_layer.is_none()
|
||||
&& self.attention_layer.is_none()
|
||||
&& self.attention_authorized.is_none()
|
||||
&& self.rows.iter().all(|row| row.completed == layer.get() + 1)
|
||||
}
|
||||
/// The seal of the journaled chunk once every row completed the layer; otherwise the transaction aborts.
|
||||
fn begin_gdn_finish(&mut self) -> Result<(GdnChunkSeal, LayerId)> {
|
||||
self.check()?;
|
||||
let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let layer = journal.start.0.layer;
|
||||
if !self.gdn_finish_ready(journal, layer) {
|
||||
self.aborted = true;
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok((GdnChunkSeal { start: journal.start.clone() }, layer))
|
||||
}
|
||||
pub(in crate::qwen_forward) fn finish_gdn_chunk<'ctx>(
|
||||
&mut self,
|
||||
owner: super::super::super::super::gdn::chunk_device::GdnChunkDevice<'ctx>,
|
||||
binding: &ModelBinding,
|
||||
cache: &super::super::super::super::dense_weight_cache::DenseWeightCache<'ctx>,
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let layer = journal.start.0.layer;
|
||||
if !Rc::ptr_eq(&self.chunk, &journal.start.0.chunk)
|
||||
|| self.active_micro.is_some()
|
||||
|| self.micro_cursor != 0
|
||||
|| self.next_row != 0
|
||||
|| self.next_layer != layer.get() + 1
|
||||
|| journal.accepted != self.rows.len()
|
||||
|| self.batch_layer.is_some()
|
||||
|| self.attention_layer.is_some()
|
||||
|| self.attention_authorized.is_some()
|
||||
|| self.rows.iter().any(|row| row.completed != layer.get() + 1)
|
||||
{
|
||||
self.aborted = true;
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let seal = GdnChunkSeal { start: journal.start.clone() };
|
||||
if owner.is_verification() {
|
||||
let result = owner.finish_verification(seal, binding, cache);
|
||||
if let Err(error) = &result {
|
||||
self.session.note_mtp_failure(error);
|
||||
self.aborted = true;
|
||||
}
|
||||
result?;
|
||||
self.gdn_chunk = None;
|
||||
return Ok(());
|
||||
}
|
||||
let result = owner.finish(seal, binding, cache).and_then(|prior| {
|
||||
prior.validate(
|
||||
&self.session.binding,
|
||||
&self.session.gdn_owner,
|
||||
layer,
|
||||
Position::new(self.end, crate::qwen_forward::contract::position_dimension())?,
|
||||
)?;
|
||||
Ok(prior)
|
||||
});
|
||||
match result {
|
||||
Ok(prior) => {
|
||||
self.next_gdn[layer.get() as usize] = Some(prior);
|
||||
self.gdn_chunk = None;
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
self.session.note_mtp_failure(&error);
|
||||
self.aborted = true;
|
||||
Err(error)
|
||||
}
|
||||
let (seal, layer) = self.begin_gdn_finish()?;
|
||||
// A verification finish keeps its state on the device; a plain finish yields the validated prior.
|
||||
let finished = if owner.is_verification() {
|
||||
owner.finish_verification(seal, binding, cache).map(|()| None)
|
||||
} else {
|
||||
owner.finish(seal, binding, cache).and_then(|prior| {
|
||||
let end = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?;
|
||||
prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)?;
|
||||
Ok(Some(prior))
|
||||
})
|
||||
};
|
||||
self.settle_failure(&finished);
|
||||
if let Some(prior) = finished? {
|
||||
self.next_gdn[layer.get() as usize] = Some(prior);
|
||||
}
|
||||
self.gdn_chunk = None;
|
||||
Ok(())
|
||||
}
|
||||
// Ephemeral, private stage view: shares real binding/Context/state owners,
|
||||
// never publishes or mints a TargetStepOrigin. Its unused layer states
|
||||
|
||||
+164
-122
@@ -1,5 +1,7 @@
|
||||
//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (4).
|
||||
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
use super::super::super::super::gr::{DetachedGrRead, GrMicroInput};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -28,17 +30,16 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Read immutable PLE inputs from the actual current layer-one window.
|
||||
/// This grants no pending history and advances no causal cursor. The
|
||||
/// batch producer still has to complete; chronological consumption below
|
||||
/// validates each pending history against the genuine rolling prior.
|
||||
/// A failed result poisons the MTP device state (when it is a CUDA failure) and aborts the transaction.
|
||||
pub(super) fn settle_failure<T>(&mut self, result: &Result<T>) {
|
||||
if let Err(error) = result {
|
||||
self.session.note_mtp_failure(error);
|
||||
self.aborted = true;
|
||||
}
|
||||
}
|
||||
/// The layer-one PLE window is complete, idle and has no device GDN lease.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn prepare_ple_micro_inputs<T>(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
mut prepare: impl FnMut(usize, &QwenStepTxn<'_, 'driver>) -> Result<T>,
|
||||
) -> Result<(PlePrior, Vec<T>)> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
fn check_ple_micro(&self, layer: LayerId, first: usize, end: usize) -> Result<()> {
|
||||
if layer.get() != 1
|
||||
|| self.next_layer != 1
|
||||
|| self.next_row != first
|
||||
@@ -51,49 +52,52 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let result = (|| {
|
||||
let prior = self.next_ple.clone().ok_or(Error::Unsupported(Stage::Input))?;
|
||||
if prior.next_position() != self.rows[first].position.get() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut inputs = Vec::new();
|
||||
inputs.try_reserve_exact(end - first).map_err(|_| Error::InputAllocation)?;
|
||||
for index in first..end {
|
||||
let mut view = self.stage_view(index)?;
|
||||
let row = &self.rows[index];
|
||||
let mut step = view.begin(row.token, row.position)?;
|
||||
step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = row.completed;
|
||||
if index == first {
|
||||
step.validate_ple_prior(&prior)?;
|
||||
}
|
||||
inputs.push(prepare(index, &step)?);
|
||||
}
|
||||
Ok((prior, inputs))
|
||||
})();
|
||||
if let Err(error) = &result {
|
||||
self.session.note_mtp_failure(error);
|
||||
self.aborted = true;
|
||||
}
|
||||
result
|
||||
Ok(())
|
||||
}
|
||||
/// Prepare one genuine micro-window chronologically, then complete its GR
|
||||
/// reads as one device batch. PLE remains causal: each real pending history
|
||||
/// is admitted before preparing the following position. None of the GR row
|
||||
/// capabilities is published until the entire actual batch has completed.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn read_attention_micro(
|
||||
fn ple_micro_inputs<T>(
|
||||
&self,
|
||||
(first, end): (usize, usize),
|
||||
mut prepare: impl FnMut(usize, &QwenStepTxn<'_, 'driver>) -> Result<T>,
|
||||
) -> Result<(PlePrior, Vec<T>)> {
|
||||
let prior = self.next_ple.clone().ok_or(Error::Unsupported(Stage::Input))?;
|
||||
if prior.next_position() != self.rows[first].position.get() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut inputs = Vec::new();
|
||||
inputs.try_reserve_exact(end - first).map_err(|_| Error::InputAllocation)?;
|
||||
for index in first..end {
|
||||
let mut view = self.stage_view(index)?;
|
||||
let row = &self.rows[index];
|
||||
let mut step = view.begin(row.token, row.position)?;
|
||||
step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = row.completed;
|
||||
if index == first {
|
||||
step.validate_ple_prior(&prior)?;
|
||||
}
|
||||
inputs.push(prepare(index, &step)?);
|
||||
}
|
||||
Ok((prior, inputs))
|
||||
}
|
||||
/// Read immutable PLE inputs from the actual current layer-one window.
|
||||
/// This grants no pending history and advances no causal cursor. The
|
||||
/// batch producer still has to complete; chronological consumption below
|
||||
/// validates each pending history against the genuine rolling prior.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn prepare_ple_micro_inputs<T>(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
mut prepare: impl FnMut(
|
||||
usize,
|
||||
&mut QwenStepTxn<'_, 'driver>,
|
||||
) -> Result<super::super::super::super::gr::GrMicroInput>,
|
||||
execute: impl FnOnce(
|
||||
Vec<super::super::super::super::gr::GrMicroInput>,
|
||||
) -> Result<Vec<super::super::super::super::gr::DetachedGrRead>>,
|
||||
) -> Result<Vec<ChunkAttentionRow>> {
|
||||
prepare: impl FnMut(usize, &QwenStepTxn<'_, 'driver>) -> Result<T>,
|
||||
) -> Result<(PlePrior, Vec<T>)> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
self.check_ple_micro(layer, first, end)?;
|
||||
let result = self.ple_micro_inputs((first, end), prepare);
|
||||
self.settle_failure(&result);
|
||||
result
|
||||
}
|
||||
/// The micro window is the next causal range of `layer`, with every row complete up to the layer before it.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn check_attention_micro(&self, layer: LayerId, first: usize, end: usize) -> Result<()> {
|
||||
if layer.get() != self.next_layer
|
||||
|| layer.get() >= 48
|
||||
|| self.next_row != first
|
||||
@@ -105,81 +109,119 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let result = (|| {
|
||||
if self.attention_layer.is_none() {
|
||||
self.attention_sources.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
|
||||
self.attention_sources.resize_with(self.rows.len(), || None);
|
||||
self.attention_layer = Some(layer);
|
||||
}
|
||||
if self.attention_sources.len() != self.rows.len()
|
||||
|| self.attention_sources[first..end].iter().any(Option::is_some)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut inputs = Vec::new();
|
||||
inputs.try_reserve_exact(end - first).map_err(|_| Error::InputAllocation)?;
|
||||
for index in first..end {
|
||||
if self.attention_next != index {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut view = self.stage_view(index)?;
|
||||
let row = &self.rows[index];
|
||||
let token = row.token;
|
||||
let position = row.position;
|
||||
let mut step = view.begin(token, position)?;
|
||||
step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = row.completed;
|
||||
let input = prepare(index, &mut step)?;
|
||||
input.validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?;
|
||||
input.identity().validate(token, position, layer)?;
|
||||
if layer.get() == 1 && self.session.ple_required {
|
||||
let next = step.ple_pending.take().ok_or(Error::Unsupported(Stage::Input))?.into_prior();
|
||||
if next.next_position() != position.get() + 1 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.next_ple = Some(next);
|
||||
self.record_verification_ple(index, position)?;
|
||||
} else if step.ple_pending.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if step.gdn_pending.iter().any(Option::is_some) || step.qsa_pending.iter().any(Option::is_some) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
inputs.push(input);
|
||||
self.attention_next += 1;
|
||||
}
|
||||
let reads = execute(inputs)?;
|
||||
if reads.len() != end - first || self.attention_next != end {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
// Validate every completed producer before publishing even the
|
||||
// first row. Token/position/role come from this actual transaction.
|
||||
for (row, read) in self.rows[first..end].iter().zip(&reads) {
|
||||
read.ready().validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?;
|
||||
read.ready().identity().validate(row.token, row.position, layer)?;
|
||||
}
|
||||
let mut completed = Vec::new();
|
||||
completed.try_reserve_exact(reads.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, read) in (first..end).zip(reads) {
|
||||
let proof = Rc::new(());
|
||||
let read = Rc::new(read);
|
||||
self.attention_sources[index] =
|
||||
Some(AttentionSource { proof: Rc::clone(&proof), read: Rc::clone(&read) });
|
||||
completed.push(ChunkAttentionRow {
|
||||
chunk: Rc::clone(&self.chunk),
|
||||
proof,
|
||||
index,
|
||||
layer,
|
||||
read,
|
||||
window: self.window_proof(),
|
||||
});
|
||||
}
|
||||
Ok(completed)
|
||||
})();
|
||||
if let Err(error) = &result {
|
||||
self.session.note_mtp_failure(error);
|
||||
self.aborted = true;
|
||||
Ok(())
|
||||
}
|
||||
/// Allocate the per-row source slots on the first window of the layer; the window must still be unread.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn admit_attention_sources(&mut self, layer: LayerId, first: usize, end: usize) -> Result<()> {
|
||||
self.open_attention_sources(layer)?;
|
||||
if self.attention_sources.len() != self.rows.len()
|
||||
|| self.attention_sources[first..end].iter().any(Option::is_some)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn attention_micro_row(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
index: usize,
|
||||
prepare: &mut impl FnMut(usize, &mut QwenStepTxn<'_, 'driver>) -> Result<GrMicroInput>,
|
||||
) -> Result<GrMicroInput> {
|
||||
if self.attention_next != index {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut view = self.stage_view(index)?;
|
||||
let row = &self.rows[index];
|
||||
let token = row.token;
|
||||
let position = row.position;
|
||||
let mut step = view.begin(token, position)?;
|
||||
step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = row.completed;
|
||||
let input = prepare(index, &mut step)?;
|
||||
input.validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?;
|
||||
input.identity().validate(token, position, layer)?;
|
||||
self.admit_row_ple(&mut step, layer, (index, position))?;
|
||||
self.attention_next += 1;
|
||||
Ok(input)
|
||||
}
|
||||
/// Every row of the window is prepared chronologically; the device batch has not run yet.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn attention_micro_inputs(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
(first, end): (usize, usize),
|
||||
mut prepare: impl FnMut(usize, &mut QwenStepTxn<'_, 'driver>) -> Result<GrMicroInput>,
|
||||
) -> Result<Vec<GrMicroInput>> {
|
||||
let mut inputs = Vec::new();
|
||||
inputs.try_reserve_exact(end - first).map_err(|_| Error::InputAllocation)?;
|
||||
for index in first..end {
|
||||
inputs.push(self.attention_micro_row(layer, index, &mut prepare)?);
|
||||
}
|
||||
Ok(inputs)
|
||||
}
|
||||
/// Validate every completed producer before publishing even the
|
||||
/// first row. Token/position/role come from this actual transaction.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn check_attention_reads(
|
||||
&self,
|
||||
layer: LayerId,
|
||||
(first, end): (usize, usize),
|
||||
reads: &[DetachedGrRead],
|
||||
) -> Result<()> {
|
||||
if reads.len() != end - first || self.attention_next != end {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
for (row, read) in self.rows[first..end].iter().zip(reads) {
|
||||
read.ready().validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?;
|
||||
read.ready().identity().validate(row.token, row.position, layer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn publish_attention_rows(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
first: usize,
|
||||
reads: Vec<DetachedGrRead>,
|
||||
) -> Result<Vec<ChunkAttentionRow>> {
|
||||
let mut completed = Vec::new();
|
||||
completed.try_reserve_exact(reads.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, read) in (first..first + reads.len()).zip(reads) {
|
||||
completed.push(self.publish_attention_source(layer, index, read));
|
||||
}
|
||||
Ok(completed)
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn attention_micro_rows(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
span: (usize, usize),
|
||||
prepare: impl FnMut(usize, &mut QwenStepTxn<'_, 'driver>) -> Result<GrMicroInput>,
|
||||
execute: impl FnOnce(Vec<GrMicroInput>) -> Result<Vec<DetachedGrRead>>,
|
||||
) -> Result<Vec<ChunkAttentionRow>> {
|
||||
self.admit_attention_sources(layer, span.0, span.1)?;
|
||||
let inputs = self.attention_micro_inputs(layer, span, prepare)?;
|
||||
let reads = execute(inputs)?;
|
||||
self.check_attention_reads(layer, span, &reads)?;
|
||||
self.publish_attention_rows(layer, span.0, reads)
|
||||
}
|
||||
/// Prepare one genuine micro-window chronologically, then complete its GR
|
||||
/// reads as one device batch. PLE remains causal: each real pending history
|
||||
/// is admitted before preparing the following position. None of the GR row
|
||||
/// capabilities is published until the entire actual batch has completed.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn read_attention_micro(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
prepare: impl FnMut(usize, &mut QwenStepTxn<'_, 'driver>) -> Result<GrMicroInput>,
|
||||
execute: impl FnOnce(Vec<GrMicroInput>) -> Result<Vec<DetachedGrRead>>,
|
||||
) -> Result<Vec<ChunkAttentionRow>> {
|
||||
let span = self.phase_span()?;
|
||||
self.check_attention_micro(layer, span.0, span.1)?;
|
||||
let result = self.attention_micro_rows(layer, span, prepare, execute);
|
||||
self.settle_failure(&result);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
+78
-59
@@ -1,16 +1,16 @@
|
||||
//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (5).
|
||||
|
||||
use super::super::super::super::gr::DetachedGrRead;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The prepared MoE row and chunk edge of a device-GDN attention FFN.
|
||||
type DeviceGdnFfn =
|
||||
(super::super::super::super::moe_expert::PreparedMoeRow, super::super::super::super::gdn::chunk_device::ChunkEdge);
|
||||
|
||||
impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
pub(in crate::qwen_forward) fn read_attention_column(
|
||||
&mut self,
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result<super::super::super::super::gr::DetachedGrRead>,
|
||||
) -> Result<ChunkAttentionRow> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
/// The column is the next causal row of `layer` inside the active phase.
|
||||
fn check_attention_column(&self, index: usize, layer: LayerId, (first, end): (usize, usize)) -> Result<()> {
|
||||
if layer.get() != self.next_layer
|
||||
|| layer.get() >= 48
|
||||
|| self.next_row != first
|
||||
@@ -23,11 +23,59 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Allocate the per-row source slots on the first read of the layer.
|
||||
pub(super) fn open_attention_sources(&mut self, layer: LayerId) -> Result<()> {
|
||||
if self.attention_layer.is_none() {
|
||||
self.attention_sources.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
|
||||
self.attention_sources.resize_with(self.rows.len(), || None);
|
||||
self.attention_layer = Some(layer);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// PLE history is admitted at layer one only, and no GDN or QSA history may be pending yet.
|
||||
pub(super) fn admit_row_ple(
|
||||
&mut self,
|
||||
step: &mut QwenStepTxn<'_, 'driver>,
|
||||
layer: LayerId,
|
||||
(index, position): (usize, Position),
|
||||
) -> Result<()> {
|
||||
if layer.get() == 1 && self.session.ple_required {
|
||||
let next = step.ple_pending.take().ok_or(Error::Unsupported(Stage::Input))?.into_prior();
|
||||
if next.next_position() != position.get() + 1 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.next_ple = Some(next);
|
||||
self.record_verification_ple(index, position)?;
|
||||
} else if step.ple_pending.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if step.gdn_pending.iter().any(Option::is_some) || step.qsa_pending.iter().any(Option::is_some) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Mint the row capability for a completed read and record its source.
|
||||
pub(super) fn publish_attention_source(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
index: usize,
|
||||
read: DetachedGrRead,
|
||||
) -> ChunkAttentionRow {
|
||||
let proof = Rc::new(());
|
||||
let read = Rc::new(read);
|
||||
self.attention_sources[index] = Some(AttentionSource { proof: Rc::clone(&proof), read: Rc::clone(&read) });
|
||||
ChunkAttentionRow { chunk: Rc::clone(&self.chunk), proof, index, layer, read, window: self.window_proof() }
|
||||
}
|
||||
pub(in crate::qwen_forward) fn read_attention_column(
|
||||
&mut self,
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result<DetachedGrRead>,
|
||||
) -> Result<ChunkAttentionRow> {
|
||||
self.check_attention_column(index, layer, self.phase_span()?)?;
|
||||
self.open_attention_sources(layer)?;
|
||||
let mut view = self.stage_view(index)?;
|
||||
let row = &self.rows[index];
|
||||
let position = row.position;
|
||||
@@ -37,43 +85,16 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
let result = execute(&mut step).and_then(|read| {
|
||||
read.ready().validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?;
|
||||
read.ready().identity().validate(step.token(), position, layer)?;
|
||||
if layer.get() == 1 && self.session.ple_required {
|
||||
let next = step.ple_pending.take().ok_or(Error::Unsupported(Stage::Input))?.into_prior();
|
||||
if next.next_position() != position.get() + 1 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.next_ple = Some(next);
|
||||
self.record_verification_ple(index, position)?;
|
||||
} else if step.ple_pending.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if step.gdn_pending.iter().any(Option::is_some) || step.qsa_pending.iter().any(Option::is_some) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.admit_row_ple(&mut step, layer, (index, position))?;
|
||||
Ok(read)
|
||||
});
|
||||
match result {
|
||||
Ok(read) => {
|
||||
let proof = Rc::new(());
|
||||
let read = Rc::new(read);
|
||||
self.attention_sources[index] =
|
||||
Some(AttentionSource { proof: Rc::clone(&proof), read: Rc::clone(&read) });
|
||||
self.attention_next += 1;
|
||||
Ok(ChunkAttentionRow {
|
||||
chunk: Rc::clone(&self.chunk),
|
||||
proof,
|
||||
index,
|
||||
layer,
|
||||
read,
|
||||
window: self.window_proof(),
|
||||
})
|
||||
}
|
||||
Err(error) => {
|
||||
self.session.note_mtp_failure(&error);
|
||||
self.aborted = true;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
let result = result.map(|read| {
|
||||
let row = self.publish_attention_source(layer, index, read);
|
||||
self.attention_next += 1;
|
||||
row
|
||||
});
|
||||
self.settle_failure(&result);
|
||||
result
|
||||
}
|
||||
pub(in crate::qwen_forward) fn validate_attention_input(
|
||||
&self,
|
||||
@@ -117,7 +138,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
read: &ChunkAttentionRow,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &super::super::super::super::gr::DetachedGrRead) -> Result<T>,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &DetachedGrRead) -> Result<T>,
|
||||
) -> Result<(T, PreparedLayerRow)> {
|
||||
self.validate_attention_input(index, layer, read.ready())?;
|
||||
self.validate_window_proof(&read.window)?;
|
||||
@@ -153,22 +174,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
row.validate(&self.session.binding, self.rows[index].token, self.rows[index].position, layer)?;
|
||||
Ok(ChunkFfnRow { proof, row })
|
||||
}
|
||||
pub(in crate::qwen_forward) fn prepare_attention_ffn_device_gdn(
|
||||
&mut self,
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
read: &ChunkAttentionRow,
|
||||
execute: impl FnOnce(
|
||||
&mut QwenStepTxn<'_, 'driver>,
|
||||
&super::super::super::super::gr::DetachedGrRead,
|
||||
GdnChunkRow,
|
||||
) -> Result<(
|
||||
super::super::super::super::moe_expert::PreparedMoeRow,
|
||||
super::super::super::super::gdn::chunk_device::ChunkEdge,
|
||||
)>,
|
||||
) -> Result<ChunkFfnRow> {
|
||||
self.validate_attention_input(index, layer, read.ready())?;
|
||||
self.validate_window_proof(&read.window)?;
|
||||
/// The read is the live source of `index` and the GDN journal stands at that row: mint its chunk row.
|
||||
pub(super) fn gdn_ffn_row(&self, index: usize, layer: LayerId, read: &ChunkAttentionRow) -> Result<GdnChunkRow> {
|
||||
let source = self.attention_sources[index].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
if !Rc::ptr_eq(&self.chunk, &read.chunk)
|
||||
@@ -191,6 +198,18 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
key: Rc::new(()),
|
||||
};
|
||||
row.validate(&journal.start, index, &self.session.binding)?;
|
||||
Ok(row)
|
||||
}
|
||||
pub(in crate::qwen_forward) fn prepare_attention_ffn_device_gdn(
|
||||
&mut self,
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
read: &ChunkAttentionRow,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &DetachedGrRead, GdnChunkRow) -> Result<DeviceGdnFfn>,
|
||||
) -> Result<ChunkFfnRow> {
|
||||
self.validate_attention_input(index, layer, read.ready())?;
|
||||
self.validate_window_proof(&read.window)?;
|
||||
let row = self.gdn_ffn_row(index, layer, read)?;
|
||||
self.attention_authorized = Some(index);
|
||||
let result = self.prepare_layer_batch_internal(index, layer, |step| {
|
||||
execute(step, &read.read, row).map(|(v, e)| (v, Some(e)))
|
||||
|
||||
+135
-129
@@ -1,5 +1,7 @@
|
||||
//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (6).
|
||||
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
use super::super::super::super::{gdn::chunk_device::ChunkEdge, gr::DetachedGrRead};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -12,36 +14,11 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
read: &ChunkAttentionRow,
|
||||
execute: impl FnOnce(
|
||||
&mut QwenStepTxn<'_, 'driver>,
|
||||
&super::super::super::super::gr::DetachedGrRead,
|
||||
GdnChunkRow,
|
||||
) -> Result<(T, super::super::super::super::gdn::chunk_device::ChunkEdge)>,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &DetachedGrRead, GdnChunkRow) -> Result<(T, ChunkEdge)>,
|
||||
) -> Result<(T, PreparedLayerRow)> {
|
||||
self.validate_attention_input(index, layer, read.ready())?;
|
||||
self.validate_window_proof(&read.window)?;
|
||||
let source = self.attention_sources[index].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
if !Rc::ptr_eq(&self.chunk, &read.chunk)
|
||||
|| !Rc::ptr_eq(&source.proof, &read.proof)
|
||||
|| !Rc::ptr_eq(&source.read, &read.read)
|
||||
|| read.index != index
|
||||
|| read.layer != layer
|
||||
|| self.attention_authorized.is_some()
|
||||
|| journal.accepted != index
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let actual = &self.rows[index];
|
||||
let row = GdnChunkRow {
|
||||
start: journal.start.clone(),
|
||||
index,
|
||||
identity: TokenLayer::new(actual.token, actual.position, layer),
|
||||
proof: source.proof.clone(),
|
||||
window: read.window.clone(),
|
||||
key: Rc::new(()),
|
||||
};
|
||||
row.validate(&journal.start, index, &self.session.binding)?;
|
||||
let row = self.gdn_ffn_row(index, layer, read)?;
|
||||
self.attention_authorized = Some(index);
|
||||
let result = self.prepare_layer_batch_internal(index, layer, |step| {
|
||||
execute(step, &read.read, row).map(|(value, edge)| (value, Some(edge)))
|
||||
@@ -53,23 +30,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
result
|
||||
}
|
||||
|
||||
/// Complete the actual whole prompt GDN window before advancing any row
|
||||
/// edge. Only genuine per-row products/edges of that completed batch may
|
||||
/// then enter the ordinary current-transaction journal and GR producer.
|
||||
/// The GDN journal stands at the window's first row, the attention reads of the window are complete and
|
||||
/// no device lease or phase is in flight: returns the chunk start.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn prepare_attention_micro_gdn<T, R>(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
attention: &[ChunkAttentionRow],
|
||||
execute: impl FnOnce(&GdnChunkMicro, &Context<'driver>) -> Result<Vec<R>>,
|
||||
mut consume: impl FnMut(
|
||||
usize,
|
||||
&mut QwenStepTxn<'_, 'driver>,
|
||||
&super::super::super::super::gr::DetachedGrRead,
|
||||
R,
|
||||
) -> Result<(T, super::super::super::super::gdn::chunk_device::ChunkEdge)>,
|
||||
) -> Result<Vec<(T, PreparedLayerRow)>> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
fn gdn_micro_start(&self, layer: LayerId, (first, end): (usize, usize), count: usize) -> Result<GdnChunkStart> {
|
||||
let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
if self.device_gdn_lease()?.is_some()
|
||||
|| self.next_layer != layer.get()
|
||||
@@ -79,12 +43,22 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
|| self.attention_layer != Some(layer)
|
||||
|| self.attention_authorized.is_some()
|
||||
|| journal.accepted != first
|
||||
|| attention.len() != end - first
|
||||
|| !(1..=64).contains(&attention.len())
|
||||
|| count != end - first
|
||||
|| !(1..=64).contains(&count)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut micro = GdnChunkMicro { start: journal.start.clone(), first, rows: Vec::new(), reads: Vec::new() };
|
||||
Ok(journal.start.clone())
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn build_gdn_micro(
|
||||
&self,
|
||||
start: GdnChunkStart,
|
||||
layer: LayerId,
|
||||
first: usize,
|
||||
attention: &[ChunkAttentionRow],
|
||||
) -> Result<GdnChunkMicro> {
|
||||
let mut micro = GdnChunkMicro { start, first, rows: Vec::new(), reads: Vec::new() };
|
||||
micro.rows.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?;
|
||||
micro.reads.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (local, read) in attention.iter().enumerate() {
|
||||
@@ -102,47 +76,71 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
micro.reads.push(Rc::clone(&read.read));
|
||||
}
|
||||
micro.validate(µ.start, first, &self.session.binding)?;
|
||||
let result = (|| {
|
||||
let products = execute(µ, self.session.mtp_context()?)?;
|
||||
if products.len() != attention.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut completed = Vec::new();
|
||||
completed.try_reserve_exact(products.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (local, (read, product)) in attention.iter().zip(products).enumerate() {
|
||||
let index = first + local;
|
||||
self.validate_attention_column(index, layer, read)?;
|
||||
if self.gdn_chunk.as_ref().is_none_or(|journal| journal.accepted != index) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.attention_authorized = Some(index);
|
||||
let prepared = self.prepare_layer_batch_internal(index, layer, |step| {
|
||||
consume(local, step, &read.read, product).map(|(value, edge)| (value, Some(edge)))
|
||||
});
|
||||
self.attention_authorized = None;
|
||||
completed.push(prepared?);
|
||||
self.attention_sources[index] = None;
|
||||
}
|
||||
Ok(completed)
|
||||
})();
|
||||
if let Err(error) = &result {
|
||||
self.session.note_mtp_failure(error);
|
||||
self.aborted = true;
|
||||
Ok(micro)
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn consume_gdn_micro_row<T, R>(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
(local, index): (usize, usize),
|
||||
(read, product): (&ChunkAttentionRow, R),
|
||||
consume: &mut impl FnMut(usize, &mut QwenStepTxn<'_, 'driver>, &DetachedGrRead, R) -> Result<(T, ChunkEdge)>,
|
||||
) -> Result<(T, PreparedLayerRow)> {
|
||||
self.validate_attention_column(index, layer, read)?;
|
||||
if self.gdn_chunk.as_ref().is_none_or(|journal| journal.accepted != index) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.attention_authorized = Some(index);
|
||||
let prepared = self.prepare_layer_batch_internal(index, layer, |step| {
|
||||
consume(local, step, &read.read, product).map(|(value, edge)| (value, Some(edge)))
|
||||
});
|
||||
self.attention_authorized = None;
|
||||
let prepared = prepared?;
|
||||
self.attention_sources[index] = None;
|
||||
Ok(prepared)
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn run_gdn_micro<T, R>(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
attention: &[ChunkAttentionRow],
|
||||
(micro, execute): (&GdnChunkMicro, impl FnOnce(&GdnChunkMicro, &Context<'driver>) -> Result<Vec<R>>),
|
||||
mut consume: impl FnMut(usize, &mut QwenStepTxn<'_, 'driver>, &DetachedGrRead, R) -> Result<(T, ChunkEdge)>,
|
||||
) -> Result<Vec<(T, PreparedLayerRow)>> {
|
||||
let products = execute(micro, self.session.mtp_context()?)?;
|
||||
if products.len() != attention.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut completed = Vec::new();
|
||||
completed.try_reserve_exact(products.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (local, (read, product)) in attention.iter().zip(products).enumerate() {
|
||||
let index = micro.first + local;
|
||||
completed.push(self.consume_gdn_micro_row(layer, (local, index), (read, product), &mut consume)?);
|
||||
}
|
||||
Ok(completed)
|
||||
}
|
||||
/// Complete the actual whole prompt GDN window before advancing any row
|
||||
/// edge. Only genuine per-row products/edges of that completed batch may
|
||||
/// then enter the ordinary current-transaction journal and GR producer.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn prepare_attention_micro_gdn<T, R>(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
attention: &[ChunkAttentionRow],
|
||||
execute: impl FnOnce(&GdnChunkMicro, &Context<'driver>) -> Result<Vec<R>>,
|
||||
consume: impl FnMut(usize, &mut QwenStepTxn<'_, 'driver>, &DetachedGrRead, R) -> Result<(T, ChunkEdge)>,
|
||||
) -> Result<Vec<(T, PreparedLayerRow)>> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
let start = self.gdn_micro_start(layer, (first, end), attention.len())?;
|
||||
let micro = self.build_gdn_micro(start, layer, first, attention)?;
|
||||
let result = self.run_gdn_micro(layer, attention, (µ, execute), consume);
|
||||
self.settle_failure(&result);
|
||||
result
|
||||
}
|
||||
|
||||
/// Validate a completed causal row against the actual read it registered.
|
||||
/// The source has already left attention_sources, so the unique live
|
||||
/// prepared-row proof carries its original Rc into the later Out batch.
|
||||
/// The prepared row is the live Out batch row of the window: same chunk, layer, window and stored proof.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn validate_prepared_attention_input(
|
||||
&self,
|
||||
proof: &PreparedLayerRow,
|
||||
input: &super::super::super::super::gr::ResidualReady,
|
||||
) -> Result<()> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
self.validate_window_proof(&proof.window)?;
|
||||
pub(super) fn check_prepared_row(&self, proof: &PreparedLayerRow, (first, end): (usize, usize)) -> Result<()> {
|
||||
if proof.index < first
|
||||
|| proof.index >= end
|
||||
|| self.batch_layer != Some(proof.layer)
|
||||
@@ -158,6 +156,20 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Validate a completed causal row against the actual read it registered.
|
||||
/// The source has already left attention_sources, so the unique live
|
||||
/// prepared-row proof carries its original Rc into the later Out batch.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn validate_prepared_attention_input(
|
||||
&self,
|
||||
proof: &PreparedLayerRow,
|
||||
input: &super::super::super::super::gr::ResidualReady,
|
||||
) -> Result<()> {
|
||||
let span = self.phase_span()?;
|
||||
self.validate_window_proof(&proof.window)?;
|
||||
self.check_prepared_row(proof, span)?;
|
||||
let source = proof.attention_source.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
if !std::ptr::eq(source.ready(), input) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
@@ -170,17 +182,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
input.identity().validate(actual.token, actual.position, proof.layer)
|
||||
}
|
||||
|
||||
/// Enlist a fully completed Out row into GR using its real causal proof
|
||||
/// and current transaction, without advancing attention a second time.
|
||||
/// The Out source is the one the prepared row registered, in this chunk and layer.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn prepare_attention_output_after_causal<T>(
|
||||
&mut self,
|
||||
proof: &PreparedLayerRow,
|
||||
source: &ChunkAttentionRow,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &super::super::super::super::gr::DetachedGrRead) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
self.validate_prepared_attention_input(proof, source.ready())?;
|
||||
self.validate_window_proof(&source.window)?;
|
||||
fn check_output_source(&self, proof: &PreparedLayerRow, source: &ChunkAttentionRow) -> Result<()> {
|
||||
if source.index != proof.index
|
||||
|| source.layer != proof.layer
|
||||
|| !Rc::ptr_eq(&self.chunk, &source.chunk)
|
||||
@@ -188,27 +192,43 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let actual = &self.rows[proof.index];
|
||||
let token = actual.token;
|
||||
let position = actual.position;
|
||||
let result = (|| {
|
||||
let mut view = self.stage_view(proof.index)?;
|
||||
let mut step = view.begin(token, position)?;
|
||||
step.input = Some(actual.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = actual.completed;
|
||||
let output = execute(&mut step, &source.read)?;
|
||||
if step.ple_pending.is_some()
|
||||
|| step.gdn_pending.iter().any(Option::is_some)
|
||||
|| step.qsa_pending.iter().any(Option::is_some)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(output)
|
||||
})();
|
||||
if let Err(error) = &result {
|
||||
self.session.note_mtp_failure(error);
|
||||
self.aborted = true;
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn run_output_step<T>(
|
||||
&self,
|
||||
index: usize,
|
||||
source: &ChunkAttentionRow,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &DetachedGrRead) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let actual = &self.rows[index];
|
||||
let mut view = self.stage_view(index)?;
|
||||
let mut step = view.begin(actual.token, actual.position)?;
|
||||
step.input = Some(actual.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = actual.completed;
|
||||
let output = execute(&mut step, &source.read)?;
|
||||
if step.ple_pending.is_some()
|
||||
|| step.gdn_pending.iter().any(Option::is_some)
|
||||
|| step.qsa_pending.iter().any(Option::is_some)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
/// Enlist a fully completed Out row into GR using its real causal proof
|
||||
/// and current transaction, without advancing attention a second time.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn prepare_attention_output_after_causal<T>(
|
||||
&mut self,
|
||||
proof: &PreparedLayerRow,
|
||||
source: &ChunkAttentionRow,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &DetachedGrRead) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
self.validate_prepared_attention_input(proof, source.ready())?;
|
||||
self.validate_window_proof(&source.window)?;
|
||||
self.check_output_source(proof, source)?;
|
||||
let result = self.run_output_step(proof.index, source, execute);
|
||||
self.settle_failure(&result);
|
||||
result
|
||||
}
|
||||
|
||||
@@ -218,25 +238,11 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
pub(in crate::qwen_forward) fn validate_prepared_ffn_read(
|
||||
&self,
|
||||
proof: &PreparedLayerRow,
|
||||
read: &super::super::super::super::gr::DetachedGrRead,
|
||||
read: &DetachedGrRead,
|
||||
) -> Result<super::super::super::super::contract::TokenLayer> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
let span = self.phase_span()?;
|
||||
self.validate_window_proof(&proof.window)?;
|
||||
if proof.index < first
|
||||
|| proof.index >= end
|
||||
|| self.batch_layer != Some(proof.layer)
|
||||
|| self.next_layer != proof.layer.get()
|
||||
|| self.next_row != end
|
||||
|| self.batch_completed != first
|
||||
|| !Rc::ptr_eq(&self.chunk, &proof.chunk)
|
||||
|| self
|
||||
.batch_rows
|
||||
.get(proof.index)
|
||||
.and_then(Option::as_ref)
|
||||
.is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof))
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.check_prepared_row(proof, span)?;
|
||||
let actual = &self.rows[proof.index];
|
||||
if actual.completed != proof.layer.get() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
|
||||
+84
-67
@@ -1,72 +1,56 @@
|
||||
//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (7).
|
||||
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
use super::super::super::super::{gr::DetachedGrRead, moe_expert::PreparedMoeRow};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn prepare_ffn_after_attention(
|
||||
&mut self,
|
||||
fn ffn_after_attention_step(
|
||||
&self,
|
||||
proof: PreparedLayerRow,
|
||||
read: super::super::super::super::gr::DetachedGrRead,
|
||||
execute: impl FnOnce(
|
||||
&mut QwenStepTxn<'_, 'driver>,
|
||||
super::super::super::super::gr::DetachedGrRead,
|
||||
) -> Result<super::super::super::super::moe_expert::PreparedMoeRow>,
|
||||
read: DetachedGrRead,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, DetachedGrRead) -> Result<PreparedMoeRow>,
|
||||
) -> Result<ChunkFfnRow> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
self.validate_window_proof(&proof.window)?;
|
||||
if proof.index < first
|
||||
|| proof.index >= end
|
||||
|| self.batch_layer != Some(proof.layer)
|
||||
|| self.next_layer != proof.layer.get()
|
||||
|| self.next_row != end
|
||||
|| self.batch_completed != first
|
||||
|| !Rc::ptr_eq(&self.chunk, &proof.chunk)
|
||||
|| self
|
||||
.batch_rows
|
||||
.get(proof.index)
|
||||
.and_then(Option::as_ref)
|
||||
.is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof))
|
||||
let actual = &self.rows[proof.index];
|
||||
let (token, position) = (actual.token, actual.position);
|
||||
let mut view = self.stage_view(proof.index)?;
|
||||
let mut step = view.begin(token, position)?;
|
||||
step.input = Some(actual.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = actual.completed;
|
||||
let row = execute(&mut step, read)?;
|
||||
if step.ple_pending.is_some()
|
||||
|| step.gdn_pending.iter().any(Option::is_some)
|
||||
|| step.qsa_pending.iter().any(Option::is_some)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
row.validate(&self.session.binding, token, position, proof.layer)?;
|
||||
Ok(ChunkFfnRow { proof, row })
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn prepare_ffn_after_attention(
|
||||
&mut self,
|
||||
proof: PreparedLayerRow,
|
||||
read: DetachedGrRead,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, DetachedGrRead) -> Result<PreparedMoeRow>,
|
||||
) -> Result<ChunkFfnRow> {
|
||||
let span = self.phase_span()?;
|
||||
self.validate_window_proof(&proof.window)?;
|
||||
self.check_prepared_row(&proof, span)?;
|
||||
let actual = &self.rows[proof.index];
|
||||
let token = actual.token;
|
||||
let position = actual.position;
|
||||
if actual.completed != proof.layer.get() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
read.ready().validate_origin(&self.session.binding, GrRole::Ffn(proof.layer.get()))?;
|
||||
read.ready().identity().validate(token, position, proof.layer)?;
|
||||
let result = (|| {
|
||||
let mut view = self.stage_view(proof.index)?;
|
||||
let mut step = view.begin(token, position)?;
|
||||
step.input = Some(actual.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = actual.completed;
|
||||
let row = execute(&mut step, read)?;
|
||||
if step.ple_pending.is_some()
|
||||
|| step.gdn_pending.iter().any(Option::is_some)
|
||||
|| step.qsa_pending.iter().any(Option::is_some)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
row.validate(&self.session.binding, token, position, proof.layer)?;
|
||||
Ok(ChunkFfnRow { proof, row })
|
||||
})();
|
||||
if let Err(error) = &result {
|
||||
self.session.note_mtp_failure(error);
|
||||
self.aborted = true;
|
||||
}
|
||||
read.ready().identity().validate(actual.token, actual.position, proof.layer)?;
|
||||
let result = self.ffn_after_attention_step(proof, read, execute);
|
||||
self.settle_failure(&result);
|
||||
result
|
||||
}
|
||||
pub(in super::super) fn roll_device_gdn(
|
||||
&mut self,
|
||||
step: &QwenStepTxn<'_, 'driver>,
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
edge: super::super::super::super::gdn::chunk_device::ChunkEdge,
|
||||
) -> Result<()> {
|
||||
/// The step holds no pending history and the row is the one authorized for this device GDN edge.
|
||||
fn check_edge_step(&self, step: &QwenStepTxn<'_, 'driver>, index: usize) -> Result<()> {
|
||||
if step.ple_pending.is_some()
|
||||
|| step.gdn_pending.iter().any(Option::is_some)
|
||||
|| step.qsa_pending.iter().any(Option::is_some)
|
||||
@@ -74,8 +58,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let (row, verified) = edge.into_parts();
|
||||
self.validate_window_proof(&row.window)?;
|
||||
Ok(())
|
||||
}
|
||||
/// The edge row is the journal's next row and the live source of `index`.
|
||||
fn check_edge_row(&self, row: &GdnChunkRow, index: usize, layer: LayerId) -> Result<()> {
|
||||
let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
row.validate(&journal.start, journal.accepted, &self.session.binding)?;
|
||||
let actual = self.rows.get(index).ok_or(Error::IdentityMismatch)?;
|
||||
@@ -87,6 +73,19 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(in super::super) fn roll_device_gdn(
|
||||
&mut self,
|
||||
step: &QwenStepTxn<'_, 'driver>,
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
edge: super::super::super::super::gdn::chunk_device::ChunkEdge,
|
||||
) -> Result<()> {
|
||||
self.check_edge_step(step, index)?;
|
||||
let (row, verified) = edge.into_parts();
|
||||
self.validate_window_proof(&row.window)?;
|
||||
self.check_edge_row(&row, index, layer)?;
|
||||
if let Some(proof) = verified {
|
||||
self.record_device_gdn(index, layer, proof)?;
|
||||
} else if self.device_gdn_lease()?.is_some() {
|
||||
@@ -149,33 +148,38 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
}
|
||||
Ok((result?, row.proof))
|
||||
}
|
||||
pub(in super::super) fn roll_actual_pending(
|
||||
/// Validate the PLE history of the step: a source-owned row holds none, other rows admit it at layer one only.
|
||||
fn roll_pending_ple(
|
||||
&mut self,
|
||||
step: &mut QwenStepTxn<'_, 'driver>,
|
||||
layer: LayerId,
|
||||
position: Position,
|
||||
(position, next_position): (Position, u64),
|
||||
) -> Result<()> {
|
||||
// Validate pending producers now, then release each previous rolling
|
||||
// state before another row executes this causal layer.
|
||||
let slot = layer.get() as usize;
|
||||
let next_position = position.get().checked_add(1).ok_or(Error::Overflow)?;
|
||||
if self.attention_layer == Some(layer) {
|
||||
let index = self.attention_authorized.ok_or(Error::IdentityMismatch)?;
|
||||
if self.attention_sources.get(index).and_then(Option::as_ref).is_none() || step.ple_pending.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
} else {
|
||||
if layer.get() == 1 && self.session.ple_required {
|
||||
let next = step.ple_pending.take().ok_or(Error::Unsupported(Stage::Input))?.into_prior();
|
||||
if next.next_position() != next_position {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.next_ple = Some(next);
|
||||
self.record_verification_ple(self.next_row, position)?;
|
||||
} else if step.ple_pending.is_some() {
|
||||
} else if layer.get() == 1 && self.session.ple_required {
|
||||
let next = step.ple_pending.take().ok_or(Error::Unsupported(Stage::Input))?.into_prior();
|
||||
if next.next_position() != next_position {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.next_ple = Some(next);
|
||||
self.record_verification_ple(self.next_row, position)?;
|
||||
} else if step.ple_pending.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Release the pending rolling state of the current causal layer (GDN or QSA) into the next priors.
|
||||
fn roll_pending_layer(
|
||||
&mut self,
|
||||
step: &mut QwenStepTxn<'_, 'driver>,
|
||||
layer: LayerId,
|
||||
next_position: u64,
|
||||
) -> Result<()> {
|
||||
let slot = layer.get() as usize;
|
||||
if self.session.gdn_layers[slot] {
|
||||
let next = step.gdn_pending[slot].take().ok_or(Error::Unsupported(Stage::Gdn))?.into_prior();
|
||||
if next.layer() != layer || next.next_position() != next_position {
|
||||
@@ -191,6 +195,19 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
} else {
|
||||
return Err(Error::InvalidLayer);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(in super::super) fn roll_actual_pending(
|
||||
&mut self,
|
||||
step: &mut QwenStepTxn<'_, 'driver>,
|
||||
layer: LayerId,
|
||||
position: Position,
|
||||
) -> Result<()> {
|
||||
// Validate pending producers now, then release each previous rolling
|
||||
// state before another row executes this causal layer.
|
||||
let next_position = position.get().checked_add(1).ok_or(Error::Overflow)?;
|
||||
self.roll_pending_ple(step, layer, (position, next_position))?;
|
||||
self.roll_pending_layer(step, layer, next_position)?;
|
||||
self.record_verification_prior(self.next_row, layer, position)?;
|
||||
// No hidden noncurrent-layer candidate is admitted.
|
||||
if step.gdn_pending.iter().any(Option::is_some) || step.qsa_pending.iter().any(Option::is_some) {
|
||||
|
||||
+123
-104
@@ -1,16 +1,24 @@
|
||||
//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (8).
|
||||
|
||||
use super::super::super::super::gdn::chunk_device::ChunkEdge;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
pub(in crate::qwen_forward) fn layer(
|
||||
&mut self,
|
||||
/// The step of row `index` over a fresh stage view: its input and completed-layer count come from the row.
|
||||
pub(super) fn row_step<'v>(
|
||||
&self,
|
||||
view: &'v mut QwenSession<'driver>,
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result<InjectedResidual>,
|
||||
) -> Result<InjectedResidual> {
|
||||
self.check()?;
|
||||
) -> Result<QwenStepTxn<'v, 'driver>> {
|
||||
let row = &self.rows[index];
|
||||
let mut step = view.begin(row.token, row.position)?;
|
||||
step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = row.completed;
|
||||
Ok(step)
|
||||
}
|
||||
/// The unwindowed layer pass runs the next row of the current layer with no batch or attention phase open.
|
||||
fn check_layer_row(&self, index: usize, layer: LayerId) -> Result<()> {
|
||||
if self.windowed || self.batch_layer.is_some() || self.attention_layer.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
@@ -21,33 +29,34 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(in crate::qwen_forward) fn layer(
|
||||
&mut self,
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result<InjectedResidual>,
|
||||
) -> Result<InjectedResidual> {
|
||||
self.check()?;
|
||||
self.check_layer_row(index, layer)?;
|
||||
let mut view = self.stage_view(index)?;
|
||||
let row = &self.rows[index];
|
||||
let mut step = view.begin(row.token, row.position)?;
|
||||
step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = row.completed;
|
||||
let mut step = self.row_step(&mut view, index)?;
|
||||
let result = execute(&mut step).and_then(|residual| {
|
||||
step.mark_layer_complete(&residual)?;
|
||||
let position = step.position();
|
||||
self.roll_actual_pending(&mut step, layer, position)?;
|
||||
Ok(residual)
|
||||
});
|
||||
match result {
|
||||
Ok(residual) => {
|
||||
self.rows[index].completed += 1;
|
||||
self.next_row += 1;
|
||||
if self.next_row == self.rows.len() {
|
||||
self.next_row = 0;
|
||||
self.next_layer += 1;
|
||||
}
|
||||
Ok(residual)
|
||||
}
|
||||
Err(error) => {
|
||||
self.session.note_mtp_failure(&error);
|
||||
self.aborted = true;
|
||||
Err(error)
|
||||
self.settle_failure(&result);
|
||||
if result.is_ok() {
|
||||
self.rows[index].completed += 1;
|
||||
self.next_row += 1;
|
||||
if self.next_row == self.rows.len() {
|
||||
self.next_row = 0;
|
||||
self.next_layer += 1;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(in crate::qwen_forward) fn prepare_layer_batch<T>(
|
||||
&mut self,
|
||||
@@ -57,15 +66,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
) -> Result<(T, PreparedLayerRow)> {
|
||||
self.prepare_layer_batch_internal(index, layer, |step| execute(step).map(|prepared| (prepared, None)))
|
||||
}
|
||||
pub(in super::super) fn prepare_layer_batch_internal<T>(
|
||||
&mut self,
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
execute: impl FnOnce(
|
||||
&mut QwenStepTxn<'_, 'driver>,
|
||||
) -> Result<(T, Option<super::super::super::super::gdn::chunk_device::ChunkEdge>)>,
|
||||
) -> Result<(T, PreparedLayerRow)> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
/// The row is inside the active phase and is the next one of `layer`, whose batch it may open or continue.
|
||||
fn check_batch_row(&self, index: usize, layer: LayerId, (first, end): (usize, usize)) -> Result<()> {
|
||||
if index < first || index >= end {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
@@ -82,6 +84,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The first row of a layer opens its batch.
|
||||
fn open_batch(&mut self, index: usize, layer: LayerId, first: usize) -> Result<()> {
|
||||
if self.batch_layer.is_none() {
|
||||
if index != first {
|
||||
return Err(Error::IdentityMismatch);
|
||||
@@ -91,50 +97,59 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
self.batch_layer = Some(layer);
|
||||
self.batch_completed = first;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// A device-GDN row rolls its edge; any other row rolls its actual pending states and may not follow a GDN chunk.
|
||||
fn roll_batch_row(
|
||||
&mut self,
|
||||
step: &mut QwenStepTxn<'_, 'driver>,
|
||||
(index, layer, position): (usize, LayerId, Position),
|
||||
edge: Option<ChunkEdge>,
|
||||
) -> Result<()> {
|
||||
if let Some(edge) = edge {
|
||||
return self.roll_device_gdn(step, index, layer, edge);
|
||||
}
|
||||
if self.gdn_chunk.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.roll_actual_pending(step, layer, position)
|
||||
}
|
||||
/// Record the prepared row in its batch and mint its capability.
|
||||
fn mint_batch_row(&mut self, index: usize, layer: LayerId) -> PreparedLayerRow {
|
||||
let proof = Rc::new(());
|
||||
self.batch_rows[index] = Some(Rc::clone(&proof));
|
||||
self.next_row += 1;
|
||||
PreparedLayerRow {
|
||||
chunk: Rc::clone(&self.chunk),
|
||||
proof,
|
||||
index,
|
||||
layer,
|
||||
window: self.window_proof(),
|
||||
attention_source: self
|
||||
.attention_sources
|
||||
.get(index)
|
||||
.and_then(Option::as_ref)
|
||||
.map(|source| Rc::clone(&source.read)),
|
||||
}
|
||||
}
|
||||
pub(in super::super) fn prepare_layer_batch_internal<T>(
|
||||
&mut self,
|
||||
index: usize,
|
||||
layer: LayerId,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result<(T, Option<ChunkEdge>)>,
|
||||
) -> Result<(T, PreparedLayerRow)> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
self.check_batch_row(index, layer, (first, end))?;
|
||||
self.open_batch(index, layer, first)?;
|
||||
let mut view = self.stage_view(index)?;
|
||||
let row = &self.rows[index];
|
||||
let position = row.position;
|
||||
let mut step = view.begin(row.token, row.position)?;
|
||||
step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = row.completed;
|
||||
let position = self.rows[index].position;
|
||||
let mut step = self.row_step(&mut view, index)?;
|
||||
let result = execute(&mut step).and_then(|(prepared, edge)| {
|
||||
if let Some(edge) = edge {
|
||||
self.roll_device_gdn(&step, index, layer, edge)?;
|
||||
} else {
|
||||
if self.gdn_chunk.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.roll_actual_pending(&mut step, layer, position)?;
|
||||
}
|
||||
self.roll_batch_row(&mut step, (index, layer, position), edge)?;
|
||||
Ok(prepared)
|
||||
});
|
||||
match result {
|
||||
Ok(prepared) => {
|
||||
let proof = Rc::new(());
|
||||
self.batch_rows[index] = Some(Rc::clone(&proof));
|
||||
self.next_row += 1;
|
||||
Ok((
|
||||
prepared,
|
||||
PreparedLayerRow {
|
||||
chunk: Rc::clone(&self.chunk),
|
||||
proof,
|
||||
index,
|
||||
layer,
|
||||
window: self.window_proof(),
|
||||
attention_source: self
|
||||
.attention_sources
|
||||
.get(index)
|
||||
.and_then(Option::as_ref)
|
||||
.map(|source| Rc::clone(&source.read)),
|
||||
},
|
||||
))
|
||||
}
|
||||
Err(error) => {
|
||||
self.session.note_mtp_failure(&error);
|
||||
self.aborted = true;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
self.settle_failure(&result);
|
||||
result.map(|prepared| (prepared, self.mint_batch_row(index, layer)))
|
||||
}
|
||||
pub(in crate::qwen_forward) fn batch_outputs<T>(
|
||||
&mut self,
|
||||
@@ -180,13 +195,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(in crate::qwen_forward) fn complete_layer_batch(
|
||||
&mut self,
|
||||
proof: PreparedLayerRow,
|
||||
residual: InjectedResidual,
|
||||
) -> Result<InjectedResidual> {
|
||||
let (first, end) = self.phase_span()?;
|
||||
self.validate_window_proof(&proof.window)?;
|
||||
/// The proof is the next uncompleted row of the live batch, and every row of the window has been prepared.
|
||||
fn check_complete_row(&self, proof: &PreparedLayerRow, (first, end): (usize, usize)) -> Result<()> {
|
||||
if proof.index < first
|
||||
|| proof.index >= end
|
||||
|| self.batch_layer != Some(proof.layer)
|
||||
@@ -197,34 +207,43 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut view = self.stage_view(proof.index)?;
|
||||
let row = &self.rows[proof.index];
|
||||
let mut step = view.begin(row.token, row.position)?;
|
||||
step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?);
|
||||
step.completed_layers = row.completed;
|
||||
// Only actual GR producer-owned finite FFN residual completes the row.
|
||||
if let Err(error) = step.mark_layer_complete(&residual) {
|
||||
self.session.note_mtp_failure(&error);
|
||||
self.aborted = true;
|
||||
return Err(error);
|
||||
Ok(())
|
||||
}
|
||||
/// The last completed row closes the batch and the attention phase; the transaction moves to the next layer.
|
||||
fn close_batch(&mut self, end: usize) {
|
||||
if self.windowed {
|
||||
self.next_row = end;
|
||||
} else {
|
||||
self.next_row = 0;
|
||||
self.next_layer += 1;
|
||||
}
|
||||
self.batch_layer = None;
|
||||
self.batch_rows.clear();
|
||||
self.batch_completed = 0;
|
||||
self.attention_layer = None;
|
||||
self.attention_next = if self.windowed { end } else { 0 };
|
||||
self.attention_sources.clear();
|
||||
self.attention_authorized = None;
|
||||
}
|
||||
pub(in crate::qwen_forward) fn complete_layer_batch(
|
||||
&mut self,
|
||||
proof: PreparedLayerRow,
|
||||
residual: InjectedResidual,
|
||||
) -> Result<InjectedResidual> {
|
||||
let span = self.phase_span()?;
|
||||
self.validate_window_proof(&proof.window)?;
|
||||
self.check_complete_row(&proof, span)?;
|
||||
let mut view = self.stage_view(proof.index)?;
|
||||
let mut step = self.row_step(&mut view, proof.index)?;
|
||||
// Only actual GR producer-owned finite FFN residual completes the row.
|
||||
let marked = step.mark_layer_complete(&residual);
|
||||
self.settle_failure(&marked);
|
||||
marked?;
|
||||
self.rows[proof.index].completed += 1;
|
||||
self.batch_rows[proof.index] = None;
|
||||
self.batch_completed += 1;
|
||||
if self.batch_completed == end {
|
||||
if self.windowed {
|
||||
self.next_row = end;
|
||||
} else {
|
||||
self.next_row = 0;
|
||||
self.next_layer += 1;
|
||||
}
|
||||
self.batch_layer = None;
|
||||
self.batch_rows.clear();
|
||||
self.batch_completed = 0;
|
||||
self.attention_layer = None;
|
||||
self.attention_next = if self.windowed { end } else { 0 };
|
||||
self.attention_sources.clear();
|
||||
self.attention_authorized = None;
|
||||
if self.batch_completed == span.1 {
|
||||
self.close_batch(span.1);
|
||||
}
|
||||
Ok(residual)
|
||||
}
|
||||
|
||||
+100
-75
@@ -10,18 +10,11 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
execute_head: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result<TokenId>,
|
||||
) -> Result<()> {
|
||||
let result = self.finish_inner(residuals, execute_head);
|
||||
if let Err(error) = &result {
|
||||
self.session.note_mtp_failure(error);
|
||||
self.aborted = true;
|
||||
}
|
||||
self.settle_failure(&result);
|
||||
result
|
||||
}
|
||||
pub(in super::super) fn finish_inner(
|
||||
&mut self,
|
||||
residuals: &[Option<InjectedResidual>],
|
||||
execute_head: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result<TokenId>,
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
/// Every layer of every row is complete and no phase or window is open.
|
||||
fn check_finishable(&self, residuals: &[Option<InjectedResidual>]) -> Result<()> {
|
||||
if self.finished
|
||||
|| self.next_layer != 48
|
||||
|| self.next_row != 0
|
||||
@@ -31,53 +24,74 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
for (index, residual) in residuals.iter().enumerate() {
|
||||
let row = &self.rows[index];
|
||||
let residual = residual.as_ref().ok_or(Error::Unsupported(Stage::Executor))?;
|
||||
residual.validate_origin(&self.session.binding, GrRole::Ffn(47))?;
|
||||
residual.identity().validate(row.token, row.position, LayerId::new(47, Dimension::new(48)?)?)?;
|
||||
if row.completed != 48
|
||||
|| residual.streams().len() != 10240
|
||||
|| residual.streams().iter().any(|v| !v.is_finite())
|
||||
{
|
||||
return Err(Error::NonFinite);
|
||||
Ok(())
|
||||
}
|
||||
/// The finite last-layer residual of row `index` as an owned witness of the row.
|
||||
fn witness_for(&self, index: usize, residual: &Option<InjectedResidual>) -> Result<ChunkRowResidual> {
|
||||
let row = &self.rows[index];
|
||||
let residual = residual.as_ref().ok_or(Error::Unsupported(Stage::Executor))?;
|
||||
residual.validate_origin(&self.session.binding, GrRole::Ffn(47))?;
|
||||
residual.identity().validate(row.token, row.position, LayerId::new(47, Dimension::new(48)?)?)?;
|
||||
if row.completed != 48 || residual.streams().len() != 10240 || residual.streams().iter().any(|v| !v.is_finite())
|
||||
{
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
let mut streams = Vec::new();
|
||||
streams.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?;
|
||||
streams.extend_from_slice(residual.streams());
|
||||
Ok(ChunkRowResidual {
|
||||
binding: self.session.binding.clone(),
|
||||
chunk: Rc::clone(&self.chunk),
|
||||
origin: self.origin.clone(),
|
||||
token: row.token,
|
||||
position: row.position,
|
||||
known_next: self.rows.get(index + 1).map(|r| r.token).or(self.known_next),
|
||||
streams: Rc::new(streams.into_boxed_slice()),
|
||||
})
|
||||
}
|
||||
/// Without a known next token the head runs on the last row and must produce the forward output.
|
||||
fn run_head(
|
||||
&mut self,
|
||||
residuals: &[Option<InjectedResidual>],
|
||||
execute_head: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result<TokenId>,
|
||||
) -> Result<()> {
|
||||
let index = self.rows.len() - 1;
|
||||
let mut view = self.stage_view(index)?;
|
||||
let row = &self.rows[index];
|
||||
let mut step = view.begin(row.token, row.position)?;
|
||||
step.input = row.input.clone();
|
||||
step.completed_layers = 48;
|
||||
match execute_head(&mut step, residuals[index].as_ref().ok_or(Error::IdentityMismatch)?) {
|
||||
Ok(output) if step.forward_output == Some(output) && !step.prefill_finished => {
|
||||
self.output = Some(output);
|
||||
Ok(())
|
||||
}
|
||||
let mut streams = Vec::new();
|
||||
streams.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?;
|
||||
streams.extend_from_slice(residual.streams());
|
||||
self.witnesses.push(ChunkRowResidual {
|
||||
binding: self.session.binding.clone(),
|
||||
chunk: Rc::clone(&self.chunk),
|
||||
origin: self.origin.clone(),
|
||||
token: row.token,
|
||||
position: row.position,
|
||||
known_next: self.rows.get(index + 1).map(|r| r.token).or(self.known_next),
|
||||
streams: Rc::new(streams.into_boxed_slice()),
|
||||
});
|
||||
Ok(_) => Err(Error::IdentityMismatch),
|
||||
Err(error) => {
|
||||
self.session.note_mtp_failure(&error);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(in super::super) fn finish_inner(
|
||||
&mut self,
|
||||
residuals: &[Option<InjectedResidual>],
|
||||
execute_head: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result<TokenId>,
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
self.check_finishable(residuals)?;
|
||||
for (index, residual) in residuals.iter().enumerate() {
|
||||
let witness = self.witness_for(index, residual)?;
|
||||
self.witnesses.push(witness);
|
||||
}
|
||||
if self.known_next.is_none() {
|
||||
let index = self.rows.len() - 1;
|
||||
let mut view = self.stage_view(index)?;
|
||||
let row = &self.rows[index];
|
||||
let mut step = view.begin(row.token, row.position)?;
|
||||
step.input = row.input.clone();
|
||||
step.completed_layers = 48;
|
||||
match execute_head(&mut step, residuals[index].as_ref().ok_or(Error::IdentityMismatch)?) {
|
||||
Ok(output) if step.forward_output == Some(output) && !step.prefill_finished => {
|
||||
self.output = Some(output)
|
||||
}
|
||||
Ok(_) => return Err(Error::IdentityMismatch),
|
||||
Err(error) => {
|
||||
self.session.note_mtp_failure(&error);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
self.run_head(residuals, execute_head)?;
|
||||
}
|
||||
self.finished = true;
|
||||
Ok(())
|
||||
}
|
||||
pub(in super::super) fn validate_publish(&self) -> Result<()> {
|
||||
self.check()?;
|
||||
/// The transaction finished every row and holds one validated witness per row.
|
||||
fn check_publishable(&self) -> Result<()> {
|
||||
if !self.finished
|
||||
|| self.active_micro.is_some()
|
||||
|| self.micro_cursor != 0
|
||||
@@ -88,6 +102,40 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// A GDN slot holds a prior at the end position (or a verified device state); other slots hold none.
|
||||
fn validate_gdn_slot(&self, slot: usize, end_position: Position) -> Result<()> {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
if !self.session.gdn_layers[slot] {
|
||||
return if self.next_gdn[slot].is_some() { Err(Error::IdentityMismatch) } else { Ok(()) };
|
||||
}
|
||||
if self.device_gdn_lease()?.is_some() {
|
||||
return self.validate_verification_state(self.rows.len() - 1).map(|_| ());
|
||||
}
|
||||
self.next_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.gdn_owner,
|
||||
layer,
|
||||
end_position,
|
||||
)
|
||||
}
|
||||
/// A QSA slot holds an index prior at the end position; other slots hold none.
|
||||
fn validate_qsa_slot(&self, slot: usize, end_position: Position) -> Result<()> {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
if !self.session.qsa_layers[slot] {
|
||||
return if self.next_qsa[slot].is_some() { Err(Error::IdentityMismatch) } else { Ok(()) };
|
||||
}
|
||||
self.next_qsa[slot].as_ref().ok_or(Error::Unsupported(Stage::QsaIndex))?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.qsa_owner,
|
||||
layer,
|
||||
end_position,
|
||||
)
|
||||
}
|
||||
pub(in super::super) fn validate_publish(&self) -> Result<()> {
|
||||
self.check()?;
|
||||
self.check_publishable()?;
|
||||
for witness in &self.witnesses {
|
||||
self.validate_row(witness)?;
|
||||
}
|
||||
@@ -100,31 +148,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
)?;
|
||||
}
|
||||
for slot in 0..STATE_CAPACITY {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
if self.session.gdn_layers[slot] {
|
||||
if self.device_gdn_lease()?.is_some() {
|
||||
self.validate_verification_state(self.rows.len() - 1)?;
|
||||
} else {
|
||||
self.next_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.gdn_owner,
|
||||
layer,
|
||||
end_position,
|
||||
)?;
|
||||
}
|
||||
} else if self.next_gdn[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if self.session.qsa_layers[slot] {
|
||||
self.next_qsa[slot].as_ref().ok_or(Error::Unsupported(Stage::QsaIndex))?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.qsa_owner,
|
||||
layer,
|
||||
end_position,
|
||||
)?;
|
||||
} else if self.next_qsa[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.validate_gdn_slot(slot, end_position)?;
|
||||
self.validate_qsa_slot(slot, end_position)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+84
-54
@@ -71,6 +71,17 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
Ok(txn)
|
||||
}
|
||||
|
||||
/// The host charge of the rows plus the device-GDN metadata must fit what remains of the verification cap.
|
||||
fn admit_verification_charge(&self, metadata: usize, host_remaining: usize) -> Result<()> {
|
||||
let charged = host_charge_bounded(self.rows.len(), self.end, 256)?
|
||||
.checked_add(verification_extra_charge(self.rows.len(), self.end)?)
|
||||
.and_then(|n| n.checked_add(metadata))
|
||||
.ok_or(Error::Overflow)?;
|
||||
if charged > host_remaining.min(HOST_LIMIT) {
|
||||
return Err(Error::InputAllocation);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(in crate::qwen_forward) fn enable_device_gdn_verification(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
@@ -84,13 +95,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
return Ok(());
|
||||
};
|
||||
let metadata = workspace.try_borrow().map_err(|_| Error::IdentityMismatch)?.metadata_bytes()?;
|
||||
let charged = host_charge_bounded(self.rows.len(), self.end, 256)?
|
||||
.checked_add(verification_extra_charge(self.rows.len(), self.end)?)
|
||||
.and_then(|n| n.checked_add(metadata))
|
||||
.ok_or(Error::Overflow)?;
|
||||
if charged > host_remaining.min(HOST_LIMIT) {
|
||||
return Err(Error::InputAllocation);
|
||||
}
|
||||
self.admit_verification_charge(metadata, host_remaining)?;
|
||||
let journal = self.verification.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
if journal.device_lease.is_some() || self.rows.len() > 3 || self.next_layer != 0 || self.next_row != 0 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
@@ -140,6 +145,49 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
state.device_gdn[layer.get() as usize] = Some(proof);
|
||||
Ok(())
|
||||
}
|
||||
/// The device proofs of the first `count` rows for GDN layer `layer`, each validated against its row.
|
||||
fn slot_proofs(
|
||||
&self,
|
||||
slot: usize,
|
||||
layer: LayerId,
|
||||
lease: &Rc<crate::qwen_forward::gdn::verification::ActiveLease>,
|
||||
count: usize,
|
||||
) -> Result<Vec<Rc<crate::qwen_forward::gdn::verification::VerifiedRow>>> {
|
||||
let mut proofs = Vec::new();
|
||||
proofs.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?;
|
||||
for index in 0..count {
|
||||
let state = self.validate_verification_state(index)?;
|
||||
let proof = state.device_gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let actual = &self.rows[index];
|
||||
proof.validate(lease, layer, index, TokenLayer::new(actual.token, actual.position, layer))?;
|
||||
proofs.push(proof.clone());
|
||||
}
|
||||
Ok(proofs)
|
||||
}
|
||||
/// Replay one GDN layer's device proofs into the canonical prior at the end of the first `count` rows.
|
||||
fn replay_slot(
|
||||
&self,
|
||||
slot: usize,
|
||||
count: usize,
|
||||
(lease, workspace): (
|
||||
&Rc<crate::qwen_forward::gdn::verification::ActiveLease>,
|
||||
&std::cell::RefCell<crate::qwen_forward::gdn::verification::Workspace<'_>>,
|
||||
),
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<GdnPrior> {
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
self.origin.validate(self.session)?;
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
let proofs = self.slot_proofs(slot, layer, lease, count)?;
|
||||
let prior =
|
||||
workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.replay(lease, &proofs, cancelled)?;
|
||||
let end = self.start_position().checked_add(count as u64).ok_or(Error::Overflow)?;
|
||||
let end = Position::new(end, crate::qwen_forward::contract::position_dimension())?;
|
||||
prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)?;
|
||||
Ok(prior)
|
||||
}
|
||||
pub(in super::super) fn replay_device_prefix(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
@@ -158,35 +206,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
if !self.session.gdn_layers[slot] {
|
||||
continue;
|
||||
}
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
self.origin.validate(self.session)?;
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
let mut proofs = Vec::new();
|
||||
proofs.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?;
|
||||
for index in 0..count {
|
||||
let state = self.validate_verification_state(index)?;
|
||||
let proof = state.device_gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let actual = &self.rows[index];
|
||||
proof.validate(&lease, layer, index, TokenLayer::new(actual.token, actual.position, layer))?;
|
||||
proofs.push(proof.clone());
|
||||
}
|
||||
let prior = workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.replay(
|
||||
&lease,
|
||||
&proofs,
|
||||
&mut cancelled,
|
||||
)?;
|
||||
prior.validate(
|
||||
&self.session.binding,
|
||||
&self.session.gdn_owner,
|
||||
layer,
|
||||
Position::new(
|
||||
self.start_position().checked_add(count as u64).ok_or(Error::Overflow)?,
|
||||
crate::qwen_forward::contract::position_dimension(),
|
||||
)?,
|
||||
)?;
|
||||
*output = Some(prior);
|
||||
*output = Some(self.replay_slot(slot, count, (&lease, &workspace), &mut cancelled)?);
|
||||
}
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
@@ -237,6 +257,33 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
crate::qwen_forward::contract::position_dimension(),
|
||||
)
|
||||
}
|
||||
/// The row is the next PLE row of the layer-one GDN chunk: same chunk, extent and position, none ahead of it.
|
||||
fn ple_row_in_chunk(
|
||||
&self,
|
||||
journal: &GdnChunkJournal,
|
||||
row: &Row,
|
||||
(index, position): (usize, Position),
|
||||
(first, end): (usize, usize),
|
||||
) -> bool {
|
||||
let start = &journal.start.0;
|
||||
Rc::ptr_eq(&start.chunk, &self.chunk)
|
||||
&& start.layer.get() == 1
|
||||
&& self.next_layer == 1
|
||||
&& start.count == self.rows.len()
|
||||
&& start.end == self.end
|
||||
&& self.rows.first().is_some_and(|row| row.position == start.first)
|
||||
&& start.first.get().checked_add(index as u64) == Some(position.get())
|
||||
&& row.position == position
|
||||
&& row.completed == 1
|
||||
&& index >= first
|
||||
&& index < end
|
||||
&& self.next_row == first
|
||||
&& self.attention_layer == Some(start.layer)
|
||||
&& self.attention_next == index
|
||||
&& self.batch_layer.is_none()
|
||||
&& self.attention_authorized.is_none()
|
||||
&& journal.accepted == first
|
||||
}
|
||||
// PLE completes before this layer's GDN recurrence consumes its rows.
|
||||
// Its genuine next prior may be journaled without claiming a GDN prior.
|
||||
pub(in super::super) fn verification_ple_row_position(&self, index: usize, position: Position) -> Result<Position> {
|
||||
@@ -247,24 +294,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
let row = self.rows.get(index).ok_or(Error::IdentityMismatch)?;
|
||||
let start = &journal.start.0;
|
||||
journal.start.validate_binding(&self.session.binding)?;
|
||||
if !Rc::ptr_eq(&start.chunk, &self.chunk)
|
||||
|| start.layer.get() != 1
|
||||
|| self.next_layer != 1
|
||||
|| start.count != self.rows.len()
|
||||
|| start.end != self.end
|
||||
|| self.rows.first().is_none_or(|row| row.position != start.first)
|
||||
|| start.first.get().checked_add(index as u64) != Some(position.get())
|
||||
|| row.position != position
|
||||
|| row.completed != 1
|
||||
|| index < first
|
||||
|| index >= end
|
||||
|| self.next_row != first
|
||||
|| self.attention_layer != Some(start.layer)
|
||||
|| self.attention_next != index
|
||||
|| self.batch_layer.is_some()
|
||||
|| self.attention_authorized.is_some()
|
||||
|| journal.accepted != first
|
||||
{
|
||||
if !self.ple_row_in_chunk(journal, row, (index, position), (first, end)) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
start.prior.validate(&self.session.binding, &self.session.gdn_owner, start.layer, start.first)?;
|
||||
|
||||
+185
-139
@@ -4,6 +4,30 @@
|
||||
use super::*;
|
||||
|
||||
impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
/// Journal the consumed GDN prior of `index` once; it must validate at the row end.
|
||||
fn record_gdn_prior(&mut self, index: usize, layer: LayerId, end: Position) -> Result<()> {
|
||||
let slot = layer.get() as usize;
|
||||
let prior = self.next_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?;
|
||||
prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)?;
|
||||
let state = journal_state_mut(&mut self.verification, index)?;
|
||||
if state.gdn[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
state.gdn[slot] = Some(prior.clone());
|
||||
Ok(())
|
||||
}
|
||||
/// Journal the consumed QSA prior of `index` once; it must validate at the row end.
|
||||
fn record_qsa_prior(&mut self, index: usize, layer: LayerId, end: Position) -> Result<()> {
|
||||
let slot = layer.get() as usize;
|
||||
let prior = self.next_qsa[slot].as_ref().ok_or(Error::Unsupported(Stage::QsaIndex))?;
|
||||
prior.validate(&self.session.binding, &self.session.qsa_owner, layer, end)?;
|
||||
let state = journal_state_mut(&mut self.verification, index)?;
|
||||
if state.qsa[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
state.qsa[slot] = Some(prior.clone());
|
||||
Ok(())
|
||||
}
|
||||
pub(in super::super::super) fn record_verification_prior(
|
||||
&mut self,
|
||||
index: usize,
|
||||
@@ -21,37 +45,53 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
// Only the consumed producer prior is cloned; no numeric constructor,
|
||||
// stale initial state or advanced metadata is used for a prefix.
|
||||
if self.session.gdn_layers[slot] {
|
||||
let prior = self.next_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?;
|
||||
prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)?;
|
||||
let state = self
|
||||
.verification
|
||||
.as_mut()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.states
|
||||
.get_mut(index)
|
||||
.ok_or(Error::IdentityMismatch)?;
|
||||
if state.gdn[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
state.gdn[slot] = Some(prior.clone());
|
||||
self.record_gdn_prior(index, layer, end)
|
||||
} else if self.session.qsa_layers[slot] {
|
||||
let prior = self.next_qsa[slot].as_ref().ok_or(Error::Unsupported(Stage::QsaIndex))?;
|
||||
prior.validate(&self.session.binding, &self.session.qsa_owner, layer, end)?;
|
||||
let state = self
|
||||
.verification
|
||||
.as_mut()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.states
|
||||
.get_mut(index)
|
||||
.ok_or(Error::IdentityMismatch)?;
|
||||
if state.qsa[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
state.qsa[slot] = Some(prior.clone());
|
||||
self.record_qsa_prior(index, layer, end)
|
||||
} else {
|
||||
return Err(Error::InvalidLayer);
|
||||
Err(Error::InvalidLayer)
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// A GDN slot of a verified row: the device proof (and the replayed prior when present), or the prior alone.
|
||||
fn validate_state_gdn(
|
||||
&self,
|
||||
state: &PrefixState,
|
||||
(slot, layer): (usize, LayerId),
|
||||
(index, row, end): (usize, &Row, Position),
|
||||
) -> Result<()> {
|
||||
if !self.session.gdn_layers[slot] {
|
||||
return if state.gdn[slot].is_some() || state.device_gdn[slot].is_some() {
|
||||
Err(Error::IdentityMismatch)
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
}
|
||||
if let Some(lease) = self.verification.as_ref().and_then(|j| j.device_lease.as_ref()) {
|
||||
let device = state.device_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?;
|
||||
device.validate(lease, layer, index, TokenLayer::new(row.token, row.position, layer))?;
|
||||
if let Some(prior) = &state.gdn[slot] {
|
||||
prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
state.gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.gdn_owner,
|
||||
layer,
|
||||
end,
|
||||
)
|
||||
}
|
||||
/// A QSA slot of a verified row holds its index prior at the row end; other slots hold none.
|
||||
fn validate_state_qsa(&self, state: &PrefixState, (slot, layer): (usize, LayerId), end: Position) -> Result<()> {
|
||||
if !self.session.qsa_layers[slot] {
|
||||
return if state.qsa[slot].is_some() { Err(Error::IdentityMismatch) } else { Ok(()) };
|
||||
}
|
||||
state.qsa[slot].as_ref().ok_or(Error::Unsupported(Stage::QsaIndex))?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.qsa_owner,
|
||||
layer,
|
||||
end,
|
||||
)
|
||||
}
|
||||
pub(in super::super::super) fn validate_verification_state(&self, index: usize) -> Result<&PrefixState> {
|
||||
self.check()?;
|
||||
@@ -63,13 +103,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
row.position.get().checked_add(1).ok_or(Error::Overflow)?,
|
||||
crate::qwen_forward::contract::position_dimension(),
|
||||
)?;
|
||||
let state = self
|
||||
.verification
|
||||
.as_ref()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.states
|
||||
.get(index)
|
||||
.ok_or(Error::IdentityMismatch)?;
|
||||
let state = journal_state(&self.verification, index)?;
|
||||
if self.session.ple_required {
|
||||
state.ple.as_ref().ok_or(Error::Unsupported(Stage::Input))?.validate(
|
||||
&self.session.binding,
|
||||
@@ -81,38 +115,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
}
|
||||
for slot in 0..STATE_CAPACITY {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
if self.session.gdn_layers[slot] {
|
||||
if let Some(lease) = self.verification.as_ref().and_then(|j| j.device_lease.as_ref()) {
|
||||
state.device_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate(
|
||||
lease,
|
||||
layer,
|
||||
index,
|
||||
TokenLayer::new(row.token, row.position, layer),
|
||||
)?;
|
||||
if let Some(prior) = &state.gdn[slot] {
|
||||
prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)?;
|
||||
}
|
||||
} else {
|
||||
state.gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.gdn_owner,
|
||||
layer,
|
||||
end,
|
||||
)?;
|
||||
}
|
||||
} else if state.gdn[slot].is_some() || state.device_gdn[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if self.session.qsa_layers[slot] {
|
||||
state.qsa[slot].as_ref().ok_or(Error::Unsupported(Stage::QsaIndex))?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.qsa_owner,
|
||||
layer,
|
||||
end,
|
||||
)?;
|
||||
} else if state.qsa[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.validate_state_gdn(state, (slot, layer), (index, row, end))?;
|
||||
self.validate_state_qsa(state, (slot, layer), end)?;
|
||||
}
|
||||
Ok(state)
|
||||
}
|
||||
@@ -129,12 +133,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(in super::super) fn finish_mtp_verification_inner(
|
||||
&mut self,
|
||||
residuals: &[Option<InjectedResidual>],
|
||||
execute_head: &mut impl FnMut(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result<TokenId>,
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
/// The verification transaction has every layer done, no witness yet and no known next token.
|
||||
fn check_mtp_finishable(&self, residuals: &[Option<InjectedResidual>]) -> Result<()> {
|
||||
if self.finished
|
||||
|| self.known_next.is_some()
|
||||
|| self.verification.as_ref().is_none_or(|j| j.states.len() != self.rows.len())
|
||||
@@ -147,73 +147,111 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The head runs on the actual complete row state, never the full chunk's final state relabelled with an
|
||||
/// intermediate position.
|
||||
fn verification_head(
|
||||
&self,
|
||||
index: usize,
|
||||
residual: &InjectedResidual,
|
||||
execute_head: &mut impl FnMut(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result<TokenId>,
|
||||
) -> Result<TokenId> {
|
||||
let row = &self.rows[index];
|
||||
let state = self.validate_verification_state(index)?;
|
||||
let mut view = self.stage_view(index)?;
|
||||
view.ple_state = state.ple.clone();
|
||||
if self.device_gdn_lease()?.is_none() || state.gdn.iter().any(Option::is_some) {
|
||||
view.gdn_states = state.gdn.clone();
|
||||
}
|
||||
// Device-only rows keep original unused canonical priors in the head
|
||||
// view; actual current provisional rows were authenticated above.
|
||||
// A diagnostic snapshot uses only real replay-materialized states.
|
||||
view.qsa_states = state.qsa.clone();
|
||||
let mut step = view.begin(row.token, row.position)?;
|
||||
step.input = row.input.clone();
|
||||
step.completed_layers = 48;
|
||||
let head = execute_head(&mut step, residual)?;
|
||||
if step.forward_output != Some(head) || step.prefill_finished {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(head)
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn observe_verification_row(&self, index: usize, head: TokenId, residual: &InjectedResidual) -> Result<()> {
|
||||
if !crate::qwen_forward::mtp_decode::batch_gpu::collecting() {
|
||||
return Ok(());
|
||||
}
|
||||
// Observation of the validated completed journal, never a
|
||||
// session/Origin constructor or publication/restore authority.
|
||||
let row = &self.rows[index];
|
||||
let state = journal_state(&self.verification, index)?;
|
||||
let snapshot = super::super::super::super::ResetReplaySnapshot {
|
||||
binding: self.session.binding.clone(),
|
||||
predecessors: [row.predecessors[1], i32::try_from(row.token.get()).map_err(|_| Error::InvalidToken)?],
|
||||
next_position: row.position.get().checked_add(1).ok_or(Error::Overflow)?,
|
||||
layer_count: self.session.layer_count,
|
||||
ple_required: self.session.ple_required,
|
||||
ple: state.ple.clone(),
|
||||
gdn_layers: self.session.gdn_layers,
|
||||
gdn: state.gdn.clone(),
|
||||
qsa_layers: self.session.qsa_layers,
|
||||
qsa: state.qsa.clone(),
|
||||
};
|
||||
crate::qwen_forward::mtp_decode::batch_gpu::collect_row(
|
||||
row.token,
|
||||
row.position,
|
||||
head,
|
||||
residual.streams(),
|
||||
snapshot,
|
||||
)
|
||||
}
|
||||
/// The finite last-layer residual of row `index` as an owned witness of the row.
|
||||
fn verification_witness(&self, index: usize, residual: &InjectedResidual) -> Result<ChunkRowResidual> {
|
||||
let row = &self.rows[index];
|
||||
let mut streams = Vec::new();
|
||||
streams.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?;
|
||||
streams.extend_from_slice(residual.streams());
|
||||
Ok(ChunkRowResidual {
|
||||
binding: self.session.binding.clone(),
|
||||
chunk: self.chunk.clone(),
|
||||
origin: self.origin.clone(),
|
||||
token: row.token,
|
||||
position: row.position,
|
||||
known_next: self.rows.get(index + 1).map(|r| r.token),
|
||||
streams: Rc::new(streams.into_boxed_slice()),
|
||||
})
|
||||
}
|
||||
fn verify_row(
|
||||
&mut self,
|
||||
index: usize,
|
||||
residual: &Option<InjectedResidual>,
|
||||
execute_head: &mut impl FnMut(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result<TokenId>,
|
||||
) -> Result<()> {
|
||||
let row = &self.rows[index];
|
||||
let residual = residual.as_ref().ok_or(Error::Unsupported(Stage::Executor))?;
|
||||
residual.validate_origin(&self.session.binding, GrRole::Ffn(47))?;
|
||||
residual.identity().validate(row.token, row.position, LayerId::new(47, Dimension::new(48)?)?)?;
|
||||
if residual.streams().len() != 10240 || residual.streams().iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
let head = self.verification_head(index, residual, execute_head)?;
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
self.observe_verification_row(index, head, residual)?;
|
||||
let witness = self.verification_witness(index, residual)?;
|
||||
self.witnesses.push(witness);
|
||||
self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states[index].head = Some(head);
|
||||
Ok(())
|
||||
}
|
||||
pub(in super::super) fn finish_mtp_verification_inner(
|
||||
&mut self,
|
||||
residuals: &[Option<InjectedResidual>],
|
||||
execute_head: &mut impl FnMut(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result<TokenId>,
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
self.check_mtp_finishable(residuals)?;
|
||||
for (index, residual) in residuals.iter().enumerate() {
|
||||
let row = &self.rows[index];
|
||||
let residual = residual.as_ref().ok_or(Error::Unsupported(Stage::Executor))?;
|
||||
residual.validate_origin(&self.session.binding, GrRole::Ffn(47))?;
|
||||
residual.identity().validate(row.token, row.position, LayerId::new(47, Dimension::new(48)?)?)?;
|
||||
if residual.streams().len() != 10240 || residual.streams().iter().any(|v| !v.is_finite()) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
let state = self.validate_verification_state(index)?;
|
||||
let mut view = self.stage_view(index)?;
|
||||
// The head view has the actual complete row state, never the full
|
||||
// chunk's final state relabelled with an intermediate position.
|
||||
view.ple_state = state.ple.clone();
|
||||
if self.device_gdn_lease()?.is_none() || state.gdn.iter().any(Option::is_some) {
|
||||
view.gdn_states = state.gdn.clone();
|
||||
}
|
||||
// Device-only rows keep original unused canonical priors in the head
|
||||
// view; actual current provisional rows were authenticated above.
|
||||
// A diagnostic snapshot uses only real replay-materialized states.
|
||||
view.qsa_states = state.qsa.clone();
|
||||
let mut step = view.begin(row.token, row.position)?;
|
||||
step.input = row.input.clone();
|
||||
step.completed_layers = 48;
|
||||
let head = execute_head(&mut step, residual)?;
|
||||
if step.forward_output != Some(head) || step.prefill_finished {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if crate::qwen_forward::mtp_decode::batch_gpu::collecting() {
|
||||
// Observation of the validated completed journal, never a
|
||||
// session/Origin constructor or publication/restore authority.
|
||||
let snapshot = super::super::super::super::ResetReplaySnapshot {
|
||||
binding: self.session.binding.clone(),
|
||||
predecessors: [
|
||||
row.predecessors[1],
|
||||
i32::try_from(row.token.get()).map_err(|_| Error::InvalidToken)?,
|
||||
],
|
||||
next_position: row.position.get().checked_add(1).ok_or(Error::Overflow)?,
|
||||
layer_count: self.session.layer_count,
|
||||
ple_required: self.session.ple_required,
|
||||
ple: state.ple.clone(),
|
||||
gdn_layers: self.session.gdn_layers,
|
||||
gdn: state.gdn.clone(),
|
||||
qsa_layers: self.session.qsa_layers,
|
||||
qsa: state.qsa.clone(),
|
||||
};
|
||||
crate::qwen_forward::mtp_decode::batch_gpu::collect_row(
|
||||
row.token,
|
||||
row.position,
|
||||
head,
|
||||
residual.streams(),
|
||||
snapshot,
|
||||
)?;
|
||||
}
|
||||
let mut streams = Vec::new();
|
||||
streams.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?;
|
||||
streams.extend_from_slice(residual.streams());
|
||||
self.witnesses.push(ChunkRowResidual {
|
||||
binding: self.session.binding.clone(),
|
||||
chunk: self.chunk.clone(),
|
||||
origin: self.origin.clone(),
|
||||
token: row.token,
|
||||
position: row.position,
|
||||
known_next: self.rows.get(index + 1).map(|r| r.token),
|
||||
streams: Rc::new(streams.into_boxed_slice()),
|
||||
});
|
||||
self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states[index].head = Some(head);
|
||||
self.verify_row(index, residual, execute_head)?;
|
||||
}
|
||||
self.output = self.verification.as_ref().and_then(|j| j.states.last()).and_then(|s| s.head);
|
||||
self.finished = true;
|
||||
@@ -221,3 +259,11 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// The journaled prefix state of row `index`.
|
||||
fn journal_state(verification: &Option<VerificationJournal>, index: usize) -> Result<&PrefixState> {
|
||||
verification.as_ref().ok_or(Error::IdentityMismatch)?.states.get(index).ok_or(Error::IdentityMismatch)
|
||||
}
|
||||
/// The journaled prefix state of row `index`, for recording.
|
||||
fn journal_state_mut(verification: &mut Option<VerificationJournal>, index: usize) -> Result<&mut PrefixState> {
|
||||
verification.as_mut().ok_or(Error::IdentityMismatch)?.states.get_mut(index).ok_or(Error::IdentityMismatch)
|
||||
}
|
||||
|
||||
+37
-22
@@ -52,6 +52,24 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// With a device lease every GDN slot of the published state holds a prior valid at the end position.
|
||||
fn validate_lease_gdn(&self, state: &PrefixState, end: u64, leased: bool) -> Result<()> {
|
||||
if !leased {
|
||||
return Ok(());
|
||||
}
|
||||
let end_position = Position::new(end, crate::qwen_forward::contract::position_dimension())?;
|
||||
for slot in 0..STATE_CAPACITY {
|
||||
if self.session.gdn_layers[slot] {
|
||||
state.gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.gdn_owner,
|
||||
LayerId::new(slot as u64, Dimension::new(48)?)?,
|
||||
end_position,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(in crate::qwen_forward) fn publish_verified_joint(
|
||||
mut self,
|
||||
prefix: VerifiedTargetPrefix,
|
||||
@@ -64,37 +82,34 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
|
||||
let source = &self.witnesses[prefix.count - 1];
|
||||
let predecessors = [row.predecessors[1], i32::try_from(row.token.get()).map_err(|_| Error::InvalidToken)?];
|
||||
let end = row.position.get().checked_add(1).ok_or(Error::Overflow)?;
|
||||
let mut streams = Vec::new();
|
||||
streams.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?;
|
||||
streams.extend_from_slice(source.streams.as_ref());
|
||||
let streams = streams.into_boxed_slice();
|
||||
let streams = copy_streams(source)?;
|
||||
let binding = source.binding.clone();
|
||||
let token = row.token;
|
||||
let position = row.position;
|
||||
let journal = self.verification.take().ok_or(Error::IdentityMismatch)?;
|
||||
let state = journal.states.into_iter().nth(prefix.count - 1).ok_or(Error::IdentityMismatch)?;
|
||||
if journal.device_lease.is_some() {
|
||||
let end_position = Position::new(end, crate::qwen_forward::contract::position_dimension())?;
|
||||
for slot in 0..STATE_CAPACITY {
|
||||
if self.session.gdn_layers[slot] {
|
||||
state.gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.gdn_owner,
|
||||
LayerId::new(slot as u64, Dimension::new(48)?)?,
|
||||
end_position,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.validate_lease_gdn(&state, end, journal.device_lease.is_some())?;
|
||||
// All fallible work precedes either owner mutation. Rejected tail
|
||||
// states and row witnesses are dropped; no epoch or position rewind.
|
||||
self.session.ple_state = state.ple;
|
||||
self.session.gdn_states = state.gdn;
|
||||
self.session.qsa_states = state.qsa;
|
||||
self.session.predecessors = predecessors;
|
||||
self.session.next_position = end;
|
||||
install_prefix(self.session, state, predecessors, end);
|
||||
draft.publish();
|
||||
let origin = super::super::super::super::checkpoint::committed_origin(self.session);
|
||||
Ok(ChunkCommit { binding, token, position, output: Some(prefix.next), streams, origin })
|
||||
}
|
||||
}
|
||||
|
||||
/// An owned copy of the witness residual streams.
|
||||
fn copy_streams(source: &ChunkRowResidual) -> Result<Box<[f32]>> {
|
||||
let mut streams = Vec::new();
|
||||
streams.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?;
|
||||
streams.extend_from_slice(source.streams.as_ref());
|
||||
Ok(streams.into_boxed_slice())
|
||||
}
|
||||
/// The infallible owner assignments of a verified publication.
|
||||
fn install_prefix(session: &mut QwenSession<'_>, state: PrefixState, predecessors: [i32; 2], end: u64) {
|
||||
session.ple_state = state.ple;
|
||||
session.gdn_states = state.gdn;
|
||||
session.qsa_states = state.qsa;
|
||||
session.predecessors = predecessors;
|
||||
session.next_position = end;
|
||||
}
|
||||
|
||||
+33
-33
@@ -73,7 +73,8 @@ impl<'ctx> OriginalDraftSession<'ctx> {
|
||||
|| self.first_materialized > self.snapshot.next_position()
|
||||
{
|
||||
crate::bringup_trace!(
|
||||
"DBG draft.validate mismatch: binding_ok={} same_prefix={} snapshot_next={} target_next={} draft_origin_next={} first_materialized={}",
|
||||
"DBG draft.validate mismatch: binding_ok={} same_prefix={} snapshot_next={} target_next={} \
|
||||
draft_origin_next={} first_materialized={}",
|
||||
self.binding.matches(&binding.identity()),
|
||||
self.origin.same_prefix(origin),
|
||||
self.snapshot.next_position(),
|
||||
@@ -141,19 +142,14 @@ impl<'ctx> OriginalDraftSession<'ctx> {
|
||||
}
|
||||
result
|
||||
}
|
||||
/// Literal generate.cpp ordering for a verified serve window: the target
|
||||
/// owner has already committed `a + 1` rows, while this independent MTP
|
||||
/// ring is still anchored at the pre-window snapshot. A normal prompt
|
||||
/// loan cannot express that intentional position skew, so this transition
|
||||
/// requires both real origins explicitly. It never advances target state.
|
||||
pub(in crate::qwen_forward) fn with_mtp_transition_ring<R>(
|
||||
&mut self,
|
||||
/// The ring is healthy and bound to this binding, prefix and context, and `committed` is the current target
|
||||
/// origin standing strictly after `before` on the same branch.
|
||||
fn check_transition(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
session: &QwenSession<'ctx>,
|
||||
before: &TargetStepOrigin,
|
||||
committed: &TargetStepOrigin,
|
||||
execute: impl FnOnce(&mut MtpOriginalInt8<'ctx>, &MtpInt8Snapshot) -> Result<R>,
|
||||
) -> Result<R> {
|
||||
(before, committed): (&TargetStepOrigin, &TargetStepOrigin),
|
||||
) -> Result<()> {
|
||||
if self.failed
|
||||
|| !self.binding.matches(&binding.identity())
|
||||
|| !self.origin.same_prefix(before)
|
||||
@@ -170,6 +166,13 @@ impl<'ctx> OriginalDraftSession<'ctx> {
|
||||
if committed.next_position() <= before.next_position() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Lend the ring after its context and snapshot validate; a failed ring or poisoned context marks it failed.
|
||||
pub(super) fn run_validated_ring<R>(
|
||||
&mut self,
|
||||
execute: impl FnOnce(&mut MtpOriginalInt8<'ctx>, &MtpInt8Snapshot) -> Result<R>,
|
||||
) -> Result<R> {
|
||||
let ring = self.ring.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
ring.validate_context(self.context).map_err(draft_driver_error)?;
|
||||
ring.validate_snapshot(&self.snapshot).map_err(draft_driver_error)?;
|
||||
@@ -179,6 +182,22 @@ impl<'ctx> OriginalDraftSession<'ctx> {
|
||||
}
|
||||
result
|
||||
}
|
||||
/// Literal generate.cpp ordering for a verified serve window: the target
|
||||
/// owner has already committed `a + 1` rows, while this independent MTP
|
||||
/// ring is still anchored at the pre-window snapshot. A normal prompt
|
||||
/// loan cannot express that intentional position skew, so this transition
|
||||
/// requires both real origins explicitly. It never advances target state.
|
||||
pub(in crate::qwen_forward) fn with_mtp_transition_ring<R>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
session: &QwenSession<'ctx>,
|
||||
before: &TargetStepOrigin,
|
||||
committed: &TargetStepOrigin,
|
||||
execute: impl FnOnce(&mut MtpOriginalInt8<'ctx>, &MtpInt8Snapshot) -> Result<R>,
|
||||
) -> Result<R> {
|
||||
self.check_transition(binding, session, (before, committed))?;
|
||||
self.run_validated_ring(execute)
|
||||
}
|
||||
/// `with_mtp_transition_ring` for a draft LAUNCHED while the verifier's commit of `prospective` is enqueued and
|
||||
/// not yet published (generate.cpp enqueues the draft behind the commit): the session still stands exactly at
|
||||
/// `before`; `prospective` must be the same branch, further on. The completion is published only through
|
||||
@@ -203,14 +222,7 @@ impl<'ctx> OriginalDraftSession<'ctx> {
|
||||
if prospective.next_position() <= before.next_position() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let ring = self.ring.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
ring.validate_context(self.context).map_err(draft_driver_error)?;
|
||||
ring.validate_snapshot(&self.snapshot).map_err(draft_driver_error)?;
|
||||
let result = execute(ring, &self.snapshot);
|
||||
if ring.is_failed() || self.context.is_poisoned() {
|
||||
self.failed = true;
|
||||
}
|
||||
result
|
||||
self.run_validated_ring(execute)
|
||||
}
|
||||
/// Rebinds only the independent MTP ring after its fully drained source
|
||||
/// draft. The target state was committed by the verifier beforehand; this
|
||||
@@ -227,19 +239,7 @@ impl<'ctx> OriginalDraftSession<'ctx> {
|
||||
// speculative snapshot, so this publication must validate that new
|
||||
// physical current state directly. Re-entering the pre-graph loan
|
||||
// would incorrectly demand the old snapshot after a successful draft.
|
||||
if self.failed
|
||||
|| !self.binding.matches(&binding.identity())
|
||||
|| !self.origin.same_prefix(before)
|
||||
|| !before.same_session(committed)
|
||||
|| !std::ptr::eq(self.context, session.mtp_context()?)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
before.validate_projection_branch(session)?;
|
||||
committed.validate(session)?;
|
||||
if committed.next_position() <= before.next_position() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.check_transition(binding, session, (before, committed))?;
|
||||
let ring = self.ring.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
ring.validate_context(self.context).map_err(draft_driver_error)?;
|
||||
completed.validate_current(ring).map_err(draft_driver_error)?;
|
||||
|
||||
+50
-58
@@ -23,14 +23,33 @@ impl<'ctx> OriginalDraftSession<'ctx> {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
origin.validate(session)?;
|
||||
let ring = self.ring.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
ring.validate_context(self.context).map_err(draft_driver_error)?;
|
||||
ring.validate_snapshot(&self.snapshot).map_err(draft_driver_error)?;
|
||||
let result = execute(ring, &self.snapshot);
|
||||
if ring.is_failed() || self.context.is_poisoned() {
|
||||
self.failed = true;
|
||||
self.run_validated_ring(execute)
|
||||
}
|
||||
/// A publication matches the completed draft: next position at the prompt end, a materialized window that
|
||||
/// still fits, and the same owner as the retained snapshot.
|
||||
fn check_publication(
|
||||
&self,
|
||||
completed: &CompletedDraftKv,
|
||||
(start, end): (usize, usize),
|
||||
first_materialized: usize,
|
||||
) -> Result<()> {
|
||||
if completed.next_position() != end
|
||||
|| end == 0
|
||||
|| first_materialized > end.saturating_sub(leleka_cuda_driver::MTP_ORIGINAL_WINDOW)
|
||||
|| !completed.owner_id().same_owner(&self.snapshot.owner_id())
|
||||
{
|
||||
crate::bringup_trace!(
|
||||
"DBG draft.prepare_publication refused: start={start} end={end} completed_next={} completed_first={} \
|
||||
prior_first={} prior_next={} lower={first_materialized} same_owner={}",
|
||||
completed.next_position(),
|
||||
completed.first_materialized(),
|
||||
self.first_materialized,
|
||||
self.snapshot.next_position(),
|
||||
completed.owner_id().same_owner(&self.snapshot.owner_id())
|
||||
);
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
result
|
||||
Ok(())
|
||||
}
|
||||
pub(in super::super) fn prepare_publication<'a>(
|
||||
&'a mut self,
|
||||
@@ -50,25 +69,31 @@ impl<'ctx> OriginalDraftSession<'ctx> {
|
||||
completed.first_materialized(),
|
||||
end,
|
||||
);
|
||||
if completed.next_position() != end
|
||||
|| end == 0
|
||||
|| first_materialized > end.saturating_sub(leleka_cuda_driver::MTP_ORIGINAL_WINDOW)
|
||||
|| !completed.owner_id().same_owner(&self.snapshot.owner_id())
|
||||
{
|
||||
crate::bringup_trace!(
|
||||
"DBG draft.prepare_publication refused: start={start} end={end} completed_next={} completed_first={} prior_first={} prior_next={} lower={first_materialized} same_owner={}",
|
||||
completed.next_position(),
|
||||
completed.first_materialized(),
|
||||
self.first_materialized,
|
||||
self.snapshot.next_position(),
|
||||
completed.owner_id().same_owner(&self.snapshot.owner_id())
|
||||
);
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.check_publication(completed, (start, end), first_materialized)?;
|
||||
let snapshot = completed.snapshot_after(end - 1).map_err(draft_driver_error)?;
|
||||
ring.validate_snapshot(&snapshot).map_err(draft_driver_error)?;
|
||||
Ok(OriginalDraftPublication { owner: self, snapshot, first_materialized })
|
||||
}
|
||||
/// Roll the physical ring back to `snapshot`; an uncertain restore poisons this owner.
|
||||
fn restore_ring(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
snapshot: &MtpInt8Snapshot,
|
||||
) -> Result<()> {
|
||||
let context = dense.retained_context(binding, self.context)?;
|
||||
let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let result = self
|
||||
.ring
|
||||
.as_mut()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.restore(&mut workspace, snapshot)
|
||||
.map_err(draft_driver_error);
|
||||
if result.is_err() {
|
||||
self.failed = true;
|
||||
}
|
||||
result
|
||||
}
|
||||
/// All physical restores are attempted by the coupled target owner. An
|
||||
/// uncertain ring restore poisons this owner even when target rollback works.
|
||||
pub(in super::super) fn restore_physical(
|
||||
@@ -84,18 +109,7 @@ impl<'ctx> OriginalDraftSession<'ctx> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let context = dense.retained_context(binding, self.context)?;
|
||||
let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let result = self
|
||||
.ring
|
||||
.as_mut()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.restore(&mut workspace, &prior.snapshot)
|
||||
.map_err(draft_driver_error);
|
||||
if result.is_err() {
|
||||
self.failed = true;
|
||||
}
|
||||
result
|
||||
self.restore_ring(binding, dense, &prior.snapshot)
|
||||
}
|
||||
/// Roll the MTP ring back to `prior` and rebind it to the (already restored) target branch. The
|
||||
/// serve host calls this for a failed round after the target side was repaired: both physical
|
||||
@@ -135,18 +149,7 @@ impl<'ctx> OriginalDraftSession<'ctx> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let context = dense.retained_context(binding, self.context)?;
|
||||
let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let result = self
|
||||
.ring
|
||||
.as_mut()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.restore(&mut workspace, &empty.snapshot)
|
||||
.map_err(draft_driver_error);
|
||||
if result.is_err() {
|
||||
self.failed = true;
|
||||
return result;
|
||||
}
|
||||
self.restore_ring(binding, dense, &empty.snapshot)?;
|
||||
self.origin = actual;
|
||||
self.snapshot = empty.snapshot.clone();
|
||||
self.first_materialized = 0;
|
||||
@@ -177,18 +180,7 @@ impl<'ctx> OriginalDraftSession<'ctx> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let context = dense.retained_context(binding, self.context)?;
|
||||
let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let result = self
|
||||
.ring
|
||||
.as_mut()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.restore(&mut workspace, &point.snapshot)
|
||||
.map_err(draft_driver_error);
|
||||
if result.is_err() {
|
||||
self.failed = true;
|
||||
return result;
|
||||
}
|
||||
self.restore_ring(binding, dense, &point.snapshot)?;
|
||||
self.origin = actual;
|
||||
self.snapshot = point.snapshot.clone();
|
||||
self.first_materialized = point.first_materialized;
|
||||
|
||||
+149
-90
@@ -3,16 +3,11 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
type RestoredLayers<'driver> = [Option<ResidentQsaPrior<'driver>>; STATE_CAPACITY];
|
||||
|
||||
impl<'driver> QwenSession<'driver> {
|
||||
pub(in crate::qwen_forward) fn original_checkpoint(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
) -> Result<OriginalSessionCheckpoint<'driver>> {
|
||||
let origin = self.target_origin()?;
|
||||
// a checkpoint of lagging recurrent priors would name a state the session does not hold
|
||||
if !self.binding.matches(&binding.identity()) || self.layer_count != 48 || self.state_lag.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
/// Every QSA slot holds a resident witness valid at the session position; every other slot holds none.
|
||||
fn check_resident_states(&self, binding: &ModelBinding) -> Result<()> {
|
||||
for slot in 0..48 {
|
||||
if self.qsa_layers[slot] {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
@@ -26,6 +21,18 @@ impl<'driver> QwenSession<'driver> {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(in crate::qwen_forward) fn original_checkpoint(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
) -> Result<OriginalSessionCheckpoint<'driver>> {
|
||||
let origin = self.target_origin()?;
|
||||
// a checkpoint of lagging recurrent priors would name a state the session does not hold
|
||||
if !self.binding.matches(&binding.identity()) || self.layer_count != 48 || self.state_lag.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.check_resident_states(binding)?;
|
||||
self.complete_cuda()?;
|
||||
Ok(OriginalSessionCheckpoint {
|
||||
origin,
|
||||
@@ -35,6 +42,79 @@ impl<'driver> QwenSession<'driver> {
|
||||
qsa: self.resident_qsa_states.clone(),
|
||||
})
|
||||
}
|
||||
/// The saved witnesses validate at the checkpoint position and still name the live layers' current priors.
|
||||
fn check_restore_slots(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
layers: &[Option<ResidentQsaLayer<'driver>>; STATE_CAPACITY],
|
||||
prior: &OriginalSessionCheckpoint<'driver>,
|
||||
) -> Result<()> {
|
||||
for slot in 0..48 {
|
||||
if self.qsa_layers[slot] {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
let saved = prior.qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
saved.validate_for_session(binding, self, layer, prior.origin.next_position())?;
|
||||
let actual = layers[slot].as_ref().ok_or(Error::IdentityMismatch)?.current();
|
||||
if self.resident_qsa_states[slot].as_ref().is_none_or(|current| !current.same_prior(&actual)) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
} else if prior.qsa[slot].is_some() || layers[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Roll every resident layer back to its saved witness, attempting all of them; the first failure is returned.
|
||||
fn restore_layers(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'driver>,
|
||||
layers: &mut [Option<ResidentQsaLayer<'driver>>; STATE_CAPACITY],
|
||||
(prior, workspace): (
|
||||
&OriginalSessionCheckpoint<'driver>,
|
||||
&mut leleka_cuda_driver::NativeBatchWorkspace<'driver>,
|
||||
),
|
||||
) -> Result<(RestoredLayers<'driver>, Option<Error>)> {
|
||||
let mut restored = std::array::from_fn(|_| None);
|
||||
let mut first_error = None;
|
||||
for (slot, layer) in layers.iter_mut().enumerate() {
|
||||
if let Some(layer) = layer {
|
||||
let saved = prior.qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
match layer.restore(binding, dense, self, saved, workspace) {
|
||||
Ok(current) => restored[slot] = Some(current),
|
||||
Err(error) => {
|
||||
first_error.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((restored, first_error))
|
||||
}
|
||||
/// A layer failure poisons the MTP device state and is the result of the whole operation.
|
||||
fn fail_first(&mut self, first_error: Option<Error>) -> Result<()> {
|
||||
match first_error {
|
||||
Some(error) => {
|
||||
self.note_mtp_failure(&error);
|
||||
Err(error)
|
||||
}
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
/// Every recurrent prior was just replaced: nothing lags any more, and the resident witnesses are the restored ones.
|
||||
fn adopt_restored(
|
||||
&mut self,
|
||||
(next_position, predecessors): (u64, [i32; 2]),
|
||||
(ple, gdn): (Option<PlePrior>, [Option<GdnPrior>; STATE_CAPACITY]),
|
||||
restored: RestoredLayers<'driver>,
|
||||
) {
|
||||
self.next_position = next_position;
|
||||
self.predecessors = predecessors;
|
||||
self.ple_state = ple;
|
||||
self.gdn_states = gdn;
|
||||
self.state_lag = None;
|
||||
self.qsa_states = std::array::from_fn(|_| None);
|
||||
self.resident_qsa_states = restored;
|
||||
}
|
||||
pub(in crate::qwen_forward) fn restore_original_checkpoint(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
@@ -49,19 +129,7 @@ impl<'driver> QwenSession<'driver> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
for slot in 0..48 {
|
||||
if self.qsa_layers[slot] {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
let saved = prior.qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
saved.validate_for_session(binding, self, layer, prior.origin.next_position())?;
|
||||
let actual = layers[slot].as_ref().ok_or(Error::IdentityMismatch)?.current();
|
||||
if self.resident_qsa_states[slot].as_ref().is_none_or(|current| !current.same_prior(&actual)) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
} else if prior.qsa[slot].is_some() || layers[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
self.check_restore_slots(binding, layers, prior)?;
|
||||
let generation = self.checkpoint_generation.checked_add(1).ok_or(Error::Overflow)?;
|
||||
self.complete_cuda()?;
|
||||
// Fence the rejected branch before physical rollback. A failed rollback
|
||||
@@ -69,33 +137,12 @@ impl<'driver> QwenSession<'driver> {
|
||||
self.checkpoint_generation = generation;
|
||||
let context = dense.retained_context(binding, self.mtp_context()?)?;
|
||||
let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let mut restored = std::array::from_fn(|_| None);
|
||||
let mut first_error = None;
|
||||
for (slot, layer) in layers.iter_mut().enumerate() {
|
||||
if let Some(layer) = layer {
|
||||
let saved = prior.qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
match layer.restore(binding, dense, self, saved, &mut workspace) {
|
||||
Ok(current) => restored[slot] = Some(current),
|
||||
Err(error) => {
|
||||
first_error.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let (restored, first_error) = self.restore_layers(binding, dense, layers, (prior, &mut workspace))?;
|
||||
drop(workspace);
|
||||
if let Some(error) = first_error {
|
||||
self.note_mtp_failure(&error);
|
||||
return Err(error);
|
||||
}
|
||||
self.fail_first(first_error)?;
|
||||
self.complete_cuda()?;
|
||||
self.next_position = prior.origin.next_position();
|
||||
self.predecessors = prior.predecessors;
|
||||
self.ple_state = prior.ple.clone();
|
||||
self.gdn_states = prior.gdn.clone();
|
||||
// every recurrent prior was just replaced from the checkpoint: nothing lags any more
|
||||
self.state_lag = None;
|
||||
self.qsa_states = std::array::from_fn(|_| None);
|
||||
self.resident_qsa_states = restored;
|
||||
let (position, predecessors) = (prior.origin.next_position(), prior.predecessors);
|
||||
self.adopt_restored((position, predecessors), (prior.ple.clone(), prior.gdn.clone()), restored);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -174,6 +221,57 @@ impl<'driver> QwenSession<'driver> {
|
||||
}
|
||||
Ok(ParkedBlock { first_token: first, tokens, layers: out })
|
||||
}
|
||||
/// The parked point names this session's own layers, fits the context, and every block covers the same layers.
|
||||
fn check_import(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
layers: &[Option<ResidentQsaLayer<'driver>>; STATE_CAPACITY],
|
||||
(parked, blocks): (&ParkedSession, &[&ParkedBlock]),
|
||||
) -> Result<()> {
|
||||
self.target_origin()?;
|
||||
if !self.binding.matches(&binding.identity())
|
||||
|| self.layer_count != 48
|
||||
|| parked.position >= u64::from(binding.input_constants().context_length())
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
for slot in 0..48 {
|
||||
let wanted = self.qsa_layers[slot];
|
||||
if wanted != layers[slot].is_some()
|
||||
|| wanted != parked.tails[slot].is_some()
|
||||
|| blocks.iter().any(|b| b.layers[slot].is_some() != wanted)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Write every layer's parked cells and re-mint its witness, attempting all of them; the first failure is returned.
|
||||
fn import_layers(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'driver>,
|
||||
layers: &mut [Option<ResidentQsaLayer<'driver>>; STATE_CAPACITY],
|
||||
(parked, blocks): (&ParkedSession, &[&ParkedBlock]),
|
||||
workspace: &mut leleka_cuda_driver::NativeBatchWorkspace<'driver>,
|
||||
) -> Result<(RestoredLayers<'driver>, Option<Error>)> {
|
||||
let mut restored = std::array::from_fn(|_| None);
|
||||
let mut first_error = None;
|
||||
let end = usize::try_from(parked.position).map_err(|_| Error::Overflow)?;
|
||||
for (slot, layer) in layers.iter_mut().enumerate() {
|
||||
if let Some(layer) = layer {
|
||||
let spans: Vec<&ParkedLayerSpan> = blocks.iter().filter_map(|b| b.layers[slot].as_ref()).collect();
|
||||
let tail = parked.tails[slot].as_deref().ok_or(Error::IdentityMismatch)?;
|
||||
match layer.import(binding, dense, self, tail, &spans, end, workspace) {
|
||||
Ok(current) => restored[slot] = Some(current),
|
||||
Err(error) => {
|
||||
first_error.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((restored, first_error))
|
||||
}
|
||||
/// Make the session and the twelve physical layers stand at `parked`, writing the cells of `blocks` (the layers'
|
||||
/// cells below the position that no block names must already hold the parked prefix; the caller knows which).
|
||||
/// Unlike `restore_original_checkpoint` this accepts a point of ANOTHER lineage, because everything a lineage
|
||||
@@ -187,23 +285,7 @@ impl<'driver> QwenSession<'driver> {
|
||||
parked: &ParkedSession,
|
||||
blocks: &[&ParkedBlock],
|
||||
) -> Result<()> {
|
||||
let origin = self.target_origin()?;
|
||||
if !self.binding.matches(&binding.identity())
|
||||
|| self.layer_count != 48
|
||||
|| parked.position >= u64::from(binding.input_constants().context_length())
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let _ = origin;
|
||||
for slot in 0..48 {
|
||||
let wanted = self.qsa_layers[slot];
|
||||
if wanted != layers[slot].is_some()
|
||||
|| wanted != parked.tails[slot].is_some()
|
||||
|| blocks.iter().any(|b| b.layers[slot].is_some() != wanted)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
self.check_import(binding, layers, (parked, blocks))?;
|
||||
let generation = self.checkpoint_generation.checked_add(1).ok_or(Error::Overflow)?;
|
||||
{
|
||||
let _p = super::super::super::super::original_serve_profile::span("prefix.import_sync");
|
||||
@@ -215,34 +297,11 @@ impl<'driver> QwenSession<'driver> {
|
||||
let _p = super::super::super::super::original_serve_profile::span("prefix.import_workspace");
|
||||
dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?
|
||||
};
|
||||
let mut restored = std::array::from_fn(|_| None);
|
||||
let mut first_error = None;
|
||||
let end = usize::try_from(parked.position).map_err(|_| Error::Overflow)?;
|
||||
for (slot, layer) in layers.iter_mut().enumerate() {
|
||||
if let Some(layer) = layer {
|
||||
let spans: Vec<&ParkedLayerSpan> = blocks.iter().filter_map(|b| b.layers[slot].as_ref()).collect();
|
||||
let tail = parked.tails[slot].as_deref().ok_or(Error::IdentityMismatch)?;
|
||||
match layer.import(binding, dense, self, tail, &spans, end, &mut workspace) {
|
||||
Ok(current) => restored[slot] = Some(current),
|
||||
Err(error) => {
|
||||
first_error.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let (restored, first_error) = self.import_layers(binding, dense, layers, (parked, blocks), &mut workspace)?;
|
||||
drop(workspace);
|
||||
if let Some(error) = first_error {
|
||||
self.note_mtp_failure(&error);
|
||||
return Err(error);
|
||||
}
|
||||
self.fail_first(first_error)?;
|
||||
self.complete_cuda()?;
|
||||
self.next_position = parked.position;
|
||||
self.predecessors = parked.predecessors;
|
||||
self.ple_state = parked.ple.clone();
|
||||
self.gdn_states = parked.gdn.clone();
|
||||
self.state_lag = None;
|
||||
self.qsa_states = std::array::from_fn(|_| None);
|
||||
self.resident_qsa_states = restored;
|
||||
self.adopt_restored((parked.position, parked.predecessors), (parked.ple.clone(), parked.gdn.clone()), restored);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+113
-83
@@ -15,60 +15,10 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let tokens = source.window(binding, session.next_position, count)?;
|
||||
for slot in 0..48 {
|
||||
if session.qsa_layers[slot] {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
session.resident_qsa_states[slot].as_ref().ok_or(Error::IdentityMismatch)?.validate_for_session(
|
||||
binding,
|
||||
session,
|
||||
layer,
|
||||
session.next_position,
|
||||
)?;
|
||||
if session.qsa_states[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
} else if session.resident_qsa_states[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
if !(1..=8192).contains(&tokens.len())
|
||||
|| binding.layer_count() != 48
|
||||
|| !session.binding.matches(&binding.identity())
|
||||
|| session.layer_count != 48
|
||||
|| session.cuda.is_none()
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let end = session.next_position.checked_add(tokens.len() as u64).ok_or(Error::Overflow)?;
|
||||
let limit = u64::from(binding.input_constants().context_length());
|
||||
// A subsequent sampled token requires one remaining valid position.
|
||||
if end >= limit {
|
||||
return Err(Error::InvalidPosition);
|
||||
}
|
||||
let vocab = Dimension::new(248320)?;
|
||||
for token in tokens {
|
||||
if *token != TokenId::new(token.get() as u64, vocab)? {
|
||||
return Err(Error::InvalidToken);
|
||||
}
|
||||
}
|
||||
let mut owned = Vec::new();
|
||||
owned.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?;
|
||||
owned.extend_from_slice(tokens);
|
||||
let mut inputs = Vec::new();
|
||||
inputs.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let phase = Rc::new(OriginalPromptPhase {
|
||||
binding: binding.identity(),
|
||||
source: Rc::clone(source),
|
||||
origin,
|
||||
owner: Rc::new(()),
|
||||
phase: Cell::new(DevicePhase::Staging),
|
||||
ple_required: session.ple_required,
|
||||
ple_done: Cell::new(false),
|
||||
failed: Cell::new(false),
|
||||
rows: tokens.len(),
|
||||
first: session.next_position,
|
||||
end,
|
||||
});
|
||||
check_prompt_session(session, binding, tokens.len())?;
|
||||
let end = prompt_end(session, binding, tokens)?;
|
||||
let owned = owned_tokens(tokens)?;
|
||||
let phase = Rc::new(OriginalPromptPhase::start(session, binding, (source, origin), (tokens.len(), end)));
|
||||
Ok(Self {
|
||||
predecessors: session.predecessors,
|
||||
next_ple: RefCell::new(None),
|
||||
@@ -81,7 +31,7 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
|
||||
session,
|
||||
phase,
|
||||
tokens: owned,
|
||||
inputs,
|
||||
inputs: reserved(tokens.len())?,
|
||||
})
|
||||
}
|
||||
pub(in super::super) fn check(&self) -> Result<()> {
|
||||
@@ -164,21 +114,9 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
|
||||
key.validate_initial(&self.session.binding, input)?;
|
||||
Ok(key)
|
||||
}
|
||||
/// Actual initial input transactions only. No intermediate layer/history
|
||||
/// is constructed by this view; each next row uses true token predecessors.
|
||||
pub(in crate::qwen_forward) fn stage_input(
|
||||
&mut self,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result<InputReady>,
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
if self.phase.phase.get() != DevicePhase::Staging || self.inputs.len() >= self.tokens.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let index = self.inputs.len();
|
||||
let token = self.tokens[index];
|
||||
let position =
|
||||
Position::new(self.phase.first + index as u64, crate::qwen_forward::contract::position_dimension())?;
|
||||
let mut view = QwenSession {
|
||||
/// The stage view of the next input row: this transaction's rolling predecessors over the session's priors.
|
||||
fn input_view(&self, position: Position) -> QwenSession<'driver> {
|
||||
QwenSession {
|
||||
binding: self.session.binding.clone(),
|
||||
owner: Rc::clone(&self.session.owner),
|
||||
owner_thread: self.session.owner_thread,
|
||||
@@ -199,24 +137,35 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
|
||||
qsa_states: self.session.qsa_states.clone(),
|
||||
state_lag: None,
|
||||
resident_qsa_states: self.session.resident_qsa_states.clone(),
|
||||
};
|
||||
}
|
||||
}
|
||||
/// Actual initial input transactions only. No intermediate layer/history
|
||||
/// is constructed by this view; each next row uses true token predecessors.
|
||||
pub(in crate::qwen_forward) fn stage_input(
|
||||
&mut self,
|
||||
execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result<InputReady>,
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
if self.phase.phase.get() != DevicePhase::Staging || self.inputs.len() >= self.tokens.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let index = self.inputs.len();
|
||||
let token = self.tokens[index];
|
||||
let position =
|
||||
Position::new(self.phase.first + index as u64, crate::qwen_forward::contract::position_dimension())?;
|
||||
let mut view = self.input_view(position);
|
||||
let operation = (|| {
|
||||
let mut step = view.begin(token, position)?;
|
||||
let input = execute(&mut step)?;
|
||||
step.stage_input(input)
|
||||
})();
|
||||
match operation {
|
||||
Ok(input) => {
|
||||
self.inputs.push(input);
|
||||
self.predecessors = [self.predecessors[1], token.get() as i32];
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
self.phase.failed.set(true);
|
||||
self.session.note_mtp_failure(&error);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
let input = operation.inspect_err(|error| {
|
||||
self.phase.failed.set(true);
|
||||
self.session.note_mtp_failure(error);
|
||||
})?;
|
||||
self.inputs.push(input);
|
||||
self.predecessors = [self.predecessors[1], token.get() as i32];
|
||||
Ok(())
|
||||
}
|
||||
pub(in crate::qwen_forward) fn validate_phase(&self, role: GrRole, read: bool) -> Result<()> {
|
||||
self.check()?;
|
||||
@@ -240,3 +189,84 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// A fresh Vec with room for `count` elements, or an input allocation error.
|
||||
fn reserved<T>(count: usize) -> Result<Vec<T>> {
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?;
|
||||
Ok(values)
|
||||
}
|
||||
/// An owned copy of the prompt window tokens.
|
||||
fn owned_tokens(tokens: &[TokenId]) -> Result<Vec<TokenId>> {
|
||||
let mut owned = reserved(tokens.len())?;
|
||||
owned.extend_from_slice(tokens);
|
||||
Ok(owned)
|
||||
}
|
||||
/// The session is a bound 48-layer device session, every QSA slot holds a resident witness valid at its
|
||||
/// position (and no non-resident state), and the window length is within the prompt bound.
|
||||
fn check_prompt_session(session: &QwenSession<'_>, binding: &ModelBinding, count: usize) -> Result<()> {
|
||||
for slot in 0..48 {
|
||||
if session.qsa_layers[slot] {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
session.resident_qsa_states[slot].as_ref().ok_or(Error::IdentityMismatch)?.validate_for_session(
|
||||
binding,
|
||||
session,
|
||||
layer,
|
||||
session.next_position,
|
||||
)?;
|
||||
if session.qsa_states[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
} else if session.resident_qsa_states[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
if !(1..=8192).contains(&count)
|
||||
|| binding.layer_count() != 48
|
||||
|| !session.binding.matches(&binding.identity())
|
||||
|| session.layer_count != 48
|
||||
|| session.cuda.is_none()
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The end position of the window: one valid position must remain for a sampled token, and every token must be in
|
||||
/// the vocabulary.
|
||||
fn prompt_end(session: &QwenSession<'_>, binding: &ModelBinding, tokens: &[TokenId]) -> Result<u64> {
|
||||
let end = session.next_position.checked_add(tokens.len() as u64).ok_or(Error::Overflow)?;
|
||||
let limit = u64::from(binding.input_constants().context_length());
|
||||
// A subsequent sampled token requires one remaining valid position.
|
||||
if end >= limit {
|
||||
return Err(Error::InvalidPosition);
|
||||
}
|
||||
let vocab = Dimension::new(248320)?;
|
||||
for token in tokens {
|
||||
if *token != TokenId::new(token.get() as u64, vocab)? {
|
||||
return Err(Error::InvalidToken);
|
||||
}
|
||||
}
|
||||
Ok(end)
|
||||
}
|
||||
impl OriginalPromptPhase {
|
||||
/// The staging phase of a window of `rows` rows from the session's position to `end`.
|
||||
fn start(
|
||||
session: &QwenSession<'_>,
|
||||
binding: &ModelBinding,
|
||||
(source, origin): (&Rc<OriginalPromptInput>, TargetStepOrigin),
|
||||
(rows, end): (usize, u64),
|
||||
) -> Self {
|
||||
Self {
|
||||
binding: binding.identity(),
|
||||
source: Rc::clone(source),
|
||||
origin,
|
||||
owner: Rc::new(()),
|
||||
phase: Cell::new(DevicePhase::Staging),
|
||||
ple_required: session.ple_required,
|
||||
ple_done: Cell::new(false),
|
||||
failed: Cell::new(false),
|
||||
rows,
|
||||
first: session.next_position,
|
||||
end,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+12
-10
@@ -124,6 +124,17 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
|
||||
self.phase.failed.set(true);
|
||||
self.session.restore_original_checkpoint(binding, dense, layers, checkpoint)
|
||||
}
|
||||
/// Rebind the restored draft to the target branch read back from the session; the failure, if any.
|
||||
fn rebind_draft(
|
||||
&self,
|
||||
draft: &mut draft::OriginalDraftSession<'driver>,
|
||||
prior: &draft::OriginalDraftCheckpoint,
|
||||
) -> Option<Error> {
|
||||
match self.session.target_origin() {
|
||||
Ok(actual) => draft.rebind_restored(prior, &actual).err(),
|
||||
Err(error) => Some(error),
|
||||
}
|
||||
}
|
||||
/// Attempt both physical restores even if one fails. The accepted target
|
||||
/// branch is read back only after the real layer rollback; it is never
|
||||
/// inferred from a requested position or the draft's end metadata.
|
||||
@@ -142,16 +153,7 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
|
||||
first.get_or_insert(error);
|
||||
}
|
||||
if first.is_none() {
|
||||
match self.session.target_origin() {
|
||||
Ok(actual) => {
|
||||
if let Err(error) = draft.rebind_restored(prior, &actual) {
|
||||
first.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
first.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
first = self.rebind_draft(draft, prior);
|
||||
}
|
||||
if let Some(error) = first {
|
||||
draft.mark_failed();
|
||||
|
||||
+129
-68
@@ -1,9 +1,133 @@
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalPromptTxn (3).
|
||||
|
||||
use super::super::super::super::qsa_index::prompt_device::resident_device::ResidentQsaPublication;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
|
||||
/// The final rows, the sampled token and the draft KV all name this transaction and agree on the next token.
|
||||
fn validate_publish_inputs(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
completed: &super::super::super::super::prompt_device_rows::PromptDeviceFinal,
|
||||
draft_kv: &super::super::super::super::prompt_device_rows::OriginalDraftKvPending,
|
||||
sample: &super::super::super::super::output::OriginalPromptSample,
|
||||
) -> Result<()> {
|
||||
self.validate_final(completed)?;
|
||||
sample.validate(binding, completed, self)?;
|
||||
draft_kv.validate(binding, self, completed)?;
|
||||
if draft_kv.last_next(binding, self, completed)? != sample.next() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// A GDN slot holds a prior valid at the end position, and a non-GDN slot holds none: whether it is required.
|
||||
fn publish_gdn_slot(&self, gdn: &Option<GdnPrior>, slot: usize, end: Position) -> Result<bool> {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
if self.session.gdn_layers[slot] {
|
||||
gdn.as_ref().ok_or(Error::IdentityMismatch)?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.gdn_owner,
|
||||
layer,
|
||||
end,
|
||||
)?;
|
||||
Ok(true)
|
||||
} else if gdn.is_some() {
|
||||
Err(Error::IdentityMismatch)
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
/// A QSA slot holds a seal continuing the resident witness to the end position over a live layer, and a
|
||||
/// non-QSA slot holds neither seal nor layer: whether it is required.
|
||||
fn publish_qsa_slot(
|
||||
&self,
|
||||
(binding, dense): (&ModelBinding, &DenseWeightCache<'driver>),
|
||||
(layer_slot, seal): (&Option<ResidentQsaLayer<'driver>>, &Option<ResidentQsaSeal<'driver>>),
|
||||
slot: usize,
|
||||
) -> Result<bool> {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
if !self.session.qsa_layers[slot] {
|
||||
return if seal.is_some() || layer_slot.is_some() { Err(Error::IdentityMismatch) } else { Ok(false) };
|
||||
}
|
||||
let seal = seal.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
seal.validate_for(binding, dense, self.session, layer, self.phase.first, self.tokens.len())?;
|
||||
let prior = self.session.resident_qsa_states[slot].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
if !seal.previous_matches(prior) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
seal.next_prior().validate_for_session(binding, self.session, layer, self.phase.end)?;
|
||||
if layer_slot.is_none() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
/// Every slot is valid at the end position and exactly the required GDN and QSA slots were completed.
|
||||
fn validate_publish_slots(
|
||||
&self,
|
||||
(binding, dense): (&ModelBinding, &DenseWeightCache<'driver>),
|
||||
layers: &[Option<ResidentQsaLayer<'driver>>; STATE_CAPACITY],
|
||||
(ple, gdn, qsa): (
|
||||
&Option<PlePrior>,
|
||||
&[Option<GdnPrior>; STATE_CAPACITY],
|
||||
&[Option<ResidentQsaSeal<'driver>>; STATE_CAPACITY],
|
||||
),
|
||||
end: Position,
|
||||
) -> Result<()> {
|
||||
if self.session.ple_required {
|
||||
ple.as_ref().ok_or(Error::IdentityMismatch)?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.ple_owner,
|
||||
end,
|
||||
)?;
|
||||
}
|
||||
let mut required_gdn = 0u64;
|
||||
let mut required_qsa = 0u64;
|
||||
for slot in 0..48 {
|
||||
required_gdn |= u64::from(self.publish_gdn_slot(&gdn[slot], slot, end)?) << slot;
|
||||
required_qsa |=
|
||||
u64::from(self.publish_qsa_slot((binding, dense), (&layers[slot], &qsa[slot]), slot)?) << slot;
|
||||
}
|
||||
if self.gdn_completed.get() != required_gdn || self.qsa_completed.get() != required_qsa {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Prepare one publication permit per resident layer from its seal; none is published yet.
|
||||
fn prepare_permits<'l>(
|
||||
&self,
|
||||
(binding, dense): (&ModelBinding, &DenseWeightCache<'driver>),
|
||||
layers: &'l mut [Option<ResidentQsaLayer<'driver>>; STATE_CAPACITY],
|
||||
qsa: &mut [Option<ResidentQsaSeal<'driver>>; STATE_CAPACITY],
|
||||
) -> Result<Vec<(usize, ResidentQsaPublication<'l, 'driver>)>> {
|
||||
let mut permits = Vec::new();
|
||||
permits.try_reserve_exact(12).map_err(|_| Error::InputAllocation)?;
|
||||
for (slot, layer) in layers.iter_mut().enumerate() {
|
||||
if let Some(layer) = layer {
|
||||
let seal = qsa[slot].take().ok_or(Error::IdentityMismatch)?;
|
||||
permits.push((slot, layer.prepare_publication(binding, dense, self.session, seal)?));
|
||||
}
|
||||
}
|
||||
if permits.len() != 12 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(permits)
|
||||
}
|
||||
/// No fallible operation after the first canonical assignment.
|
||||
fn install_published(
|
||||
&mut self,
|
||||
ple: Option<PlePrior>,
|
||||
gdn: [Option<GdnPrior>; STATE_CAPACITY],
|
||||
resident: [Option<ResidentQsaPrior<'driver>>; STATE_CAPACITY],
|
||||
) {
|
||||
self.session.ple_state = ple;
|
||||
self.session.gdn_states = gdn;
|
||||
self.session.qsa_states = std::array::from_fn(|_| None);
|
||||
self.session.resident_qsa_states = resident;
|
||||
self.session.predecessors = self.predecessors;
|
||||
self.session.next_position = self.phase.end;
|
||||
self.phase.phase.set(DevicePhase::Published);
|
||||
}
|
||||
/// Validate every real layer seal before preparing any publication. All
|
||||
/// twelve affine permits then perform only infallible state assignment.
|
||||
/// No host QsaIndexPrior is fabricated from an end-only resident checkpoint.
|
||||
@@ -17,85 +141,22 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
|
||||
draft_kv: &super::super::super::super::prompt_device_rows::OriginalDraftKvPending,
|
||||
sample: &super::super::super::super::output::OriginalPromptSample,
|
||||
) -> Result<(TargetStepOrigin, Option<TokenId>)> {
|
||||
self.validate_final(completed)?;
|
||||
sample.validate(binding, completed, self)?;
|
||||
draft_kv.validate(binding, self, completed)?;
|
||||
if draft_kv.last_next(binding, self, completed)? != sample.next() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.validate_publish_inputs(binding, completed, draft_kv, sample)?;
|
||||
let draft_permit = draft.prepare_publication(binding, self, draft_kv.completed())?;
|
||||
let end = Position::new(self.phase.end, crate::qwen_forward::contract::position_dimension())?;
|
||||
let ple = self.next_ple.get_mut().clone();
|
||||
let gdn = self.next_gdn.get_mut().clone();
|
||||
let mut qsa = std::mem::replace(self.next_qsa.get_mut(), std::array::from_fn(|_| None));
|
||||
if self.session.ple_required {
|
||||
ple.as_ref().ok_or(Error::IdentityMismatch)?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.ple_owner,
|
||||
end,
|
||||
)?;
|
||||
}
|
||||
let mut required_gdn = 0u64;
|
||||
let mut required_qsa = 0u64;
|
||||
for slot in 0..48 {
|
||||
let layer = LayerId::new(slot as u64, Dimension::new(48)?)?;
|
||||
if self.session.gdn_layers[slot] {
|
||||
required_gdn |= 1 << slot;
|
||||
gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?.validate(
|
||||
&self.session.binding,
|
||||
&self.session.gdn_owner,
|
||||
layer,
|
||||
end,
|
||||
)?;
|
||||
} else if gdn[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if self.session.qsa_layers[slot] {
|
||||
required_qsa |= 1 << slot;
|
||||
let seal = qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
seal.validate_for(binding, dense, self.session, layer, self.phase.first, self.tokens.len())?;
|
||||
let prior = self.session.resident_qsa_states[slot].as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
if !seal.previous_matches(prior) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
seal.next_prior().validate_for_session(binding, self.session, layer, self.phase.end)?;
|
||||
if layers[slot].is_none() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
} else if qsa[slot].is_some() || layers[slot].is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
if self.gdn_completed.get() != required_gdn || self.qsa_completed.get() != required_qsa {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let output = sample.emitted();
|
||||
let mut permits = Vec::new();
|
||||
permits.try_reserve_exact(12).map_err(|_| Error::InputAllocation)?;
|
||||
for (slot, layer) in layers.iter_mut().enumerate() {
|
||||
if let Some(layer) = layer {
|
||||
let seal = qsa[slot].take().ok_or(Error::IdentityMismatch)?;
|
||||
permits.push((slot, layer.prepare_publication(binding, dense, self.session, seal)?));
|
||||
}
|
||||
}
|
||||
if permits.len() != 12 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.validate_publish_slots((binding, dense), layers, (&ple, &gdn, &qsa), end)?;
|
||||
let permits = self.prepare_permits((binding, dense), layers, &mut qsa)?;
|
||||
self.session.complete_cuda()?;
|
||||
let mut resident = std::array::from_fn(|_| None);
|
||||
for (slot, permit) in permits {
|
||||
resident[slot] = Some(permit.publish_validated());
|
||||
}
|
||||
// No fallible operation after the first canonical assignment.
|
||||
self.session.ple_state = ple;
|
||||
self.session.gdn_states = gdn;
|
||||
self.session.qsa_states = std::array::from_fn(|_| None);
|
||||
self.session.resident_qsa_states = resident;
|
||||
self.session.predecessors = self.predecessors;
|
||||
self.session.next_position = self.phase.end;
|
||||
self.phase.phase.set(DevicePhase::Published);
|
||||
self.install_published(ple, gdn, resident);
|
||||
let actual = super::super::super::checkpoint::committed_origin(self.session);
|
||||
draft_permit.publish_validated(actual.clone());
|
||||
Ok((actual, output))
|
||||
Ok((actual, sample.emitted()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,6 +56,27 @@ pub(in crate::qwen_forward) fn predecessors_after(predecessors: [i32; 2], accept
|
||||
}
|
||||
|
||||
impl<'driver> QwenSession<'driver> {
|
||||
/// The PLE prior at `state_position`: the retained one, or the zero prior at position 0; none without PLE.
|
||||
fn verified_ple(&self, state_position: u64) -> Result<Option<PlePrior>> {
|
||||
if !self.ple_required {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(match &self.ple_state {
|
||||
Some(prior) => prior.clone(),
|
||||
None if state_position == 0 => PlePrior::zero(self.binding.clone(), &self.ple_owner)?,
|
||||
None => return Err(Error::IdentityMismatch),
|
||||
}))
|
||||
}
|
||||
/// The GDN prior of `slot` at `state_position`: the retained one, or the zero prior at position 0.
|
||||
fn verified_gdn(&self, slot: usize, state_position: u64) -> Result<GdnPrior> {
|
||||
Ok(match &self.gdn_states[slot] {
|
||||
Some(prior) => prior.clone(),
|
||||
None if state_position == 0 => {
|
||||
GdnPrior::zero(self.binding.clone(), &self.gdn_owner, LayerId::new(slot as u64, Dimension::new(48)?)?)?
|
||||
}
|
||||
None => return Err(Error::IdentityMismatch),
|
||||
})
|
||||
}
|
||||
/// The current priors, for deriving the lineage after the next accepted prefix. Position 0 has no
|
||||
/// published GDN/PLE state yet; the zero priors are the genuine initial ones, as in the prompt transaction.
|
||||
pub(in crate::qwen_forward) fn original_verified_base(&self) -> Result<OriginalVerifiedBase<'driver>> {
|
||||
@@ -64,28 +85,12 @@ impl<'driver> QwenSession<'driver> {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let state_position = self.state_lag.unwrap_or(self.next_position);
|
||||
let ple = if self.ple_required {
|
||||
Some(match &self.ple_state {
|
||||
Some(prior) => prior.clone(),
|
||||
None if state_position == 0 => PlePrior::zero(self.binding.clone(), &self.ple_owner)?,
|
||||
None => return Err(Error::IdentityMismatch),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let ple = self.verified_ple(state_position)?;
|
||||
let mut gdn: [Option<GdnPrior>; STATE_CAPACITY] = std::array::from_fn(|_| None);
|
||||
let mut qsa: [Option<ResidentQsaPrior<'driver>>; STATE_CAPACITY] = std::array::from_fn(|_| None);
|
||||
for slot in 0..STATE_CAPACITY {
|
||||
if self.gdn_layers[slot] {
|
||||
gdn[slot] = Some(match &self.gdn_states[slot] {
|
||||
Some(prior) => prior.clone(),
|
||||
None if state_position == 0 => GdnPrior::zero(
|
||||
self.binding.clone(),
|
||||
&self.gdn_owner,
|
||||
LayerId::new(slot as u64, Dimension::new(48)?)?,
|
||||
)?,
|
||||
None => return Err(Error::IdentityMismatch),
|
||||
});
|
||||
gdn[slot] = Some(self.verified_gdn(slot, state_position)?);
|
||||
}
|
||||
if self.qsa_layers[slot] {
|
||||
qsa[slot] = Some(self.resident_qsa_states[slot].clone().ok_or(Error::IdentityMismatch)?);
|
||||
|
||||
@@ -64,6 +64,20 @@ pub(super) fn validate_descriptors(keys: &[MoeWeightDescriptor; 4]) -> Result<()
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The shared-expert weight buffers with the kinds their descriptors name.
|
||||
fn shared_weights<'a, 'ctx>(
|
||||
keys: &[MoeWeightDescriptor; 4],
|
||||
buffers: [&'a DeviceBuffer<'ctx>; 4],
|
||||
) -> Result<SharedExpertWeights<'a, 'ctx>> {
|
||||
Ok(SharedExpertWeights {
|
||||
gate: buffers[0],
|
||||
up: buffers[1],
|
||||
down: buffers[2],
|
||||
scalar: buffers[3],
|
||||
gu_kind: [gu_kind(keys[0])?, gu_kind(keys[1])?],
|
||||
down_kind: down_kind(keys[2])?,
|
||||
})
|
||||
}
|
||||
impl<'ctx> TargetSharedWorkspace<'ctx> {
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(super) fn new(binding: BindingIdentity, owner: Rc<()>, context: &'ctx Context<'ctx>) -> Result<Self> {
|
||||
@@ -74,19 +88,15 @@ impl<'ctx> TargetSharedWorkspace<'ctx> {
|
||||
}
|
||||
Ok(Self { binding, owner, context, workspace })
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn compose(
|
||||
&mut self,
|
||||
/// The workspace belongs to this binding, owner and context, and the descriptors name `identity`'s layer with
|
||||
/// buffers of exactly their sizes.
|
||||
fn check_compose(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
owner: &Rc<()>,
|
||||
context: &Context<'_>,
|
||||
(owner, context): (&Rc<()>, &Context<'_>),
|
||||
identity: TokenLayer,
|
||||
keys: &[MoeWeightDescriptor; 4],
|
||||
buffers: [&DeviceBuffer<'ctx>; 4],
|
||||
activation: &DeviceBuffer<'_>,
|
||||
packed: &DeviceBuffer<'_>,
|
||||
route: &[f32; 10],
|
||||
) -> Result<Box<[f32]>> {
|
||||
(keys, buffers): (&[MoeWeightDescriptor; 4], &[&DeviceBuffer<'ctx>; 4]),
|
||||
) -> Result<()> {
|
||||
if !self.binding.matches(&binding.identity())
|
||||
|| !Rc::ptr_eq(&self.owner, owner)
|
||||
|| !std::ptr::eq(self.context, context)
|
||||
@@ -101,22 +111,24 @@ impl<'ctx> TargetSharedWorkspace<'ctx> {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
let completion = self
|
||||
.workspace
|
||||
.compose(
|
||||
activation,
|
||||
SharedExpertWeights {
|
||||
gate: buffers[0],
|
||||
up: buffers[1],
|
||||
down: buffers[2],
|
||||
scalar: buffers[3],
|
||||
gu_kind: [gu_kind(keys[0])?, gu_kind(keys[1])?],
|
||||
down_kind: down_kind(keys[2])?,
|
||||
},
|
||||
packed,
|
||||
route,
|
||||
)
|
||||
.map_err(driver_error)?;
|
||||
Ok(())
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn compose(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
owner: &Rc<()>,
|
||||
context: &Context<'_>,
|
||||
identity: TokenLayer,
|
||||
keys: &[MoeWeightDescriptor; 4],
|
||||
buffers: [&DeviceBuffer<'ctx>; 4],
|
||||
activation: &DeviceBuffer<'_>,
|
||||
packed: &DeviceBuffer<'_>,
|
||||
route: &[f32; 10],
|
||||
) -> Result<Box<[f32]>> {
|
||||
self.check_compose(binding, (owner, context), identity, (keys, &buffers))?;
|
||||
let weights = shared_weights(keys, buffers)?;
|
||||
let completion = self.workspace.compose(activation, weights, packed, route).map_err(driver_error)?;
|
||||
// All driver numeric refusals retain the original runtime NonFinite class.
|
||||
completion.into_final_values().map_err(|refusal| match refusal {
|
||||
SharedTailRefusal::InvalidQ8Activation
|
||||
|
||||
@@ -192,15 +192,9 @@ pub(crate) struct CacheFacts {
|
||||
pub(crate) prefix_budget_bytes: u64,
|
||||
}
|
||||
|
||||
/// The `build`, `model` and `config` lines (without the `leleka-serve ` prefix), in this order.
|
||||
pub(crate) fn startup_lines(
|
||||
build: &BuildInfo,
|
||||
profile: &ProfileInfo,
|
||||
model: &ModelInfo,
|
||||
config: &ConfigFacts,
|
||||
) -> Vec<String> {
|
||||
let mut lines = Vec::with_capacity(3);
|
||||
lines.push(line(
|
||||
/// The `build` line.
|
||||
fn build_line(build: &BuildInfo, profile: &ProfileInfo, config: &ConfigFacts) -> String {
|
||||
line(
|
||||
"build",
|
||||
&[
|
||||
("commit", build.commit.clone()),
|
||||
@@ -212,7 +206,10 @@ pub(crate) fn startup_lines(
|
||||
("profile_sha256", profile.sha256.clone().unwrap_or_else(|| "unset".to_owned())),
|
||||
("values_sha256", config.values_sha256()),
|
||||
],
|
||||
));
|
||||
)
|
||||
}
|
||||
/// The `model` line.
|
||||
fn model_line(model: &ModelInfo) -> String {
|
||||
let mut model_fields = vec![
|
||||
("digest", model.digest.clone()),
|
||||
("mapping", MODEL_DIGEST_MAPPING.to_owned()),
|
||||
@@ -229,9 +226,17 @@ pub(crate) fn startup_lines(
|
||||
}
|
||||
let owned: Vec<(&str, String)> = file_keys.iter().map(|(k, v)| (k.as_str(), v.clone())).collect();
|
||||
model_fields.extend(owned);
|
||||
lines.push(line("model", &model_fields));
|
||||
lines.push(line("config", &config.fields()));
|
||||
lines
|
||||
line("model", &model_fields)
|
||||
}
|
||||
|
||||
/// The `build`, `model` and `config` lines (without the `leleka-serve ` prefix), in this order.
|
||||
pub(crate) fn startup_lines(
|
||||
build: &BuildInfo,
|
||||
profile: &ProfileInfo,
|
||||
model: &ModelInfo,
|
||||
config: &ConfigFacts,
|
||||
) -> Vec<String> {
|
||||
vec![build_line(build, profile, config), model_line(model), line("config", &config.fields())]
|
||||
}
|
||||
|
||||
/// The `cache` line.
|
||||
|
||||
Reference in New Issue
Block a user