Merge branch 'claude/size2-en4' into claude/hexagonal-integ
This commit is contained in:
+74
-35
@@ -3,25 +3,48 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
pub(super) fn former_fixture_domain_refusal(context: &Context<'_>) {
|
||||
// One new diagnostic of the actual prior failure, in the same scheduled
|
||||
// run: original scale1/input/8 chain, preserving the raw driver error.
|
||||
let input: Vec<f32> = (0..N).map(|i| ((i % 31) as f32 - 15.) / 8.).collect();
|
||||
let x = upload_f32(context, &input).unwrap();
|
||||
let gate_matrix = upload_bytes(context, &encoded(MoeMatrixKind::Iq3Xxs, FF, N, 0)).unwrap();
|
||||
let up_matrix = upload_bytes(context, &encoded(MoeMatrixKind::Iq3Xxs, FF, N, 1)).unwrap();
|
||||
let down_matrix = upload_bytes(context, &encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 2)).unwrap();
|
||||
let gate = project_retained_gate_up(context, |output| {
|
||||
launch_projection(context, MoeMatrixKind::Iq3Xxs, &gate_matrix, &x, output, FF, N)
|
||||
})
|
||||
.unwrap();
|
||||
let up = project_retained_gate_up(context, |output| {
|
||||
launch_projection(context, MoeMatrixKind::Iq3Xxs, &up_matrix, &x, output, FF, N)
|
||||
})
|
||||
.unwrap();
|
||||
let mut hidden = context.allocate(FF * 4).unwrap();
|
||||
context.moe_swiglu_f32(&gate, &up, &mut hidden).unwrap();
|
||||
let values = download_f32(&hidden, FF).unwrap();
|
||||
struct DomainFixture<'ctx> {
|
||||
x: DeviceBuffer<'ctx>,
|
||||
gate_matrix: DeviceBuffer<'ctx>,
|
||||
up_matrix: DeviceBuffer<'ctx>,
|
||||
down_matrix: DeviceBuffer<'ctx>,
|
||||
gate: DeviceBuffer<'ctx>,
|
||||
up: DeviceBuffer<'ctx>,
|
||||
hidden: DeviceBuffer<'ctx>,
|
||||
}
|
||||
|
||||
impl<'ctx> DomainFixture<'ctx> {
|
||||
fn build(context: &'ctx Context<'_>) -> Self {
|
||||
let input: Vec<f32> = (0..N).map(|i| ((i % 31) as f32 - 15.) / 8.).collect();
|
||||
let x = upload_f32(context, &input).unwrap();
|
||||
let gate_matrix = upload_bytes(context, &encoded(MoeMatrixKind::Iq3Xxs, FF, N, 0)).unwrap();
|
||||
let up_matrix = upload_bytes(context, &encoded(MoeMatrixKind::Iq3Xxs, FF, N, 1)).unwrap();
|
||||
let down_matrix = upload_bytes(context, &encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 2)).unwrap();
|
||||
let gate = project_retained_gate_up(context, |output| {
|
||||
launch_projection(context, MoeMatrixKind::Iq3Xxs, &gate_matrix, &x, output, FF, N)
|
||||
})
|
||||
.unwrap();
|
||||
let up = project_retained_gate_up(context, |output| {
|
||||
launch_projection(context, MoeMatrixKind::Iq3Xxs, &up_matrix, &x, output, FF, N)
|
||||
})
|
||||
.unwrap();
|
||||
let mut hidden = context.allocate(FF * 4).unwrap();
|
||||
context.moe_swiglu_f32(&gate, &up, &mut hidden).unwrap();
|
||||
Self { x, gate_matrix, up_matrix, down_matrix, gate, up, hidden }
|
||||
}
|
||||
|
||||
fn release(self) {
|
||||
self.hidden.release().unwrap();
|
||||
self.up.release().unwrap();
|
||||
self.gate.release().unwrap();
|
||||
self.down_matrix.release().unwrap();
|
||||
self.up_matrix.release().unwrap();
|
||||
self.gate_matrix.release().unwrap();
|
||||
self.x.release().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn hidden_extrema(values: &[f32]) -> (f32, f64) {
|
||||
let maximum = values.iter().map(|value| value.abs()).fold(0.0f32, f32::max);
|
||||
let maximum_sum = values
|
||||
.as_chunks::<32>()
|
||||
@@ -29,11 +52,21 @@ pub(super) fn former_fixture_domain_refusal(context: &Context<'_>) {
|
||||
.iter()
|
||||
.map(|warp| warp.iter().map(|value| f64::from(*value)).sum::<f64>().abs())
|
||||
.fold(0.0f64, f64::max);
|
||||
(maximum, maximum_sum)
|
||||
}
|
||||
|
||||
pub(super) fn former_fixture_domain_refusal(context: &Context<'_>) {
|
||||
// One new diagnostic of the actual prior failure, in the same scheduled
|
||||
// run: original scale1/input/8 chain, preserving the raw driver error.
|
||||
let fixture = DomainFixture::build(context);
|
||||
let values = download_f32(&fixture.hidden, FF).unwrap();
|
||||
let (maximum, maximum_sum) = hidden_extrema(&values);
|
||||
let mut output = context.allocate(N * 4).unwrap();
|
||||
let sentinel = vec![0xa5; N * 4];
|
||||
output.copy_from(&sentinel).unwrap();
|
||||
let charged = context.allocated_bytes();
|
||||
let result = down_projection(context, MoeMatrixKind::RoutedIq4Nl, &down_matrix, &hidden, &mut output);
|
||||
let result =
|
||||
down_projection(context, MoeMatrixKind::RoutedIq4Nl, &fixture.down_matrix, &fixture.hidden, &mut output);
|
||||
println!(
|
||||
"MOE_RETAINED original_domain raw_down_error={result:?} hidden_abs_max={maximum} warp_sum_abs_max={maximum_sum}"
|
||||
);
|
||||
@@ -43,25 +76,12 @@ pub(super) fn former_fixture_domain_refusal(context: &Context<'_>) {
|
||||
output.copy_to(&mut untouched).unwrap();
|
||||
assert_eq!(untouched, sentinel);
|
||||
output.release().unwrap();
|
||||
hidden.release().unwrap();
|
||||
up.release().unwrap();
|
||||
gate.release().unwrap();
|
||||
down_matrix.release().unwrap();
|
||||
up_matrix.release().unwrap();
|
||||
gate_matrix.release().unwrap();
|
||||
x.release().unwrap();
|
||||
fixture.release();
|
||||
context.synchronize().unwrap();
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
}
|
||||
|
||||
pub(super) fn saturation_and_refusals(context: &Context<'_>) {
|
||||
let down_bytes = encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 3);
|
||||
let matrix = upload_bytes(context, &down_bytes).unwrap();
|
||||
let gate = upload_f32(context, &[-1000.; FF]).unwrap();
|
||||
let up = upload_f32(context, &[1.; FF]).unwrap();
|
||||
compare_mlp(context, gate, up, MoeMatrixKind::RoutedIq4Nl, &matrix);
|
||||
matrix.release().unwrap();
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
fn nonfinite_hidden_refused(context: &Context<'_>) {
|
||||
for (gate_bad, bits) in [(true, 0x7fc00001u32), (false, 0x7f800000)] {
|
||||
let mut gate_values = vec![0.25; FF];
|
||||
let mut up_values = vec![0.5; FF];
|
||||
@@ -79,6 +99,9 @@ pub(super) fn saturation_and_refusals(context: &Context<'_>) {
|
||||
assert!(!called.get());
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
fn late_nan_projection_refused(context: &Context<'_>) {
|
||||
// Actual projection writes a late NaN, exercising finite admission before
|
||||
// the newly retained projection owner can be published.
|
||||
let mut malformed = encoded(MoeMatrixKind::Q6K, FF, N, 0);
|
||||
@@ -95,6 +118,9 @@ pub(super) fn saturation_and_refusals(context: &Context<'_>) {
|
||||
assert_eq!(context.allocated_bytes(), initial);
|
||||
x.release().unwrap();
|
||||
w.release().unwrap();
|
||||
}
|
||||
|
||||
fn down_shape_refused(context: &Context<'_>) {
|
||||
// Down shape refusal is genuine native admission, not a fabricated error.
|
||||
let w = upload_bytes(context, &encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 0)).unwrap();
|
||||
let mut wrong = context.allocate(N * 4 - 4).unwrap();
|
||||
@@ -112,5 +138,18 @@ pub(super) fn saturation_and_refusals(context: &Context<'_>) {
|
||||
assert_eq!(unchanged, sentinel);
|
||||
wrong.release().unwrap();
|
||||
w.release().unwrap();
|
||||
}
|
||||
|
||||
pub(super) fn saturation_and_refusals(context: &Context<'_>) {
|
||||
let down_bytes = encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 3);
|
||||
let matrix = upload_bytes(context, &down_bytes).unwrap();
|
||||
let gate = upload_f32(context, &[-1000.; FF]).unwrap();
|
||||
let up = upload_f32(context, &[1.; FF]).unwrap();
|
||||
compare_mlp(context, gate, up, MoeMatrixKind::RoutedIq4Nl, &matrix);
|
||||
matrix.release().unwrap();
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
nonfinite_hidden_refused(context);
|
||||
late_nan_projection_refused(context);
|
||||
down_shape_refused(context);
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
}
|
||||
|
||||
@@ -108,6 +108,15 @@ impl<'ctx> DownScope<'ctx> {
|
||||
}
|
||||
let mut output = self.allocate(N * 4)?;
|
||||
let result = project(output.buffer_mut()?).and_then(|()| download_f32(output.buffer()?, N));
|
||||
self.retain_down(output, result, selection)
|
||||
}
|
||||
/// Records the producer result and either retains the Down output or closes it on the primary failure.
|
||||
fn retain_down(
|
||||
&self,
|
||||
output: TransportBuffer<'ctx>,
|
||||
result: Result<Box<[f32]>>,
|
||||
selection: DownSelection,
|
||||
) -> Result<RetainedDown<'ctx>> {
|
||||
self.record(&result);
|
||||
let values = match result {
|
||||
Ok(values) => values,
|
||||
@@ -130,12 +139,7 @@ impl<'ctx> DownScope<'ctx> {
|
||||
row: usize,
|
||||
) -> Result<RetainedDown<'ctx>> {
|
||||
self.check()?;
|
||||
if !matches!(selection, DownSelection::Routed(slot) if slot < K) || !completed.matches(binding, keys) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let start = row.checked_mul(N).ok_or(Error::Overflow)?;
|
||||
let end = start.checked_add(N).ok_or(Error::Overflow)?;
|
||||
let source = completed.values().get(start..end).ok_or(Error::IdentityMismatch)?;
|
||||
let source = completed_row_source(binding, keys, selection, completed, row)?;
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(N * 4).map_err(|_| Error::InputAllocation)?;
|
||||
for value in source {
|
||||
@@ -147,23 +151,21 @@ impl<'ctx> DownScope<'ctx> {
|
||||
return self.project(selection, |buffer| buffer.copy_from(&bytes).map_err(driver_error));
|
||||
}
|
||||
let mut output = self.allocate(N * 4)?;
|
||||
let result = (|| {
|
||||
output.buffer_mut()?.copy_from(&bytes).map_err(driver_error)?;
|
||||
self.finite_stage(output.buffer()?, RoutedFiniteStage::Down, 1)?;
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?;
|
||||
values.extend_from_slice(source);
|
||||
Ok(values.into_boxed_slice())
|
||||
})();
|
||||
self.record(&result);
|
||||
let values = match result {
|
||||
Ok(values) => values,
|
||||
Err(primary) => {
|
||||
let _ = output.close();
|
||||
return Err(primary);
|
||||
}
|
||||
};
|
||||
Ok(RetainedDown { output, values, epoch: Rc::clone(&self.epoch), context: self.context, selection })
|
||||
let result = self.upload_completed_row_checked(&mut output, &bytes, source);
|
||||
self.retain_down(output, result, selection)
|
||||
}
|
||||
fn upload_completed_row_checked(
|
||||
&self,
|
||||
output: &mut TransportBuffer<'ctx>,
|
||||
bytes: &[u8],
|
||||
source: &[f32],
|
||||
) -> Result<Box<[f32]>> {
|
||||
output.buffer_mut()?.copy_from(bytes).map_err(driver_error)?;
|
||||
self.finite_stage(output.buffer()?, RoutedFiniteStage::Down, 1)?;
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?;
|
||||
values.extend_from_slice(source);
|
||||
Ok(values.into_boxed_slice())
|
||||
}
|
||||
/// Closed real grouped producer: validate its own bulk readback before
|
||||
/// splitting actual columns into the original selected Down owners.
|
||||
@@ -174,48 +176,61 @@ impl<'ctx> DownScope<'ctx> {
|
||||
cancelled: &mut F,
|
||||
) -> Result<Vec<RetainedDown<'ctx>>> {
|
||||
self.check()?;
|
||||
if !(1..=64).contains(&selections.len())
|
||||
|| selections.iter().any(|s| !matches!(s, DownSelection::Routed(slot) if *slot < K))
|
||||
{
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
check_grouped_selections(selections)?;
|
||||
let mut grouped = self.allocate(selections.len() * N * 4)?;
|
||||
let result = (|| {
|
||||
project(grouped.buffer_mut()?, cancelled)?;
|
||||
let values = download_f32(grouped.buffer()?, selections.len() * N)?;
|
||||
let mut outputs = Vec::new();
|
||||
outputs.try_reserve_exact(selections.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, selection) in selections.iter().copied().enumerate() {
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(super::super::Stage::Executor));
|
||||
}
|
||||
let mut output = self.allocate(N * 4)?;
|
||||
let copy = self
|
||||
.context
|
||||
.copy_routed_down_column(grouped.buffer()?, selections.len(), index, output.buffer_mut()?)
|
||||
.map_err(driver_error);
|
||||
self.record(©);
|
||||
if let Err(primary) = copy {
|
||||
let _ = output.close();
|
||||
return Err(primary);
|
||||
}
|
||||
let mut actual = Vec::new();
|
||||
actual.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?;
|
||||
actual.extend_from_slice(&values[index * N..(index + 1) * N]);
|
||||
outputs.push(RetainedDown {
|
||||
output,
|
||||
values: actual.into_boxed_slice(),
|
||||
epoch: Rc::clone(&self.epoch),
|
||||
context: self.context,
|
||||
selection,
|
||||
});
|
||||
}
|
||||
Ok(outputs)
|
||||
})();
|
||||
let result = self.split_grouped_columns(&mut grouped, selections, project, cancelled);
|
||||
self.record(&result);
|
||||
let cleanup = grouped.close();
|
||||
result.and_then(|values| cleanup.map(|()| values))
|
||||
}
|
||||
fn split_grouped_columns<F: FnMut() -> bool>(
|
||||
&self,
|
||||
grouped: &mut TransportBuffer<'ctx>,
|
||||
selections: &[DownSelection],
|
||||
project: impl FnOnce(&mut DeviceBuffer<'ctx>, &mut F) -> Result<()>,
|
||||
cancelled: &mut F,
|
||||
) -> Result<Vec<RetainedDown<'ctx>>> {
|
||||
project(grouped.buffer_mut()?, cancelled)?;
|
||||
let values = download_f32(grouped.buffer()?, selections.len() * N)?;
|
||||
let mut outputs = Vec::new();
|
||||
outputs.try_reserve_exact(selections.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, selection) in selections.iter().copied().enumerate() {
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(super::super::Stage::Executor));
|
||||
}
|
||||
outputs.push(self.split_column(grouped, &values, selections.len(), index, selection)?);
|
||||
}
|
||||
Ok(outputs)
|
||||
}
|
||||
fn split_column(
|
||||
&self,
|
||||
grouped: &TransportBuffer<'ctx>,
|
||||
values: &[f32],
|
||||
columns: usize,
|
||||
index: usize,
|
||||
selection: DownSelection,
|
||||
) -> Result<RetainedDown<'ctx>> {
|
||||
let mut output = self.allocate(N * 4)?;
|
||||
let copy = self
|
||||
.context
|
||||
.copy_routed_down_column(grouped.buffer()?, columns, index, output.buffer_mut()?)
|
||||
.map_err(driver_error);
|
||||
self.record(©);
|
||||
if let Err(primary) = copy {
|
||||
let _ = output.close();
|
||||
return Err(primary);
|
||||
}
|
||||
let mut actual = Vec::new();
|
||||
actual.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?;
|
||||
actual.extend_from_slice(&values[index * N..(index + 1) * N]);
|
||||
Ok(RetainedDown {
|
||||
output,
|
||||
values: actual.into_boxed_slice(),
|
||||
epoch: Rc::clone(&self.epoch),
|
||||
context: self.context,
|
||||
selection,
|
||||
})
|
||||
}
|
||||
/// Same completed native producer/full finite readback, retaining its one
|
||||
/// genuine grouped allocation through a private packet-copy callback.
|
||||
pub(in super::super) fn project_columns_direct<F: FnMut() -> bool>(
|
||||
@@ -226,25 +241,29 @@ impl<'ctx> DownScope<'ctx> {
|
||||
cancelled: &mut F,
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
if !(1..=64).contains(&selections.len())
|
||||
|| selections.iter().any(|s| !matches!(s, DownSelection::Routed(slot) if *slot < K))
|
||||
{
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
check_grouped_selections(selections)?;
|
||||
let mut grouped = self.allocate(selections.len() * N * 4)?;
|
||||
let result = (|| {
|
||||
project(grouped.buffer_mut()?, cancelled)?;
|
||||
// Complete original Down finite boundary precedes packet mutation.
|
||||
self.finite_stage(grouped.buffer()?, RoutedFiniteStage::Down, selections.len())?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(super::super::Stage::Executor));
|
||||
}
|
||||
copy(grouped.buffer()?, cancelled)
|
||||
})();
|
||||
let result = self.copy_grouped_direct(&mut grouped, selections.len(), project, copy, cancelled);
|
||||
self.record(&result);
|
||||
let cleanup = grouped.close();
|
||||
result.and(cleanup)
|
||||
}
|
||||
fn copy_grouped_direct<F: FnMut() -> bool>(
|
||||
&self,
|
||||
grouped: &mut TransportBuffer<'ctx>,
|
||||
columns: usize,
|
||||
project: impl FnOnce(&mut DeviceBuffer<'ctx>, &mut F) -> Result<()>,
|
||||
copy: impl FnOnce(&DeviceBuffer<'ctx>, &mut F) -> Result<()>,
|
||||
cancelled: &mut F,
|
||||
) -> Result<()> {
|
||||
project(grouped.buffer_mut()?, cancelled)?;
|
||||
// Complete original Down finite boundary precedes packet mutation.
|
||||
self.finite_stage(grouped.buffer()?, RoutedFiniteStage::Down, columns)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(super::super::Stage::Executor));
|
||||
}
|
||||
copy(grouped.buffer()?, cancelled)
|
||||
}
|
||||
pub(in super::super) fn shared_scalar(
|
||||
&self,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
@@ -271,3 +290,27 @@ impl<'ctx> DownScope<'ctx> {
|
||||
Ok(RetainedScalar { output, epoch: Rc::clone(&self.epoch), context: self.context })
|
||||
}
|
||||
}
|
||||
|
||||
fn check_grouped_selections(selections: &[DownSelection]) -> Result<()> {
|
||||
if !(1..=64).contains(&selections.len())
|
||||
|| selections.iter().any(|s| !matches!(s, DownSelection::Routed(slot) if *slot < K))
|
||||
{
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn completed_row_source<'a>(
|
||||
binding: &crate::model_binding::qwen4exp_input::ModelBinding,
|
||||
keys: &[crate::model_binding::qwen4exp_input::MoeWeightDescriptor; 3],
|
||||
selection: DownSelection,
|
||||
completed: &'a super::super::super::cpu_expert_miss::CpuMissRows,
|
||||
row: usize,
|
||||
) -> Result<&'a [f32]> {
|
||||
if !matches!(selection, DownSelection::Routed(slot) if slot < K) || !completed.matches(binding, keys) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let start = row.checked_mul(N).ok_or(Error::Overflow)?;
|
||||
let end = start.checked_add(N).ok_or(Error::Overflow)?;
|
||||
completed.values().get(start..end).ok_or(Error::IdentityMismatch)
|
||||
}
|
||||
|
||||
@@ -51,36 +51,9 @@ impl<'ctx> ResidentPackedDown<'ctx> {
|
||||
copy_and_validate: impl FnOnce(&mut [(u32, &mut DeviceBuffer<'ctx>, u32)]) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
let result = (|| {
|
||||
if !(1..=64).contains(&packets.len()) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
for (packet, slot) in packets.iter() {
|
||||
packet.validate(scope)?;
|
||||
if *slot >= K || packet.coverage & (1u16 << slot) != 0 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut copies = Vec::new();
|
||||
copies.try_reserve_exact(packets.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (column, (packet, slot)) in packets.iter_mut().enumerate() {
|
||||
copies.push((
|
||||
u32::try_from(column).map_err(|_| Error::Overflow)?,
|
||||
packet.output.buffer_mut()?,
|
||||
u32::try_from(*slot).map_err(|_| Error::Overflow)?,
|
||||
));
|
||||
}
|
||||
copy_and_validate(&mut copies)?;
|
||||
}
|
||||
// Numerical/copy completion and caller's real origin/cancellation
|
||||
// postchecks succeeded before any selected packet gains coverage.
|
||||
for (packet, _) in packets.iter() {
|
||||
packet.validate(scope)?;
|
||||
}
|
||||
for (packet, slot) in packets.iter_mut() {
|
||||
packet.coverage |= 1u16 << *slot;
|
||||
}
|
||||
Ok(())
|
||||
Self::admit_packets(scope, packets)?;
|
||||
Self::copy_packets(packets, copy_and_validate)?;
|
||||
Self::publish_coverage(scope, packets)
|
||||
})();
|
||||
if result.is_err() {
|
||||
for (packet, _) in packets.iter_mut() {
|
||||
@@ -90,6 +63,44 @@ impl<'ctx> ResidentPackedDown<'ctx> {
|
||||
scope.record(&result);
|
||||
result
|
||||
}
|
||||
fn admit_packets(scope: &DownScope<'ctx>, packets: &[(&mut Self, usize)]) -> Result<()> {
|
||||
if !(1..=64).contains(&packets.len()) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
for (packet, slot) in packets.iter() {
|
||||
packet.validate(scope)?;
|
||||
if *slot >= K || packet.coverage & (1u16 << slot) != 0 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn copy_packets(
|
||||
packets: &mut [(&mut Self, usize)],
|
||||
copy_and_validate: impl FnOnce(&mut [(u32, &mut DeviceBuffer<'ctx>, u32)]) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
let mut copies = Vec::new();
|
||||
copies.try_reserve_exact(packets.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (column, (packet, slot)) in packets.iter_mut().enumerate() {
|
||||
copies.push((
|
||||
u32::try_from(column).map_err(|_| Error::Overflow)?,
|
||||
packet.output.buffer_mut()?,
|
||||
u32::try_from(*slot).map_err(|_| Error::Overflow)?,
|
||||
));
|
||||
}
|
||||
copy_and_validate(&mut copies)
|
||||
}
|
||||
fn publish_coverage(scope: &DownScope<'ctx>, packets: &mut [(&mut Self, usize)]) -> Result<()> {
|
||||
// Numerical/copy completion and caller's real origin/cancellation
|
||||
// postchecks succeeded before any selected packet gains coverage.
|
||||
for (packet, _) in packets.iter() {
|
||||
packet.validate(scope)?;
|
||||
}
|
||||
for (packet, slot) in packets.iter_mut() {
|
||||
packet.coverage |= 1u16 << *slot;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(in super::super) fn combine(
|
||||
&self,
|
||||
scope: &DownScope<'ctx>,
|
||||
@@ -103,33 +114,7 @@ impl<'ctx> ResidentPackedDown<'ctx> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if super::super::super::oracle_capture::enabled() {
|
||||
super::super::super::oracle_capture::stage_current(
|
||||
"routed_parts",
|
||||
&download_f32(self.output.buffer()?, K * N)?,
|
||||
)?;
|
||||
super::super::super::oracle_capture::stage_current(
|
||||
"shared_scaled",
|
||||
&download_f32(scaled.output.buffer()?, N)?,
|
||||
)?;
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if crate::qwen_forward::layer0_mmq_observation::enabled() {
|
||||
crate::qwen_forward::layer0_mmq_observation::packed_shared(
|
||||
&download_f32(self.output.buffer()?, K * N)?,
|
||||
&download_f32(scaled.output.buffer()?, N)?,
|
||||
)?;
|
||||
}
|
||||
let mut output = scope.allocate(N * 4)?;
|
||||
let result = scope
|
||||
.context
|
||||
.moe_combine_f64(self.output.buffer()?, weights, scaled.output.buffer()?, output.buffer_mut()?)
|
||||
.map_err(driver_error)
|
||||
.and_then(|()| download_f32(output.buffer()?, N));
|
||||
scope.record(&result);
|
||||
let cleanup = output.close();
|
||||
result.and_then(|values| cleanup.map(|()| values))
|
||||
super::impl_retainedscalar::combine_routed_shared(scope, &self.output, weights, scaled)
|
||||
}
|
||||
pub(in super::super) fn close(self) -> Result<()> {
|
||||
self.output.close()
|
||||
|
||||
@@ -76,9 +76,7 @@ impl<'ctx> RetainedDown<'ctx> {
|
||||
scalar: &RetainedScalar<'_>,
|
||||
) -> Result<ScaledDown<'ctx>> {
|
||||
self.validate(scope, DownSelection::Shared)?;
|
||||
if !Rc::ptr_eq(&scalar.epoch, &scope.epoch) || !std::ptr::eq(scalar.context, scope.context) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
scalar_in_scope(scalar, scope)?;
|
||||
let mut output = scope.allocate(N * 4)?;
|
||||
let result = scope
|
||||
.context
|
||||
@@ -155,37 +153,62 @@ impl<'ctx> PackedDown<'ctx> {
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if super::super::super::oracle_capture::enabled() {
|
||||
super::super::super::oracle_capture::stage_current(
|
||||
"routed_parts",
|
||||
&download_f32(self.output.buffer()?, K * N)?,
|
||||
)?;
|
||||
super::super::super::oracle_capture::stage_current(
|
||||
"shared_scaled",
|
||||
&download_f32(scaled.output.buffer()?, N)?,
|
||||
)?;
|
||||
}
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if crate::qwen_forward::layer0_mmq_observation::enabled() {
|
||||
crate::qwen_forward::layer0_mmq_observation::packed_shared(
|
||||
&download_f32(self.output.buffer()?, K * N)?,
|
||||
&download_f32(scaled.output.buffer()?, N)?,
|
||||
)?;
|
||||
}
|
||||
let mut output = scope.allocate(N * 4)?;
|
||||
let result = scope
|
||||
.context
|
||||
.moe_combine_f64(self.output.buffer()?, weights, scaled.output.buffer()?, output.buffer_mut()?)
|
||||
.map_err(driver_error)
|
||||
.and_then(|()| download_f32(output.buffer()?, N));
|
||||
scope.record(&result);
|
||||
let cleanup = output.close();
|
||||
let values = result?;
|
||||
cleanup?;
|
||||
Ok(values)
|
||||
combine_routed_shared(scope, &self.output, weights, scaled)
|
||||
}
|
||||
pub(in super::super) fn close(self) -> Result<()> {
|
||||
self.output.close()
|
||||
}
|
||||
}
|
||||
|
||||
fn scalar_in_scope(scalar: &RetainedScalar<'_>, scope: &DownScope<'_>) -> Result<()> {
|
||||
if !Rc::ptr_eq(&scalar.epoch, &scope.epoch) || !std::ptr::eq(scalar.context, scope.context) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn capture_oracle_parts(routed: &TransportBuffer<'_>, scaled: &ScaledDown<'_>) -> Result<()> {
|
||||
if super::super::super::oracle_capture::enabled() {
|
||||
super::super::super::oracle_capture::stage_current("routed_parts", &download_f32(routed.buffer()?, K * N)?)?;
|
||||
super::super::super::oracle_capture::stage_current(
|
||||
"shared_scaled",
|
||||
&download_f32(scaled.output.buffer()?, N)?,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn capture_mmq_observation(routed: &TransportBuffer<'_>, scaled: &ScaledDown<'_>) -> Result<()> {
|
||||
if crate::qwen_forward::layer0_mmq_observation::enabled() {
|
||||
crate::qwen_forward::layer0_mmq_observation::packed_shared(
|
||||
&download_f32(routed.buffer()?, K * N)?,
|
||||
&download_f32(scaled.output.buffer()?, N)?,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Shared routed-plus-shared combine of the packed and resident Down owners: test captures, then one combine
|
||||
/// into a fresh output whose close error only surfaces after the primary result.
|
||||
pub(super) fn combine_routed_shared<'ctx>(
|
||||
scope: &DownScope<'ctx>,
|
||||
routed: &TransportBuffer<'ctx>,
|
||||
weights: &DeviceBuffer<'_>,
|
||||
scaled: &ScaledDown<'_>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
capture_oracle_parts(routed, scaled)?;
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
capture_mmq_observation(routed, scaled)?;
|
||||
let mut output = scope.allocate(N * 4)?;
|
||||
let result = scope
|
||||
.context
|
||||
.moe_combine_f64(routed.buffer()?, weights, scaled.output.buffer()?, output.buffer_mut()?)
|
||||
.map_err(driver_error)
|
||||
.and_then(|()| download_f32(output.buffer()?, N));
|
||||
scope.record(&result);
|
||||
let cleanup = output.close();
|
||||
result.and_then(|values| cleanup.map(|()| values))
|
||||
}
|
||||
|
||||
@@ -10,209 +10,38 @@ fn retained_down_pack_scale_combine_matches_old_uploads_and_fences_abort() {
|
||||
let driver = Driver::load().unwrap();
|
||||
let device = driver.device(0).unwrap();
|
||||
let ctx = device.create_context(144 * 1024 * 1024).unwrap();
|
||||
let failed = Rc::new(Cell::new(false));
|
||||
let refusals = Cell::new(0);
|
||||
let route: [f32; K] = std::array::from_fn(|i| if i < 6 { 0.125 } else { 0.0625 });
|
||||
let env = Env {
|
||||
ctx: &ctx,
|
||||
failed: Rc::new(Cell::new(false)),
|
||||
refusals: Cell::new(0),
|
||||
route: std::array::from_fn(|i| if i < 6 { 0.125 } else { 0.0625 }),
|
||||
};
|
||||
for zero in [false, true] {
|
||||
let hidden: Vec<f32> = (0..640)
|
||||
.map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { ((i % 17) as f32 - 8.) / 64. })
|
||||
.collect();
|
||||
let input: Vec<f32> = (0..N)
|
||||
.map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { ((i % 13) as f32 - 6.) / 128. })
|
||||
.collect();
|
||||
let scalar_bytes = scalar_weights();
|
||||
// Independent genuine old path FIRST, complete host concatenation.
|
||||
let expected_parts: Vec<f32> = (0..K).flat_map(|i| original_down(&ctx, &hidden, i).into_vec()).collect();
|
||||
let expected_shared = original_down(&ctx, &hidden, K);
|
||||
let scalar_input = upload_f32(&ctx, &input).unwrap();
|
||||
let scalar_matrix = upload_bytes(&ctx, &scalar_bytes).unwrap();
|
||||
let mut scalar = ctx.allocate(4).unwrap();
|
||||
ctx.moe_shared_scalar_f32_bf16(&scalar_input, &scalar_matrix, &mut scalar).unwrap();
|
||||
let expected_scalar = download_f32(&scalar, 1).unwrap();
|
||||
assert!((0.0..=1.0).contains(&expected_scalar[0]));
|
||||
let old_shared = upload_f32(&ctx, &expected_shared).unwrap();
|
||||
let mut old_scaled = ctx.allocate(N * 4).unwrap();
|
||||
ctx.moe_shared_scale_f32(&old_shared, &scalar, &mut old_scaled).unwrap();
|
||||
let expected_scaled = download_f32(&old_scaled, N).unwrap();
|
||||
let old_parts = upload_f32(&ctx, &expected_parts).unwrap();
|
||||
let weights = upload_f32(&ctx, &route).unwrap();
|
||||
let mut old_output = ctx.allocate(N * 4).unwrap();
|
||||
ctx.moe_combine_f64(&old_parts, &weights, &old_scaled, &mut old_output).unwrap();
|
||||
let expected_out = download_f32(&old_output, N).unwrap();
|
||||
old_output.release().unwrap();
|
||||
old_parts.release().unwrap();
|
||||
old_scaled.release().unwrap();
|
||||
old_shared.release().unwrap();
|
||||
scalar.release().unwrap();
|
||||
let scope = DownScope::new(&ctx, failed.clone());
|
||||
let mut parts = PackedDown::new(&scope).unwrap();
|
||||
let x = upload_f32(&ctx, &hidden).unwrap();
|
||||
for slot in 0..K {
|
||||
let down = retained(&scope, &x, DownSelection::Routed(slot), slot);
|
||||
exact(down.values(), &expected_parts[slot * N..(slot + 1) * N]);
|
||||
parts.pack(&scope, down).unwrap();
|
||||
assert_eq!(parts.next, slot + 1);
|
||||
}
|
||||
exact(&download_f32(parts.output.buffer().unwrap(), K * N).unwrap(), &expected_parts);
|
||||
let shared = retained(&scope, &x, DownSelection::Shared, K);
|
||||
exact(shared.values(), &expected_shared);
|
||||
let scalar = scope.shared_scalar(&scalar_input, &scalar_matrix).unwrap();
|
||||
exact(&download_f32(scalar.output.buffer().unwrap(), 1).unwrap(), &expected_scalar);
|
||||
let scaled = shared.scale(&scope, &scalar).unwrap();
|
||||
exact(&download_f32(scaled.output.buffer().unwrap(), N).unwrap(), &expected_scaled);
|
||||
exact(&parts.combine(&scope, &weights, &scaled).unwrap(), &expected_out);
|
||||
if !zero {
|
||||
let wrong = DownScope::new(&ctx, failed.clone());
|
||||
refused(parts.combine(&wrong, &weights, &scaled), Error::IdentityMismatch, &refusals);
|
||||
let malformed = upload_bytes(&ctx, &[0; 4]).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(parts.combine(&scope, &malformed, &scaled), Error::InvalidDimension, &refusals);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
malformed.release().unwrap();
|
||||
let mut bad_route = route;
|
||||
bad_route[K - 1] = f32::NAN;
|
||||
let bad = upload_bytes(&ctx, &bad_route.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>()).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(parts.combine(&scope, &bad, &scaled), Error::NonFinite, &refusals);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
bad.release().unwrap();
|
||||
assert!(!failed.get());
|
||||
}
|
||||
let mut unchanged = vec![0; hidden.len() * 4];
|
||||
x.copy_to(&mut unchanged).unwrap();
|
||||
assert_eq!(unchanged, hidden.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
|
||||
let mut unchanged = vec![0; scalar_bytes.len()];
|
||||
scalar_matrix.copy_to(&mut unchanged).unwrap();
|
||||
assert_eq!(unchanged, scalar_bytes);
|
||||
let mut unchanged = vec![0; input.len() * 4];
|
||||
scalar_input.copy_to(&mut unchanged).unwrap();
|
||||
assert_eq!(unchanged, input.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
|
||||
let mut unchanged = vec![0; K * 4];
|
||||
weights.copy_to(&mut unchanged).unwrap();
|
||||
assert_eq!(unchanged, route.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
|
||||
x.release().unwrap();
|
||||
parts.close().unwrap();
|
||||
scaled.close().unwrap();
|
||||
scalar.close().unwrap();
|
||||
weights.release().unwrap();
|
||||
scalar_matrix.release().unwrap();
|
||||
scalar_input.release().unwrap();
|
||||
assert_eq!(ctx.allocated_bytes(), 0);
|
||||
println!("MOE_DOWN_RETAINED PAIR zero={zero} exact_words=58881 unique_words=33281");
|
||||
}
|
||||
let scope = DownScope::new(&ctx, failed.clone());
|
||||
let rival = DownScope::new(&ctx, failed.clone());
|
||||
let x = upload_f32(&ctx, &[0.125; 640]).unwrap();
|
||||
let input = upload_f32(&ctx, &[0.125; N]).unwrap();
|
||||
let matrix = upload_bytes(&ctx, &scalar_weights()).unwrap();
|
||||
let scalar = scope.shared_scalar(&input, &matrix).unwrap();
|
||||
let rival_scalar = rival.shared_scalar(&input, &matrix).unwrap();
|
||||
let mut parts = PackedDown::new(&scope).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(parts.pack(&scope, retained(&scope, &x, DownSelection::Routed(1), 1)), Error::IdentityMismatch, &refusals);
|
||||
refused(parts.pack(&scope, retained(&scope, &x, DownSelection::Shared, K)), Error::IdentityMismatch, &refusals);
|
||||
refused(parts.pack(&scope, retained(&rival, &x, DownSelection::Routed(0), 0)), Error::IdentityMismatch, &refusals);
|
||||
assert_eq!(parts.next, 0);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
parts.pack(&scope, retained(&scope, &x, DownSelection::Routed(0), 0)).unwrap();
|
||||
refused(parts.pack(&scope, retained(&scope, &x, DownSelection::Routed(0), 0)), Error::IdentityMismatch, &refusals);
|
||||
assert_eq!(parts.next, 1);
|
||||
refused(
|
||||
retained(&scope, &x, DownSelection::Shared, K).scale(&scope, &rival_scalar),
|
||||
Error::IdentityMismatch,
|
||||
&refusals,
|
||||
);
|
||||
let scaled = retained(&scope, &x, DownSelection::Shared, K).scale(&scope, &scalar).unwrap();
|
||||
let weights = upload_f32(&ctx, &route).unwrap();
|
||||
refused(parts.combine(&scope, &weights, &scaled), Error::IdentityMismatch, &refusals);
|
||||
let called = Cell::new(false);
|
||||
refused(
|
||||
scope.project(DownSelection::Routed(K), |_| {
|
||||
called.set(true);
|
||||
unreachable!()
|
||||
}),
|
||||
Error::InvalidExpert,
|
||||
&refusals,
|
||||
);
|
||||
assert!(!called.get());
|
||||
let malformed = upload_bytes(&ctx, &[0; 2]).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(
|
||||
scope.project(DownSelection::Routed(1), |out| project(&ctx, &malformed, &x, out)),
|
||||
Error::InvalidDimension,
|
||||
&refusals,
|
||||
);
|
||||
refused(scope.shared_scalar(&input, &malformed), Error::InvalidDimension, &refusals);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
malformed.release().unwrap();
|
||||
let mut bad_down = down_weights(1);
|
||||
let end = bad_down.len();
|
||||
bad_down[end - 34..end - 32].copy_from_slice(&0x7c00u16.to_le_bytes());
|
||||
let bad = upload_bytes(&ctx, &bad_down).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(scope.project(DownSelection::Routed(1), |out| project(&ctx, &bad, &x, out)), Error::NonFinite, &refusals);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
bad.release().unwrap();
|
||||
// Actual scalar kernel refuses malformed raw operands and finite F32_MAX
|
||||
// that rounds to BF16 infinity; DOUBLE-dot overflow is not alleged.
|
||||
for value in [f32::NAN, f32::INFINITY, f32::MAX] {
|
||||
let mut raw = vec![0.125; N];
|
||||
raw[N - 1] = value;
|
||||
let bad = upload_bytes(&ctx, &raw.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>()).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(scope.shared_scalar(&bad, &matrix), Error::NonFinite, &refusals);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
bad.release().unwrap();
|
||||
env.pair_case(zero);
|
||||
}
|
||||
let mut rig = Rig::new(&env);
|
||||
rig.pack_refusals();
|
||||
let (scaled, weights) = rig.scale_refusals();
|
||||
rig.project_refusals();
|
||||
rig.scalar_kernel_refusals();
|
||||
let foreign = device.create_context(144 * 1024 * 1024).unwrap();
|
||||
let foreign_scope = DownScope::new(&foreign, Rc::new(Cell::new(false)));
|
||||
let foreign_x = upload_f32(&foreign, &[0.125; 640]).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(
|
||||
parts.pack(&scope, retained(&foreign_scope, &foreign_x, DownSelection::Routed(1), 1)),
|
||||
Error::IdentityMismatch,
|
||||
&refusals,
|
||||
);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
assert_eq!(foreign.allocated_bytes(), 640 * 4);
|
||||
foreign_x.release().unwrap();
|
||||
assert_eq!(foreign.allocated_bytes(), 0);
|
||||
// Partial packed and completed-but-unconsumed products are aborted. No new
|
||||
// scope can consume their prior epoch; Drop frees genuine outputs once.
|
||||
drop(parts);
|
||||
let aborted = retained(&scope, &x, DownSelection::Routed(1), 1);
|
||||
let charge = ctx.allocated_bytes();
|
||||
drop(aborted);
|
||||
assert_eq!(ctx.allocated_bytes(), charge - N * 4);
|
||||
let mut partial = PackedDown::new(&scope).unwrap();
|
||||
let pending = retained(&scope, &x, DownSelection::Routed(0), 0);
|
||||
failed.set(true); // Explicit shared policy only; never clear it.
|
||||
refused(PackedDown::new(&scope), Error::CudaExecution, &refusals);
|
||||
refused(scope.upload(&[0.]), Error::CudaExecution, &refusals);
|
||||
refused(partial.pack(&scope, pending), Error::CudaExecution, &refusals);
|
||||
refused(partial.combine(&scope, &weights, &scaled), Error::CudaExecution, &refusals);
|
||||
assert_eq!(partial.close(), Err(Error::CudaExecution));
|
||||
assert_eq!(scalar.close(), Err(Error::CudaExecution));
|
||||
assert_eq!(rival_scalar.close(), Err(Error::CudaExecution));
|
||||
assert_eq!(scaled.close(), Err(Error::CudaExecution));
|
||||
weights.release().unwrap();
|
||||
matrix.release().unwrap();
|
||||
input.release().unwrap();
|
||||
x.release().unwrap();
|
||||
assert!(failed.get());
|
||||
assert_eq!(ctx.allocated_bytes(), 0);
|
||||
assert_eq!(refusals.get(), 21);
|
||||
drop(scope);
|
||||
drop(rival);
|
||||
drop(foreign_scope);
|
||||
let foreign_scope = rig.foreign_refusal(&foreign);
|
||||
rig.abort_cleanup(scaled, weights, foreign_scope);
|
||||
ctx.synchronize().unwrap();
|
||||
ctx.close().unwrap();
|
||||
foreign.close().unwrap();
|
||||
println!(
|
||||
"MOE_DOWN_RETAINED COMPLETE finite_cases=2 exact_words=117762 unique_words=66562 refusals=21 abort_cleanup=2 allocated=0"
|
||||
"MOE_DOWN_RETAINED COMPLETE finite_cases=2 exact_words=117762 unique_words=66562 refusals=21 \
|
||||
abort_cleanup=2 allocated=0"
|
||||
);
|
||||
}
|
||||
|
||||
#[path = "moe_down_reuse_gpu/pair_fn.rs"]
|
||||
mod pair_fn;
|
||||
#[path = "moe_down_reuse_gpu/rig_fn.rs"]
|
||||
mod rig_fn;
|
||||
use pair_fn::Env;
|
||||
use rig_fn::Rig;
|
||||
#[path = "moe_down_reuse_gpu/exact_fn.rs"]
|
||||
mod exact_fn;
|
||||
#[allow(unused_imports)]
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! The two finite pair cases of the retained Down proof (one body per phase, STRA-338).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Shared state of the proof: one context, the shared failure bit, the refusal counter and the routing weights.
|
||||
pub(super) struct Env<'c> {
|
||||
pub(super) ctx: &'c Context<'c>,
|
||||
pub(super) failed: Rc<Cell<bool>>,
|
||||
pub(super) refusals: Cell<usize>,
|
||||
pub(super) route: [f32; K],
|
||||
}
|
||||
|
||||
struct OldPath<'c> {
|
||||
parts: Vec<f32>,
|
||||
shared: Box<[f32]>,
|
||||
scalar: Box<[f32]>,
|
||||
scaled: Box<[f32]>,
|
||||
out: Box<[f32]>,
|
||||
scalar_input: DeviceBuffer<'c>,
|
||||
scalar_matrix: DeviceBuffer<'c>,
|
||||
weights: DeviceBuffer<'c>,
|
||||
}
|
||||
|
||||
fn pattern(count: usize, zero: bool, modulus: usize, offset: f32, divisor: f32) -> Vec<f32> {
|
||||
(0..count)
|
||||
.map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { ((i % modulus) as f32 - offset) / divisor })
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn le_bytes(values: &[f32]) -> Vec<u8> {
|
||||
values.iter().flat_map(|v| v.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
fn assert_unchanged(buffer: &DeviceBuffer<'_>, expected: &[u8]) {
|
||||
let mut unchanged = vec![0; expected.len()];
|
||||
buffer.copy_to(&mut unchanged).unwrap();
|
||||
assert_eq!(unchanged, expected);
|
||||
}
|
||||
|
||||
impl<'c> Env<'c> {
|
||||
/// Independent genuine old path FIRST, complete host concatenation.
|
||||
fn old_path(&self, hidden: &[f32], input: &[f32], scalar_bytes: &[u8]) -> OldPath<'c> {
|
||||
let ctx = self.ctx;
|
||||
let parts: Vec<f32> = (0..K).flat_map(|i| original_down(ctx, hidden, i).into_vec()).collect();
|
||||
let shared = original_down(ctx, hidden, K);
|
||||
let scalar_input = upload_f32(ctx, input).unwrap();
|
||||
let scalar_matrix = upload_bytes(ctx, scalar_bytes).unwrap();
|
||||
let mut scalar = ctx.allocate(4).unwrap();
|
||||
ctx.moe_shared_scalar_f32_bf16(&scalar_input, &scalar_matrix, &mut scalar).unwrap();
|
||||
let expected_scalar = download_f32(&scalar, 1).unwrap();
|
||||
assert!((0.0..=1.0).contains(&expected_scalar[0]));
|
||||
let old_shared = upload_f32(ctx, &shared).unwrap();
|
||||
let mut old_scaled = ctx.allocate(N * 4).unwrap();
|
||||
ctx.moe_shared_scale_f32(&old_shared, &scalar, &mut old_scaled).unwrap();
|
||||
let scaled = download_f32(&old_scaled, N).unwrap();
|
||||
let old_parts = upload_f32(ctx, &parts).unwrap();
|
||||
let weights = upload_f32(ctx, &self.route).unwrap();
|
||||
let mut old_output = ctx.allocate(N * 4).unwrap();
|
||||
ctx.moe_combine_f64(&old_parts, &weights, &old_scaled, &mut old_output).unwrap();
|
||||
let out = download_f32(&old_output, N).unwrap();
|
||||
old_output.release().unwrap();
|
||||
old_parts.release().unwrap();
|
||||
old_scaled.release().unwrap();
|
||||
old_shared.release().unwrap();
|
||||
scalar.release().unwrap();
|
||||
OldPath { parts, shared, scalar: expected_scalar, scaled, out, scalar_input, scalar_matrix, weights }
|
||||
}
|
||||
|
||||
/// Packs every routed Down, scales the shared one and checks each retained value against the old path.
|
||||
fn retained_chain(
|
||||
&self,
|
||||
scope: &DownScope<'c>,
|
||||
x: &DeviceBuffer<'_>,
|
||||
parts: &mut PackedDown<'c>,
|
||||
old: &OldPath<'_>,
|
||||
) -> (RetainedScalar<'c>, ScaledDown<'c>) {
|
||||
for slot in 0..K {
|
||||
let down = retained(scope, x, DownSelection::Routed(slot), slot);
|
||||
exact(down.values(), &old.parts[slot * N..(slot + 1) * N]);
|
||||
parts.pack(scope, down).unwrap();
|
||||
assert_eq!(parts.next, slot + 1);
|
||||
}
|
||||
exact(&download_f32(parts.output.buffer().unwrap(), K * N).unwrap(), &old.parts);
|
||||
let shared = retained(scope, x, DownSelection::Shared, K);
|
||||
exact(shared.values(), &old.shared);
|
||||
let scalar = scope.shared_scalar(&old.scalar_input, &old.scalar_matrix).unwrap();
|
||||
exact(&download_f32(scalar.output.buffer().unwrap(), 1).unwrap(), &old.scalar);
|
||||
let scaled = shared.scale(scope, &scalar).unwrap();
|
||||
exact(&download_f32(scaled.output.buffer().unwrap(), N).unwrap(), &old.scaled);
|
||||
(scalar, scaled)
|
||||
}
|
||||
|
||||
fn combine_refusals(
|
||||
&self,
|
||||
scope: &DownScope<'c>,
|
||||
parts: &PackedDown<'c>,
|
||||
scaled: &ScaledDown<'c>,
|
||||
weights: &DeviceBuffer<'_>,
|
||||
) {
|
||||
let ctx = self.ctx;
|
||||
let wrong = DownScope::new(ctx, self.failed.clone());
|
||||
refused(parts.combine(&wrong, weights, scaled), Error::IdentityMismatch, &self.refusals);
|
||||
let malformed = upload_bytes(ctx, &[0; 4]).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(parts.combine(scope, &malformed, scaled), Error::InvalidDimension, &self.refusals);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
malformed.release().unwrap();
|
||||
let mut bad_route = self.route;
|
||||
bad_route[K - 1] = f32::NAN;
|
||||
let bad = upload_bytes(ctx, &le_bytes(&bad_route)).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(parts.combine(scope, &bad, scaled), Error::NonFinite, &self.refusals);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
bad.release().unwrap();
|
||||
assert!(!self.failed.get());
|
||||
}
|
||||
|
||||
pub(super) fn pair_case(&self, zero: bool) {
|
||||
let ctx = self.ctx;
|
||||
let hidden = pattern(640, zero, 17, 8., 64.);
|
||||
let input = pattern(N, zero, 13, 6., 128.);
|
||||
let scalar_bytes = scalar_weights();
|
||||
let old = self.old_path(&hidden, &input, &scalar_bytes);
|
||||
let scope = DownScope::new(ctx, self.failed.clone());
|
||||
let mut parts = PackedDown::new(&scope).unwrap();
|
||||
let x = upload_f32(ctx, &hidden).unwrap();
|
||||
let (scalar, scaled) = self.retained_chain(&scope, &x, &mut parts, &old);
|
||||
exact(&parts.combine(&scope, &old.weights, &scaled).unwrap(), &old.out);
|
||||
if !zero {
|
||||
self.combine_refusals(&scope, &parts, &scaled, &old.weights);
|
||||
}
|
||||
assert_unchanged(&x, &le_bytes(&hidden));
|
||||
assert_unchanged(&old.scalar_matrix, &scalar_bytes);
|
||||
assert_unchanged(&old.scalar_input, &le_bytes(&input));
|
||||
assert_unchanged(&old.weights, &le_bytes(&self.route));
|
||||
x.release().unwrap();
|
||||
parts.close().unwrap();
|
||||
scaled.close().unwrap();
|
||||
scalar.close().unwrap();
|
||||
old.weights.release().unwrap();
|
||||
old.scalar_matrix.release().unwrap();
|
||||
old.scalar_input.release().unwrap();
|
||||
assert_eq!(ctx.allocated_bytes(), 0);
|
||||
println!("MOE_DOWN_RETAINED PAIR zero={zero} exact_words=58881 unique_words=33281");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//! The refusal and abort phases of the retained Down proof (one body per phase, STRA-338).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::pair_fn::{Env, le_bytes};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Scopes, inputs and the half-packed owner shared by the refusal phases.
|
||||
pub(super) struct Rig<'c> {
|
||||
env: &'c Env<'c>,
|
||||
scope: DownScope<'c>,
|
||||
rival: DownScope<'c>,
|
||||
x: DeviceBuffer<'c>,
|
||||
input: DeviceBuffer<'c>,
|
||||
matrix: DeviceBuffer<'c>,
|
||||
scalar: RetainedScalar<'c>,
|
||||
rival_scalar: RetainedScalar<'c>,
|
||||
parts: PackedDown<'c>,
|
||||
}
|
||||
|
||||
impl<'c> Rig<'c> {
|
||||
pub(super) fn new(env: &'c Env<'c>) -> Self {
|
||||
let ctx = env.ctx;
|
||||
let scope = DownScope::new(ctx, env.failed.clone());
|
||||
let rival = DownScope::new(ctx, env.failed.clone());
|
||||
let x = upload_f32(ctx, &[0.125; 640]).unwrap();
|
||||
let input = upload_f32(ctx, &[0.125; N]).unwrap();
|
||||
let matrix = upload_bytes(ctx, &scalar_weights()).unwrap();
|
||||
let scalar = scope.shared_scalar(&input, &matrix).unwrap();
|
||||
let rival_scalar = rival.shared_scalar(&input, &matrix).unwrap();
|
||||
let parts = PackedDown::new(&scope).unwrap();
|
||||
Self { env, scope, rival, x, input, matrix, scalar, rival_scalar, parts }
|
||||
}
|
||||
|
||||
pub(super) fn pack_refusals(&mut self) {
|
||||
let (env, scope, x) = (self.env, &self.scope, &self.x);
|
||||
let charge = env.ctx.allocated_bytes();
|
||||
let mismatch = Error::IdentityMismatch;
|
||||
refused(self.parts.pack(scope, retained(scope, x, DownSelection::Routed(1), 1)), mismatch, &env.refusals);
|
||||
refused(self.parts.pack(scope, retained(scope, x, DownSelection::Shared, K)), mismatch, &env.refusals);
|
||||
refused(self.parts.pack(scope, retained(&self.rival, x, DownSelection::Routed(0), 0)), mismatch, &env.refusals);
|
||||
assert_eq!(self.parts.next, 0);
|
||||
assert_eq!(env.ctx.allocated_bytes(), charge);
|
||||
self.parts.pack(scope, retained(scope, x, DownSelection::Routed(0), 0)).unwrap();
|
||||
refused(self.parts.pack(scope, retained(scope, x, DownSelection::Routed(0), 0)), mismatch, &env.refusals);
|
||||
assert_eq!(self.parts.next, 1);
|
||||
}
|
||||
|
||||
/// Returns the scaled shared owner and the routing weights the later phases keep using.
|
||||
pub(super) fn scale_refusals(&self) -> (ScaledDown<'c>, DeviceBuffer<'c>) {
|
||||
let (env, scope, x) = (self.env, &self.scope, &self.x);
|
||||
refused(
|
||||
retained(scope, x, DownSelection::Shared, K).scale(scope, &self.rival_scalar),
|
||||
Error::IdentityMismatch,
|
||||
&env.refusals,
|
||||
);
|
||||
let scaled = retained(scope, x, DownSelection::Shared, K).scale(scope, &self.scalar).unwrap();
|
||||
let weights = upload_f32(env.ctx, &env.route).unwrap();
|
||||
refused(self.parts.combine(scope, &weights, &scaled), Error::IdentityMismatch, &env.refusals);
|
||||
(scaled, weights)
|
||||
}
|
||||
|
||||
pub(super) fn project_refusals(&self) {
|
||||
let (env, scope, x) = (self.env, &self.scope, &self.x);
|
||||
let ctx = env.ctx;
|
||||
let called = Cell::new(false);
|
||||
refused(
|
||||
scope.project(DownSelection::Routed(K), |_| {
|
||||
called.set(true);
|
||||
unreachable!()
|
||||
}),
|
||||
Error::InvalidExpert,
|
||||
&env.refusals,
|
||||
);
|
||||
assert!(!called.get());
|
||||
let malformed = upload_bytes(ctx, &[0; 2]).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(
|
||||
scope.project(DownSelection::Routed(1), |out| project(ctx, &malformed, x, out)),
|
||||
Error::InvalidDimension,
|
||||
&env.refusals,
|
||||
);
|
||||
refused(scope.shared_scalar(&self.input, &malformed), Error::InvalidDimension, &env.refusals);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
malformed.release().unwrap();
|
||||
self.bad_down_refusal();
|
||||
}
|
||||
|
||||
fn bad_down_refusal(&self) {
|
||||
let (env, scope, x) = (self.env, &self.scope, &self.x);
|
||||
let ctx = env.ctx;
|
||||
let mut bad_down = down_weights(1);
|
||||
let end = bad_down.len();
|
||||
bad_down[end - 34..end - 32].copy_from_slice(&0x7c00u16.to_le_bytes());
|
||||
let bad = upload_bytes(ctx, &bad_down).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(
|
||||
scope.project(DownSelection::Routed(1), |out| project(ctx, &bad, x, out)),
|
||||
Error::NonFinite,
|
||||
&env.refusals,
|
||||
);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
bad.release().unwrap();
|
||||
}
|
||||
|
||||
/// Actual scalar kernel refuses malformed raw operands and finite F32_MAX
|
||||
/// that rounds to BF16 infinity; DOUBLE-dot overflow is not alleged.
|
||||
pub(super) fn scalar_kernel_refusals(&self) {
|
||||
let ctx = self.env.ctx;
|
||||
for value in [f32::NAN, f32::INFINITY, f32::MAX] {
|
||||
let mut raw = vec![0.125; N];
|
||||
raw[N - 1] = value;
|
||||
let bad = upload_bytes(ctx, &le_bytes(&raw)).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refused(self.scope.shared_scalar(&bad, &self.matrix), Error::NonFinite, &self.env.refusals);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
bad.release().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A scope of another context cannot feed this packet; returns the foreign scope for the final drop.
|
||||
pub(super) fn foreign_refusal<'f>(&mut self, foreign: &'f Context<'f>) -> DownScope<'f> {
|
||||
let foreign_scope = DownScope::new(foreign, Rc::new(Cell::new(false)));
|
||||
let foreign_x = upload_f32(foreign, &[0.125; 640]).unwrap();
|
||||
let charge = self.env.ctx.allocated_bytes();
|
||||
refused(
|
||||
self.parts.pack(&self.scope, retained(&foreign_scope, &foreign_x, DownSelection::Routed(1), 1)),
|
||||
Error::IdentityMismatch,
|
||||
&self.env.refusals,
|
||||
);
|
||||
assert_eq!(self.env.ctx.allocated_bytes(), charge);
|
||||
assert_eq!(foreign.allocated_bytes(), 640 * 4);
|
||||
foreign_x.release().unwrap();
|
||||
assert_eq!(foreign.allocated_bytes(), 0);
|
||||
foreign_scope
|
||||
}
|
||||
|
||||
/// Partial packed and completed-but-unconsumed products are aborted. No new
|
||||
/// scope can consume their prior epoch; Drop frees genuine outputs once.
|
||||
pub(super) fn abort_cleanup(self, scaled: ScaledDown<'c>, weights: DeviceBuffer<'c>, foreign_scope: DownScope<'_>) {
|
||||
let Self { env, scope, rival, x, input, matrix, scalar, rival_scalar, parts } = self;
|
||||
let ctx = env.ctx;
|
||||
drop(parts);
|
||||
let aborted = retained(&scope, &x, DownSelection::Routed(1), 1);
|
||||
let charge = ctx.allocated_bytes();
|
||||
drop(aborted);
|
||||
assert_eq!(ctx.allocated_bytes(), charge - N * 4);
|
||||
let mut partial = PackedDown::new(&scope).unwrap();
|
||||
let pending = retained(&scope, &x, DownSelection::Routed(0), 0);
|
||||
env.failed.set(true); // Explicit shared policy only; never clear it.
|
||||
refused(PackedDown::new(&scope), Error::CudaExecution, &env.refusals);
|
||||
refused(scope.upload(&[0.]), Error::CudaExecution, &env.refusals);
|
||||
refused(partial.pack(&scope, pending), Error::CudaExecution, &env.refusals);
|
||||
refused(partial.combine(&scope, &weights, &scaled), Error::CudaExecution, &env.refusals);
|
||||
assert_eq!(partial.close(), Err(Error::CudaExecution));
|
||||
assert_eq!(scalar.close(), Err(Error::CudaExecution));
|
||||
assert_eq!(rival_scalar.close(), Err(Error::CudaExecution));
|
||||
assert_eq!(scaled.close(), Err(Error::CudaExecution));
|
||||
weights.release().unwrap();
|
||||
matrix.release().unwrap();
|
||||
input.release().unwrap();
|
||||
x.release().unwrap();
|
||||
assert!(env.failed.get());
|
||||
assert_eq!(ctx.allocated_bytes(), 0);
|
||||
assert_eq!(env.refusals.get(), 21);
|
||||
drop(scope);
|
||||
drop(rival);
|
||||
drop(foreign_scope);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,109 @@
|
||||
//! Moved out of the parent module by STRA-338: fn cached_mlp_down, fn cached_gate_up_scoped.
|
||||
|
||||
use super::project_matrix_fn::{MatrixDims, gate_up_dims, gate_up_prepared_format};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
fn check_origin(origin: &DownOrigin, binding: &ModelBinding, weights: &MoeExpertWeights) -> Result<()> {
|
||||
if !origin.binding.matches(&binding.identity())
|
||||
|| !weights.matches(&binding.identity(), origin.identity.layer().get())
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn swiglu_hidden(
|
||||
context: &Context<'_>,
|
||||
scope: &DownScope<'_>,
|
||||
gate: &TransportBuffer<'_>,
|
||||
up: &TransportBuffer<'_>,
|
||||
hidden: &mut TransportBuffer<'_>,
|
||||
) -> Result<()> {
|
||||
let swiglu = context.moe_swiglu_f32(gate.buffer()?, up.buffer()?, hidden.buffer_mut()?).map_err(driver_error);
|
||||
scope.record(&swiglu);
|
||||
swiglu?;
|
||||
let readback = download_f32(hidden.buffer()?, FF);
|
||||
scope.record(&readback);
|
||||
readback?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn project_down<'ctx>(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
scope: &DownScope<'ctx>,
|
||||
hidden: &TransportBuffer<'_>,
|
||||
) -> Result<RetainedDown<'ctx>> {
|
||||
cache.validate(binding, context)?;
|
||||
let (columns, rows) = weights.shape(selection, MoeMatrixRole::Down).map_err(binding_error)?;
|
||||
let kind = weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?;
|
||||
if columns != FF || rows != N {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let matrix = cache.matrix(binding, weights, selection, MoeMatrixRole::Down)?;
|
||||
let numeric_selection = match selection {
|
||||
MoeExpertSelection::Routed { slot } => DownSelection::Routed(slot),
|
||||
MoeExpertSelection::Shared => DownSelection::Shared,
|
||||
};
|
||||
scope.project(numeric_selection, |output| {
|
||||
launch_cached_projection(context, kind, matrix, hidden.buffer()?, output, rows, columns)
|
||||
})
|
||||
}
|
||||
|
||||
/// Records the Down result, then attempts every owned close; the primary failure wins over cleanup failures.
|
||||
fn close_down_parts<'ctx>(
|
||||
scope: &DownScope<'ctx>,
|
||||
result: Result<RetainedDown<'ctx>>,
|
||||
gate: TransportBuffer<'ctx>,
|
||||
up: TransportBuffer<'ctx>,
|
||||
hidden: TransportBuffer<'ctx>,
|
||||
) -> Result<RetainedDown<'ctx>> {
|
||||
scope.record(&result);
|
||||
let gate_close = gate.close();
|
||||
let up_close = up.close();
|
||||
let hidden_close = hidden.close();
|
||||
let output = result?;
|
||||
gate_close?;
|
||||
up_close?;
|
||||
hidden_close?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Gate and Up of one expert plus the hidden buffer they feed; a failure closes every owner already made.
|
||||
fn gate_up_hidden<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
(activation, prepared): (&DeviceBuffer<'_>, Option<&RoutedGateUpQ8<'_>>),
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
scope: &DownScope<'ctx>,
|
||||
) -> Result<(TransportBuffer<'ctx>, TransportBuffer<'ctx>, TransportBuffer<'ctx>)> {
|
||||
let scoped = |cache: &mut MoeWeightCache<'_>, role| {
|
||||
cached_gate_up_scoped(context, binding, weights, selection, role, activation, cache, prepared, scope)
|
||||
};
|
||||
let gate = scoped(cache, MoeMatrixRole::Gate)?;
|
||||
let up = match scoped(cache, MoeMatrixRole::Up) {
|
||||
Ok(up) => up,
|
||||
Err(primary) => {
|
||||
let _ = gate.close();
|
||||
return Err(primary);
|
||||
}
|
||||
};
|
||||
match scope.allocate(FF * 4) {
|
||||
Ok(hidden) => Ok((gate, up, hidden)),
|
||||
Err(primary) => {
|
||||
let _ = gate.close();
|
||||
let _ = up.close();
|
||||
Err(primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn cached_mlp_down<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
@@ -15,79 +116,46 @@ pub(super) fn cached_mlp_down<'ctx>(
|
||||
scope: &DownScope<'ctx>,
|
||||
origin: &Rc<DownOrigin>,
|
||||
) -> Result<ActualDown<'ctx>> {
|
||||
if !origin.binding.matches(&binding.identity())
|
||||
|| !weights.matches(&binding.identity(), origin.identity.layer().get())
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let gate = cached_gate_up_scoped(
|
||||
context,
|
||||
binding,
|
||||
weights,
|
||||
check_origin(origin, binding, weights)?;
|
||||
let inputs = (activation, prepared);
|
||||
let (gate, up, mut hidden) = gate_up_hidden(context, binding, weights, selection, inputs, cache, scope)?;
|
||||
let result = swiglu_hidden(context, scope, &gate, &up, &mut hidden)
|
||||
.and_then(|()| project_down(context, binding, weights, selection, cache, scope, &hidden));
|
||||
close_down_parts(scope, result, gate, up, hidden).map(|output| ActualDown {
|
||||
origin: Rc::clone(origin),
|
||||
selection,
|
||||
MoeMatrixRole::Gate,
|
||||
activation,
|
||||
cache,
|
||||
prepared,
|
||||
scope,
|
||||
)?;
|
||||
let up = match cached_gate_up_scoped(
|
||||
context,
|
||||
binding,
|
||||
weights,
|
||||
selection,
|
||||
MoeMatrixRole::Up,
|
||||
activation,
|
||||
cache,
|
||||
prepared,
|
||||
scope,
|
||||
) {
|
||||
Ok(up) => up,
|
||||
Err(primary) => {
|
||||
let _ = gate.close();
|
||||
return Err(primary);
|
||||
}
|
||||
};
|
||||
let mut hidden = match scope.allocate(FF * 4) {
|
||||
Ok(hidden) => hidden,
|
||||
Err(primary) => {
|
||||
let _ = gate.close();
|
||||
let _ = up.close();
|
||||
return Err(primary);
|
||||
}
|
||||
};
|
||||
let result = (|| {
|
||||
let swiglu = context.moe_swiglu_f32(gate.buffer()?, up.buffer()?, hidden.buffer_mut()?).map_err(driver_error);
|
||||
scope.record(&swiglu);
|
||||
swiglu?;
|
||||
let readback = download_f32(hidden.buffer()?, FF);
|
||||
scope.record(&readback);
|
||||
readback?;
|
||||
cache.validate(binding, context)?;
|
||||
let (columns, rows) = weights.shape(selection, MoeMatrixRole::Down).map_err(binding_error)?;
|
||||
let kind = weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?;
|
||||
if columns != FF || rows != N {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let matrix = cache.matrix(binding, weights, selection, MoeMatrixRole::Down)?;
|
||||
let numeric_selection = match selection {
|
||||
MoeExpertSelection::Routed { slot } => DownSelection::Routed(slot),
|
||||
MoeExpertSelection::Shared => DownSelection::Shared,
|
||||
};
|
||||
scope.project(numeric_selection, |output| {
|
||||
launch_cached_projection(context, kind, matrix, hidden.buffer()?, output, rows, columns)
|
||||
})
|
||||
})();
|
||||
scope.record(&result);
|
||||
let gate_close = gate.close();
|
||||
let up_close = up.close();
|
||||
let hidden_close = hidden.close();
|
||||
let output = result?;
|
||||
gate_close?;
|
||||
up_close?;
|
||||
hidden_close?;
|
||||
Ok(ActualDown { origin: Rc::clone(origin), selection, output })
|
||||
output,
|
||||
})
|
||||
}
|
||||
fn launch_scoped_gate_up(
|
||||
context: &Context<'_>,
|
||||
matrix: CachedMoeMatrix<'_, '_>,
|
||||
dims: MatrixDims,
|
||||
selection: MoeExpertSelection,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
output: &mut TransportBuffer<'_>,
|
||||
) -> Result<()> {
|
||||
match prepared {
|
||||
Some(prepared) => {
|
||||
let format = gate_up_prepared_format(selection, dims.kind)?;
|
||||
launch_cached_prepared(context, matrix, prepared, output.buffer_mut()?, format)?;
|
||||
}
|
||||
None => {
|
||||
launch_cached_projection(
|
||||
context,
|
||||
dims.kind,
|
||||
matrix,
|
||||
activation,
|
||||
output.buffer_mut()?,
|
||||
dims.rows,
|
||||
dims.columns,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
download_f32(output.buffer()?, FF).map(|_| ())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn cached_gate_up_scoped<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
@@ -100,32 +168,11 @@ pub(super) fn cached_gate_up_scoped<'ctx>(
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
scope: &DownScope<'ctx>,
|
||||
) -> Result<TransportBuffer<'ctx>> {
|
||||
let (columns, rows) = weights.shape(selection, role).map_err(binding_error)?;
|
||||
let kind = weights.kind(selection, role).map_err(binding_error)?;
|
||||
if !matches!(role, MoeMatrixRole::Gate | MoeMatrixRole::Up) || rows != FF || columns != N {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let dims = gate_up_dims(weights, selection, role)?;
|
||||
cache.validate(binding, context)?;
|
||||
let matrix = cache.matrix(binding, weights, selection, role)?;
|
||||
let mut output = scope.allocate(FF * 4)?;
|
||||
let result = (|| {
|
||||
if let Some(prepared) = prepared {
|
||||
if !matches!(selection, MoeExpertSelection::Routed { .. }) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let format = match kind {
|
||||
MoeMatrixKind::Iq3Xxs => RoutedFormat::IQ3_XXS,
|
||||
MoeMatrixKind::Iq3S => RoutedFormat::IQ3_S,
|
||||
MoeMatrixKind::Iq2S => RoutedFormat::IQ2_S,
|
||||
MoeMatrixKind::RoutedIq4Xs => RoutedFormat::IQ4_XS,
|
||||
_ => return Err(Error::Unsupported(Stage::MoeExpert)),
|
||||
};
|
||||
launch_cached_prepared(context, matrix, prepared, output.buffer_mut()?, format)?;
|
||||
} else {
|
||||
launch_cached_projection(context, kind, matrix, activation, output.buffer_mut()?, rows, columns)?;
|
||||
}
|
||||
download_f32(output.buffer()?, FF).map(|_| ())
|
||||
})();
|
||||
let result = launch_scoped_gate_up(context, matrix, dims, selection, prepared, activation, &mut output);
|
||||
scope.record(&result);
|
||||
if let Err(primary) = result {
|
||||
let _ = output.close();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Moved out of the parent module by STRA-338: fn expert_mlp, fn project_cached_gate_up, fn project_retained_gate_up, fn finish_cached_mlp.
|
||||
|
||||
use super::project_matrix_fn::{gate_up_dims, gate_up_prepared_format};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -13,64 +14,15 @@ pub(super) fn expert_mlp(
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
if let Some(cache) = cache.as_deref_mut() {
|
||||
let gate = project_cached_gate_up(
|
||||
context,
|
||||
binding,
|
||||
weights,
|
||||
selection,
|
||||
MoeMatrixRole::Gate,
|
||||
activation,
|
||||
cache,
|
||||
prepared,
|
||||
)?;
|
||||
let up = match project_cached_gate_up(
|
||||
context,
|
||||
binding,
|
||||
weights,
|
||||
selection,
|
||||
MoeMatrixRole::Up,
|
||||
activation,
|
||||
cache,
|
||||
prepared,
|
||||
) {
|
||||
Ok(up) => up,
|
||||
Err(primary) => {
|
||||
let _ = gate.release();
|
||||
return Err(primary);
|
||||
}
|
||||
};
|
||||
return finish_cached_mlp(context, gate, up, |hidden| {
|
||||
project_matrix(context, binding, weights, selection, MoeMatrixRole::Down, hidden, Some(cache), None)
|
||||
});
|
||||
return cached_expert_mlp(context, binding, weights, selection, activation, cache, prepared);
|
||||
}
|
||||
// Genuine uncached diagnostic: keep its original download/reupload chain.
|
||||
let gate = project_matrix(
|
||||
context,
|
||||
binding,
|
||||
weights,
|
||||
selection,
|
||||
MoeMatrixRole::Gate,
|
||||
activation,
|
||||
cache.as_deref_mut(),
|
||||
prepared,
|
||||
)?;
|
||||
let up = project_matrix(
|
||||
context,
|
||||
binding,
|
||||
weights,
|
||||
selection,
|
||||
MoeMatrixRole::Up,
|
||||
activation,
|
||||
cache.as_deref_mut(),
|
||||
prepared,
|
||||
)?;
|
||||
let gate = upload_f32(context, &gate)?;
|
||||
let up = upload_f32(context, &up)?;
|
||||
let mut hidden = context.allocate(FF * 4).map_err(driver_error)?;
|
||||
context.moe_swiglu_f32(&gate, &up, &mut hidden).map_err(driver_error)?;
|
||||
download_f32(&hidden, FF)?;
|
||||
gate.release().map_err(driver_error)?;
|
||||
up.release().map_err(driver_error)?;
|
||||
let project = |role, cache: Option<&mut MoeWeightCache<'_>>| {
|
||||
project_matrix(context, binding, weights, selection, role, activation, cache, prepared)
|
||||
};
|
||||
let gate = project(MoeMatrixRole::Gate, cache.as_deref_mut())?;
|
||||
let up = project(MoeMatrixRole::Up, cache.as_deref_mut())?;
|
||||
let hidden = uncached_hidden(context, gate, up)?;
|
||||
let result = project_matrix(context, binding, weights, selection, MoeMatrixRole::Down, &hidden, cache, None);
|
||||
let release = hidden.release().map_err(driver_error);
|
||||
match result {
|
||||
@@ -81,6 +33,41 @@ pub(super) fn expert_mlp(
|
||||
}
|
||||
}
|
||||
}
|
||||
fn cached_expert_mlp(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let project = |role, cache: &mut MoeWeightCache<'_>| {
|
||||
project_cached_gate_up(context, binding, weights, selection, role, activation, cache, prepared)
|
||||
};
|
||||
let gate = project(MoeMatrixRole::Gate, cache)?;
|
||||
let up = match project(MoeMatrixRole::Up, cache) {
|
||||
Ok(up) => up,
|
||||
Err(primary) => {
|
||||
let _ = gate.release();
|
||||
return Err(primary);
|
||||
}
|
||||
};
|
||||
finish_cached_mlp(context, gate, up, |hidden| {
|
||||
project_matrix(context, binding, weights, selection, MoeMatrixRole::Down, hidden, Some(cache), None)
|
||||
})
|
||||
}
|
||||
/// Re-uploads the host Gate/Up of the uncached diagnostic and returns the checked SwiGLU hidden buffer.
|
||||
fn uncached_hidden<'ctx>(context: &'ctx Context<'_>, gate: Box<[f32]>, up: Box<[f32]>) -> Result<DeviceBuffer<'ctx>> {
|
||||
let gate = upload_f32(context, &gate)?;
|
||||
let up = upload_f32(context, &up)?;
|
||||
let mut hidden = context.allocate(FF * 4).map_err(driver_error)?;
|
||||
context.moe_swiglu_f32(&gate, &up, &mut hidden).map_err(driver_error)?;
|
||||
download_f32(&hidden, FF)?;
|
||||
gate.release().map_err(driver_error)?;
|
||||
up.release().map_err(driver_error)?;
|
||||
Ok(hidden)
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn project_cached_gate_up<'ctx>(
|
||||
context: &'ctx Context<'_>,
|
||||
@@ -92,29 +79,15 @@ pub(super) fn project_cached_gate_up<'ctx>(
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<DeviceBuffer<'ctx>> {
|
||||
let (columns, rows) = weights.shape(selection, role).map_err(binding_error)?;
|
||||
let kind = weights.kind(selection, role).map_err(binding_error)?;
|
||||
if !matches!(role, MoeMatrixRole::Gate | MoeMatrixRole::Up) || rows != FF || columns != N {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let dims = gate_up_dims(weights, selection, role)?;
|
||||
cache.validate(binding, context)?;
|
||||
let matrix = cache.matrix(binding, weights, selection, role)?;
|
||||
project_retained_gate_up(context, |output| {
|
||||
if let Some(prepared) = prepared {
|
||||
if !matches!(selection, MoeExpertSelection::Routed { .. }) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let format = match kind {
|
||||
MoeMatrixKind::Iq3Xxs => RoutedFormat::IQ3_XXS,
|
||||
MoeMatrixKind::Iq3S => RoutedFormat::IQ3_S,
|
||||
MoeMatrixKind::Iq2S => RoutedFormat::IQ2_S,
|
||||
MoeMatrixKind::RoutedIq4Xs => RoutedFormat::IQ4_XS,
|
||||
_ => return Err(Error::Unsupported(Stage::MoeExpert)),
|
||||
};
|
||||
project_retained_gate_up(context, |output| match prepared {
|
||||
Some(prepared) => {
|
||||
let format = gate_up_prepared_format(selection, dims.kind)?;
|
||||
launch_cached_prepared(context, matrix, prepared, output, format)
|
||||
} else {
|
||||
launch_cached_projection(context, kind, matrix, activation, output, rows, columns)
|
||||
}
|
||||
None => launch_cached_projection(context, dims.kind, matrix, activation, output, dims.rows, dims.columns),
|
||||
})
|
||||
}
|
||||
// Fixed 640-value projection lifecycle shared by the cached artifact path and
|
||||
@@ -133,6 +106,23 @@ pub(super) fn project_retained_gate_up<'ctx>(
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Attempts every owned release after the last use; primary work/readback
|
||||
/// failure wins, and any cleanup failure withholds a completed candidate.
|
||||
fn release_mlp_parts(
|
||||
result: Result<Box<[f32]>>,
|
||||
gate: DeviceBuffer<'_>,
|
||||
up: DeviceBuffer<'_>,
|
||||
hidden: DeviceBuffer<'_>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let gate_close = gate.release().map_err(driver_error);
|
||||
let up_close = up.release().map_err(driver_error);
|
||||
let hidden_close = hidden.release().map_err(driver_error);
|
||||
let values = result?;
|
||||
gate_close?;
|
||||
up_close?;
|
||||
hidden_close?;
|
||||
Ok(values)
|
||||
}
|
||||
pub(super) fn finish_cached_mlp(
|
||||
context: &Context<'_>,
|
||||
gate: DeviceBuffer<'_>,
|
||||
@@ -153,14 +143,5 @@ pub(super) fn finish_cached_mlp(
|
||||
download_f32(&hidden, FF)?;
|
||||
down(&hidden)
|
||||
})();
|
||||
// Attempt every owned release after the last use; primary work/readback
|
||||
// failure wins, and any cleanup failure withholds a completed candidate.
|
||||
let gate_close = gate.release().map_err(driver_error);
|
||||
let up_close = up.release().map_err(driver_error);
|
||||
let hidden_close = hidden.release().map_err(driver_error);
|
||||
let values = result?;
|
||||
gate_close?;
|
||||
up_close?;
|
||||
hidden_close?;
|
||||
Ok(values)
|
||||
release_mlp_parts(result, gate, up, hidden)
|
||||
}
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
//! Moved out of the parent module by STRA-338: fn finish_with_parts, impl ActualSlotPacket, impl ActualDown, fn execute_cuda_cached.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::moe_down::{RetainedScalar, ScaledDown};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Shared expert, router-weighted combine and readback over already computed
|
||||
/// routed expert outputs (`parts` is K*N values in router slot order).
|
||||
pub(super) fn finish_with_parts(
|
||||
context: &Context<'_>,
|
||||
/// Shared scalar gate of the shared expert: the scalar buffer plus the uncached path's owned weight upload.
|
||||
fn shared_scalar_buffers<'ctx>(
|
||||
context: &'ctx Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
route: &RoutedExperts,
|
||||
parts: &[f32],
|
||||
mut cache: Option<&mut MoeWeightCache<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let shared =
|
||||
expert_mlp(context, binding, weights, MoeExpertSelection::Shared, activation, cache.as_deref_mut(), None)?;
|
||||
let shared_input = upload_f32(context, &shared)?;
|
||||
cache: Option<&mut MoeWeightCache<'_>>,
|
||||
) -> Result<(DeviceBuffer<'ctx>, Option<DeviceBuffer<'ctx>>)> {
|
||||
let owned_scalar;
|
||||
let scalar_weights = match cache {
|
||||
Some(cache) => {
|
||||
@@ -35,15 +31,51 @@ pub(super) fn finish_with_parts(
|
||||
if !(0.0..=1.0).contains(&scalar_value[0]) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
let mut scaled = context.allocate(N * 4).map_err(driver_error)?;
|
||||
context.moe_shared_scale_f32(&shared_input, &scalar, &mut scaled).map_err(driver_error)?;
|
||||
download_f32(&scaled, N)?;
|
||||
Ok((scalar, owned_scalar))
|
||||
}
|
||||
fn release_shared_inputs(
|
||||
owned_scalar: Option<DeviceBuffer<'_>>,
|
||||
scalar: DeviceBuffer<'_>,
|
||||
shared_input: DeviceBuffer<'_>,
|
||||
) -> Result<()> {
|
||||
if let Some(buffer) = owned_scalar {
|
||||
buffer.release().map_err(driver_error)?;
|
||||
}
|
||||
for buffer in [scalar, shared_input] {
|
||||
buffer.release().map_err(driver_error)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The shared expert output scaled by its scalar gate, read back and finite-checked.
|
||||
fn scaled_shared<'ctx>(
|
||||
context: &'ctx Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
mut cache: Option<&mut MoeWeightCache<'_>>,
|
||||
) -> Result<DeviceBuffer<'ctx>> {
|
||||
let shared =
|
||||
expert_mlp(context, binding, weights, MoeExpertSelection::Shared, activation, cache.as_deref_mut(), None)?;
|
||||
let shared_input = upload_f32(context, &shared)?;
|
||||
let (scalar, owned_scalar) = shared_scalar_buffers(context, binding, weights, activation, cache)?;
|
||||
let mut scaled = context.allocate(N * 4).map_err(driver_error)?;
|
||||
context.moe_shared_scale_f32(&shared_input, &scalar, &mut scaled).map_err(driver_error)?;
|
||||
download_f32(&scaled, N)?;
|
||||
release_shared_inputs(owned_scalar, scalar, shared_input)?;
|
||||
Ok(scaled)
|
||||
}
|
||||
/// Shared expert, router-weighted combine and readback over already computed
|
||||
/// routed expert outputs (`parts` is K*N values in router slot order).
|
||||
pub(super) fn finish_with_parts(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
route: &RoutedExperts,
|
||||
parts: &[f32],
|
||||
cache: Option<&mut MoeWeightCache<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let scaled = scaled_shared(context, binding, weights, activation, cache)?;
|
||||
let parts = upload_f32(context, &parts)?;
|
||||
let route_values: [f32; K] = std::array::from_fn(|i| route.weights()[i].get());
|
||||
let route_weights = upload_f32(context, &route_values)?;
|
||||
@@ -86,6 +118,91 @@ impl<'ctx> ActualDown<'ctx> {
|
||||
Ok(self.output)
|
||||
}
|
||||
}
|
||||
/// Everything one cached execution reads: the validated inputs and its step-local scope.
|
||||
struct CachedRun<'a, 'ctx, 'b, 'q> {
|
||||
context: &'ctx Context<'ctx>,
|
||||
binding: &'a ModelBinding,
|
||||
weights: &'a MoeExpertWeights,
|
||||
activation: &'a DeviceBuffer<'b>,
|
||||
route: &'a RoutedExperts,
|
||||
prepared: Option<&'a RoutedGateUpQ8<'q>>,
|
||||
scope: &'a DownScope<'ctx>,
|
||||
origin: &'a Rc<DownOrigin>,
|
||||
}
|
||||
impl<'ctx> CachedRun<'_, 'ctx, '_, '_> {
|
||||
fn down(
|
||||
&self,
|
||||
selection: MoeExpertSelection,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<ActualDown<'ctx>> {
|
||||
let (context, binding, weights, activation) = (self.context, self.binding, self.weights, self.activation);
|
||||
cached_mlp_down(context, binding, weights, selection, activation, cache, prepared, self.scope, self.origin)
|
||||
}
|
||||
fn take(&self, down: ActualDown<'ctx>, selection: MoeExpertSelection) -> Result<RetainedDown<'ctx>> {
|
||||
down.take(self.origin, self.binding, self.route.identity(), selection)
|
||||
}
|
||||
}
|
||||
/// Partial owners of one cached execution; every one is closed explicitly, whatever failed.
|
||||
#[derive(Default)]
|
||||
struct CachedOwners<'ctx> {
|
||||
parts: Option<PackedDown<'ctx>>,
|
||||
shared: Option<RetainedDown<'ctx>>,
|
||||
scalar: Option<RetainedScalar<'ctx>>,
|
||||
scaled: Option<ScaledDown<'ctx>>,
|
||||
route_weights: Option<TransportBuffer<'ctx>>,
|
||||
}
|
||||
impl<'ctx> CachedOwners<'ctx> {
|
||||
fn run(&mut self, run: &CachedRun<'_, 'ctx, '_, '_>, cache: &mut MoeWeightCache<'_>) -> Result<Box<[f32]>> {
|
||||
self.pack_routed(run, cache)?;
|
||||
self.scale_shared(run, cache)?;
|
||||
self.combine(run)
|
||||
}
|
||||
fn pack_routed(&mut self, run: &CachedRun<'_, 'ctx, '_, '_>, cache: &mut MoeWeightCache<'_>) -> Result<()> {
|
||||
// Charge the single destination before any cache miss/eviction, so
|
||||
// the existing Context-aware room policy accounts for its lifetime.
|
||||
self.parts = Some(PackedDown::new(run.scope)?);
|
||||
for slot in 0..K {
|
||||
let selection = MoeExpertSelection::Routed { slot };
|
||||
let down = run.down(selection, cache, run.prepared)?;
|
||||
self.parts.as_mut().ok_or(Error::IdentityMismatch)?.pack(run.scope, run.take(down, selection)?)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn scale_shared(&mut self, run: &CachedRun<'_, 'ctx, '_, '_>, cache: &mut MoeWeightCache<'_>) -> Result<()> {
|
||||
let selection = MoeExpertSelection::Shared;
|
||||
self.shared = Some(run.take(run.down(selection, cache, None)?, selection)?);
|
||||
let scalar_weights = cache.shared_scalar(run.binding, run.weights)?;
|
||||
self.scalar = Some(run.scope.shared_scalar(run.activation, scalar_weights)?);
|
||||
self.scaled = Some(
|
||||
self.shared
|
||||
.take()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.scale(run.scope, self.scalar.as_ref().ok_or(Error::IdentityMismatch)?)?,
|
||||
);
|
||||
self.scalar.take().ok_or(Error::IdentityMismatch)?.close()
|
||||
}
|
||||
fn combine(&mut self, run: &CachedRun<'_, 'ctx, '_, '_>) -> Result<Box<[f32]>> {
|
||||
let route_values: [f32; K] = std::array::from_fn(|i| run.route.weights()[i].get());
|
||||
self.route_weights = Some(run.scope.upload(&route_values)?);
|
||||
self.parts.as_ref().ok_or(Error::IdentityMismatch)?.combine(
|
||||
run.scope,
|
||||
self.route_weights.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?,
|
||||
self.scaled.as_ref().ok_or(Error::IdentityMismatch)?,
|
||||
)
|
||||
}
|
||||
/// Attempts every partial owner explicitly before a primary is selected, in the fixed order shared, scalar,
|
||||
/// weights, parts, scaled; the caller still fences cache use on a transport failure before surfacing the primary.
|
||||
fn close_all(self) -> [Result<()>; 5] {
|
||||
[
|
||||
self.shared.map_or(Ok(()), |owner| owner.close()),
|
||||
self.scalar.map_or(Ok(()), |owner| owner.close()),
|
||||
self.route_weights.map_or(Ok(()), |owner| owner.close()),
|
||||
self.parts.map_or(Ok(()), |owner| owner.close()),
|
||||
self.scaled.map_or(Ok(()), |owner| owner.close()),
|
||||
]
|
||||
}
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn execute_cuda_cached(
|
||||
context: &Context<'_>,
|
||||
@@ -104,65 +221,15 @@ pub(super) fn execute_cuda_cached(
|
||||
let origin = Rc::new(DownOrigin { binding: binding.identity(), identity: route.identity() });
|
||||
let failed = Rc::new(Cell::new(false));
|
||||
let scope = DownScope::new(context, Rc::clone(&failed));
|
||||
let mut parts = None;
|
||||
let mut shared = None;
|
||||
let mut scalar = None;
|
||||
let mut scaled = None;
|
||||
let mut route_weights = None;
|
||||
let result =
|
||||
(|| {
|
||||
// Charge the single destination before any cache miss/eviction, so
|
||||
// the existing Context-aware room policy accounts for its lifetime.
|
||||
parts = Some(PackedDown::new(&scope)?);
|
||||
for slot in 0..K {
|
||||
let selection = MoeExpertSelection::Routed { slot };
|
||||
let down = cached_mlp_down(
|
||||
context, binding, weights, selection, activation, cache, prepared, &scope, &origin,
|
||||
)?;
|
||||
parts
|
||||
.as_mut()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.pack(&scope, down.take(&origin, binding, route.identity(), selection)?)?;
|
||||
}
|
||||
let selection = MoeExpertSelection::Shared;
|
||||
shared =
|
||||
Some(
|
||||
cached_mlp_down(context, binding, weights, selection, activation, cache, None, &scope, &origin)?
|
||||
.take(&origin, binding, route.identity(), selection)?,
|
||||
);
|
||||
let scalar_weights = cache.shared_scalar(binding, weights)?;
|
||||
scalar = Some(scope.shared_scalar(activation, scalar_weights)?);
|
||||
scaled = Some(
|
||||
shared
|
||||
.take()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.scale(&scope, scalar.as_ref().ok_or(Error::IdentityMismatch)?)?,
|
||||
);
|
||||
scalar.take().ok_or(Error::IdentityMismatch)?.close()?;
|
||||
let route_values: [f32; K] = std::array::from_fn(|i| route.weights()[i].get());
|
||||
route_weights = Some(scope.upload(&route_values)?);
|
||||
parts.as_ref().ok_or(Error::IdentityMismatch)?.combine(
|
||||
&scope,
|
||||
route_weights.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?,
|
||||
scaled.as_ref().ok_or(Error::IdentityMismatch)?,
|
||||
)
|
||||
})();
|
||||
let run = CachedRun { context, binding, weights, activation, route, prepared, scope: &scope, origin: &origin };
|
||||
let mut owners = CachedOwners::default();
|
||||
let result = owners.run(&run, cache);
|
||||
scope.record(&result);
|
||||
// Attempt every partial owner explicitly before selecting a primary.
|
||||
let shared_close = shared.map_or(Ok(()), |owner| owner.close());
|
||||
let scalar_close = scalar.map_or(Ok(()), |owner| owner.close());
|
||||
let weights_close = route_weights.map_or(Ok(()), |owner| owner.close());
|
||||
let parts_close = parts.map_or(Ok(()), |owner| owner.close());
|
||||
let scaled_close = scaled.map_or(Ok(()), |owner| owner.close());
|
||||
// Preserve the primary numeric error while fencing future cache use.
|
||||
let closes = owners.close_all();
|
||||
if failed.get() {
|
||||
cache.note_transport_failure();
|
||||
}
|
||||
let values = result?;
|
||||
shared_close?;
|
||||
scalar_close?;
|
||||
weights_close?;
|
||||
parts_close?;
|
||||
scaled_close?;
|
||||
closes.into_iter().collect::<Result<()>>()?;
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,90 @@ impl ExpertReady {
|
||||
Ok(Self { binding, identity, values })
|
||||
}
|
||||
}
|
||||
fn validate_step(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
route: &RoutedExperts,
|
||||
input: &ResidualReady,
|
||||
txn: &QwenStepTxn,
|
||||
) -> Result<()> {
|
||||
txn.validate_binding(&binding.identity())?;
|
||||
route.validate_binding(&binding.identity())?;
|
||||
route.validate_for(txn.token(), txn.position(), layer)?;
|
||||
input.validate_origin(&binding.identity(), GrRole::Ffn(layer.get()))?;
|
||||
input.identity().validate(txn.token(), txn.position(), layer)?;
|
||||
if input.identity() != route.identity() || layer.get() >= binding.layer_count() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
txn.validate_input(txn.token(), txn.position())?;
|
||||
validate_values(input.mixed(), N)
|
||||
}
|
||||
fn admit_step_resources(
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
cache: Option<&mut MoeWeightCache<'_>>,
|
||||
) -> Result<()> {
|
||||
if let Some(cache) = cache {
|
||||
cache.prepare_step(binding, context)?;
|
||||
}
|
||||
admit_budget(context.allocated_bytes(), context.budget_bytes())
|
||||
}
|
||||
fn admitted_weights(binding: &ModelBinding, layer: LayerId, route: &RoutedExperts) -> Result<MoeExpertWeights> {
|
||||
let ids = std::array::from_fn(|i| route.experts()[i].get());
|
||||
// All seven descriptors and all ten IDs admitted before CUDA work.
|
||||
let weights = binding.moe_expert_weights(layer.get(), ids).map_err(binding_error)?;
|
||||
if !weights.matches(&binding.identity(), layer.get()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(weights)
|
||||
}
|
||||
/// The validated inputs of one expert step on the device.
|
||||
struct StepCuda<'a, 'c, 'b> {
|
||||
context: &'a Context<'c>,
|
||||
binding: &'a ModelBinding,
|
||||
weights: &'a MoeExpertWeights,
|
||||
activation: &'a DeviceBuffer<'b>,
|
||||
route: &'a RoutedExperts,
|
||||
}
|
||||
impl StepCuda<'_, '_, '_> {
|
||||
/// The expert output and the result of closing the step-local prepared owner.
|
||||
fn dispatch(
|
||||
&self,
|
||||
input: &ResidualReady,
|
||||
layer: LayerId,
|
||||
cache: Option<&mut MoeWeightCache<'_>>,
|
||||
) -> (Result<Box<[f32]>>, Result<()>) {
|
||||
let Self { context, binding, weights, activation, route } = *self;
|
||||
// One immutable, step-local owner only on the explicitly selected
|
||||
// cache path. It never enters the weight cache or recurrence state.
|
||||
if let Some(kar) = binding.kar_expert_source() {
|
||||
// Routed experts come from the KAR archive and never touch the MMQ
|
||||
// weight cache. The serving backend always owns a cache and hands
|
||||
// it to every step, so a present cache cannot be a reason to
|
||||
// refuse: it is simply not consulted for any expert here (the
|
||||
// shared expert takes the uncached path inside the KAR branch).
|
||||
let host = input.mixed();
|
||||
return (execute_cuda_kar(context, binding, weights, activation, route, host, (layer.get(), kar)), Ok(()));
|
||||
}
|
||||
match cache {
|
||||
Some(cache) => self.dispatch_prepared(cache),
|
||||
None => (execute_cuda(context, binding, weights, activation, route, None, None), Ok(())),
|
||||
}
|
||||
}
|
||||
fn dispatch_prepared(&self, cache: &mut MoeWeightCache<'_>) -> (Result<Box<[f32]>>, Result<()>) {
|
||||
let Self { context, binding, weights, activation, route } = *self;
|
||||
match context.prepare_routed_gate_up_q8(activation) {
|
||||
Ok(prepared) => {
|
||||
let result = execute_cuda(context, binding, weights, activation, route, Some(cache), Some(&prepared));
|
||||
// Always attempt owner close before releasing its borrowed
|
||||
// activation, including a projection/readback failure.
|
||||
let closed = prepared.close().map_err(driver_error);
|
||||
(result, closed)
|
||||
}
|
||||
Err(error) => (Err(driver_error(error)), Ok(())),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl MoeExpertStage {
|
||||
pub(in super::super) fn execute(
|
||||
binding: &ModelBinding,
|
||||
@@ -33,54 +117,13 @@ impl MoeExpertStage {
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
let _owner_wall_scope =
|
||||
crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Moe);
|
||||
txn.validate_binding(&binding.identity())?;
|
||||
route.validate_binding(&binding.identity())?;
|
||||
route.validate_for(txn.token(), txn.position(), layer)?;
|
||||
input.validate_origin(&binding.identity(), GrRole::Ffn(layer.get()))?;
|
||||
input.identity().validate(txn.token(), txn.position(), layer)?;
|
||||
if input.identity() != route.identity() || layer.get() >= binding.layer_count() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
txn.validate_input(txn.token(), txn.position())?;
|
||||
validate_values(input.mixed(), N)?;
|
||||
validate_step(binding, layer, &route, input, txn)?;
|
||||
let context = txn.cuda_context()?;
|
||||
if let Some(cache) = cache.as_deref_mut() {
|
||||
cache.prepare_step(binding, context)?;
|
||||
}
|
||||
admit_budget(context.allocated_bytes(), context.budget_bytes())?;
|
||||
let ids = std::array::from_fn(|i| route.experts()[i].get());
|
||||
// All seven descriptors and all ten IDs admitted before CUDA work.
|
||||
let weights = binding.moe_expert_weights(layer.get(), ids).map_err(binding_error)?;
|
||||
if !weights.matches(&binding.identity(), layer.get()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
admit_step_resources(binding, context, cache.as_deref_mut())?;
|
||||
let weights = admitted_weights(binding, layer, &route)?;
|
||||
let activation = upload_f32(context, input.mixed())?;
|
||||
// One immutable, step-local owner only on the explicitly selected
|
||||
// cache path. It never enters the weight cache or recurrence state.
|
||||
let (result, prepared_close) = if let Some(kar) = binding.kar_expert_source() {
|
||||
// Routed experts come from the KAR archive and never touch the MMQ
|
||||
// weight cache. The serving backend always owns a cache and hands
|
||||
// it to every step, so a present cache cannot be a reason to
|
||||
// refuse: it is simply not consulted for any expert here (the
|
||||
// shared expert takes the uncached path inside the KAR branch).
|
||||
(
|
||||
execute_cuda_kar(context, binding, &weights, &activation, &route, input.mixed(), (layer.get(), kar)),
|
||||
Ok(()),
|
||||
)
|
||||
} else if cache.is_some() {
|
||||
match context.prepare_routed_gate_up_q8(&activation) {
|
||||
Ok(prepared) => {
|
||||
let result = execute_cuda(context, binding, &weights, &activation, &route, cache, Some(&prepared));
|
||||
// Always attempt owner close before releasing its borrowed
|
||||
// activation, including a projection/readback failure.
|
||||
let closed = prepared.close().map_err(driver_error);
|
||||
(result, closed)
|
||||
}
|
||||
Err(error) => (Err(driver_error(error)), Ok(())),
|
||||
}
|
||||
} else {
|
||||
(execute_cuda(context, binding, &weights, &activation, &route, None, None), Ok(()))
|
||||
};
|
||||
let step = StepCuda { context, binding, weights: &weights, activation: &activation, route: &route };
|
||||
let (result, prepared_close) = step.dispatch(input, layer, cache);
|
||||
let activation_close = activation.release().map_err(driver_error);
|
||||
let values = result?;
|
||||
prepared_close?;
|
||||
|
||||
@@ -3,6 +3,115 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Shape and format of one expert matrix as the binding declares it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct MatrixDims {
|
||||
pub(super) columns: usize,
|
||||
pub(super) rows: usize,
|
||||
pub(super) kind: MoeMatrixKind,
|
||||
}
|
||||
|
||||
fn matrix_dims(weights: &MoeExpertWeights, selection: MoeExpertSelection, role: MoeMatrixRole) -> Result<MatrixDims> {
|
||||
let (columns, rows) = weights.shape(selection, role).map_err(binding_error)?;
|
||||
let kind = weights.kind(selection, role).map_err(binding_error)?;
|
||||
Ok(MatrixDims { columns, rows, kind })
|
||||
}
|
||||
|
||||
pub(super) fn gate_up_dims(
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
role: MoeMatrixRole,
|
||||
) -> Result<MatrixDims> {
|
||||
let dims = matrix_dims(weights, selection, role)?;
|
||||
if !matches!(role, MoeMatrixRole::Gate | MoeMatrixRole::Up) || dims.rows != FF || dims.columns != N {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
Ok(dims)
|
||||
}
|
||||
|
||||
/// The routed prepared-Q8 format of a Gate/Up matrix kind; any other kind has no prepared path.
|
||||
fn prepared_routed_format(kind: MoeMatrixKind) -> Result<RoutedFormat> {
|
||||
Ok(match kind {
|
||||
MoeMatrixKind::Iq3Xxs => RoutedFormat::IQ3_XXS,
|
||||
MoeMatrixKind::Iq3S => RoutedFormat::IQ3_S,
|
||||
MoeMatrixKind::Iq2S => RoutedFormat::IQ2_S,
|
||||
MoeMatrixKind::RoutedIq4Xs => RoutedFormat::IQ4_XS,
|
||||
_ => return Err(Error::Unsupported(Stage::MoeExpert)),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn gate_up_prepared_format(selection: MoeExpertSelection, kind: MoeMatrixKind) -> Result<RoutedFormat> {
|
||||
if !matches!(selection, MoeExpertSelection::Routed { .. }) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
prepared_routed_format(kind)
|
||||
}
|
||||
|
||||
/// Uploads the raw matrix bytes of the uncached diagnostic path after the block matches the declared shape.
|
||||
fn upload_raw_matrix<'ctx>(
|
||||
context: &'ctx Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
(selection, role): (MoeExpertSelection, MoeMatrixRole),
|
||||
dims: MatrixDims,
|
||||
) -> Result<DeviceBuffer<'ctx>> {
|
||||
let block: MoeExpertBlock =
|
||||
binding.moe_expert_block(weights, selection, role, 0, dims.rows).map_err(binding_error)?;
|
||||
if block.kind() != dims.kind || block.columns() != dims.columns || block.rows() != dims.rows {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
upload_bytes(context, block.bytes())
|
||||
}
|
||||
|
||||
fn project_into(
|
||||
context: &Context<'_>,
|
||||
matrix: CachedMoeMatrix<'_, '_>,
|
||||
dims: MatrixDims,
|
||||
(selection, role): (MoeExpertSelection, MoeMatrixRole),
|
||||
(activation, prepared): (&DeviceBuffer<'_>, Option<&RoutedGateUpQ8<'_>>),
|
||||
output: &mut DeviceBuffer<'_>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
match prepared {
|
||||
Some(prepared) => {
|
||||
if !matches!(selection, MoeExpertSelection::Routed { .. })
|
||||
|| !matches!(role, MoeMatrixRole::Gate | MoeMatrixRole::Up)
|
||||
|| dims.rows != FF
|
||||
|| dims.columns != N
|
||||
{
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let format = prepared_routed_format(dims.kind)?;
|
||||
launch_cached_prepared(context, matrix, prepared, output, format)?;
|
||||
}
|
||||
None => {
|
||||
launch_cached_projection(context, dims.kind, matrix, activation, output, dims.rows, dims.columns)?;
|
||||
}
|
||||
}
|
||||
download_f32(output, dims.rows)
|
||||
}
|
||||
|
||||
/// Releases the projection output and the optional owned matrix; the primary result wins over cleanup failures.
|
||||
fn close_projection(
|
||||
result: Result<Box<[f32]>>,
|
||||
output: DeviceBuffer<'_>,
|
||||
owned: Option<DeviceBuffer<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let output_close = output.release().map_err(driver_error);
|
||||
let matrix_close = match owned {
|
||||
Some(matrix) => matrix.release().map_err(driver_error),
|
||||
None => Ok(()),
|
||||
};
|
||||
let values = result?;
|
||||
output_close?;
|
||||
matrix_close?;
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
fn allocate_output<'ctx>(context: &'ctx Context<'_>, rows: usize) -> Result<DeviceBuffer<'ctx>> {
|
||||
let output_bytes = rows.checked_mul(4).ok_or(Error::Overflow)?;
|
||||
context.allocate(output_bytes).map_err(driver_error)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn project_matrix(
|
||||
context: &Context<'_>,
|
||||
@@ -14,9 +123,8 @@ pub(super) fn project_matrix(
|
||||
cache: Option<&mut MoeWeightCache<'_>>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let (columns, rows) = weights.shape(selection, role).map_err(binding_error)?;
|
||||
let expected_kind = weights.kind(selection, role).map_err(binding_error)?;
|
||||
if ![FF, N].contains(&rows) {
|
||||
let dims = matrix_dims(weights, selection, role)?;
|
||||
if ![FF, N].contains(&dims.rows) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let owned;
|
||||
@@ -27,50 +135,14 @@ pub(super) fn project_matrix(
|
||||
cache.matrix(binding, weights, selection, role)?
|
||||
}
|
||||
None => {
|
||||
let block: MoeExpertBlock =
|
||||
binding.moe_expert_block(weights, selection, role, 0, rows).map_err(binding_error)?;
|
||||
if block.kind() != expected_kind || block.columns() != columns || block.rows() != rows {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
owned = Some(upload_bytes(context, block.bytes())?);
|
||||
owned = Some(upload_raw_matrix(context, binding, weights, (selection, role), dims)?);
|
||||
CachedMoeMatrix::Raw(owned.as_ref().ok_or(Error::IdentityMismatch)?)
|
||||
}
|
||||
};
|
||||
let output_bytes = rows.checked_mul(4).ok_or(Error::Overflow)?;
|
||||
let mut output = context.allocate(output_bytes).map_err(driver_error)?;
|
||||
let result = (|| {
|
||||
if let Some(prepared) = prepared {
|
||||
if !matches!(selection, MoeExpertSelection::Routed { .. })
|
||||
|| !matches!(role, MoeMatrixRole::Gate | MoeMatrixRole::Up)
|
||||
|| rows != FF
|
||||
|| columns != N
|
||||
{
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let format = match expected_kind {
|
||||
MoeMatrixKind::Iq3Xxs => RoutedFormat::IQ3_XXS,
|
||||
MoeMatrixKind::Iq3S => RoutedFormat::IQ3_S,
|
||||
MoeMatrixKind::Iq2S => RoutedFormat::IQ2_S,
|
||||
MoeMatrixKind::RoutedIq4Xs => RoutedFormat::IQ4_XS,
|
||||
_ => return Err(Error::Unsupported(Stage::MoeExpert)),
|
||||
};
|
||||
launch_cached_prepared(context, matrix, prepared, &mut output, format)?;
|
||||
} else {
|
||||
launch_cached_projection(context, expected_kind, matrix, activation, &mut output, rows, columns)?;
|
||||
}
|
||||
download_f32(&output, rows)
|
||||
})();
|
||||
let output_close = output.release().map_err(driver_error);
|
||||
let matrix_close = match owned {
|
||||
Some(matrix) => matrix.release().map_err(driver_error),
|
||||
None => Ok(()),
|
||||
};
|
||||
let values = result?;
|
||||
output_close?;
|
||||
matrix_close?;
|
||||
Ok(values)
|
||||
}
|
||||
// Retained legacy 64-row transport reference for its original refusal tests.
|
||||
let mut output = allocate_output(context, dims.rows)?;
|
||||
let result = project_into(context, matrix, dims, (selection, role), (activation, prepared), &mut output);
|
||||
close_projection(result, output, owned)
|
||||
} // Retained legacy 64-row transport reference for its original refusal tests.
|
||||
// Production projects the complete matrix above, without host projection/math.
|
||||
#[cfg(test)]
|
||||
pub(super) fn collect_rows(
|
||||
@@ -162,6 +234,46 @@ pub(super) fn launch_cached_prepared(
|
||||
}
|
||||
}
|
||||
}
|
||||
enum Launch {
|
||||
Q5K,
|
||||
Q6K,
|
||||
Plain(ProjectionKind),
|
||||
}
|
||||
|
||||
fn dense_format(kind: MoeMatrixKind) -> Option<DenseFormat> {
|
||||
use MoeMatrixKind as K;
|
||||
match kind {
|
||||
K::Q4K => Some(DenseFormat::Q4_K),
|
||||
K::DenseIq4Xs => Some(DenseFormat::IQ4_XS),
|
||||
K::Q8_0 => Some(DenseFormat::Q8_0),
|
||||
K::DenseIq4Nl => Some(DenseFormat::IQ4_NL),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn routed_projection_format(kind: MoeMatrixKind) -> Option<RoutedFormat> {
|
||||
use MoeMatrixKind as K;
|
||||
match kind {
|
||||
K::Iq3Xxs => Some(RoutedFormat::IQ3_XXS),
|
||||
K::Iq3S => Some(RoutedFormat::IQ3_S),
|
||||
K::Iq2S => Some(RoutedFormat::IQ2_S),
|
||||
K::RoutedIq4Xs => Some(RoutedFormat::IQ4_XS),
|
||||
K::RoutedIq4Nl => Some(RoutedFormat::IQ4_NL),
|
||||
K::Q2_0 => Some(RoutedFormat::Q2_0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// How a matrix kind is launched; every kind of the binding has exactly one plan.
|
||||
fn launch_plan(kind: MoeMatrixKind) -> Option<Launch> {
|
||||
match kind {
|
||||
MoeMatrixKind::Q5K => Some(Launch::Q5K),
|
||||
MoeMatrixKind::Q6K => Some(Launch::Q6K),
|
||||
_ => dense_format(kind)
|
||||
.map(|format| Launch::Plain(ProjectionKind::Dense(format)))
|
||||
.or_else(|| routed_projection_format(kind).map(|format| Launch::Plain(ProjectionKind::Routed(format)))),
|
||||
}
|
||||
}
|
||||
pub(super) fn launch_projection(
|
||||
context: &Context<'_>,
|
||||
kind: MoeMatrixKind,
|
||||
@@ -171,32 +283,20 @@ pub(super) fn launch_projection(
|
||||
rows: usize,
|
||||
columns: usize,
|
||||
) -> Result<()> {
|
||||
use MoeMatrixKind as K;
|
||||
let projection = match kind {
|
||||
K::Q5K => {
|
||||
return context
|
||||
.q5_k_q8_1(matrix, activation, output, Q5KProjectionShape { rows, columns })
|
||||
.map_err(driver_error);
|
||||
}
|
||||
K::Q6K => {
|
||||
return context
|
||||
.q6_k_q8_1(matrix, activation, output, Q6KProjectionShape { rows, columns })
|
||||
.map_err(driver_error);
|
||||
}
|
||||
K::Q4K => ProjectionKind::Dense(DenseFormat::Q4_K),
|
||||
K::DenseIq4Xs => ProjectionKind::Dense(DenseFormat::IQ4_XS),
|
||||
K::Q8_0 => ProjectionKind::Dense(DenseFormat::Q8_0),
|
||||
K::DenseIq4Nl => ProjectionKind::Dense(DenseFormat::IQ4_NL),
|
||||
K::Iq3Xxs => ProjectionKind::Routed(RoutedFormat::IQ3_XXS),
|
||||
K::Iq3S => ProjectionKind::Routed(RoutedFormat::IQ3_S),
|
||||
K::Iq2S => ProjectionKind::Routed(RoutedFormat::IQ2_S),
|
||||
K::RoutedIq4Xs => ProjectionKind::Routed(RoutedFormat::IQ4_XS),
|
||||
K::RoutedIq4Nl => ProjectionKind::Routed(RoutedFormat::IQ4_NL),
|
||||
K::Q2_0 => ProjectionKind::Routed(RoutedFormat::Q2_0),
|
||||
let Some(plan) = launch_plan(kind) else {
|
||||
return Err(Error::Unsupported(Stage::MoeExpert));
|
||||
};
|
||||
context
|
||||
.project_q8_1(matrix, activation, output, ProjectionSpec { kind: projection, rows, columns })
|
||||
.map_err(driver_error)
|
||||
match plan {
|
||||
Launch::Q5K => {
|
||||
context.q5_k_q8_1(matrix, activation, output, Q5KProjectionShape { rows, columns }).map_err(driver_error)
|
||||
}
|
||||
Launch::Q6K => {
|
||||
context.q6_k_q8_1(matrix, activation, output, Q6KProjectionShape { rows, columns }).map_err(driver_error)
|
||||
}
|
||||
Launch::Plain(projection) => context
|
||||
.project_q8_1(matrix, activation, output, ProjectionSpec { kind: projection, rows, columns })
|
||||
.map_err(driver_error),
|
||||
}
|
||||
}
|
||||
pub(super) fn admit_budget(allocated: usize, budget: usize) -> Result<()> {
|
||||
if allocated.checked_add(DEVICE_PEAK).ok_or(Error::Overflow)? > budget {
|
||||
|
||||
+69
-39
@@ -3,6 +3,70 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Partial owners of the shared expert of one row; every one is closed explicitly, whatever failed.
|
||||
#[derive(Default)]
|
||||
struct SharedOwners<'ctx> {
|
||||
shared: Option<super::super::moe_down::RetainedDown<'ctx>>,
|
||||
scalar: Option<super::super::moe_down::RetainedScalar<'ctx>>,
|
||||
scaled: Option<super::super::moe_down::ScaledDown<'ctx>>,
|
||||
route_weights: Option<super::super::moe_down::TransportBuffer<'ctx>>,
|
||||
}
|
||||
impl<'ctx> SharedOwners<'ctx> {
|
||||
fn scale_shared(
|
||||
&mut self,
|
||||
context: &'ctx Context<'ctx>,
|
||||
binding: &ModelBinding,
|
||||
row: &PreparedMoeRow,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
(scope, origin): (&DownScope<'ctx>, &Rc<DownOrigin>),
|
||||
) -> Result<()> {
|
||||
let selection = MoeExpertSelection::Shared;
|
||||
self.shared =
|
||||
Some(
|
||||
cached_mlp_down(context, binding, &row.weights, selection, activation, cache, None, scope, origin)?
|
||||
.take(origin, binding, row.route.identity(), selection)?,
|
||||
);
|
||||
let scalar_weights = cache.shared_scalar(binding, &row.weights)?;
|
||||
self.scalar = Some(scope.shared_scalar(activation, scalar_weights)?);
|
||||
self.scaled = Some(
|
||||
self.shared
|
||||
.take()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.scale(scope, self.scalar.as_ref().ok_or(Error::IdentityMismatch)?)?,
|
||||
);
|
||||
self.scalar.take().ok_or(Error::IdentityMismatch)?.close()
|
||||
}
|
||||
fn combine_with(
|
||||
&mut self,
|
||||
row: &PreparedMoeRow,
|
||||
scope: &DownScope<'ctx>,
|
||||
combine: impl FnOnce(&DeviceBuffer<'_>, &super::super::moe_down::ScaledDown<'_>) -> Result<Box<[f32]>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let values: [f32; K] = std::array::from_fn(|i| row.route.weights()[i].get());
|
||||
self.route_weights = Some(scope.upload(&values)?);
|
||||
combine(
|
||||
self.route_weights.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?,
|
||||
self.scaled.as_ref().ok_or(Error::IdentityMismatch)?,
|
||||
)
|
||||
}
|
||||
/// Attempts every close in the fixed order shared, scalar, scaled, weights; the first failure is reported.
|
||||
fn close_all(self) -> Result<()> {
|
||||
let mut cleanup = Ok(());
|
||||
for next in [
|
||||
self.shared.map_or(Ok(()), |v| v.close()),
|
||||
self.scalar.map_or(Ok(()), |v| v.close()),
|
||||
self.scaled.map_or(Ok(()), |v| v.close()),
|
||||
self.route_weights.map_or(Ok(()), |v| v.close()),
|
||||
] {
|
||||
if cleanup.is_ok() {
|
||||
cleanup = next;
|
||||
}
|
||||
}
|
||||
cleanup
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn finish_shared_with<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
@@ -18,48 +82,14 @@ pub(super) fn finish_shared_with<'ctx>(
|
||||
if crate::qwen_forward::layer0_mmq_observation::enabled() {
|
||||
crate::qwen_forward::layer0_mmq_observation::row(row.route.identity().position().get())?;
|
||||
}
|
||||
let selection = MoeExpertSelection::Shared;
|
||||
let mut shared = None;
|
||||
let mut scalar = None;
|
||||
let mut scaled = None;
|
||||
let mut route_weights = None;
|
||||
let operation = (|| {
|
||||
shared =
|
||||
Some(
|
||||
cached_mlp_down(context, binding, &row.weights, selection, activation, cache, None, scope, origin)?
|
||||
.take(origin, binding, row.route.identity(), selection)?,
|
||||
);
|
||||
let scalar_weights = cache.shared_scalar(binding, &row.weights)?;
|
||||
scalar = Some(scope.shared_scalar(activation, scalar_weights)?);
|
||||
scaled = Some(
|
||||
shared
|
||||
.take()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.scale(scope, scalar.as_ref().ok_or(Error::IdentityMismatch)?)?,
|
||||
);
|
||||
scalar.take().ok_or(Error::IdentityMismatch)?.close()?;
|
||||
let values: [f32; K] = std::array::from_fn(|i| row.route.weights()[i].get());
|
||||
route_weights = Some(scope.upload(&values)?);
|
||||
combine(
|
||||
route_weights.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?,
|
||||
scaled.as_ref().ok_or(Error::IdentityMismatch)?,
|
||||
)
|
||||
})();
|
||||
let mut owners = SharedOwners::default();
|
||||
let operation = owners
|
||||
.scale_shared(context, binding, row, activation, cache, (scope, origin))
|
||||
.and_then(|()| owners.combine_with(row, scope, combine));
|
||||
scope.record(&operation);
|
||||
let mut cleanup = Ok(());
|
||||
for next in [
|
||||
shared.map_or(Ok(()), |v| v.close()),
|
||||
scalar.map_or(Ok(()), |v| v.close()),
|
||||
scaled.map_or(Ok(()), |v| v.close()),
|
||||
route_weights.map_or(Ok(()), |v| v.close()),
|
||||
] {
|
||||
if cleanup.is_ok() {
|
||||
cleanup = next;
|
||||
}
|
||||
}
|
||||
let cleanup = owners.close_all();
|
||||
operation.and_then(|values| cleanup.map(|()| values))
|
||||
}
|
||||
|
||||
pub(super) fn uses_adaptive(cache: &MoeWeightCache<'_>) -> bool {
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
{
|
||||
|
||||
@@ -75,30 +75,10 @@ impl MoeExpertStage {
|
||||
}
|
||||
if use_direct_packets(cache) {
|
||||
return chunk.batch_outputs_ffn(layer, rows, |actual, context| {
|
||||
execute_bound(
|
||||
context,
|
||||
binding,
|
||||
rows,
|
||||
cache,
|
||||
cancelled,
|
||||
Some(actual),
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
None,
|
||||
)
|
||||
execute_bound_unprompted(context, binding, rows, cache, cancelled, Some(actual))
|
||||
});
|
||||
}
|
||||
chunk.batch_outputs(|context| {
|
||||
execute_bound(
|
||||
context,
|
||||
binding,
|
||||
rows,
|
||||
cache,
|
||||
cancelled,
|
||||
None,
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
None,
|
||||
)
|
||||
})
|
||||
chunk.batch_outputs(|context| execute_bound_unprompted(context, binding, rows, cache, cancelled, None))
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn execute_chunk_native_prompt<'ctx>(
|
||||
@@ -130,7 +110,26 @@ impl MoeExpertStage {
|
||||
})
|
||||
}
|
||||
}
|
||||
// Actual Strata counts/offsets algorithm, with per-row uniqueness and a checked
|
||||
/// `execute_bound` of the ordinary chunk path: no native prompt finish.
|
||||
fn execute_bound_unprompted<'ctx>(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
rows: &[ChunkFfnRow],
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
|
||||
) -> Result<Vec<ExpertReady>> {
|
||||
execute_bound(
|
||||
context,
|
||||
binding,
|
||||
rows,
|
||||
cache,
|
||||
cancelled,
|
||||
actual,
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
None,
|
||||
)
|
||||
} // Actual Strata counts/offsets algorithm, with per-row uniqueness and a checked
|
||||
// inverse mapping. Private route producers are the only production input.
|
||||
pub(super) fn grouped_pairs(ids: &[[u32; K]]) -> Result<Vec<Vec<Pair>>> {
|
||||
if !(1..=64).contains(&ids.len()) {
|
||||
|
||||
+16
-10
@@ -3,6 +3,21 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn source_members<'a>(rows: &'a [ChunkFfnRow], pairs: &[Pair]) -> Result<Vec<(&'a MoeExpertWeights, usize)>> {
|
||||
let mut members = Vec::new();
|
||||
members.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for pair in pairs {
|
||||
members.push((&rows[pair.row].row().weights, pair.slot));
|
||||
}
|
||||
Ok(members)
|
||||
}
|
||||
|
||||
/// The source callback keeps the actual artifact RefMut for all descriptor
|
||||
/// and cold-read consumers. Its mapped-error bridge preserves runtime
|
||||
/// primary failures while still attempting the mandatory source finish.
|
||||
/// The real cache is rechecked after the matrix loan and source loan have ended;
|
||||
/// private packets still belong to execute_direct_packets on any failure.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn project_group_source_fenced<'ctx>(
|
||||
@@ -23,21 +38,12 @@ pub(super) fn project_group_source_fenced<'ctx>(
|
||||
if !cache.uses_direct_native_down_packets() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut members = Vec::new();
|
||||
members.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for pair in pairs {
|
||||
members.push((&rows[pair.row].row().weights, pair.slot));
|
||||
}
|
||||
// The source callback keeps the actual artifact RefMut for all descriptor
|
||||
// and cold-read consumers. Its mapped-error bridge preserves runtime
|
||||
// primary failures while still attempting the mandatory source finish.
|
||||
let members = source_members(rows, pairs)?;
|
||||
let operation = binding.with_moe_routed_source(&members, binding_error, |source| {
|
||||
project_group_source_consumers(
|
||||
context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, source,
|
||||
)
|
||||
});
|
||||
// Recheck the real cache after the matrix loan and source loan have ended.
|
||||
// Private packets still belong to execute_direct_packets on any failure.
|
||||
let health_check = cache.validate(binding, context);
|
||||
operation.and(health_check)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! ONE loaded actual-row transport proof. No source admission, ModelBinding,
|
||||
//! session advancement, standalone Load or full-model qualification is minted.
|
||||
use super::*;
|
||||
use crate::qwen_forward::gr::DetachedGrRead;
|
||||
use crate::qwen_forward::session::{QwenStepTxn, ResetReplaySnapshot, chunk::ChunkAttentionRow};
|
||||
use crate::qwen_forward::{
|
||||
contract::{Dimension, TokenId},
|
||||
dense_weight_cache::DenseWeightCache,
|
||||
@@ -82,7 +84,9 @@ impl DirectDownReport {
|
||||
assert_eq!(self.differences, 0);
|
||||
assert!(self.cancelled_after_copy && self.allocated_unchanged && self.reset_exact && self.guards);
|
||||
eprintln!(
|
||||
"direct native Down PASS exact_words={} original_copy_first=true real_rows=true packet_mapping=true signedzero=true postcopy_cancel=true cleanup_checked=true full_model=false speed_claim=false",
|
||||
"direct native Down PASS exact_words={} original_copy_first=true real_rows=true \
|
||||
packet_mapping=true signedzero=true \
|
||||
postcopy_cancel=true cleanup_checked=true full_model=false speed_claim=false",
|
||||
self.words
|
||||
);
|
||||
}
|
||||
@@ -105,6 +109,89 @@ fn compare(a: &[Box<[f32]>], b: &[Box<[f32]>]) -> Result<(usize, usize)> {
|
||||
Ok((differences, words))
|
||||
}
|
||||
type ObservedArm = (Vec<ExpertReady>, Vec<Box<[f32]>>);
|
||||
fn arm_consume_inputs<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
kar: &mut KarPleCache<'_>,
|
||||
chunk: &mut QwenChunkTxn<'_, 'ctx>,
|
||||
) -> Result<()> {
|
||||
for index in 0..3 {
|
||||
let (token, position) = chunk.row_ids(index)?;
|
||||
chunk.input(index, |txn| InputStage::consume_kar(binding, kar, token, position, txn))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn arm_attention_reads<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
layer: LayerId,
|
||||
chunk: &mut QwenChunkTxn<'_, 'ctx>,
|
||||
) -> Result<Vec<ChunkAttentionRow>> {
|
||||
let mut reads = Vec::new();
|
||||
reads.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
for index in 0..3 {
|
||||
reads.push(chunk.read_attention_column(index, layer, |txn| {
|
||||
let read = GrStage::apply(binding, layer, txn, Some(dense))?;
|
||||
GrStage::detach_attention(binding, read, txn)
|
||||
})?);
|
||||
}
|
||||
Ok(reads)
|
||||
}
|
||||
fn arm_ffn_rows<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
layer: LayerId,
|
||||
chunk: &mut QwenChunkTxn<'_, 'ctx>,
|
||||
reads: &[ChunkAttentionRow],
|
||||
) -> Result<Vec<ChunkFfnRow>> {
|
||||
let mut rows = Vec::new();
|
||||
rows.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, read) in reads.iter().enumerate() {
|
||||
rows.push(chunk.prepare_attention_ffn(index, layer, read, |txn, residual| {
|
||||
arm_prepare_row(binding, dense, layer, txn, residual)
|
||||
})?);
|
||||
}
|
||||
Ok(rows)
|
||||
}
|
||||
fn arm_prepare_row<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
layer: LayerId,
|
||||
txn: &mut QwenStepTxn<'_, 'ctx>,
|
||||
residual: &DetachedGrRead,
|
||||
) -> Result<PreparedMoeRow> {
|
||||
let prior = txn.gdn_prior(layer)?;
|
||||
let mut attention = GdnStage::step(binding, layer, residual.ready(), &prior, txn, Some(dense))?;
|
||||
attention.validate_origin(&binding.identity())?;
|
||||
let pending = attention.take_pending()?;
|
||||
txn.stage_gdn(&prior, pending)?;
|
||||
let retained = GrStage::inject_retained(binding, residual, attention.output(), attention.identity(), txn, dense)?;
|
||||
let ffn = GrStage::read_retained_ffn(binding, retained, txn, dense)?;
|
||||
let route = MoeRouteStage::route_from_ffn(binding, layer, ffn.ready(), txn, Some(dense))?;
|
||||
MoeExpertStage::prepare_chunk_row(binding, layer, ffn, route, txn)
|
||||
}
|
||||
fn arm_tokens() -> Result<(LayerId, [TokenId; 3])> {
|
||||
let layer = LayerId::new(0, Dimension::new(48)?)?;
|
||||
let vocab = Dimension::new(248320)?;
|
||||
Ok((layer, [TokenId::new(0, vocab)?, TokenId::new(1, vocab)?, TokenId::new(0, vocab)?]))
|
||||
}
|
||||
fn arm_chunk_rows<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
kar: &mut KarPleCache<'_>,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
layer: LayerId,
|
||||
chunk: &mut QwenChunkTxn<'_, 'ctx>,
|
||||
) -> Result<Vec<ChunkFfnRow>> {
|
||||
arm_consume_inputs(binding, kar, chunk)?;
|
||||
let reads = arm_attention_reads(binding, dense, layer, chunk)?;
|
||||
arm_ffn_rows(binding, dense, layer, chunk, &reads)
|
||||
}
|
||||
fn cancel_probe(cancel_after_copy: bool) -> bool {
|
||||
let cancel = cancel_after_copy && COPIED.get();
|
||||
if cancel {
|
||||
CANCELLED_ON_COPY.set(true);
|
||||
}
|
||||
cancel
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn arm<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
@@ -117,49 +204,13 @@ fn arm<'ctx>(
|
||||
cancel_after_copy: bool,
|
||||
) -> Result<ObservedArm> {
|
||||
let observation = Observation::begin(old)?;
|
||||
let layer = LayerId::new(0, Dimension::new(48)?)?;
|
||||
let vocab = Dimension::new(248320)?;
|
||||
let tokens = [TokenId::new(0, vocab)?, TokenId::new(1, vocab)?, TokenId::new(0, vocab)?];
|
||||
cache.reserve_mmq_transient(
|
||||
binding,
|
||||
context,
|
||||
3 * (K * N * 4 + 10240 + 2884 + 3 * FF * 4 + N * 4 + 720) + DEVICE_PEAK,
|
||||
)?;
|
||||
let (layer, tokens) = arm_tokens()?;
|
||||
let transient = 3 * (K * N * 4 + 10240 + 2884 + 3 * FF * 4 + N * 4 + 720) + DEVICE_PEAK;
|
||||
cache.reserve_mmq_transient(binding, context, transient)?;
|
||||
let mut chunk = QwenChunkTxn::begin(session, binding, &tokens, None, 512 * 1024 * 1024)?;
|
||||
for index in 0..3 {
|
||||
let (token, position) = chunk.row_ids(index)?;
|
||||
chunk.input(index, |txn| InputStage::consume_kar(binding, kar, token, position, txn))?;
|
||||
}
|
||||
let mut reads = Vec::new();
|
||||
reads.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
for index in 0..3 {
|
||||
reads.push(chunk.read_attention_column(index, layer, |txn| {
|
||||
let read = GrStage::apply(binding, layer, txn, Some(dense))?;
|
||||
GrStage::detach_attention(binding, read, txn)
|
||||
})?);
|
||||
}
|
||||
let mut rows = Vec::new();
|
||||
rows.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, read) in reads.iter().enumerate() {
|
||||
rows.push(chunk.prepare_attention_ffn(index, layer, read, |txn, residual| {
|
||||
let prior = txn.gdn_prior(layer)?;
|
||||
let mut attention = GdnStage::step(binding, layer, residual.ready(), &prior, txn, Some(dense))?;
|
||||
attention.validate_origin(&binding.identity())?;
|
||||
let pending = attention.take_pending()?;
|
||||
txn.stage_gdn(&prior, pending)?;
|
||||
let retained =
|
||||
GrStage::inject_retained(binding, residual, attention.output(), attention.identity(), txn, dense)?;
|
||||
let ffn = GrStage::read_retained_ffn(binding, retained, txn, dense)?;
|
||||
let route = MoeRouteStage::route_from_ffn(binding, layer, ffn.ready(), txn, Some(dense))?;
|
||||
MoeExpertStage::prepare_chunk_row(binding, layer, ffn, route, txn)
|
||||
})?);
|
||||
}
|
||||
let rows = arm_chunk_rows(binding, kar, dense, layer, &mut chunk)?;
|
||||
let values = MoeExpertStage::execute_chunk(binding, layer, &rows, &mut chunk, cache, &mut || {
|
||||
let cancel = cancel_after_copy && COPIED.get();
|
||||
if cancel {
|
||||
CANCELLED_ON_COPY.set(true);
|
||||
}
|
||||
cancel
|
||||
cancel_probe(cancel_after_copy)
|
||||
})?;
|
||||
let packets = observation.take()?;
|
||||
// Completed layer0 FFN products remain private: no injection/head/all48 or
|
||||
@@ -167,14 +218,8 @@ fn arm<'ctx>(
|
||||
drop(chunk);
|
||||
Ok((values, packets))
|
||||
}
|
||||
// Independent byte-only old split+pack FIRST, then direct whole-group copy.
|
||||
// Genuine selected rows supply scope/origin. The finite payload deliberately
|
||||
// contains both signed zeros and different columns/slots; no model state is faked.
|
||||
fn transport_probe(context: &Context<'_>) -> Result<bool> {
|
||||
let failed = Rc::new(Cell::new(false));
|
||||
let scope = DownScope::new(context, failed.clone());
|
||||
let slots = [9usize, 0, 4];
|
||||
let selections = slots.map(DownSelection::Routed);
|
||||
const SLOTS: [usize; 3] = [9, 0, 4];
|
||||
fn probe_payload() -> Result<Vec<f32>> {
|
||||
let mut payload = Vec::new();
|
||||
payload.try_reserve_exact(3 * N).map_err(|_| Error::InputAllocation)?;
|
||||
for c in 0..3 {
|
||||
@@ -188,119 +233,169 @@ fn transport_probe(context: &Context<'_>) -> Result<bool> {
|
||||
});
|
||||
}
|
||||
}
|
||||
let source = scope.upload(&payload)?;
|
||||
let mut old_parts = Vec::new();
|
||||
let mut direct_parts = Vec::new();
|
||||
old_parts.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
direct_parts.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
let operation = (|| {
|
||||
// Both whole packets are sentinel initialized, so every untouched slot
|
||||
// is compared too. Original scalar copies establish the reference.
|
||||
Ok(payload)
|
||||
}
|
||||
/// Column and slot of copy `c` in the all-copy preflight: the last copy is made invalid in column or in slot.
|
||||
fn preflight_copy(bad_column: bool, c: usize) -> (u32, u32) {
|
||||
(if bad_column && c == 2 { 3 } else { c as u32 }, if !bad_column && c == 2 { 10 } else { SLOTS[c] as u32 })
|
||||
}
|
||||
fn corrupted_bytes(payload: &[f32], invalid: f32) -> Result<Vec<u8>> {
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(payload.len() * 4).map_err(|_| Error::InputAllocation)?;
|
||||
for (i, v) in payload.iter().copied().enumerate() {
|
||||
bytes.extend_from_slice(&(if i == 2 * N + 17 { invalid } else { v }).to_le_bytes());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
fn refuse_alien_scope<'ctx>(
|
||||
scope: &DownScope<'ctx>,
|
||||
alien_scope: &DownScope<'ctx>,
|
||||
packet: &mut super::super::moe_down::ResidentPackedDown<'ctx>,
|
||||
) -> Result<()> {
|
||||
if packet.complete(scope).is_ok() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let called = Cell::new(false);
|
||||
let refusal =
|
||||
super::super::moe_down::ResidentPackedDown::copy_group_with(alien_scope, &mut [(&mut *packet, 0)], |_| {
|
||||
called.set(true);
|
||||
Ok(())
|
||||
});
|
||||
if !matches!(refusal, Err(Error::IdentityMismatch)) || called.get() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
// A refused packet cannot be completed/reused within the old scope.
|
||||
if packet.complete(scope).is_ok() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Genuine selected rows supply scope/origin; both packet sets and the source stay owned for the final close.
|
||||
struct Probe<'a, 'ctx> {
|
||||
context: &'ctx Context<'ctx>,
|
||||
scope: &'a DownScope<'ctx>,
|
||||
payload: &'a [f32],
|
||||
source: TransportBuffer<'ctx>,
|
||||
old_parts: Vec<TransportBuffer<'ctx>>,
|
||||
direct_parts: Vec<TransportBuffer<'ctx>>,
|
||||
}
|
||||
impl<'ctx> Probe<'_, 'ctx> {
|
||||
fn run(&mut self) -> Result<bool> {
|
||||
self.fill_sentinels()?;
|
||||
self.split_and_pack_old()?;
|
||||
self.copy_direct()?;
|
||||
self.require_old_equals_direct()?;
|
||||
let before = self.download_direct()?;
|
||||
self.refuse_invalid_preflight()?;
|
||||
self.require_direct_unchanged(before)?;
|
||||
self.refuse_alien_packet_scope()?;
|
||||
self.refuse_nonfinite_source()?;
|
||||
Ok(true)
|
||||
}
|
||||
/// Both whole packets are sentinel initialized, so every untouched slot
|
||||
/// is compared too. Original scalar copies establish the reference.
|
||||
fn fill_sentinels(&mut self) -> Result<()> {
|
||||
let mut sentinel = Vec::new();
|
||||
sentinel.try_reserve_exact(K * N).map_err(|_| Error::InputAllocation)?;
|
||||
sentinel.resize(K * N, 17.0);
|
||||
for _ in 0..3 {
|
||||
old_parts.push(scope.upload(&sentinel)?);
|
||||
direct_parts.push(scope.upload(&sentinel)?);
|
||||
self.old_parts.push(self.scope.upload(&sentinel)?);
|
||||
self.direct_parts.push(self.scope.upload(&sentinel)?);
|
||||
}
|
||||
for (c, slot) in slots.iter().enumerate() {
|
||||
let mut split = scope.allocate(N * 4)?;
|
||||
let op = context
|
||||
.copy_routed_down_column(source.buffer()?, 3, c, split.buffer_mut()?)
|
||||
Ok(())
|
||||
}
|
||||
fn split_and_pack_old(&mut self) -> Result<()> {
|
||||
for (c, slot) in SLOTS.iter().enumerate() {
|
||||
let mut split = self.scope.allocate(N * 4)?;
|
||||
let op = self
|
||||
.context
|
||||
.copy_routed_down_column(self.source.buffer()?, 3, c, split.buffer_mut()?)
|
||||
.map_err(driver_error)
|
||||
.and_then(|()| {
|
||||
context
|
||||
.pack_moe_down_f32(split.buffer()?, old_parts[c].buffer_mut()?, *slot as u32)
|
||||
self.context
|
||||
.pack_moe_down_f32(split.buffer()?, self.old_parts[c].buffer_mut()?, *slot as u32)
|
||||
.map_err(driver_error)
|
||||
});
|
||||
let close = split.close();
|
||||
op?;
|
||||
close?;
|
||||
}
|
||||
{
|
||||
let mut copies = Vec::new();
|
||||
copies.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
for (c, part) in direct_parts.iter_mut().enumerate() {
|
||||
copies.push((c as u32, part.buffer_mut()?, slots[c] as u32));
|
||||
}
|
||||
context.copy_routed_down_columns_to_slots(source.buffer()?, 3, &mut copies).map_err(driver_error)?;
|
||||
Ok(())
|
||||
}
|
||||
fn copy_direct(&mut self) -> Result<()> {
|
||||
let mut copies = Vec::new();
|
||||
copies.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
for (c, part) in self.direct_parts.iter_mut().enumerate() {
|
||||
copies.push((c as u32, part.buffer_mut()?, SLOTS[c] as u32));
|
||||
}
|
||||
for (old, new) in old_parts.iter().zip(&direct_parts) {
|
||||
self.context.copy_routed_down_columns_to_slots(self.source.buffer()?, 3, &mut copies).map_err(driver_error)
|
||||
}
|
||||
fn require_old_equals_direct(&self) -> Result<()> {
|
||||
for (old, new) in self.old_parts.iter().zip(&self.direct_parts) {
|
||||
let a = download_f32(old.buffer()?, K * N)?;
|
||||
let b = download_f32(new.buffer()?, K * N)?;
|
||||
if a.iter().zip(b.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn download_direct(&self) -> Result<Vec<Box<[f32]>>> {
|
||||
let mut before = Vec::new();
|
||||
before.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
for part in &direct_parts {
|
||||
for part in &self.direct_parts {
|
||||
before.push(download_f32(part.buffer()?, K * N)?);
|
||||
}
|
||||
// All-copy preflight: last slot/column invalid cannot mutate earlier
|
||||
// valid destinations. Exact full-size genuine buffers, not fake aliases.
|
||||
Ok(before)
|
||||
}
|
||||
/// All-copy preflight: last slot/column invalid cannot mutate earlier
|
||||
/// valid destinations. Exact full-size genuine buffers, not fake aliases.
|
||||
fn refuse_invalid_preflight(&mut self) -> Result<()> {
|
||||
for bad_column in [false, true] {
|
||||
let mut copies = Vec::new();
|
||||
copies.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
for (c, part) in direct_parts.iter_mut().enumerate() {
|
||||
copies.push((
|
||||
if bad_column && c == 2 { 3 } else { c as u32 },
|
||||
part.buffer_mut()?,
|
||||
if !bad_column && c == 2 { 10 } else { slots[c] as u32 },
|
||||
));
|
||||
for (c, part) in self.direct_parts.iter_mut().enumerate() {
|
||||
let (column, slot) = preflight_copy(bad_column, c);
|
||||
copies.push((column, part.buffer_mut()?, slot));
|
||||
}
|
||||
if !matches!(
|
||||
context.copy_routed_down_columns_to_slots(source.buffer()?, 3, &mut copies),
|
||||
Err(DriverError::InvalidProjectionShape)
|
||||
) {
|
||||
let refused = self.context.copy_routed_down_columns_to_slots(self.source.buffer()?, 3, &mut copies);
|
||||
if !matches!(refused, Err(DriverError::InvalidProjectionShape)) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
for (part, before) in direct_parts.iter().zip(before) {
|
||||
Ok(())
|
||||
}
|
||||
fn require_direct_unchanged(&self, before: Vec<Box<[f32]>>) -> Result<()> {
|
||||
for (part, before) in self.direct_parts.iter().zip(before) {
|
||||
let after = download_f32(part.buffer()?, K * N)?;
|
||||
if before.iter().zip(after.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
let alien_scope = DownScope::new(context, Rc::new(Cell::new(false)));
|
||||
let mut packet = super::super::moe_down::ResidentPackedDown::new(&scope)?;
|
||||
let scope_guard = (|| {
|
||||
if packet.complete(&scope).is_ok() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let called = Cell::new(false);
|
||||
let refusal = super::super::moe_down::ResidentPackedDown::copy_group_with(
|
||||
&alien_scope,
|
||||
&mut [(&mut packet, 0)],
|
||||
|_| {
|
||||
called.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
if !matches!(refusal, Err(Error::IdentityMismatch)) || called.get() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
// A refused packet cannot be completed/reused within the old scope.
|
||||
if packet.complete(&scope).is_ok() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
Ok(())
|
||||
}
|
||||
fn refuse_alien_packet_scope(&self) -> Result<()> {
|
||||
let alien_scope = DownScope::new(self.context, Rc::new(Cell::new(false)));
|
||||
let mut packet = super::super::moe_down::ResidentPackedDown::new(self.scope)?;
|
||||
let scope_guard = refuse_alien_scope(self.scope, &alien_scope, &mut packet);
|
||||
let close = packet.close();
|
||||
scope_guard?;
|
||||
close?;
|
||||
// Full finite source refusal precedes any copy callback, including an
|
||||
// interior NaN; the old producer is evaluated first on exact bytes.
|
||||
Ok(())
|
||||
}
|
||||
/// Full finite source refusal precedes any copy callback, including an
|
||||
/// interior NaN; the old producer is evaluated first on exact bytes.
|
||||
fn refuse_nonfinite_source(&self) -> Result<()> {
|
||||
let selections = SLOTS.map(DownSelection::Routed);
|
||||
for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(payload.len() * 4).map_err(|_| Error::InputAllocation)?;
|
||||
for (i, v) in payload.iter().copied().enumerate() {
|
||||
bytes.extend_from_slice(&(if i == 2 * N + 17 { invalid } else { v }).to_le_bytes());
|
||||
}
|
||||
let old =
|
||||
scope.project_columns(&selections, |out, _| out.copy_from(&bytes).map_err(driver_error), &mut || false);
|
||||
let bytes = corrupted_bytes(self.payload, invalid)?;
|
||||
let old = self.scope.project_columns(
|
||||
&selections,
|
||||
|out, _| out.copy_from(&bytes).map_err(driver_error),
|
||||
&mut || false,
|
||||
);
|
||||
let called = Cell::new(false);
|
||||
let new = scope.project_columns_direct(
|
||||
let new = self.scope.project_columns_direct(
|
||||
&selections,
|
||||
|out, _| out.copy_from(&bytes).map_err(driver_error),
|
||||
|_, _| {
|
||||
@@ -313,18 +408,123 @@ fn transport_probe(context: &Context<'_>) -> Result<bool> {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
})();
|
||||
scope.record(&operation);
|
||||
let mut cleanup = Ok(());
|
||||
for owner in old_parts.into_iter().chain(direct_parts).chain(std::iter::once(source)) {
|
||||
let next = owner.close();
|
||||
if cleanup.is_ok() {
|
||||
cleanup = next;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn close_all(self) -> Result<()> {
|
||||
let mut cleanup = Ok(());
|
||||
for owner in self.old_parts.into_iter().chain(self.direct_parts).chain(std::iter::once(self.source)) {
|
||||
let next = owner.close();
|
||||
if cleanup.is_ok() {
|
||||
cleanup = next;
|
||||
}
|
||||
}
|
||||
cleanup
|
||||
}
|
||||
}
|
||||
// Independent byte-only old split+pack FIRST, then direct whole-group copy.
|
||||
// Genuine selected rows supply scope/origin. The finite payload deliberately
|
||||
// contains both signed zeros and different columns/slots; no model state is faked.
|
||||
fn transport_probe(context: &Context<'_>) -> Result<bool> {
|
||||
let failed = Rc::new(Cell::new(false));
|
||||
let scope = DownScope::new(context, failed.clone());
|
||||
let payload = probe_payload()?;
|
||||
let source = scope.upload(&payload)?;
|
||||
let mut probe =
|
||||
Probe { context, scope: &scope, payload: &payload, source, old_parts: Vec::new(), direct_parts: Vec::new() };
|
||||
probe.old_parts.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
probe.direct_parts.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
let operation = probe.run();
|
||||
scope.record(&operation);
|
||||
let cleanup = probe.close_all();
|
||||
operation.and_then(|value| cleanup.map(|()| value))
|
||||
}
|
||||
/// What the first two arms and the cancelled arm established; the reference outputs and packets stay for recovery.
|
||||
struct DirectRun {
|
||||
reference: Vec<ExpertReady>,
|
||||
old_packets: Vec<Box<[f32]>>,
|
||||
original_unchanged: bool,
|
||||
allocated: usize,
|
||||
differences: usize,
|
||||
words: usize,
|
||||
}
|
||||
fn output_differences(reference: &[ExpertReady], candidate: &[ExpertReady]) -> Result<usize> {
|
||||
let mut differences = 0;
|
||||
for (a, b) in reference.iter().zip(candidate) {
|
||||
validate_values(a.output(), N)?;
|
||||
validate_values(b.output(), N)?;
|
||||
differences += a.output().iter().zip(b.output()).filter(|(a, b)| a.to_bits() != b.to_bits()).count();
|
||||
}
|
||||
Ok(differences)
|
||||
}
|
||||
fn same_outputs(reference: &[ExpertReady], recovery: &[ExpertReady]) -> bool {
|
||||
reference
|
||||
.iter()
|
||||
.zip(recovery)
|
||||
.all(|(a, b)| a.output().iter().zip(b.output()).all(|(a, b)| a.to_bits() == b.to_bits()))
|
||||
}
|
||||
/// The loaded direct-Down inputs of one fresh session; every arm is run against the same snapshot.
|
||||
struct LoadedArms<'a, 'k, 'ctx> {
|
||||
binding: &'a ModelBinding,
|
||||
context: &'a Rc<Context<'ctx>>,
|
||||
session: &'a mut QwenSession<'ctx>,
|
||||
kar: &'a mut KarPleCache<'k>,
|
||||
cache: &'a mut MoeWeightCache<'ctx>,
|
||||
dense: &'a DenseWeightCache<'ctx>,
|
||||
}
|
||||
impl LoadedArms<'_, '_, '_> {
|
||||
fn arm(&mut self, old: bool, cancel_after_copy: bool) -> Result<ObservedArm> {
|
||||
arm(self.binding, self.context, self.session, self.kar, self.cache, self.dense, old, cancel_after_copy)
|
||||
}
|
||||
fn matches_snapshot(&self, initial: &ResetReplaySnapshot) -> Result<bool> {
|
||||
Ok(initial.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding)?))
|
||||
}
|
||||
fn precheck(&self) -> Result<ResetReplaySnapshot> {
|
||||
self.cache.validate(self.binding, self.context)?;
|
||||
self.dense.retained_context(self.binding, self.context)?;
|
||||
if !self.cache.uses_direct_native_down_packets() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let initial = self.session.test_reset_replay_snapshot(self.binding)?;
|
||||
if !initial.has_prefix(0, [-1, -1]) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(initial)
|
||||
}
|
||||
fn reference_and_candidate(&mut self, initial: &ResetReplaySnapshot) -> Result<DirectRun> {
|
||||
let (reference, old_packets) = self.arm(true, false)?;
|
||||
let original_unchanged = self.matches_snapshot(initial)?;
|
||||
let allocated = self.context.allocated_bytes();
|
||||
let (candidate, new_packets) = self.arm(false, false)?;
|
||||
if [reference.len(), candidate.len(), old_packets.len(), new_packets.len()].iter().any(|n| *n != 3) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let (mut differences, mut words) = compare(&old_packets, &new_packets)?;
|
||||
differences += output_differences(&reference, &candidate)?;
|
||||
words += reference.len() * N;
|
||||
Ok(DirectRun { reference, old_packets, original_unchanged, allocated, differences, words })
|
||||
}
|
||||
/// A cancelled arm is refused after the original copy and leaves the session snapshot untouched.
|
||||
fn cancelled_arm(&mut self, initial: &ResetReplaySnapshot) -> Result<bool> {
|
||||
Ok(matches!(self.arm(false, true), Err(Error::Unsupported(Stage::Executor)))
|
||||
&& CANCELLED_ON_COPY.get()
|
||||
&& self.matches_snapshot(initial)?)
|
||||
}
|
||||
/// After a reset the recovery arm reproduces the reference outputs and the old packets.
|
||||
fn cancel_and_recover(&mut self, initial: &ResetReplaySnapshot, run: &mut DirectRun) -> Result<(bool, bool)> {
|
||||
let cancelled_after_copy = self.cancelled_arm(initial)?;
|
||||
self.session.reset()?;
|
||||
let reset_prefix = self.matches_snapshot(initial)?;
|
||||
let (recovery, recovered_packets) = self.arm(false, false)?;
|
||||
if recovery.len() != 3 || recovered_packets.len() != 3 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let (d, n) = compare(&run.old_packets, &recovered_packets)?;
|
||||
run.differences += d;
|
||||
run.words += n;
|
||||
let reset_exact = run.original_unchanged && reset_prefix && same_outputs(&run.reference, &recovery);
|
||||
Ok((cancelled_after_copy, reset_exact))
|
||||
}
|
||||
}
|
||||
impl QwenForward {
|
||||
/// ONE genuine loaded binding/fresh session. Every arm independently mints
|
||||
/// real three-row chunk/FFN proofs; canceled chunks are dropped unchanged.
|
||||
@@ -336,60 +536,21 @@ impl QwenForward {
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
) -> Result<DirectDownReport> {
|
||||
cache.validate(binding, context)?;
|
||||
dense.retained_context(binding, context)?;
|
||||
if !cache.uses_direct_native_down_packets() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let initial = session.test_reset_replay_snapshot(binding)?;
|
||||
if !initial.has_prefix(0, [-1, -1]) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let (reference, old_packets) = arm(binding, context, session, kar, cache, dense, true, false)?;
|
||||
let original_unchanged = initial.numeric_eq(&session.test_reset_replay_snapshot(binding)?);
|
||||
let allocated = context.allocated_bytes();
|
||||
let (candidate, new_packets) = arm(binding, context, session, kar, cache, dense, false, false)?;
|
||||
if reference.len() != 3 || candidate.len() != 3 || old_packets.len() != 3 || new_packets.len() != 3 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let (mut differences, mut words) = compare(&old_packets, &new_packets)?;
|
||||
for (a, b) in reference.iter().zip(&candidate) {
|
||||
validate_values(a.output(), N)?;
|
||||
validate_values(b.output(), N)?;
|
||||
differences += a.output().iter().zip(b.output()).filter(|(a, b)| a.to_bits() != b.to_bits()).count();
|
||||
words += N;
|
||||
}
|
||||
let cancelled_after_copy = matches!(
|
||||
arm(binding, context, session, kar, cache, dense, false, true),
|
||||
Err(Error::Unsupported(Stage::Executor))
|
||||
) && CANCELLED_ON_COPY.get()
|
||||
&& initial.numeric_eq(&session.test_reset_replay_snapshot(binding)?);
|
||||
session.reset()?;
|
||||
let reset_prefix = initial.numeric_eq(&session.test_reset_replay_snapshot(binding)?);
|
||||
let (recovery, recovered_packets) = arm(binding, context, session, kar, cache, dense, false, false)?;
|
||||
if recovery.len() != 3 || recovered_packets.len() != 3 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let (d, n) = compare(&old_packets, &recovered_packets)?;
|
||||
differences += d;
|
||||
words += n;
|
||||
let reset_exact = original_unchanged
|
||||
&& reset_prefix
|
||||
&& reference
|
||||
.iter()
|
||||
.zip(&recovery)
|
||||
.all(|(a, b)| a.output().iter().zip(b.output()).all(|(a, b)| a.to_bits() == b.to_bits()));
|
||||
let mut arms = LoadedArms { binding, context, session, kar, cache, dense };
|
||||
let initial = arms.precheck()?;
|
||||
let mut run = arms.reference_and_candidate(&initial)?;
|
||||
let (cancelled_after_copy, reset_exact) = arms.cancel_and_recover(&initial, &mut run)?;
|
||||
let guards = transport_probe(context)?;
|
||||
if words != 3 * (2 * K * N + N) {
|
||||
if run.words != 3 * (2 * K * N + N) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(DirectDownReport {
|
||||
differences,
|
||||
words,
|
||||
differences: run.differences,
|
||||
words: run.words,
|
||||
cancelled_after_copy,
|
||||
reset_exact,
|
||||
guards,
|
||||
allocated_unchanged: allocated == context.allocated_bytes(),
|
||||
allocated_unchanged: run.allocated == context.allocated_bytes(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,27 @@ fn counters(cache: &MoeWeightCache<'_>) -> [u64; 5] {
|
||||
let c = cache.counters();
|
||||
[c.hits, c.misses, c.read_bytes, c.upload_bytes, c.eviction_bytes]
|
||||
}
|
||||
fn validate_source_row(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
chunk: &QwenChunkTxn<'_, '_>,
|
||||
(index, row): (usize, &ChunkFfnRow),
|
||||
initial: bool,
|
||||
) -> Result<()> {
|
||||
chunk.validate_ffn_row(index, layer, row)?;
|
||||
let (token, position) = chunk.row_ids(index)?;
|
||||
if position.get() != index as u64 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
row.row().validate(&binding.identity(), token, position, layer)?;
|
||||
let ids: [u32; K] = std::array::from_fn(|slot| row.row().route.experts()[slot].get());
|
||||
let weights: [f32; K] = std::array::from_fn(|slot| row.row().route.weights()[slot].get());
|
||||
if initial {
|
||||
observation::input(index, row.row().read.ready().mixed(), &ids, &weights)
|
||||
} else {
|
||||
observation::validate_input(index, row.row().read.ready().mixed(), &ids, &weights)
|
||||
}
|
||||
}
|
||||
fn validate_sources(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
@@ -16,23 +37,51 @@ fn validate_sources(
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
chunk.validate_ffn_row(index, layer, row)?;
|
||||
let (token, position) = chunk.row_ids(index)?;
|
||||
if position.get() != index as u64 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
row.row().validate(&binding.identity(), token, position, layer)?;
|
||||
let ids: [u32; K] = std::array::from_fn(|slot| row.row().route.experts()[slot].get());
|
||||
let weights: [f32; K] = std::array::from_fn(|slot| row.row().route.weights()[slot].get());
|
||||
if initial {
|
||||
observation::input(index, row.row().read.ready().mixed(), &ids, &weights)?;
|
||||
} else {
|
||||
observation::validate_input(index, row.row().read.ready().mixed(), &ids, &weights)?;
|
||||
}
|
||||
validate_source_row(binding, layer, chunk, (index, row), initial)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn check_products(binding: &ModelBinding, rows: &[ChunkFfnRow], products: &[ExpertReady]) -> Result<()> {
|
||||
if products.len() != rows.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
for (index, (product, row)) in products.iter().zip(rows).enumerate() {
|
||||
product.validate_origin(&binding.identity())?;
|
||||
if product.identity() != row.row().route.identity() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
observation::final_values(index, product.output())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn witness_delta(before: (u64, u64, u64), after: (u64, u64, u64)) -> Result<[u64; 3]> {
|
||||
Ok([
|
||||
after.0.checked_sub(before.0).ok_or(Error::Overflow)?,
|
||||
after.1.checked_sub(before.1).ok_or(Error::Overflow)?,
|
||||
after.2.checked_sub(before.2).ok_or(Error::Overflow)?,
|
||||
])
|
||||
}
|
||||
impl MoeExpertStage {
|
||||
fn test_layer0_arm<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
rows: &[ChunkFfnRow],
|
||||
chunk: &mut QwenChunkTxn<'_, 'ctx>,
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
arm: usize,
|
||||
) -> Result<()> {
|
||||
let _arm = observation::arm(arm)?;
|
||||
let products = if arm == 0 {
|
||||
Self::execute_chunk(binding, layer, rows, chunk, cache, &mut || false)?
|
||||
} else {
|
||||
Self::execute_chunk_mmq(binding, layer, rows, chunk, cache, &mut || false)?
|
||||
};
|
||||
check_products(binding, rows, &products)?;
|
||||
validate_sources(binding, layer, rows, chunk, false)?;
|
||||
observation::cache(arm + 1, counters(cache))?;
|
||||
drop(products);
|
||||
Ok(())
|
||||
}
|
||||
pub(in crate::qwen_forward) fn test_layer0_same_rows<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
@@ -44,32 +93,8 @@ impl MoeExpertStage {
|
||||
observation::cache(0, counters(cache))?;
|
||||
let before = cache.test_mmq_dispatch_witness();
|
||||
for arm in 0..2 {
|
||||
let _arm = observation::arm(arm)?;
|
||||
let products = if arm == 0 {
|
||||
Self::execute_chunk(binding, layer, rows, chunk, cache, &mut || false)?
|
||||
} else {
|
||||
Self::execute_chunk_mmq(binding, layer, rows, chunk, cache, &mut || false)?
|
||||
};
|
||||
if products.len() != rows.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
for (index, (product, row)) in products.iter().zip(rows).enumerate() {
|
||||
product.validate_origin(&binding.identity())?;
|
||||
if product.identity() != row.row().route.identity() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
observation::final_values(index, product.output())?;
|
||||
}
|
||||
validate_sources(binding, layer, rows, chunk, false)?;
|
||||
observation::cache(arm + 1, counters(cache))?;
|
||||
drop(products);
|
||||
Self::test_layer0_arm(binding, layer, rows, chunk, cache, arm)?;
|
||||
}
|
||||
let after = cache.test_mmq_dispatch_witness();
|
||||
let delta = [
|
||||
after.0.checked_sub(before.0).ok_or(Error::Overflow)?,
|
||||
after.1.checked_sub(before.1).ok_or(Error::Overflow)?,
|
||||
after.2.checked_sub(before.2).ok_or(Error::Overflow)?,
|
||||
];
|
||||
observation::complete(delta)
|
||||
observation::complete(witness_delta(before, cache.test_mmq_dispatch_witness())?)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,79 @@ fn validate_row(
|
||||
origin.identity.validate(token, position, layer)?;
|
||||
row.row().validate(&binding.identity(), token, position, layer)
|
||||
}
|
||||
/// The sealed rows a group copy is validated against, borrowed apart from the mutable packet storage.
|
||||
struct RowsView<'a, 'session, 'ctx> {
|
||||
txn: &'a QwenChunkTxn<'session, 'ctx>,
|
||||
binding: &'a ModelBinding,
|
||||
layer: LayerId,
|
||||
rows: &'a [ChunkFfnRow],
|
||||
origins: &'a [Rc<DownOrigin>],
|
||||
}
|
||||
impl RowsView<'_, '_, '_> {
|
||||
fn validate_group_columns(&self, group: &GroupOrigin) -> Result<()> {
|
||||
for (column, pair) in group.pairs.iter().enumerate() {
|
||||
let row = self.rows.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
let origin = self.origins.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
if !Rc::ptr_eq(origin, &group.origins[column]) || row.row().route.experts()[pair.slot].get() != group.expert
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
validate_row(self.txn, self.binding, self.layer, pair.row, row, origin)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// The packets of the group rows, in ascending row order, each with the slot its column lands in.
|
||||
fn select_packets<'p, 'ctx>(
|
||||
packets: &'p mut [ResidentPackedDown<'ctx>],
|
||||
pairs: &[Pair],
|
||||
) -> Result<Vec<(&'p mut ResidentPackedDown<'ctx>, usize)>> {
|
||||
let mut selected = Vec::new();
|
||||
selected.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut pairs_left = pairs.iter().peekable();
|
||||
for (row, packet) in packets.iter_mut().enumerate() {
|
||||
if pairs_left.peek().is_some_and(|pair| pair.row == row) {
|
||||
let pair = pairs_left.next().ok_or(Error::IdentityMismatch)?;
|
||||
selected.push((packet, pair.slot));
|
||||
}
|
||||
}
|
||||
if pairs_left.next().is_some() || selected.len() != pairs.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(selected)
|
||||
}
|
||||
/// Before allocating any private destinations, validate every actual
|
||||
/// sealed phase row. Immutable txn/row borrows forbid phase mutation.
|
||||
fn validate_phase_rows(
|
||||
txn: &QwenChunkTxn<'_, '_>,
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
rows: &[ChunkFfnRow],
|
||||
) -> Result<()> {
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
let global = txn.micro_row_index(index)?;
|
||||
txn.validate_ffn_row(global, layer, row)?;
|
||||
let (token, position) = txn.row_ids(global)?;
|
||||
row.row().validate(&binding.identity(), token, position, layer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// One fresh origin and one private resident destination per row of the window.
|
||||
fn reserve_packets<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
rows: &[ChunkFfnRow],
|
||||
scope: &DownScope<'ctx>,
|
||||
) -> Result<(Vec<Rc<DownOrigin>>, Vec<ResidentPackedDown<'ctx>>)> {
|
||||
let mut origins = Vec::new();
|
||||
origins.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut packets = Vec::new();
|
||||
packets.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for row in rows {
|
||||
origins.push(Rc::new(DownOrigin { binding: binding.identity(), identity: row.row().route.identity() }));
|
||||
packets.push(ResidentPackedDown::new(scope)?);
|
||||
}
|
||||
Ok((origins, packets))
|
||||
}
|
||||
impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
|
||||
pub(super) fn new(
|
||||
txn: &'source QwenChunkTxn<'session, 'ctx>,
|
||||
@@ -49,22 +122,8 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
|
||||
if rows.len() != txn.micro_len()? || !(1..=64).contains(&rows.len()) || !std::ptr::eq(context, txn.context()?) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
// Before allocating any private destinations, validate every actual
|
||||
// sealed phase row. Immutable txn/row borrows forbid phase mutation.
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
let global = txn.micro_row_index(index)?;
|
||||
txn.validate_ffn_row(global, layer, row)?;
|
||||
let (token, position) = txn.row_ids(global)?;
|
||||
row.row().validate(&binding.identity(), token, position, layer)?;
|
||||
}
|
||||
let mut origins = Vec::new();
|
||||
origins.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut packets = Vec::new();
|
||||
packets.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for row in rows {
|
||||
origins.push(Rc::new(DownOrigin { binding: binding.identity(), identity: row.row().route.identity() }));
|
||||
packets.push(ResidentPackedDown::new(scope)?);
|
||||
}
|
||||
validate_phase_rows(txn, binding, layer, rows)?;
|
||||
let (origins, packets) = reserve_packets(binding, rows, scope)?;
|
||||
Ok(Self { owner: Rc::new(()), txn, binding, layer, rows, context, scope, origins, packets })
|
||||
}
|
||||
pub(super) fn group(&self, expert: u32, pairs: &[Pair]) -> Result<GroupOrigin> {
|
||||
@@ -77,21 +136,25 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
|
||||
let mut origins = Vec::new();
|
||||
origins.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for pair in pairs {
|
||||
let row = self.rows.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
let origin = self.origins.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
validate_row(self.txn, self.binding, self.layer, pair.row, row, origin)?;
|
||||
if pair.slot >= K
|
||||
|| previous.is_some_and(|old| old >= pair.row)
|
||||
|| row.row().route.experts()[pair.slot].get() != expert
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
origins.push(self.admit_pair(expert, previous, pair)?);
|
||||
previous = Some(pair.row);
|
||||
actual.push(*pair);
|
||||
origins.push(Rc::clone(origin));
|
||||
}
|
||||
Ok(GroupOrigin { owner: Rc::clone(&self.owner), expert, pairs: actual, origins })
|
||||
}
|
||||
/// A pair of a group: a genuine row of this window routed to `expert` in ascending row order, in a valid slot.
|
||||
fn admit_pair(&self, expert: u32, previous: Option<usize>, pair: &Pair) -> Result<Rc<DownOrigin>> {
|
||||
let row = self.rows.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
let origin = self.origins.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
validate_row(self.txn, self.binding, self.layer, pair.row, row, origin)?;
|
||||
if pair.slot >= K
|
||||
|| previous.is_some_and(|old| old >= pair.row)
|
||||
|| row.row().route.experts()[pair.slot].get() != expert
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(Rc::clone(origin))
|
||||
}
|
||||
fn validate_group(&self, group: &GroupOrigin) -> Result<()> {
|
||||
if !Rc::ptr_eq(&self.owner, &group.owner)
|
||||
|| !(1..=self.rows.len()).contains(&group.pairs.len())
|
||||
@@ -101,20 +164,31 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
|
||||
}
|
||||
let mut previous = None;
|
||||
for (column, pair) in group.pairs.iter().enumerate() {
|
||||
let row = self.rows.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
let origin = self.origins.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
if !Rc::ptr_eq(origin, &group.origins[column])
|
||||
|| pair.slot >= K
|
||||
|| previous.is_some_and(|old| old >= pair.row)
|
||||
|| row.row().route.experts()[pair.slot].get() != group.expert
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
validate_row(self.txn, self.binding, self.layer, pair.row, row, origin)?;
|
||||
let origin = self.admit_group_column(group, column, previous, pair)?;
|
||||
validate_row(self.txn, self.binding, self.layer, pair.row, origin.0, origin.1)?;
|
||||
previous = Some(pair.row);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// A column of a published group still names its own row, origin and expert; returns the row and origin to re-validate.
|
||||
fn admit_group_column(
|
||||
&self,
|
||||
group: &GroupOrigin,
|
||||
column: usize,
|
||||
previous: Option<usize>,
|
||||
pair: &Pair,
|
||||
) -> Result<(&ChunkFfnRow, &Rc<DownOrigin>)> {
|
||||
let row = self.rows.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
let origin = self.origins.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
if !Rc::ptr_eq(origin, &group.origins[column])
|
||||
|| pair.slot >= K
|
||||
|| previous.is_some_and(|old| old >= pair.row)
|
||||
|| row.row().route.experts()[pair.slot].get() != group.expert
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok((row, origin))
|
||||
}
|
||||
pub(super) fn copy_group(
|
||||
&mut self,
|
||||
group: &GroupOrigin,
|
||||
@@ -128,35 +202,17 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
|
||||
// Iterating unique storage once supplies disjoint exclusive packets.
|
||||
// Genuine group row order is strictly ascending, so producer column
|
||||
// index remains its real inverse route mapping without raw buffer views.
|
||||
let mut selected = Vec::new();
|
||||
selected.try_reserve_exact(group.pairs.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut pairs = group.pairs.iter().peekable();
|
||||
for (row, packet) in self.packets.iter_mut().enumerate() {
|
||||
if pairs.peek().is_some_and(|pair| pair.row == row) {
|
||||
let pair = pairs.next().ok_or(Error::IdentityMismatch)?;
|
||||
selected.push((packet, pair.slot));
|
||||
}
|
||||
}
|
||||
if pairs.next().is_some() || selected.len() != group.pairs.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let txn = self.txn;
|
||||
let binding = self.binding;
|
||||
let layer = self.layer;
|
||||
let rows = self.rows;
|
||||
let origins = &self.origins;
|
||||
let mut selected = select_packets(&mut self.packets, &group.pairs)?;
|
||||
let view = RowsView {
|
||||
txn: self.txn,
|
||||
binding: self.binding,
|
||||
layer: self.layer,
|
||||
rows: self.rows,
|
||||
origins: &self.origins,
|
||||
};
|
||||
ResidentPackedDown::copy_group_with(self.scope, &mut selected, |destinations| {
|
||||
copy(destinations)?;
|
||||
for (column, pair) in group.pairs.iter().enumerate() {
|
||||
let row = rows.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
let origin = origins.get(pair.row).ok_or(Error::IdentityMismatch)?;
|
||||
if !Rc::ptr_eq(origin, &group.origins[column])
|
||||
|| row.row().route.experts()[pair.slot].get() != group.expert
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
validate_row(txn, binding, layer, pair.row, row, origin)?;
|
||||
}
|
||||
view.validate_group_columns(group)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
@@ -190,6 +246,25 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
|
||||
cancelled,
|
||||
)
|
||||
}
|
||||
fn finish_values(
|
||||
&self,
|
||||
row: &ChunkFfnRow,
|
||||
origin: &Rc<DownOrigin>,
|
||||
packed: &ResidentPackedDown<'ctx>,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let (context, binding, scope) = (self.context, self.binding, self.scope);
|
||||
if use_shared_tail(cache) {
|
||||
packed.with_completed(scope, |packet| {
|
||||
finish_shared_queued(context, binding, row.row(), activation, cache, scope, origin, packet)
|
||||
})
|
||||
} else {
|
||||
finish_shared_with(context, binding, row.row(), activation, cache, scope, origin, |weights, scaled| {
|
||||
packed.combine(scope, weights, scaled)
|
||||
})
|
||||
}
|
||||
}
|
||||
pub(super) fn finish_row(
|
||||
&self,
|
||||
index: usize,
|
||||
@@ -205,31 +280,7 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
|
||||
}
|
||||
let packed = self.packets.get(index).ok_or(Error::IdentityMismatch)?;
|
||||
packed.complete(self.scope)?;
|
||||
let values = if use_shared_tail(cache) {
|
||||
packed.with_completed(self.scope, |packet| {
|
||||
finish_shared_queued(
|
||||
self.context,
|
||||
self.binding,
|
||||
row.row(),
|
||||
activation,
|
||||
cache,
|
||||
self.scope,
|
||||
origin,
|
||||
packet,
|
||||
)
|
||||
})?
|
||||
} else {
|
||||
finish_shared_with(
|
||||
self.context,
|
||||
self.binding,
|
||||
row.row(),
|
||||
activation,
|
||||
cache,
|
||||
self.scope,
|
||||
origin,
|
||||
|weights, scaled| packed.combine(self.scope, weights, scaled),
|
||||
)?
|
||||
};
|
||||
let values = self.finish_values(row, origin, packed, activation, cache)?;
|
||||
validate_row(self.txn, self.binding, self.layer, index, row, origin)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
|
||||
@@ -9,6 +9,191 @@ pub(super) struct NativePromptFinish<'loan, 'ctx, 'dense> {
|
||||
pub(super) dense: &'loan DenseWeightCache<'dense>,
|
||||
}
|
||||
|
||||
/// The sealed window rows one native prompt finish is checked against.
|
||||
struct PromptRows<'a, 'session, 'ctx> {
|
||||
context: &'ctx Context<'ctx>,
|
||||
binding: &'a ModelBinding,
|
||||
layer: LayerId,
|
||||
rows: &'a [ChunkFfnRow],
|
||||
txn: &'a QwenChunkTxn<'session, 'ctx>,
|
||||
scope: &'a DownScope<'ctx>,
|
||||
}
|
||||
impl<'ctx> PromptRows<'_, '_, 'ctx> {
|
||||
fn validate_shape(&self, packets: &[&ResidentPackedDown<'ctx>]) -> Result<()> {
|
||||
if self.rows.len() != self.txn.micro_len()?
|
||||
|| self.rows.len() != packets.len()
|
||||
|| !(1..=64).contains(&self.rows.len())
|
||||
|| !std::ptr::eq(self.context, self.txn.context()?)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn expected(&self, packets: &[&ResidentPackedDown<'ctx>]) -> Result<Vec<TokenLayer>> {
|
||||
let mut expected = Vec::new();
|
||||
expected.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, (row, packet)) in self.rows.iter().zip(packets).enumerate() {
|
||||
self.txn.validate_ffn_row(self.txn.micro_row_index(index)?, self.layer, row)?;
|
||||
let identity = row.row().route.identity();
|
||||
row.row().validate(&self.binding.identity(), identity.token(), identity.position(), self.layer)?;
|
||||
packet.complete(self.scope)?;
|
||||
expected.push(identity);
|
||||
}
|
||||
Ok(expected)
|
||||
}
|
||||
/// The route that drove each expert slot is the producer's same real route,
|
||||
/// including bit-exact weights. A same-sized packet bank is insufficient.
|
||||
fn check_routes(&self, products: &MoeMicroProducts<'ctx>) -> Result<()> {
|
||||
for (row, route) in self.rows.iter().zip(products.rows()) {
|
||||
for slot in 0..K {
|
||||
if route.ids[slot] != row.row().route.experts()[slot].get() as i32
|
||||
|| route.weights[slot].to_bits() != row.row().route.weights()[slot].get().to_bits()
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Both actual packet storage and the produced shared/route owners already
|
||||
/// exist. Reserve the simultaneous gathered Dm and whole Bo before allocation.
|
||||
fn reserve_dm(&self, cache: &mut MoeWeightCache<'ctx>) -> Result<usize> {
|
||||
let (context, rows) = (self.context, self.rows);
|
||||
let dm_bytes = rows.len().checked_mul(K * N * 4).ok_or(Error::Overflow)?;
|
||||
let extra = dm_bytes.checked_add(rows.len() * N * 4).ok_or(Error::Overflow)?;
|
||||
cache.reserve_mmq_transient(self.binding, context, extra)?;
|
||||
let needed =
|
||||
extra.checked_add(super::super::super::moe_weight_cache::WORKING_RESERVE).ok_or(Error::Overflow)?;
|
||||
if context.allocated_bytes().checked_add(needed).is_none_or(|n| n > context.budget_bytes())
|
||||
|| context.memory_info().map_err(driver_error)?.0 < needed
|
||||
{
|
||||
return Err(Error::InputAllocation);
|
||||
}
|
||||
Ok(dm_bytes)
|
||||
}
|
||||
fn gather_sources<'p>(
|
||||
&self,
|
||||
packets: &[&'p ResidentPackedDown<'ctx>],
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<Vec<&'p DeviceBuffer<'ctx>>> {
|
||||
let mut sources = Vec::new();
|
||||
sources.try_reserve_exact(packets.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, packet) in packets.iter().enumerate() {
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
self.txn.validate_ffn_row(self.txn.micro_row_index(index)?, self.layer, &self.rows[index])?;
|
||||
sources.push(packet.completed_buffer(self.scope)?);
|
||||
}
|
||||
Ok(sources)
|
||||
}
|
||||
fn copy_packets_into(
|
||||
&self,
|
||||
packets: &[&ResidentPackedDown<'ctx>],
|
||||
dm: &mut TransportBuffer<'ctx>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<()> {
|
||||
let sources = self.gather_sources(packets, cancelled)?;
|
||||
self.context.copy_moe_prompt_packets(&sources, dm.buffer_mut()?).map_err(driver_error)?;
|
||||
for (index, packet) in packets.iter().enumerate() {
|
||||
packet.complete(self.scope)?;
|
||||
self.txn.validate_ffn_row(self.txn.micro_row_index(index)?, self.layer, &self.rows[index])?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn slot_indices(&self) -> Result<Vec<i32>> {
|
||||
let mut slots = Vec::new();
|
||||
slots.try_reserve_exact(self.rows.len() * K).map_err(|_| Error::InputAllocation)?;
|
||||
for slot in 0..self.rows.len() * K {
|
||||
slots.push(i32::try_from(slot).map_err(|_| Error::Overflow)?);
|
||||
}
|
||||
Ok(slots)
|
||||
}
|
||||
fn combine(
|
||||
&self,
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
finish: &mut NativePromptFinish<'_, 'ctx, '_>,
|
||||
expected: &[TokenLayer],
|
||||
(dm, slots): (&TransportBuffer<'ctx>, &[i32]),
|
||||
) -> Result<()> {
|
||||
let (binding, context) = (self.binding, self.context);
|
||||
let mut resources = cache.native_prefill_resources(binding, context)?;
|
||||
let mut workspace = finish.dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let gemm = workspace.gdn_gemm().map_err(driver_error)?;
|
||||
MoePrefillStage::combine_micro(
|
||||
binding,
|
||||
self.layer,
|
||||
expected,
|
||||
context,
|
||||
finish.products,
|
||||
CombineInput { dm: dm.buffer()?, slot: slots },
|
||||
&mut resources,
|
||||
&gemm,
|
||||
)
|
||||
}
|
||||
fn collect_outputs(
|
||||
&self,
|
||||
products: &MoeMicroProducts<'ctx>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<Vec<ExpertReady>> {
|
||||
let values = download_f32(products.combined().ok_or(Error::IdentityMismatch)?, self.rows.len() * N)?;
|
||||
let mut outputs = Vec::new();
|
||||
outputs.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, row) in self.rows.iter().enumerate() {
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
self.txn.validate_ffn_row(self.txn.micro_row_index(index)?, self.layer, row)?;
|
||||
let start = index * N;
|
||||
let mut actual = Vec::new();
|
||||
actual.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?;
|
||||
actual.extend_from_slice(&values[start..start + N]);
|
||||
let identity = row.row().route.identity();
|
||||
outputs.push(ExpertReady::from_completed(self.binding.identity(), identity, actual.into_boxed_slice())?);
|
||||
}
|
||||
Ok(outputs)
|
||||
}
|
||||
fn run(
|
||||
&self,
|
||||
packets: &[&ResidentPackedDown<'ctx>],
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
finish: &mut NativePromptFinish<'_, 'ctx, '_>,
|
||||
(expected, dm): (&[TokenLayer], &mut TransportBuffer<'ctx>),
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<Vec<ExpertReady>> {
|
||||
self.copy_packets_into(packets, dm, cancelled)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let slots = self.slot_indices()?;
|
||||
self.combine(cache, finish, expected, (dm, &slots))?;
|
||||
self.collect_outputs(finish.products, cancelled)
|
||||
}
|
||||
fn finish(
|
||||
&self,
|
||||
packets: &[&ResidentPackedDown<'ctx>],
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
finish: &mut NativePromptFinish<'_, 'ctx, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<Vec<ExpertReady>> {
|
||||
self.validate_shape(packets)?;
|
||||
cache.validate(self.binding, self.context)?;
|
||||
finish.dense.retained_context(self.binding, self.context)?;
|
||||
let expected = self.expected(packets)?;
|
||||
finish.products.validate_window(&self.binding.identity(), self.layer, &expected)?;
|
||||
self.check_routes(finish.products)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let dm_bytes = self.reserve_dm(cache)?;
|
||||
let mut dm = self.scope.allocate(dm_bytes)?;
|
||||
let operation = self.run(packets, cache, finish, (&expected, &mut dm), cancelled);
|
||||
self.scope.record(&operation);
|
||||
let cleanup = dm.close();
|
||||
operation.and_then(|values| cleanup.map(|()| values))
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn finish<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
@@ -22,108 +207,5 @@ pub(super) fn finish<'ctx>(
|
||||
finish: &mut NativePromptFinish<'_, 'ctx, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<Vec<ExpertReady>> {
|
||||
if rows.len() != txn.micro_len()?
|
||||
|| rows.len() != packets.len()
|
||||
|| !(1..=64).contains(&rows.len())
|
||||
|| !std::ptr::eq(context, txn.context()?)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
cache.validate(binding, context)?;
|
||||
finish.dense.retained_context(binding, context)?;
|
||||
let mut expected = Vec::new();
|
||||
expected.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, (row, packet)) in rows.iter().zip(packets).enumerate() {
|
||||
txn.validate_ffn_row(txn.micro_row_index(index)?, layer, row)?;
|
||||
let identity = row.row().route.identity();
|
||||
row.row().validate(&binding.identity(), identity.token(), identity.position(), layer)?;
|
||||
packet.complete(scope)?;
|
||||
expected.push(identity);
|
||||
}
|
||||
finish.products.validate_window(&binding.identity(), layer, &expected)?;
|
||||
// The route that drove each expert slot is the producer's same real route,
|
||||
// including bit-exact weights. A same-sized packet bank is insufficient.
|
||||
for (row, route) in rows.iter().zip(finish.products.rows()) {
|
||||
for slot in 0..K {
|
||||
if route.ids[slot] != row.row().route.experts()[slot].get() as i32
|
||||
|| route.weights[slot].to_bits() != row.row().route.weights()[slot].get().to_bits()
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
}
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
// Both actual packet storage and the produced shared/route owners already
|
||||
// exist. Reserve the simultaneous gathered Dm and whole Bo before allocation.
|
||||
let dm_bytes = rows.len().checked_mul(K * N * 4).ok_or(Error::Overflow)?;
|
||||
let extra = dm_bytes.checked_add(rows.len() * N * 4).ok_or(Error::Overflow)?;
|
||||
cache.reserve_mmq_transient(binding, context, extra)?;
|
||||
let needed = extra.checked_add(super::super::super::moe_weight_cache::WORKING_RESERVE).ok_or(Error::Overflow)?;
|
||||
if context.allocated_bytes().checked_add(needed).is_none_or(|n| n > context.budget_bytes())
|
||||
|| context.memory_info().map_err(driver_error)?.0 < needed
|
||||
{
|
||||
return Err(Error::InputAllocation);
|
||||
}
|
||||
let mut dm = scope.allocate(dm_bytes)?;
|
||||
let operation = (|| {
|
||||
let mut sources = Vec::new();
|
||||
sources.try_reserve_exact(packets.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, packet) in packets.iter().enumerate() {
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
txn.validate_ffn_row(txn.micro_row_index(index)?, layer, &rows[index])?;
|
||||
sources.push(packet.completed_buffer(scope)?);
|
||||
}
|
||||
context.copy_moe_prompt_packets(&sources, dm.buffer_mut()?).map_err(driver_error)?;
|
||||
for (index, packet) in packets.iter().enumerate() {
|
||||
packet.complete(scope)?;
|
||||
txn.validate_ffn_row(txn.micro_row_index(index)?, layer, &rows[index])?;
|
||||
}
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let mut slots = Vec::new();
|
||||
slots.try_reserve_exact(rows.len() * K).map_err(|_| Error::InputAllocation)?;
|
||||
for slot in 0..rows.len() * K {
|
||||
slots.push(i32::try_from(slot).map_err(|_| Error::Overflow)?);
|
||||
}
|
||||
let mut resources = cache.native_prefill_resources(binding, context)?;
|
||||
let mut workspace = finish.dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let gemm = workspace.gdn_gemm().map_err(driver_error)?;
|
||||
MoePrefillStage::combine_micro(
|
||||
binding,
|
||||
layer,
|
||||
&expected,
|
||||
context,
|
||||
finish.products,
|
||||
CombineInput { dm: dm.buffer()?, slot: &slots },
|
||||
&mut resources,
|
||||
&gemm,
|
||||
)?;
|
||||
let values = download_f32(finish.products.combined().ok_or(Error::IdentityMismatch)?, rows.len() * N)?;
|
||||
let mut outputs = Vec::new();
|
||||
outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
txn.validate_ffn_row(txn.micro_row_index(index)?, layer, row)?;
|
||||
let start = index * N;
|
||||
let mut actual = Vec::new();
|
||||
actual.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?;
|
||||
actual.extend_from_slice(&values[start..start + N]);
|
||||
outputs.push(ExpertReady::from_completed(
|
||||
binding.identity(),
|
||||
row.row().route.identity(),
|
||||
actual.into_boxed_slice(),
|
||||
)?);
|
||||
}
|
||||
Ok(outputs)
|
||||
})();
|
||||
scope.record(&operation);
|
||||
let cleanup = dm.close();
|
||||
operation.and_then(|values| cleanup.map(|()| values))
|
||||
PromptRows { context, binding, layer, rows, txn, scope }.finish(packets, cache, finish, cancelled)
|
||||
}
|
||||
|
||||
@@ -60,7 +60,67 @@ impl RoutedExperts {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_ffn_inputs(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
residual: &ResidualReady,
|
||||
txn: &QwenStepTxn,
|
||||
) -> Result<TokenLayer> {
|
||||
txn.validate_binding(&binding.identity())?;
|
||||
if layer.get() >= binding.layer_count() {
|
||||
return Err(Error::InvalidLayer);
|
||||
}
|
||||
if binding.expert_count() != EXPERTS as u32 || binding.expert_used_count() != SELECTED as u32 {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
residual.validate_origin(&binding.identity(), GrRole::Ffn(layer.get()))?;
|
||||
let identity = residual.identity();
|
||||
identity.validate(txn.token(), txn.position(), layer)?;
|
||||
txn.validate_input(identity.token(), identity.position())?;
|
||||
validate_activation(residual.mixed())?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn admitted_route_weights(binding: &ModelBinding, layer: LayerId, context: &Context<'_>) -> Result<MoeRouteWeights> {
|
||||
admit_projection_budget(context.allocated_bytes(), context.budget_bytes())?;
|
||||
let weights = binding.moe_route_weights(layer.get()).map_err(binding_error)?;
|
||||
if !weights.matches(&binding.identity(), layer.get()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(weights)
|
||||
}
|
||||
|
||||
fn logits_from_values(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
identity: TokenLayer,
|
||||
values: [f32; EXPERTS],
|
||||
) -> Result<RouterLogits> {
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if super::super::oracle_capture::enabled() {
|
||||
super::super::oracle_capture::stage_current("router_logits", &values)?;
|
||||
}
|
||||
RouterLogits::from_preceding(binding, identity.token(), identity.position(), layer, values)
|
||||
}
|
||||
|
||||
impl MoeRouteStage {
|
||||
/// Routes through the retained router scratch: its own projection, routing and completion fence.
|
||||
fn route_leased(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
identity: TokenLayer,
|
||||
txn: &QwenStepTxn,
|
||||
mut lease: crate::qwen_forward::router_scratch::RouterLease<'_, '_>,
|
||||
) -> Result<RoutedExperts> {
|
||||
let values = lease.project()?;
|
||||
let logits = logits_from_values(binding, layer, identity, values)?;
|
||||
let current = validate_request(binding, layer, &logits, identity.token(), txn)?;
|
||||
let routed =
|
||||
route_with(binding.identity(), binding.expert_count(), &logits, current, |values| lease.route(values))?;
|
||||
lease.complete()?;
|
||||
Ok(routed)
|
||||
}
|
||||
|
||||
/// Native-profile router projection from the exact typed FFN GR read.
|
||||
pub(in super::super) fn route_from_ffn(
|
||||
binding: &ModelBinding,
|
||||
@@ -69,49 +129,18 @@ impl MoeRouteStage {
|
||||
txn: &mut QwenStepTxn,
|
||||
cache: Option<&DenseWeightCache<'_>>,
|
||||
) -> Result<RoutedExperts> {
|
||||
txn.validate_binding(&binding.identity())?;
|
||||
if layer.get() >= binding.layer_count() {
|
||||
return Err(Error::InvalidLayer);
|
||||
}
|
||||
if binding.expert_count() != EXPERTS as u32 || binding.expert_used_count() != SELECTED as u32 {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
residual.validate_origin(&binding.identity(), GrRole::Ffn(layer.get()))?;
|
||||
let identity = residual.identity();
|
||||
identity.validate(txn.token(), txn.position(), layer)?;
|
||||
txn.validate_input(identity.token(), identity.position())?;
|
||||
validate_activation(residual.mixed())?;
|
||||
let identity = validate_ffn_inputs(binding, layer, residual, txn)?;
|
||||
let context = txn.cuda_context()?;
|
||||
admit_projection_budget(context.allocated_bytes(), context.budget_bytes())?;
|
||||
let weights = binding.moe_route_weights(layer.get()).map_err(binding_error)?;
|
||||
if !weights.matches(&binding.identity(), layer.get()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let weights = admitted_route_weights(binding, layer, context)?;
|
||||
if let Some(cache) = cache
|
||||
&& let Some(mut lease) = cache.router_scratch(binding, context, residual)?
|
||||
&& let Some(lease) = cache.router_scratch(binding, context, residual)?
|
||||
{
|
||||
let values = lease.project()?;
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if super::super::oracle_capture::enabled() {
|
||||
super::super::oracle_capture::stage_current("router_logits", &values)?;
|
||||
}
|
||||
let logits = RouterLogits::from_preceding(binding, identity.token(), identity.position(), layer, values)?;
|
||||
let current = validate_request(binding, layer, &logits, identity.token(), txn)?;
|
||||
let routed =
|
||||
route_with(binding.identity(), binding.expert_count(), &logits, current, |values| lease.route(values))?;
|
||||
lease.complete()?;
|
||||
return Ok(routed);
|
||||
return Self::route_leased(binding, layer, identity, txn, lease);
|
||||
}
|
||||
let values = project_logits(context, binding, &weights, residual.mixed(), layer.get(), cache)?;
|
||||
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if super::super::oracle_capture::enabled() {
|
||||
super::super::oracle_capture::stage_current("router_logits", &values)?;
|
||||
}
|
||||
let logits = RouterLogits::from_preceding(binding, identity.token(), identity.position(), layer, values)?;
|
||||
let logits = logits_from_values(binding, layer, identity, values)?;
|
||||
Self::route(binding, layer, &logits, identity.token(), txn)
|
||||
}
|
||||
|
||||
/// Route one token using the closed, fixed CUDA Driver operation. The
|
||||
/// transaction owns the device context; no kernel name or geometry is
|
||||
/// supplied here. All products remain local until output validation ends.
|
||||
|
||||
@@ -2,35 +2,34 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use leleka_cuda_driver::DeviceBuffer;
|
||||
|
||||
pub(super) fn project_logits(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeRouteWeights,
|
||||
activation: &[f32],
|
||||
layer: u32,
|
||||
cache: Option<&DenseWeightCache<'_>>,
|
||||
) -> Result<[f32; EXPERTS]> {
|
||||
fn activation_bytes(activation: &[f32]) -> [u8; COLUMNS * 4] {
|
||||
let mut input_bytes = [0u8; COLUMNS * 4];
|
||||
for (bytes, value) in input_bytes.as_chunks_mut::<4>().0.iter_mut().zip(activation) {
|
||||
*bytes = value.to_bits().to_le_bytes();
|
||||
}
|
||||
let mut input = context.allocate(input_bytes.len()).map_err(map_driver_error)?;
|
||||
input.copy_from(&input_bytes).map_err(map_driver_error)?;
|
||||
let mut owned = None;
|
||||
let matrix = if let Some(cache) = cache {
|
||||
cache.router(binding, layer)?
|
||||
} else {
|
||||
let block = binding.moe_route_matrix_block(weights, 0, EXPERTS).map_err(binding_error)?;
|
||||
let mut b = context.allocate(block.bytes().len()).map_err(map_driver_error)?;
|
||||
b.copy_from(block.bytes()).map_err(map_driver_error)?;
|
||||
owned = Some(b);
|
||||
owned.as_ref().ok_or(Error::IdentityMismatch)?
|
||||
};
|
||||
let mut output = context.allocate(EXPERTS * 4).map_err(map_driver_error)?;
|
||||
context
|
||||
.bf16_f32(matrix, &input, &mut output, Bf16ProjectionShape { rows: EXPERTS, columns: COLUMNS })
|
||||
.map_err(map_driver_error)?;
|
||||
input_bytes
|
||||
}
|
||||
|
||||
/// The uncached diagnostic uploads the router matrix once for this projection.
|
||||
fn upload_router_matrix<'ctx>(
|
||||
context: &'ctx Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeRouteWeights,
|
||||
) -> Result<DeviceBuffer<'ctx>> {
|
||||
let block = binding.moe_route_matrix_block(weights, 0, EXPERTS).map_err(binding_error)?;
|
||||
let mut b = context.allocate(block.bytes().len()).map_err(map_driver_error)?;
|
||||
b.copy_from(block.bytes()).map_err(map_driver_error)?;
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
/// Reads the projected logits back, releases every owner explicitly and checks the values finite.
|
||||
fn finish_logits(
|
||||
output: DeviceBuffer<'_>,
|
||||
owned: Option<DeviceBuffer<'_>>,
|
||||
input: DeviceBuffer<'_>,
|
||||
) -> Result<[f32; EXPERTS]> {
|
||||
let mut bytes = [0u8; EXPERTS * 4];
|
||||
output.copy_to(&mut bytes).map_err(map_driver_error)?;
|
||||
output.release().map_err(map_driver_error)?;
|
||||
@@ -44,6 +43,30 @@ pub(super) fn project_logits(
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
pub(super) fn project_logits(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeRouteWeights,
|
||||
activation: &[f32],
|
||||
layer: u32,
|
||||
cache: Option<&DenseWeightCache<'_>>,
|
||||
) -> Result<[f32; EXPERTS]> {
|
||||
let input_bytes = activation_bytes(activation);
|
||||
let mut input = context.allocate(input_bytes.len()).map_err(map_driver_error)?;
|
||||
input.copy_from(&input_bytes).map_err(map_driver_error)?;
|
||||
let mut owned = None;
|
||||
let matrix = if let Some(cache) = cache {
|
||||
cache.router(binding, layer)?
|
||||
} else {
|
||||
owned = Some(upload_router_matrix(context, binding, weights)?);
|
||||
owned.as_ref().ok_or(Error::IdentityMismatch)?
|
||||
};
|
||||
let mut output = context.allocate(EXPERTS * 4).map_err(map_driver_error)?;
|
||||
context
|
||||
.bf16_f32(matrix, &input, &mut output, Bf16ProjectionShape { rows: EXPERTS, columns: COLUMNS })
|
||||
.map_err(map_driver_error)?;
|
||||
finish_logits(output, owned, input)
|
||||
}
|
||||
pub(super) fn collect_logits(mut tile: impl FnMut(usize) -> Result<[f32; TILE_ROWS]>) -> Result<[f32; EXPERTS]> {
|
||||
let mut values = [0.0; EXPERTS];
|
||||
for first in (0..EXPERTS).step_by(TILE_ROWS) {
|
||||
@@ -66,13 +89,7 @@ pub(super) fn binding_error(error: InputBindingError) -> Error {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn validate_request(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
logits: &RouterLogits,
|
||||
token: TokenId,
|
||||
txn: &QwenStepTxn,
|
||||
) -> Result<TokenLayer> {
|
||||
fn check_request_shape(binding: &ModelBinding, layer: LayerId) -> Result<()> {
|
||||
let expert_count = binding.expert_count();
|
||||
let used_count = binding.expert_used_count();
|
||||
if expert_count != EXPERTS as u32 || used_count != SELECTED as u32 {
|
||||
@@ -83,7 +100,17 @@ pub(super) fn validate_request(
|
||||
if LayerId::new(u64::from(layer.get()), layer_bound)? != layer {
|
||||
return Err(Error::InvalidLayer);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn validate_request(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
logits: &RouterLogits,
|
||||
token: TokenId,
|
||||
txn: &QwenStepTxn,
|
||||
) -> Result<TokenLayer> {
|
||||
check_request_shape(binding, layer)?;
|
||||
let position = txn.position();
|
||||
if txn.token() != token {
|
||||
return Err(Error::IdentityMismatch);
|
||||
@@ -124,6 +151,32 @@ pub(super) fn route_with(
|
||||
routed_from_raw(binding, expert_count, identity, raw_ids, raw_weights)
|
||||
}
|
||||
|
||||
/// One slot of the raw top-10: a fresh in-range expert id and a finite rank weight in [0, 1] that never grows.
|
||||
fn route_slot(
|
||||
expert_bound: Dimension,
|
||||
seen: &mut [bool; EXPERTS],
|
||||
(raw_id, raw_weight): (i32, f32),
|
||||
previous: Option<FiniteF32>,
|
||||
) -> Result<(ExpertId, FiniteF32)> {
|
||||
let id = ExpertId::from_signed(i64::from(raw_id), expert_bound)?;
|
||||
let slot = usize::try_from(id.get()).map_err(|_| Error::InvalidExpert)?;
|
||||
if seen[slot] {
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
seen[slot] = true;
|
||||
|
||||
let weight = FiniteF32::new(raw_weight)?;
|
||||
if !(0.0..=1.0).contains(&weight.get()) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
// Normalized rank weights are non-increasing. Distinct source
|
||||
// probabilities may round to equal weights, so equality stays valid.
|
||||
if previous.is_some_and(|previous| weight.get() > previous.get()) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
Ok((id, weight))
|
||||
}
|
||||
|
||||
/// The tail of `route_with`, shared with the Original batch router: raw CUDA ids / weights become the
|
||||
/// producer-owned `RoutedExperts` only through these checks.
|
||||
pub(super) fn routed_from_raw(
|
||||
@@ -138,28 +191,12 @@ pub(super) fn routed_from_raw(
|
||||
let mut seen = [false; EXPERTS];
|
||||
let mut weights = [FiniteF32::new(0.0)?; SELECTED];
|
||||
for index in 0..SELECTED {
|
||||
let id = ExpertId::from_signed(i64::from(raw_ids[index]), expert_bound)?;
|
||||
let slot = usize::try_from(id.get()).map_err(|_| Error::InvalidExpert)?;
|
||||
if seen[slot] {
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
seen[slot] = true;
|
||||
|
||||
let weight = FiniteF32::new(raw_weights[index])?;
|
||||
if !(0.0..=1.0).contains(&weight.get()) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
// Normalized rank weights are non-increasing. Distinct source
|
||||
// probabilities may round to equal weights, so equality stays valid.
|
||||
if index > 0 && weight.get() > weights[index - 1].get() {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
ids[index] = id;
|
||||
weights[index] = weight;
|
||||
let previous = index.checked_sub(1).map(|before| weights[before]);
|
||||
let raw = (raw_ids[index], raw_weights[index]);
|
||||
(ids[index], weights[index]) = route_slot(expert_bound, &mut seen, raw, previous)?;
|
||||
}
|
||||
Ok(RoutedExperts::new(binding, identity, ids, weights))
|
||||
}
|
||||
|
||||
/// One row of the Original whole-window router (`MoePrefillStage::route_shared_micro`): the genuine FFN read's
|
||||
/// identity and its raw top-10, checked by exactly the checks of a per-row CUDA route.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
|
||||
@@ -2,12 +2,46 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use leleka_cuda_driver::DeviceBuffer;
|
||||
|
||||
pub(super) fn run_cuda(context: &Context<'_>, values: &[f32; EXPERTS]) -> Result<([i32; SELECTED], [f32; SELECTED])> {
|
||||
fn logits_to_bytes(values: &[f32; EXPERTS]) -> [u8; LOGITS_BYTES] {
|
||||
let mut logits_bytes = [0_u8; LOGITS_BYTES];
|
||||
for (chunk, value) in logits_bytes.as_chunks_mut::<{ std::mem::size_of::<f32>() }>().0.iter_mut().zip(values) {
|
||||
chunk.copy_from_slice(&value.to_ne_bytes());
|
||||
}
|
||||
logits_bytes
|
||||
}
|
||||
|
||||
fn decode_route(
|
||||
ids_bytes: &[u8; IDS_BYTES],
|
||||
weights_bytes: &[u8; WEIGHTS_BYTES],
|
||||
) -> ([i32; SELECTED], [f32; SELECTED]) {
|
||||
let ids = std::array::from_fn(|index| {
|
||||
let start = index * std::mem::size_of::<i32>();
|
||||
i32::from_ne_bytes(ids_bytes[start..start + 4].try_into().expect("fixed ID extent"))
|
||||
});
|
||||
let weights = std::array::from_fn(|index| {
|
||||
let start = index * std::mem::size_of::<f32>();
|
||||
f32::from_ne_bytes(weights_bytes[start..start + 4].try_into().expect("fixed weight extent"))
|
||||
});
|
||||
(ids, weights)
|
||||
}
|
||||
|
||||
/// Explicit releases are part of success: a cleanup/restoration failure
|
||||
/// withholds the host result. On an earlier error, Drop remains best-effort
|
||||
/// and the poisoned Driver retains uncertain resources as its contract says.
|
||||
fn release_route_buffers(
|
||||
input: DeviceBuffer<'_>,
|
||||
ids_buffer: DeviceBuffer<'_>,
|
||||
weights_buffer: DeviceBuffer<'_>,
|
||||
) -> Result<()> {
|
||||
weights_buffer.release().map_err(map_driver_error)?;
|
||||
ids_buffer.release().map_err(map_driver_error)?;
|
||||
input.release().map_err(map_driver_error)
|
||||
}
|
||||
|
||||
pub(super) fn run_cuda(context: &Context<'_>, values: &[f32; EXPERTS]) -> Result<([i32; SELECTED], [f32; SELECTED])> {
|
||||
let logits_bytes = logits_to_bytes(values);
|
||||
|
||||
let mut input = context.allocate(LOGITS_BYTES).map_err(map_driver_error)?;
|
||||
let mut ids_buffer = context.allocate(IDS_BYTES).map_err(map_driver_error)?;
|
||||
@@ -21,22 +55,9 @@ pub(super) fn run_cuda(context: &Context<'_>, values: &[f32; EXPERTS]) -> Result
|
||||
ids_buffer.copy_to(&mut ids_bytes).map_err(map_driver_error)?;
|
||||
weights_buffer.copy_to(&mut weights_bytes).map_err(map_driver_error)?;
|
||||
|
||||
// Explicit releases are part of success: a cleanup/restoration failure
|
||||
// withholds the host result. On an earlier error, Drop remains best-effort
|
||||
// and the poisoned Driver retains uncertain resources as its contract says.
|
||||
weights_buffer.release().map_err(map_driver_error)?;
|
||||
ids_buffer.release().map_err(map_driver_error)?;
|
||||
input.release().map_err(map_driver_error)?;
|
||||
release_route_buffers(input, ids_buffer, weights_buffer)?;
|
||||
|
||||
let ids = std::array::from_fn(|index| {
|
||||
let start = index * std::mem::size_of::<i32>();
|
||||
i32::from_ne_bytes(ids_bytes[start..start + 4].try_into().expect("fixed ID extent"))
|
||||
});
|
||||
let weights = std::array::from_fn(|index| {
|
||||
let start = index * std::mem::size_of::<f32>();
|
||||
f32::from_ne_bytes(weights_bytes[start..start + 4].try_into().expect("fixed weight extent"))
|
||||
});
|
||||
Ok((ids, weights))
|
||||
Ok(decode_route(&ids_bytes, &weights_bytes))
|
||||
}
|
||||
|
||||
pub(in super::super) fn map_driver_error(error: DriverError) -> Error {
|
||||
|
||||
+53
-68
@@ -3,96 +3,65 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// A shared owner closes only when this cache holds its last reference; any other holder counts as a failed close.
|
||||
fn close_shared<T>(owner: Rc<T>, close: impl FnOnce(T) -> bool) -> bool {
|
||||
match Rc::try_unwrap(owner) {
|
||||
Ok(owner) => close(owner),
|
||||
Err(owner) => {
|
||||
drop(owner);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> MoeWeightCache<'ctx> {
|
||||
pub(crate) fn close(mut self) -> Result<()> {
|
||||
let mut failed = self.failed.get();
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn close_original_owners(&mut self) -> bool {
|
||||
let mut failed = false;
|
||||
if let Some(owner) = self.original_copy_schedule.take() {
|
||||
failed |= owner.close().is_err();
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if let Some(owner) = self.original_prompt_device.take() {
|
||||
failed |= owner.close().is_err();
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
{
|
||||
self.original_finite_experts = [0; 48 * 512 / 64];
|
||||
self.original_span_cache = (0, Vec::new());
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
self.original_finite_experts = [0; 48 * 512 / 64];
|
||||
self.original_span_cache = (0, Vec::new());
|
||||
if let Some(bank) = self.original_expert_bank.take() {
|
||||
failed |= match Rc::try_unwrap(bank) {
|
||||
Ok(bank) => bank.close().is_err(),
|
||||
Err(bank) => {
|
||||
drop(bank);
|
||||
true
|
||||
}
|
||||
};
|
||||
failed |= close_shared(bank, |bank| bank.close().is_err());
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if let Some(owner) = self.ephemeral_routed.take() {
|
||||
failed |= match Rc::try_unwrap(owner) {
|
||||
Ok(owner) => owner.into_inner().close().is_err(),
|
||||
Err(owner) => {
|
||||
drop(owner);
|
||||
true
|
||||
}
|
||||
};
|
||||
failed |= close_shared(owner, |owner| owner.into_inner().close().is_err());
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if let Some(owner) = self.routed_outputs.take() {
|
||||
failed |= match Rc::try_unwrap(owner) {
|
||||
Ok(owner) => owner.close().is_err(),
|
||||
Err(owner) => {
|
||||
drop(owner);
|
||||
true
|
||||
}
|
||||
};
|
||||
failed |= close_shared(owner, |owner| owner.close().is_err());
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if let Some(adaptive) = self.adaptive.take() {
|
||||
failed |= adaptive.close().is_err();
|
||||
}
|
||||
failed
|
||||
}
|
||||
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
|
||||
fn close_original_owners(&mut self) -> bool {
|
||||
false
|
||||
}
|
||||
fn close_shared_owners(&mut self) -> bool {
|
||||
let mut failed = false;
|
||||
if let Some(owner) = self.mtp_input_workspace.take() {
|
||||
failed |= match Rc::try_unwrap(owner) {
|
||||
Ok(owner) => owner.close().is_err(),
|
||||
Err(owner) => {
|
||||
drop(owner);
|
||||
true
|
||||
}
|
||||
};
|
||||
failed |= close_shared(owner, |owner| owner.close().is_err());
|
||||
}
|
||||
if let Some(owner) = self.routed_resident.take() {
|
||||
failed |= match Rc::try_unwrap(owner) {
|
||||
Ok(owner) => owner.close().is_err(),
|
||||
Err(owner) => {
|
||||
drop(owner);
|
||||
true
|
||||
}
|
||||
};
|
||||
failed |= close_shared(owner, |owner| owner.close().is_err());
|
||||
}
|
||||
if let Some(owner) = self.routed_workspace.take() {
|
||||
failed |= match Rc::try_unwrap(owner) {
|
||||
Ok(owner) => owner.close().is_err(),
|
||||
Err(owner) => {
|
||||
drop(owner);
|
||||
true
|
||||
}
|
||||
};
|
||||
failed |= close_shared(owner, |owner| owner.close().is_err());
|
||||
}
|
||||
if let Some(owner) = self.routed_finite.take() {
|
||||
failed |= match Rc::try_unwrap(owner) {
|
||||
Ok(owner) => owner.close().is_err(),
|
||||
Err(owner) => {
|
||||
drop(owner);
|
||||
true
|
||||
}
|
||||
};
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if let Some(owner) = self.native_prefill.take() {
|
||||
failed |= owner.into_inner().close().is_err();
|
||||
failed |= close_shared(owner, |owner| owner.close().is_err());
|
||||
}
|
||||
failed
|
||||
}
|
||||
fn close_workspaces(&mut self) -> bool {
|
||||
let mut failed = false;
|
||||
if let Some(workspace) = self.target_shared.take() {
|
||||
failed |= workspace.close().is_err();
|
||||
}
|
||||
@@ -105,8 +74,12 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
if let Some(workspace) = self.mmq_workspace.take() {
|
||||
failed |= workspace.close().is_err();
|
||||
}
|
||||
// No more lookup/publication is possible during consuming teardown.
|
||||
// Drop metadata before draining every actual weight owner.
|
||||
failed
|
||||
}
|
||||
/// No more lookup/publication is possible during consuming teardown.
|
||||
/// Drop metadata before draining every actual weight owner.
|
||||
fn drain_weights(&mut self) -> bool {
|
||||
let mut failed = false;
|
||||
drop(self.lru.take());
|
||||
for (_, entry) in self.main.drain() {
|
||||
failed |= entry.weight.close().is_err();
|
||||
@@ -123,6 +96,18 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
failed |= bank.release().is_err();
|
||||
}
|
||||
}
|
||||
failed
|
||||
}
|
||||
pub(crate) fn close(mut self) -> Result<()> {
|
||||
let mut failed = self.failed.get();
|
||||
failed |= self.close_original_owners();
|
||||
failed |= self.close_shared_owners();
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if let Some(owner) = self.native_prefill.take() {
|
||||
failed |= owner.into_inner().close().is_err();
|
||||
}
|
||||
failed |= self.close_workspaces();
|
||||
failed |= self.drain_weights();
|
||||
if failed { Err(Error::CudaExecution) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
|
||||
+112
-89
@@ -3,39 +3,13 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl<'ctx> MoeWeightCache<'ctx> {
|
||||
/// Source-only experimental candidate: preserve a reusable 1 GiB spill floor.
|
||||
/// Root must bind this policy in fixture/serving identity before selection.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor(
|
||||
binding: &ModelBinding,
|
||||
context: &'ctx Context<'ctx>,
|
||||
bytes: &[u8],
|
||||
) -> Result<Self> {
|
||||
Self::profile_with_mtp_input_and_spill_floor(binding, context, bytes, true, 1usize << 30)
|
||||
}
|
||||
pub(in super::super::super) fn note_transport_failure(&self) {
|
||||
self.failed.set(true);
|
||||
}
|
||||
pub(crate) fn new(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result<Self> {
|
||||
Self::new_with_mtp_experts(binding, context, true)
|
||||
}
|
||||
/// Bytes `new` charges against the budget for the pinned MTP pack: the dense roles always, the 675 MiB expert bank only when it is uploaded.
|
||||
pub(in crate::qwen_forward) const fn mtp_pack_charge(mtp_experts: bool) -> usize {
|
||||
(if mtp_experts { MTP_PACK_EXPERT_BANK_BYTES } else { 0 }) + MTP_DENSE_LIMIT
|
||||
}
|
||||
/// `mtp_experts == false` leaves the pinned pack's EXPERT BANK (707,788,800 bytes, the draft layer's routed experts) out of VRAM. The serve stack
|
||||
/// passes false when it loads the draft layer from an RT directory (`--mtp-rt-dir`, the product path): that path streams its own copy of the
|
||||
/// experts (`original_mtp_rt_bank`) and never reads this one, so keeping both held 675 MiB of VRAM (and the host copy during the upload) for nothing.
|
||||
/// The pack's dense roles are still uploaded: the draft-KV recording of the prompt path reads them through `mtp_matrix`.
|
||||
pub(crate) fn new_with_mtp_experts(
|
||||
binding: &ModelBinding,
|
||||
context: &'ctx Context<'ctx>,
|
||||
mtp_experts: bool,
|
||||
) -> Result<Self> {
|
||||
let mut cache = Self {
|
||||
context,
|
||||
binding: binding.identity(),
|
||||
/// The unfilled cache of one binding/context: every owner empty, every counter zero. The field list is a data literal
|
||||
/// of the cache struct, kept out of the constructor's body.
|
||||
macro_rules! blank_cache {
|
||||
($binding:expr, $context:expr) => {
|
||||
Self {
|
||||
context: $context,
|
||||
binding: $binding.identity(),
|
||||
main: HashMap::new(),
|
||||
main_bytes: 0,
|
||||
lru: None,
|
||||
@@ -98,50 +72,103 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
mmq_dispatch_witness: Cell::new((0, 0, 0)),
|
||||
#[cfg(test)]
|
||||
mmq_triplet_witness: Cell::new((0, 0, 0)),
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
use crate::model_binding::qwen4exp_input::MtpWeights;
|
||||
|
||||
/// F32 dense rows keep a host copy of their words; every other kind keeps none.
|
||||
fn dense_f32_words(kind: MtpKind, bytes: &[u8]) -> Result<Option<Box<[f32]>>> {
|
||||
if kind != MtpKind::F32 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(bytes.len() / 4).map_err(|_| Error::InputAllocation)?;
|
||||
for word in bytes.as_chunks::<4>().0 {
|
||||
values.push(f32::from_le_bytes(*word));
|
||||
}
|
||||
Ok(Some(values.into_boxed_slice()))
|
||||
}
|
||||
impl<'ctx> MoeWeightCache<'ctx> {
|
||||
/// Source-only experimental candidate: preserve a reusable 1 GiB spill floor.
|
||||
/// Root must bind this policy in fixture/serving identity before selection.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor(
|
||||
binding: &ModelBinding,
|
||||
context: &'ctx Context<'ctx>,
|
||||
bytes: &[u8],
|
||||
) -> Result<Self> {
|
||||
Self::profile_with_mtp_input_and_spill_floor(binding, context, bytes, true, 1usize << 30)
|
||||
}
|
||||
pub(in super::super::super) fn note_transport_failure(&self) {
|
||||
self.failed.set(true);
|
||||
}
|
||||
pub(crate) fn new(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result<Self> {
|
||||
Self::new_with_mtp_experts(binding, context, true)
|
||||
}
|
||||
/// Bytes `new` charges against the budget for the pinned MTP pack: the dense roles always, the 675 MiB expert bank only when it is uploaded.
|
||||
pub(in crate::qwen_forward) const fn mtp_pack_charge(mtp_experts: bool) -> usize {
|
||||
(if mtp_experts { MTP_PACK_EXPERT_BANK_BYTES } else { 0 }) + MTP_DENSE_LIMIT
|
||||
}
|
||||
/// `mtp_experts == false` leaves the pinned pack's EXPERT BANK (707,788,800 bytes, the draft layer's routed experts) out of VRAM. The serve stack
|
||||
/// passes false when it loads the draft layer from an RT directory (`--mtp-rt-dir`, the product path): that path streams its own copy of the
|
||||
/// experts (`original_mtp_rt_bank`) and never reads this one, so keeping both held 675 MiB of VRAM (and the host copy during the upload) for nothing.
|
||||
/// The pack's dense roles are still uploaded: the draft-KV recording of the prompt path reads them through `mtp_matrix`.
|
||||
pub(crate) fn new_with_mtp_experts(
|
||||
binding: &ModelBinding,
|
||||
context: &'ctx Context<'ctx>,
|
||||
mtp_experts: bool,
|
||||
) -> Result<Self> {
|
||||
let mut cache = blank_cache!(binding, context);
|
||||
cache.room(0)?;
|
||||
if binding.has_mtp() {
|
||||
let pack = binding.mtp_weights().map_err(binding_error)?;
|
||||
cache.room(Self::mtp_pack_charge(mtp_experts))?;
|
||||
if mtp_experts {
|
||||
let data = pack.expert_bank(binding).map_err(binding_error)?;
|
||||
let bank = cache.upload(&data)?;
|
||||
cache.bank = Some(Rc::new(bank));
|
||||
drop(data);
|
||||
cache.counters.misses = cache.counters.misses.saturating_add(1);
|
||||
}
|
||||
let mut total = 0usize;
|
||||
for role in pack.dense_roles(binding).map_err(binding_error)? {
|
||||
let rows = pack.dense_complete(binding, role).map_err(binding_error)?;
|
||||
total = total.checked_add(rows.bytes().len()).ok_or(Error::Overflow)?;
|
||||
if total > MTP_DENSE_LIMIT {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let f32 = if rows.kind() == MtpKind::F32 {
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(rows.bytes().len() / 4).map_err(|_| Error::InputAllocation)?;
|
||||
for word in rows.bytes().as_chunks::<4>().0 {
|
||||
values.push(f32::from_le_bytes(*word));
|
||||
}
|
||||
Some(values.into_boxed_slice())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let buffer = cache.upload(rows.bytes())?;
|
||||
cache.dense.try_reserve(1).map_err(|_| Error::InputAllocation)?;
|
||||
cache.counters.misses = cache.counters.misses.saturating_add(1);
|
||||
cache.dense.push(Dense {
|
||||
role,
|
||||
kind: rows.kind(),
|
||||
rows: rows.rows(),
|
||||
columns: rows.columns(),
|
||||
buffer: Rc::new(buffer),
|
||||
f32,
|
||||
});
|
||||
}
|
||||
cache.upload_mtp_pack(binding, mtp_experts)?;
|
||||
}
|
||||
Ok(cache)
|
||||
}
|
||||
fn upload_mtp_pack(&mut self, binding: &ModelBinding, mtp_experts: bool) -> Result<()> {
|
||||
let pack = binding.mtp_weights().map_err(binding_error)?;
|
||||
self.room(Self::mtp_pack_charge(mtp_experts))?;
|
||||
if mtp_experts {
|
||||
let data = pack.expert_bank(binding).map_err(binding_error)?;
|
||||
let bank = self.upload(&data)?;
|
||||
self.bank = Some(Rc::new(bank));
|
||||
drop(data);
|
||||
self.counters.misses = self.counters.misses.saturating_add(1);
|
||||
}
|
||||
let mut total = 0usize;
|
||||
for role in pack.dense_roles(binding).map_err(binding_error)? {
|
||||
self.upload_dense_role(pack, binding, role, &mut total)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn upload_dense_role(
|
||||
&mut self,
|
||||
pack: &MtpWeights,
|
||||
binding: &ModelBinding,
|
||||
role: MtpRole,
|
||||
total: &mut usize,
|
||||
) -> Result<()> {
|
||||
let rows = pack.dense_complete(binding, role).map_err(binding_error)?;
|
||||
*total = total.checked_add(rows.bytes().len()).ok_or(Error::Overflow)?;
|
||||
if *total > MTP_DENSE_LIMIT {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let f32 = dense_f32_words(rows.kind(), rows.bytes())?;
|
||||
let buffer = self.upload(rows.bytes())?;
|
||||
self.dense.try_reserve(1).map_err(|_| Error::InputAllocation)?;
|
||||
self.counters.misses = self.counters.misses.saturating_add(1);
|
||||
self.dense.push(Dense {
|
||||
role,
|
||||
kind: rows.kind(),
|
||||
rows: rows.rows(),
|
||||
columns: rows.columns(),
|
||||
buffer: Rc::new(buffer),
|
||||
f32,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
/// Explicit private experiment only. Allocate/charge the persistent
|
||||
/// workspace before MTP-bank upload or any lazy main-LRU fill. Normal new()
|
||||
/// creates no workspace and keeps the unchanged native T1 path.
|
||||
@@ -177,21 +204,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
cache.mmq_policy = MmqRoutingPolicy::NativeIntegerIq3;
|
||||
cache.original_prompt_mmq = original_prompt;
|
||||
if binding.has_mtp() {
|
||||
let result = (|| {
|
||||
let charge = super::super::super::mtp_experts::fixed_workspace::ALLOCATED_BYTES;
|
||||
cache.reserve_mmq_transient(
|
||||
binding,
|
||||
context,
|
||||
charge.checked_add(512 * 1024).ok_or(Error::Overflow)?,
|
||||
)?;
|
||||
let fixed = super::super::super::mtp_experts::fixed_workspace::MtpExpertWorkspace::new(
|
||||
binding.identity(),
|
||||
Rc::clone(&cache.mmq_owner),
|
||||
context,
|
||||
)?;
|
||||
*cache.mtp_experts.get_mut() = Some(fixed);
|
||||
Ok(())
|
||||
})();
|
||||
let result = cache.admit_fixed_mtp_experts(binding, context);
|
||||
if let Err(primary) = result {
|
||||
let _ = cache.close();
|
||||
return Err(primary);
|
||||
@@ -199,8 +212,18 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
}
|
||||
Ok(cache)
|
||||
}
|
||||
/// Existing explicit NativeDown outer256 retained-GR mode only. All old
|
||||
/// constructors keep the original full-window MTP transport.
|
||||
fn admit_fixed_mtp_experts(&mut self, binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result<()> {
|
||||
let charge = super::super::super::mtp_experts::fixed_workspace::ALLOCATED_BYTES;
|
||||
self.reserve_mmq_transient(binding, context, charge.checked_add(512 * 1024).ok_or(Error::Overflow)?)?;
|
||||
let fixed = super::super::super::mtp_experts::fixed_workspace::MtpExpertWorkspace::new(
|
||||
binding.identity(),
|
||||
Rc::clone(&self.mmq_owner),
|
||||
context,
|
||||
)?;
|
||||
*self.mtp_experts.get_mut() = Some(fixed);
|
||||
Ok(())
|
||||
}
|
||||
/// Existing explicit NativeDown outer256 retained-GR mode only. All old /// constructors keep the original full-window MTP transport.
|
||||
pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv(
|
||||
binding: &ModelBinding,
|
||||
context: &'ctx Context<'ctx>,
|
||||
|
||||
+40
-41
@@ -21,41 +21,38 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
) -> Result<Self> {
|
||||
let mut cache =
|
||||
Self::new_native_integer_iq3_mmq_retained_mtp_kv_with_prompt(binding, context, original_prompt)?;
|
||||
let operation = (|| {
|
||||
cache.reserve_mmq_transient(
|
||||
binding,
|
||||
context,
|
||||
super::super::super::shared_expert_workspace::ALLOCATED_BYTES,
|
||||
)?;
|
||||
cache.reserve_mmq_transient(
|
||||
binding,
|
||||
context,
|
||||
super::super::super::moe_prefill_batch::MOE_PREFILL_PERSISTENT_BYTES,
|
||||
)?;
|
||||
let native = super::super::super::moe_prefill_batch::MoePrefillResources::new(
|
||||
context,
|
||||
super::super::super::moe_prefill_batch::MoeBf16Profile::HighOnly,
|
||||
)?;
|
||||
if native.allocated_bytes() != super::super::super::moe_prefill_batch::MOE_PREFILL_PERSISTENT_BYTES {
|
||||
let _ = native.close();
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
cache.native_prefill = Some(RefCell::new(native));
|
||||
cache.target_shared = Some(super::super::super::shared_expert_workspace::TargetSharedWorkspace::new(
|
||||
binding.identity(),
|
||||
Rc::clone(&cache.mmq_owner),
|
||||
context,
|
||||
)?);
|
||||
cache.validate(binding, context)
|
||||
})();
|
||||
let operation = cache.admit_shared_tail(binding, context);
|
||||
if let Err(primary) = operation {
|
||||
let _ = cache.close();
|
||||
return Err(primary);
|
||||
}
|
||||
Ok(cache)
|
||||
}
|
||||
/// Only this private changed-model candidate creates bounded host index
|
||||
/// metadata. Every prior constructor retains its original unindexed policy.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn admit_shared_tail(&mut self, binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result<()> {
|
||||
self.reserve_mmq_transient(binding, context, super::super::super::shared_expert_workspace::ALLOCATED_BYTES)?;
|
||||
self.reserve_mmq_transient(
|
||||
binding,
|
||||
context,
|
||||
super::super::super::moe_prefill_batch::MOE_PREFILL_PERSISTENT_BYTES,
|
||||
)?;
|
||||
let native = super::super::super::moe_prefill_batch::MoePrefillResources::new(
|
||||
context,
|
||||
super::super::super::moe_prefill_batch::MoeBf16Profile::HighOnly,
|
||||
)?;
|
||||
if native.allocated_bytes() != super::super::super::moe_prefill_batch::MOE_PREFILL_PERSISTENT_BYTES {
|
||||
let _ = native.close();
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
self.native_prefill = Some(RefCell::new(native));
|
||||
self.target_shared = Some(super::super::super::shared_expert_workspace::TargetSharedWorkspace::new(
|
||||
binding.identity(),
|
||||
Rc::clone(&self.mmq_owner),
|
||||
context,
|
||||
)?);
|
||||
self.validate(binding, context)
|
||||
}
|
||||
/// Only this private changed-model candidate creates bounded host index /// metadata. Every prior constructor retains its original unindexed policy.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(
|
||||
binding: &ModelBinding,
|
||||
@@ -79,18 +76,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
let _ = cache.close();
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let operation = (|| {
|
||||
// Fixed status and helper module precede indexed/pinned lazy weights.
|
||||
// The existing physical and typed 128 MiB reserve remains separate.
|
||||
cache.reserve_mmq_transient(binding, context, 4)?;
|
||||
cache.routed_finite = Some(Rc::new(RoutedFiniteOwner::new(context)?));
|
||||
// Actual table/DownQ8/status capacity is separate from the reserve.
|
||||
// Construct and observe module residency while main weights are empty.
|
||||
cache.reserve_mmq_transient(binding, context, 46_596)?;
|
||||
cache.routed_workspace = Some(Rc::new(RoutedWorkspaceOwner::new(context)?));
|
||||
cache.room(0)?;
|
||||
cache.validate(binding, context)
|
||||
})();
|
||||
let operation = cache.admit_lru_owners(binding, context);
|
||||
if let Err(primary) = operation {
|
||||
let _ = cache.close();
|
||||
return Err(primary);
|
||||
@@ -98,6 +84,19 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
cache.lru = Some(index);
|
||||
Ok(cache)
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn admit_lru_owners(&mut self, binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result<()> {
|
||||
// Fixed status and helper module precede indexed/pinned lazy weights.
|
||||
// The existing physical and typed 128 MiB reserve remains separate.
|
||||
self.reserve_mmq_transient(binding, context, 4)?;
|
||||
self.routed_finite = Some(Rc::new(RoutedFiniteOwner::new(context)?));
|
||||
// Actual table/DownQ8/status capacity is separate from the reserve.
|
||||
// Construct and observe module residency while main weights are empty.
|
||||
self.reserve_mmq_transient(binding, context, 46_596)?;
|
||||
self.routed_workspace = Some(Rc::new(RoutedWorkspaceOwner::new(context)?));
|
||||
self.room(0)?;
|
||||
self.validate(binding, context)
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_lru_witness(&self) -> (u64, u64, u64) {
|
||||
self.lru_witness.get()
|
||||
|
||||
+70
-72
@@ -3,6 +3,10 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
#[path = "impl_moeweightcache_3/shared_keys_fn.rs"]
|
||||
pub(super) mod shared_keys_fn;
|
||||
use shared_keys_fn::{raw_shared_buffers, shared_descriptors};
|
||||
|
||||
impl<'ctx> MoeWeightCache<'ctx> {
|
||||
pub(in super::super) fn prepare_lru_updates(
|
||||
&self,
|
||||
@@ -17,6 +21,17 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
if !(1..=3).contains(&updates.len()) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let (spill, count) = self.spill_updates(index, updates)?;
|
||||
if count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
index.prepare_updates(&spill[..count]).map(Some)
|
||||
}
|
||||
fn spill_updates(
|
||||
&self,
|
||||
index: &LruIndex,
|
||||
updates: &[(MoeWeightDescriptor, u64)],
|
||||
) -> Result<([(MoeWeightDescriptor, u64); 3], usize)> {
|
||||
let mut spill = [(updates[0].0, 0u64); 3];
|
||||
let mut count = 0;
|
||||
for &(key, age) in updates {
|
||||
@@ -32,10 +47,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
index.prepare_updates(&spill[..count]).map(Some)
|
||||
Ok((spill, count))
|
||||
}
|
||||
pub(in super::super) fn pinned_updates_allowed(&self) -> bool {
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
@@ -62,32 +74,33 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
_ => Err(Error::IdentityMismatch),
|
||||
}
|
||||
}
|
||||
pub(in super::super) fn eviction_key(&self, protected: &[MoeWeightDescriptor]) -> Result<MoeWeightDescriptor> {
|
||||
let key = if let Some(index) = &self.lru {
|
||||
if index.len() != self.spill_len()? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let key = index.oldest(protected)?.ok_or(Error::InputAllocation)?;
|
||||
if self.is_pinned(key) || index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
let (lookups, updates, removals) = self.lru_witness.get();
|
||||
self.lru_witness.set((lookups.saturating_add(1), updates, removals));
|
||||
}
|
||||
key
|
||||
} else {
|
||||
oldest_weight(
|
||||
self.main
|
||||
.iter()
|
||||
.filter(|(key, _)| !protected.contains(key) && !self.is_pinned(**key))
|
||||
.map(|(key, entry)| (*key, entry.age)),
|
||||
)
|
||||
.ok_or(Error::InputAllocation)?
|
||||
};
|
||||
fn lru_eviction_key(&self, index: &LruIndex, protected: &[MoeWeightDescriptor]) -> Result<MoeWeightDescriptor> {
|
||||
if index.len() != self.spill_len()? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let key = index.oldest(protected)?.ok_or(Error::InputAllocation)?;
|
||||
if self.is_pinned(key) || index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
let (lookups, updates, removals) = self.lru_witness.get();
|
||||
self.lru_witness.set((lookups.saturating_add(1), updates, removals));
|
||||
}
|
||||
Ok(key)
|
||||
}
|
||||
pub(in super::super) fn eviction_key(&self, protected: &[MoeWeightDescriptor]) -> Result<MoeWeightDescriptor> {
|
||||
if let Some(index) = &self.lru {
|
||||
return self.lru_eviction_key(index, protected);
|
||||
}
|
||||
oldest_weight(
|
||||
self.main
|
||||
.iter()
|
||||
.filter(|(key, _)| !protected.contains(key) && !self.is_pinned(**key))
|
||||
.map(|(key, entry)| (*key, entry.age)),
|
||||
)
|
||||
.ok_or(Error::InputAllocation)
|
||||
}
|
||||
pub(in super::super) fn remove_lru_entry(&mut self, key: MoeWeightDescriptor) -> Result<()> {
|
||||
if self.is_pinned(key) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
@@ -122,6 +135,33 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
owner.validate_context(context)?;
|
||||
Ok(owner)
|
||||
}
|
||||
/// Resolves the shared descriptors of `layer`, fills them without evicting one another and re-admits the real
|
||||
/// transient peak while every lent owner stays protected.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn admit_native_shared(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
layer: super::super::super::contract::LayerId,
|
||||
transient: usize,
|
||||
) -> Result<[MoeWeightDescriptor; 4]> {
|
||||
self.validate(binding, context)?;
|
||||
let weights =
|
||||
binding.moe_expert_weights(layer.get(), std::array::from_fn(|slot| slot as u32)).map_err(binding_error)?;
|
||||
if !weights.matches(&binding.identity(), layer.get()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let keys = shared_descriptors(binding, &weights)?;
|
||||
if keys.iter().any(|key| key.layer != layer.get()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.fill_shared_weights(binding, &weights, &keys)?;
|
||||
// Filling these four weights may consume an earlier physical snapshot.
|
||||
// Re-admit the real transient peak while protecting every lent owner.
|
||||
self.room_protected(transient, &keys)?;
|
||||
self.validate(binding, context)?;
|
||||
Ok(keys)
|
||||
}
|
||||
/// Genuine binding-resolved whole immutable shared weights, held through
|
||||
/// the closed native producer. Descriptors never authenticate arbitrary bytes.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
@@ -137,50 +177,8 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
&mut super::super::super::moe_prefill_batch::MoePrefillResources<'ctx>,
|
||||
) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
self.validate(binding, context)?;
|
||||
let weights =
|
||||
binding.moe_expert_weights(layer.get(), std::array::from_fn(|slot| slot as u32)).map_err(binding_error)?;
|
||||
if !weights.matches(&binding.identity(), layer.get()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down];
|
||||
let keys = [
|
||||
binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[0]).map_err(binding_error)?,
|
||||
binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[1]).map_err(binding_error)?,
|
||||
binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[2]).map_err(binding_error)?,
|
||||
binding.moe_shared_scalar_descriptor(&weights).map_err(binding_error)?,
|
||||
];
|
||||
super::super::super::shared_expert_workspace::validate_descriptors(&keys)?;
|
||||
if keys.iter().any(|key| key.layer != layer.get()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
for (index, key) in keys.iter().enumerate() {
|
||||
let _ = self.main_entry_protected(*key, &keys, || {
|
||||
if index == 3 {
|
||||
binding.moe_shared_scalar(&weights).map_err(binding_error)
|
||||
} else {
|
||||
Ok(binding
|
||||
.moe_expert_block(&weights, MoeExpertSelection::Shared, roles[index], 0, key.rows)
|
||||
.map_err(binding_error)?
|
||||
.into_bytes())
|
||||
}
|
||||
})?;
|
||||
}
|
||||
// Filling these four weights may consume an earlier physical snapshot.
|
||||
// Re-admit the real transient peak while protecting every lent owner.
|
||||
self.room_protected(transient, &keys)?;
|
||||
self.validate(binding, context)?;
|
||||
let raw = |index: usize| -> Result<&DeviceBuffer<'ctx>> {
|
||||
let entry = self.main.get(&keys[index]).ok_or(Error::IdentityMismatch)?;
|
||||
if entry.charged_bytes != keys[index].bytes {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
match &entry.weight {
|
||||
EncodedWeight::Raw(buffer) => Ok(buffer),
|
||||
EncodedWeight::Dual(_, _) => Err(Error::IdentityMismatch),
|
||||
}
|
||||
};
|
||||
let buffers = [raw(0)?, raw(1)?, raw(2)?, raw(3)?];
|
||||
let keys = self.admit_native_shared(binding, context, layer, transient)?;
|
||||
let buffers = raw_shared_buffers(&self.main, &keys)?;
|
||||
let mut owner = self.native_prefill_resources(binding, context)?;
|
||||
let result = execute(
|
||||
self.context,
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
//! The four shared-expert descriptors, their fill and their raw buffers: common to the native shared-weights loan and
|
||||
//! the target shared tail.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
const SHARED_ROLES: [MoeMatrixRole; 3] = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down];
|
||||
|
||||
/// Gate, Up, Down and scalar descriptors of the shared expert, validated as one workspace set.
|
||||
pub(in super::super) fn shared_descriptors(
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
) -> Result<[MoeWeightDescriptor; 4]> {
|
||||
let shared = MoeExpertSelection::Shared;
|
||||
let keys = [
|
||||
binding.moe_weight_descriptor(weights, shared, SHARED_ROLES[0]).map_err(binding_error)?,
|
||||
binding.moe_weight_descriptor(weights, shared, SHARED_ROLES[1]).map_err(binding_error)?,
|
||||
binding.moe_weight_descriptor(weights, shared, SHARED_ROLES[2]).map_err(binding_error)?,
|
||||
binding.moe_shared_scalar_descriptor(weights).map_err(binding_error)?,
|
||||
];
|
||||
crate::qwen_forward::shared_expert_workspace::validate_descriptors(&keys)?;
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
fn shared_bytes(
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
index: usize,
|
||||
key: &MoeWeightDescriptor,
|
||||
) -> Result<Box<[u8]>> {
|
||||
if index == 3 {
|
||||
binding.moe_shared_scalar(weights).map_err(binding_error)
|
||||
} else {
|
||||
Ok(binding
|
||||
.moe_expert_block(weights, MoeExpertSelection::Shared, SHARED_ROLES[index], 0, key.rows)
|
||||
.map_err(binding_error)?
|
||||
.into_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
/// The four resident raw buffers, each exactly its descriptor's charge; dual storage is refused.
|
||||
pub(in super::super) fn raw_shared_buffers<'a, 'ctx>(
|
||||
main: &'a HashMap<MoeWeightDescriptor, Entry<'ctx>>,
|
||||
keys: &[MoeWeightDescriptor; 4],
|
||||
) -> Result<[&'a DeviceBuffer<'ctx>; 4]> {
|
||||
let raw = |index: usize| -> Result<&'a DeviceBuffer<'ctx>> {
|
||||
let entry = main.get(&keys[index]).ok_or(Error::IdentityMismatch)?;
|
||||
if entry.charged_bytes != keys[index].bytes {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
match &entry.weight {
|
||||
EncodedWeight::Raw(buffer) => Ok(buffer),
|
||||
EncodedWeight::Dual(_, _) => Err(Error::IdentityMismatch),
|
||||
}
|
||||
};
|
||||
Ok([raw(0)?, raw(1)?, raw(2)?, raw(3)?])
|
||||
}
|
||||
|
||||
impl<'ctx> MoeWeightCache<'ctx> {
|
||||
/// Fills the four shared weights, none of which may evict another.
|
||||
pub(in super::super) fn fill_shared_weights(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
keys: &[MoeWeightDescriptor; 4],
|
||||
) -> Result<()> {
|
||||
for (index, key) in keys.iter().enumerate() {
|
||||
let _ = self.main_entry_protected(*key, keys, || shared_bytes(binding, weights, index, key))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+56
-50
@@ -1,5 +1,6 @@
|
||||
//! Moved out of the parent module by STRA-338: impl MoeWeightCache (4).
|
||||
|
||||
use super::impl_moeweightcache_3::shared_keys_fn::{raw_shared_buffers, shared_descriptors};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -22,50 +23,10 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
if !weights.matches(&binding.identity(), identity.layer().get()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down];
|
||||
let keys = [
|
||||
binding.moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[0]).map_err(binding_error)?,
|
||||
binding.moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[1]).map_err(binding_error)?,
|
||||
binding.moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[2]).map_err(binding_error)?,
|
||||
binding.moe_shared_scalar_descriptor(weights).map_err(binding_error)?,
|
||||
];
|
||||
super::super::super::shared_expert_workspace::validate_descriptors(&keys)?;
|
||||
for (index, key) in keys.iter().enumerate() {
|
||||
let _ = self.main_entry_protected(*key, &keys, || {
|
||||
if index == 3 {
|
||||
binding.moe_shared_scalar(weights).map_err(binding_error)
|
||||
} else {
|
||||
Ok(binding
|
||||
.moe_expert_block(weights, MoeExpertSelection::Shared, roles[index], 0, key.rows)
|
||||
.map_err(binding_error)?
|
||||
.into_bytes())
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let keys = shared_descriptors(binding, weights)?;
|
||||
self.fill_shared_weights(binding, weights, &keys)?;
|
||||
self.validate(binding, context)?;
|
||||
let entries = &self.main;
|
||||
let raw = |index: usize| -> Result<&DeviceBuffer<'ctx>> {
|
||||
let entry = entries.get(&keys[index]).ok_or(Error::IdentityMismatch)?;
|
||||
if entry.charged_bytes != keys[index].bytes {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
match &entry.weight {
|
||||
EncodedWeight::Raw(buffer) => Ok(buffer),
|
||||
EncodedWeight::Dual(_, _) => Err(Error::IdentityMismatch),
|
||||
}
|
||||
};
|
||||
let buffers = [raw(0)?, raw(1)?, raw(2)?, raw(3)?];
|
||||
let result = self.target_shared.as_mut().ok_or(Error::IdentityMismatch)?.compose(
|
||||
binding,
|
||||
&self.mmq_owner,
|
||||
context,
|
||||
identity,
|
||||
&keys,
|
||||
buffers,
|
||||
activation,
|
||||
packed,
|
||||
route,
|
||||
);
|
||||
let result = self.compose_shared(binding, context, identity, &keys, (activation, packed, route));
|
||||
if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) {
|
||||
self.failed.set(true);
|
||||
}
|
||||
@@ -75,6 +36,27 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
}
|
||||
result
|
||||
}
|
||||
fn compose_shared(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
identity: super::super::super::contract::TokenLayer,
|
||||
keys: &[MoeWeightDescriptor; 4],
|
||||
(activation, packed, route): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &[f32; 10]),
|
||||
) -> Result<Box<[f32]>> {
|
||||
let buffers = raw_shared_buffers(&self.main, keys)?;
|
||||
self.target_shared.as_mut().ok_or(Error::IdentityMismatch)?.compose(
|
||||
binding,
|
||||
&self.mmq_owner,
|
||||
context,
|
||||
identity,
|
||||
keys,
|
||||
buffers,
|
||||
activation,
|
||||
packed,
|
||||
route,
|
||||
)
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in super::super::super) fn compose_fixed_mtp_experts(
|
||||
&self,
|
||||
@@ -89,6 +71,23 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
weights: [f32; 10],
|
||||
failed: Rc<Cell<bool>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
self.admit_fixed_mtp(binding, context, frame, session, bank, shared)?;
|
||||
let result =
|
||||
self.compose_mtp_slot(binding, context, (frame, session), (bank, shared), (mixed, ids, weights), &failed);
|
||||
if failed.get() || context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) {
|
||||
self.failed.set(true);
|
||||
}
|
||||
result
|
||||
}
|
||||
fn admit_fixed_mtp(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
frame: &super::super::super::mtp::MtpFrame,
|
||||
session: &super::super::super::session::QwenSession<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
shared: [&DeviceBuffer<'_>; 4],
|
||||
) -> Result<()> {
|
||||
self.validate(binding, context)?;
|
||||
frame.validate(binding, session)?;
|
||||
if !self.requires_iq3_mmq_admission() {
|
||||
@@ -107,8 +106,19 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn compose_mtp_slot(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
(frame, session): (&super::super::super::mtp::MtpFrame, &super::super::super::session::QwenSession<'_>),
|
||||
(bank, shared): (&DeviceBuffer<'_>, [&DeviceBuffer<'_>; 4]),
|
||||
(mixed, ids, weights): (&[f32], [u32; 10], [f32; 10]),
|
||||
failed: &Rc<Cell<bool>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let mut slot = self.mtp_experts.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
|
||||
let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.compose(
|
||||
slot.as_mut().ok_or(Error::IdentityMismatch)?.compose(
|
||||
binding,
|
||||
&self.mmq_owner,
|
||||
context,
|
||||
@@ -119,12 +129,8 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
mixed,
|
||||
ids,
|
||||
weights,
|
||||
Rc::clone(&failed),
|
||||
);
|
||||
if failed.get() || context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) {
|
||||
self.failed.set(true);
|
||||
}
|
||||
result
|
||||
Rc::clone(failed),
|
||||
)
|
||||
}
|
||||
pub(in super::super::super) fn has_mtp_kv_ring(&self) -> Result<bool> {
|
||||
let slot = self.mtp_kv.try_borrow().map_err(|_| Error::IdentityMismatch)?;
|
||||
|
||||
+34
-15
@@ -3,6 +3,19 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Every triplet of the window passes the policy's kind admission; the first refused one declines the whole chunk.
|
||||
fn admit_triplets(triplets: &[[MoeWeightDescriptor; 3]], rows: usize, original_prompt: bool) -> Result<bool> {
|
||||
if triplets.len() != rows.checked_mul(10).ok_or(Error::Overflow)? {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
for keys in triplets {
|
||||
if !(if original_prompt { original_mmq_triplet(keys)? } else { integer_iq3_triplet(keys)? }) {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
impl<'ctx> MoeWeightCache<'ctx> {
|
||||
#[cfg(test)]
|
||||
pub(in crate::qwen_forward) fn note_test_mmq_dispatch(&self, resident: bool, rows: usize) {
|
||||
@@ -63,27 +76,24 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
original_prompt: bool,
|
||||
) -> Result<Option<MmqChunkAdmission>> {
|
||||
self.validate(binding, context)?;
|
||||
self.check_mmq_chunk_shape(rows, original_prompt)?;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if self.adaptive.is_some() && !original_prompt {
|
||||
return Ok(None);
|
||||
}
|
||||
if (original_prompt || self.requires_iq3_mmq_admission()) && !admit_triplets(triplets, rows, original_prompt)? {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(MmqChunkAdmission { owner: Rc::clone(&self.mmq_owner), policy: self.mmq_policy, original_prompt }))
|
||||
}
|
||||
fn check_mmq_chunk_shape(&self, rows: usize, original_prompt: bool) -> Result<()> {
|
||||
if !(if original_prompt { 1..=64 } else { 2..=64 }).contains(&rows)
|
||||
|| self.mmq_workspace.is_none()
|
||||
|| (original_prompt && !self.original_prompt_mmq)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if self.adaptive.is_some() && !original_prompt {
|
||||
return Ok(None);
|
||||
}
|
||||
if original_prompt || self.requires_iq3_mmq_admission() {
|
||||
if triplets.len() != rows.checked_mul(10).ok_or(Error::Overflow)? {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
for keys in triplets {
|
||||
if !(if original_prompt { original_mmq_triplet(keys)? } else { integer_iq3_triplet(keys)? }) {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(MmqChunkAdmission { owner: Rc::clone(&self.mmq_owner), policy: self.mmq_policy, original_prompt }))
|
||||
Ok(())
|
||||
}
|
||||
pub(in super::super::super) fn with_mmq_workspace<T>(
|
||||
&mut self,
|
||||
@@ -124,6 +134,15 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
if original_prompt || self.requires_iq3_mmq_admission() {
|
||||
return self.with_integer_mmq_triplet(binding, weights, selection, original_prompt, execute);
|
||||
}
|
||||
self.with_native_mmq_triplet(binding, weights, selection, execute)
|
||||
}
|
||||
fn with_native_mmq_triplet<T>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
self.validate(binding, self.context)?;
|
||||
let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down];
|
||||
let mut keys = Vec::new();
|
||||
|
||||
+18
-72
@@ -1,31 +1,40 @@
|
||||
//! Moved out of the parent module by STRA-338: impl MoeWeightCache (7).
|
||||
|
||||
use super::impl_moeweightcache_8::fill_fns::Room;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl<'ctx> MoeWeightCache<'ctx> {
|
||||
pub(crate) fn validate(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> {
|
||||
if self.failed.get()
|
||||
fn owners_failed(&self) -> bool {
|
||||
self.failed.get()
|
||||
|| self.context.is_poisoned()
|
||||
|| self.routed_finite.as_ref().is_some_and(|owner| owner.is_failed())
|
||||
|| self.routed_workspace.as_ref().is_some_and(|owner| owner.is_failed())
|
||||
|| self.routed_resident.as_ref().is_some_and(|owner| owner.is_failed())
|
||||
|| self.mtp_input_workspace.as_ref().is_some_and(|owner| owner.is_failed())
|
||||
{
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn validate_original_owners(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> {
|
||||
if let Some(adaptive) = &self.adaptive {
|
||||
adaptive.validate(binding)?;
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if let Some(outputs) = &self.routed_outputs {
|
||||
outputs.validate(&binding.identity(), context)?;
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if let Some(owner) = &self.ephemeral_routed {
|
||||
owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.validate(binding, context)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
|
||||
fn validate_original_owners(&self, _binding: &ModelBinding, _context: &Context<'_>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn validate(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> {
|
||||
if self.owners_failed() {
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
self.validate_original_owners(binding, context)?;
|
||||
if !self.binding.matches(&binding.identity()) || !std::ptr::eq(self.context, context) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
@@ -95,69 +104,6 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
protected: &[MoeWeightDescriptor],
|
||||
read: impl FnOnce() -> Result<Box<[u8]>>,
|
||||
) -> Result<CachedMoeMatrix<'_, 'ctx>> {
|
||||
if self.failed.get() {
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
let hit = self.main.contains_key(&key);
|
||||
if self.is_pinned(key) && !hit {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.note_profile_request(key, hit);
|
||||
self.age = self.age.checked_add(1).ok_or(Error::Overflow)?;
|
||||
if hit {
|
||||
let update = self.prepare_lru_updates(&[(key, self.age)])?;
|
||||
self.commit_lru_updates(update, 1)?;
|
||||
self.counters.hits = self.counters.hits.saturating_add(1);
|
||||
} else {
|
||||
self.counters.misses = self.counters.misses.saturating_add(1);
|
||||
let dual = self.weight_layout(key)?;
|
||||
let charged_bytes = dual.map_or(key.bytes, |(_, bytes)| bytes);
|
||||
self.room_protected(charged_bytes, protected)?;
|
||||
self.reserve_main(1)?;
|
||||
let update = self.prepare_lru_updates(&[(key, self.age)])?;
|
||||
let bytes = read()?;
|
||||
if bytes.len() != key.bytes {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let weight = if let Some((format, expected)) = dual {
|
||||
let owner = match self.context.mmq_weights(format, &bytes) {
|
||||
Ok(owner) => owner,
|
||||
Err(error) => {
|
||||
if self.context.is_poisoned() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(driver_error(error));
|
||||
}
|
||||
};
|
||||
if owner.allocated_bytes() != expected {
|
||||
let cleanup = owner.close();
|
||||
if cleanup.is_err() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.counters.read_bytes = self.counters.read_bytes.saturating_add(bytes.len() as u64);
|
||||
self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(charged_bytes as u64);
|
||||
EncodedWeight::Dual(format, owner)
|
||||
} else {
|
||||
EncodedWeight::Raw(self.upload(&bytes)?)
|
||||
};
|
||||
let main_bytes = self.main_bytes.checked_add(charged_bytes).ok_or(Error::Overflow)?;
|
||||
if let Err(primary) = self.commit_lru_updates(update, 1) {
|
||||
if weight.close().is_err() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(primary);
|
||||
}
|
||||
self.main_bytes = main_bytes;
|
||||
self.main.insert(key, Entry { weight, charged_bytes, age: self.age });
|
||||
}
|
||||
self.note_permanent_lookup(key, hit);
|
||||
let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?;
|
||||
entry.age = self.age;
|
||||
Ok(match &entry.weight {
|
||||
EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer),
|
||||
EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner),
|
||||
})
|
||||
self.fill_main_entry(key, Room::Protected(protected), Self::build_weight_plain, read)
|
||||
}
|
||||
}
|
||||
|
||||
+47
-154
@@ -3,76 +3,17 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
#[path = "impl_moeweightcache_8/fill_fns.rs"]
|
||||
pub(super) mod fill_fns;
|
||||
use fill_fns::Room;
|
||||
|
||||
impl<'ctx> MoeWeightCache<'ctx> {
|
||||
pub(in super::super) fn main_entry(
|
||||
&mut self,
|
||||
key: MoeWeightDescriptor,
|
||||
read: impl FnOnce() -> Result<Box<[u8]>>,
|
||||
) -> Result<CachedMoeMatrix<'_, 'ctx>> {
|
||||
if self.failed.get() {
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
let hit = self.main.contains_key(&key);
|
||||
if self.is_pinned(key) && !hit {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.note_profile_request(key, hit);
|
||||
self.age = self.age.checked_add(1).ok_or(Error::Overflow)?;
|
||||
if hit {
|
||||
let update = self.prepare_lru_updates(&[(key, self.age)])?;
|
||||
self.commit_lru_updates(update, 1)?;
|
||||
self.counters.hits = self.counters.hits.saturating_add(1);
|
||||
} else {
|
||||
self.counters.misses = self.counters.misses.saturating_add(1);
|
||||
let dual = self.weight_layout(key)?;
|
||||
let charged_bytes = dual.map_or(key.bytes, |(_, bytes)| bytes);
|
||||
self.room(charged_bytes)?;
|
||||
self.reserve_main(1)?;
|
||||
let update = self.prepare_lru_updates(&[(key, self.age)])?;
|
||||
let bytes = read()?;
|
||||
if bytes.len() != key.bytes {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let weight = if let Some((format, expected)) = dual {
|
||||
let owner = match self.context.mmq_weights(format, &bytes) {
|
||||
Ok(owner) => owner,
|
||||
Err(error) => {
|
||||
if self.context.is_poisoned() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(driver_error(error));
|
||||
}
|
||||
};
|
||||
if owner.allocated_bytes() != expected {
|
||||
let cleanup = owner.close();
|
||||
if cleanup.is_err() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.counters.read_bytes = self.counters.read_bytes.saturating_add(bytes.len() as u64);
|
||||
self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(charged_bytes as u64);
|
||||
EncodedWeight::Dual(format, owner)
|
||||
} else {
|
||||
EncodedWeight::Raw(self.upload(&bytes)?)
|
||||
};
|
||||
let main_bytes = self.main_bytes.checked_add(charged_bytes).ok_or(Error::Overflow)?;
|
||||
if let Err(primary) = self.commit_lru_updates(update, 1) {
|
||||
if weight.close().is_err() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(primary);
|
||||
}
|
||||
self.main_bytes = main_bytes;
|
||||
self.main.insert(key, Entry { weight, charged_bytes, age: self.age });
|
||||
}
|
||||
self.note_permanent_lookup(key, hit);
|
||||
let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?;
|
||||
entry.age = self.age;
|
||||
Ok(match &entry.weight {
|
||||
EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer),
|
||||
EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner),
|
||||
})
|
||||
self.fill_main_entry(key, Room::Unprotected, Self::build_weight_plain, read)
|
||||
}
|
||||
/// Selected scoped cold GU only. The genuine final source block transfers
|
||||
/// its storage at the original role point; hits keep the original policy.
|
||||
@@ -82,81 +23,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
key: MoeWeightDescriptor,
|
||||
read: impl FnOnce() -> Result<Box<[u8]>>,
|
||||
) -> Result<CachedMoeMatrix<'_, 'ctx>> {
|
||||
if self.failed.get() {
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
let hit = self.main.contains_key(&key);
|
||||
if self.is_pinned(key) && !hit {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.note_profile_request(key, hit);
|
||||
self.age = self.age.checked_add(1).ok_or(Error::Overflow)?;
|
||||
if hit {
|
||||
let update = self.prepare_lru_updates(&[(key, self.age)])?;
|
||||
self.commit_lru_updates(update, 1)?;
|
||||
self.counters.hits = self.counters.hits.saturating_add(1);
|
||||
} else {
|
||||
self.counters.misses = self.counters.misses.saturating_add(1);
|
||||
let dual = self.weight_layout(key)?;
|
||||
let charged_bytes = dual.map_or(key.bytes, |(_, bytes)| bytes);
|
||||
self.room(charged_bytes)?;
|
||||
self.reserve_main(1)?;
|
||||
let update = self.prepare_lru_updates(&[(key, self.age)])?;
|
||||
let bytes = read()?;
|
||||
if bytes.len() != key.bytes {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let raw_bytes = bytes.len();
|
||||
let weight = if let Some((format, expected)) = dual {
|
||||
let kind = match key.raw_kind {
|
||||
18 => leleka_cuda_driver::RoutedFormat::IQ3_XXS,
|
||||
22 => leleka_cuda_driver::RoutedFormat::IQ2_S,
|
||||
_ => return Err(Error::InvalidDimension),
|
||||
};
|
||||
let shape = leleka_cuda_driver::ProjectionSpec {
|
||||
kind: leleka_cuda_driver::ProjectionKind::Routed(kind),
|
||||
rows: key.rows,
|
||||
columns: key.columns,
|
||||
};
|
||||
let owner = match self.context.mmq_weights_owned_gate_up(shape, format, bytes.into_vec()) {
|
||||
Ok(owner) => owner,
|
||||
Err(error) => {
|
||||
if self.context.is_poisoned() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(driver_error(error));
|
||||
}
|
||||
};
|
||||
if owner.allocated_bytes() != expected {
|
||||
let cleanup = owner.close();
|
||||
if cleanup.is_err() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.counters.read_bytes = self.counters.read_bytes.saturating_add(raw_bytes as u64);
|
||||
self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(charged_bytes as u64);
|
||||
EncodedWeight::Dual(format, owner)
|
||||
} else {
|
||||
EncodedWeight::Raw(self.upload(&bytes)?)
|
||||
};
|
||||
let main_bytes = self.main_bytes.checked_add(charged_bytes).ok_or(Error::Overflow)?;
|
||||
if let Err(primary) = self.commit_lru_updates(update, 1) {
|
||||
if weight.close().is_err() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(primary);
|
||||
}
|
||||
self.main_bytes = main_bytes;
|
||||
self.main.insert(key, Entry { weight, charged_bytes, age: self.age });
|
||||
}
|
||||
self.note_permanent_lookup(key, hit);
|
||||
let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?;
|
||||
entry.age = self.age;
|
||||
Ok(match &entry.weight {
|
||||
EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer),
|
||||
EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner),
|
||||
})
|
||||
self.fill_main_entry(key, Room::Unprotected, Self::build_weight_owned_gate_up, read)
|
||||
}
|
||||
/// Fill through the original cache policy, then retain actual immutable
|
||||
/// cache/weight/failure-cell loans for the complete closed consumer.
|
||||
@@ -179,30 +46,56 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
}
|
||||
source.validate_binding(binding).map_err(binding_error)?;
|
||||
let key = source.descriptor(member, role).map_err(binding_error)?;
|
||||
if let Some(adaptive) = &self.adaptive
|
||||
&& key.expert.is_some()
|
||||
{
|
||||
let matrix = adaptive
|
||||
.matrix(binding, key)?
|
||||
.ok_or(Error::Unsupported(super::super::super::contract::Stage::MoeExpert))?;
|
||||
let health = RoutedSourceHealth { binding: &self.binding, context: self.context, failed: &self.failed };
|
||||
return consume(matrix, &health, source);
|
||||
if let Some(matrix) = self.adaptive_source_matrix(binding, key)? {
|
||||
return consume(matrix, &self.source_health(), source);
|
||||
}
|
||||
// The temporary returned view ends here. No cache fill/eviction occurs
|
||||
// while the consumer below holds actual cache fields immutably.
|
||||
self.fill_routed_source(key, member, role, source)?;
|
||||
self.validate(binding, self.context)?;
|
||||
let matrix = self.resident_matrix(key)?;
|
||||
consume(matrix, &self.source_health(), source)
|
||||
}
|
||||
fn source_health(&self) -> RoutedSourceHealth<'_, 'ctx> {
|
||||
RoutedSourceHealth { binding: &self.binding, context: self.context, failed: &self.failed }
|
||||
}
|
||||
/// The adaptive slot's matrix of an expert descriptor; no cache fill or eviction can happen on this path.
|
||||
fn adaptive_source_matrix(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
key: MoeWeightDescriptor,
|
||||
) -> Result<Option<CachedMoeMatrix<'_, 'ctx>>> {
|
||||
let Some(adaptive) = &self.adaptive else {
|
||||
return Ok(None);
|
||||
};
|
||||
if key.expert.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
adaptive
|
||||
.matrix(binding, key)?
|
||||
.ok_or(Error::Unsupported(super::super::super::contract::Stage::MoeExpert))
|
||||
.map(Some)
|
||||
}
|
||||
/// The temporary returned view ends here. No cache fill/eviction occurs
|
||||
/// while the consumer holds actual cache fields immutably.
|
||||
fn fill_routed_source(
|
||||
&mut self,
|
||||
key: MoeWeightDescriptor,
|
||||
member: usize,
|
||||
role: MoeMatrixRole,
|
||||
source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>,
|
||||
) -> Result<()> {
|
||||
let read = || Ok(source.block(member, role).map_err(binding_error)?.into_bytes());
|
||||
let _ = if key.expert.is_some() && matches!(key.role, 0 | 1) && matches!(key.raw_kind, 18 | 22) {
|
||||
self.main_entry_owned_gate_up(key, read)?
|
||||
} else {
|
||||
self.main_entry(key, read)?
|
||||
};
|
||||
self.validate(binding, self.context)?;
|
||||
Ok(())
|
||||
}
|
||||
fn resident_matrix(&self, key: MoeWeightDescriptor) -> Result<CachedMoeMatrix<'_, 'ctx>> {
|
||||
let entry = self.main.get(&key).ok_or(Error::IdentityMismatch)?;
|
||||
let matrix = match &entry.weight {
|
||||
Ok(match &entry.weight {
|
||||
EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer),
|
||||
EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner),
|
||||
};
|
||||
let health = RoutedSourceHealth { binding: &self.binding, context: self.context, failed: &self.failed };
|
||||
consume(matrix, &health, source)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
//! The one fill path of the main weight cache: lookup, miss admission, weight construction and publication. The three
|
||||
//! public entries differ only in how room is made and how a dual weight is built from the bytes.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// How a miss makes room: plain eviction, or eviction that never takes a descriptor the caller still lends.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in super::super) enum Room<'a> {
|
||||
Unprotected,
|
||||
Protected(&'a [MoeWeightDescriptor]),
|
||||
}
|
||||
|
||||
type Layout = Option<(MmqFormat, usize)>;
|
||||
|
||||
/// The Gate/Up kernel shape of a routed IQ3_XXS/IQ2_S block whose storage transfers into the dual weight.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn gate_up_shape(key: MoeWeightDescriptor) -> Result<leleka_cuda_driver::ProjectionSpec> {
|
||||
let kind = match key.raw_kind {
|
||||
18 => leleka_cuda_driver::RoutedFormat::IQ3_XXS,
|
||||
22 => leleka_cuda_driver::RoutedFormat::IQ2_S,
|
||||
_ => return Err(Error::InvalidDimension),
|
||||
};
|
||||
Ok(leleka_cuda_driver::ProjectionSpec {
|
||||
kind: leleka_cuda_driver::ProjectionKind::Routed(kind),
|
||||
rows: key.rows,
|
||||
columns: key.columns,
|
||||
})
|
||||
}
|
||||
|
||||
impl<'ctx> MoeWeightCache<'ctx> {
|
||||
pub(in super::super) fn fill_main_entry(
|
||||
&mut self,
|
||||
key: MoeWeightDescriptor,
|
||||
room: Room<'_>,
|
||||
build: impl FnOnce(&mut Self, MoeWeightDescriptor, Layout, Box<[u8]>, usize) -> Result<EncodedWeight<'ctx>>,
|
||||
read: impl FnOnce() -> Result<Box<[u8]>>,
|
||||
) -> Result<CachedMoeMatrix<'_, 'ctx>> {
|
||||
let hit = self.begin_main_lookup(key)?;
|
||||
if hit {
|
||||
let update = self.prepare_lru_updates(&[(key, self.age)])?;
|
||||
self.commit_lru_updates(update, 1)?;
|
||||
self.counters.hits = self.counters.hits.saturating_add(1);
|
||||
} else {
|
||||
self.fill_main_miss(key, room, build, read)?;
|
||||
}
|
||||
self.note_permanent_lookup(key, hit);
|
||||
let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?;
|
||||
entry.age = self.age;
|
||||
Ok(match &entry.weight {
|
||||
EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer),
|
||||
EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner),
|
||||
})
|
||||
}
|
||||
/// A failed cache serves nothing; a pinned descriptor may only hit. Counts the request and advances the age.
|
||||
fn begin_main_lookup(&mut self, key: MoeWeightDescriptor) -> Result<bool> {
|
||||
if self.failed.get() {
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
let hit = self.main.contains_key(&key);
|
||||
if self.is_pinned(key) && !hit {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.note_profile_request(key, hit);
|
||||
self.age = self.age.checked_add(1).ok_or(Error::Overflow)?;
|
||||
Ok(hit)
|
||||
}
|
||||
fn fill_main_miss(
|
||||
&mut self,
|
||||
key: MoeWeightDescriptor,
|
||||
room: Room<'_>,
|
||||
build: impl FnOnce(&mut Self, MoeWeightDescriptor, Layout, Box<[u8]>, usize) -> Result<EncodedWeight<'ctx>>,
|
||||
read: impl FnOnce() -> Result<Box<[u8]>>,
|
||||
) -> Result<()> {
|
||||
self.counters.misses = self.counters.misses.saturating_add(1);
|
||||
let dual = self.weight_layout(key)?;
|
||||
let charged_bytes = dual.map_or(key.bytes, |(_, bytes)| bytes);
|
||||
match room {
|
||||
Room::Unprotected => self.room(charged_bytes)?,
|
||||
Room::Protected(protected) => self.room_protected(charged_bytes, protected)?,
|
||||
}
|
||||
self.reserve_main(1)?;
|
||||
let update = self.prepare_lru_updates(&[(key, self.age)])?;
|
||||
let bytes = read()?;
|
||||
if bytes.len() != key.bytes {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let weight = build(self, key, dual, bytes, charged_bytes)?;
|
||||
self.publish_main_entry(key, weight, charged_bytes, update)
|
||||
}
|
||||
/// The commit of the LRU update decides: on its failure the freshly built weight is closed, never published.
|
||||
fn publish_main_entry(
|
||||
&mut self,
|
||||
key: MoeWeightDescriptor,
|
||||
weight: EncodedWeight<'ctx>,
|
||||
charged_bytes: usize,
|
||||
update: Option<PreparedUpdates>,
|
||||
) -> Result<()> {
|
||||
let main_bytes = self.main_bytes.checked_add(charged_bytes).ok_or(Error::Overflow)?;
|
||||
if let Err(primary) = self.commit_lru_updates(update, 1) {
|
||||
if weight.close().is_err() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(primary);
|
||||
}
|
||||
self.main_bytes = main_bytes;
|
||||
self.main.insert(key, Entry { weight, charged_bytes, age: self.age });
|
||||
Ok(())
|
||||
}
|
||||
/// A built dual weight is admitted only at exactly its predicted size; the read/upload counters follow.
|
||||
fn admit_dual_weight(
|
||||
&mut self,
|
||||
built: std::result::Result<MmqWeights<'ctx>, leleka_cuda_driver::Error>,
|
||||
(format, expected): (MmqFormat, usize),
|
||||
(raw_bytes, charged_bytes): (usize, usize),
|
||||
) -> Result<EncodedWeight<'ctx>> {
|
||||
let owner = match built {
|
||||
Ok(owner) => owner,
|
||||
Err(error) => {
|
||||
if self.context.is_poisoned() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(driver_error(error));
|
||||
}
|
||||
};
|
||||
if owner.allocated_bytes() != expected {
|
||||
let cleanup = owner.close();
|
||||
if cleanup.is_err() {
|
||||
self.failed.set(true);
|
||||
}
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.counters.read_bytes = self.counters.read_bytes.saturating_add(raw_bytes as u64);
|
||||
self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(charged_bytes as u64);
|
||||
Ok(EncodedWeight::Dual(format, owner))
|
||||
}
|
||||
pub(in super::super) fn build_weight_plain(
|
||||
&mut self,
|
||||
_key: MoeWeightDescriptor,
|
||||
dual: Layout,
|
||||
bytes: Box<[u8]>,
|
||||
charged_bytes: usize,
|
||||
) -> Result<EncodedWeight<'ctx>> {
|
||||
let Some((format, expected)) = dual else {
|
||||
return Ok(EncodedWeight::Raw(self.upload(&bytes)?));
|
||||
};
|
||||
let built = self.context.mmq_weights(format, &bytes);
|
||||
self.admit_dual_weight(built, (format, expected), (bytes.len(), charged_bytes))
|
||||
}
|
||||
/// Selected scoped cold GU: the genuine final source block transfers its storage at the original role point.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in super::super) fn build_weight_owned_gate_up(
|
||||
&mut self,
|
||||
key: MoeWeightDescriptor,
|
||||
dual: Layout,
|
||||
bytes: Box<[u8]>,
|
||||
charged_bytes: usize,
|
||||
) -> Result<EncodedWeight<'ctx>> {
|
||||
let Some((format, expected)) = dual else {
|
||||
return Ok(EncodedWeight::Raw(self.upload(&bytes)?));
|
||||
};
|
||||
let raw_bytes = bytes.len();
|
||||
let shape = gate_up_shape(key)?;
|
||||
let built = self.context.mmq_weights_owned_gate_up(shape, format, bytes.into_vec());
|
||||
self.admit_dual_weight(built, (format, expected), (raw_bytes, charged_bytes))
|
||||
}
|
||||
}
|
||||
+26
-10
@@ -3,6 +3,30 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The Gate/Up/Down descriptors of one group member, in role order.
|
||||
fn triplet_keys(
|
||||
source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>,
|
||||
member: usize,
|
||||
) -> Result<[MoeWeightDescriptor; 3]> {
|
||||
Ok([
|
||||
source.descriptor(member, MoeMatrixRole::Gate).map_err(binding_error)?,
|
||||
source.descriptor(member, MoeMatrixRole::Up).map_err(binding_error)?,
|
||||
source.descriptor(member, MoeMatrixRole::Down).map_err(binding_error)?,
|
||||
])
|
||||
}
|
||||
/// The three raw whole buffers of one completed adaptive slot; any other storage is refused.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn adaptive_raw_triplet<'a, 'ctx>(
|
||||
adaptive: &'a cache_strata_adaptive::AdaptiveCache<'ctx>,
|
||||
binding: &ModelBinding,
|
||||
keys: &[MoeWeightDescriptor; 3],
|
||||
) -> Result<[&'a DeviceBuffer<'ctx>; 3]> {
|
||||
let raw = |key| match adaptive.matrix(binding, key)? {
|
||||
Some(CachedMoeMatrix::Raw(raw)) => Ok(raw),
|
||||
_ => Err(Error::IdentityMismatch),
|
||||
};
|
||||
Ok([raw(keys[0])?, raw(keys[1])?, raw(keys[2])?])
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
impl<'ctx> MoeWeightCache<'ctx> {
|
||||
pub(in super::super) fn routed_output_owner(
|
||||
@@ -59,20 +83,12 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
self.validate(binding, self.context)?;
|
||||
source.validate_binding(binding).map_err(binding_error)?;
|
||||
let adaptive = self.adaptive.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let keys = [
|
||||
source.descriptor(member, MoeMatrixRole::Gate).map_err(binding_error)?,
|
||||
source.descriptor(member, MoeMatrixRole::Up).map_err(binding_error)?,
|
||||
source.descriptor(member, MoeMatrixRole::Down).map_err(binding_error)?,
|
||||
];
|
||||
let keys = triplet_keys(source, member)?;
|
||||
if keys.iter().any(|key| key.layer != keys[0].layer || key.expert != keys[0].expert) || keys[0].expert.is_none()
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let raw = |key| match adaptive.matrix(binding, key)? {
|
||||
Some(CachedMoeMatrix::Raw(raw)) => Ok(raw),
|
||||
_ => Err(Error::IdentityMismatch),
|
||||
};
|
||||
let buffers = [raw(keys[0])?, raw(keys[1])?, raw(keys[2])?];
|
||||
let buffers = adaptive_raw_triplet(adaptive, binding, &keys)?;
|
||||
let health = RoutedSourceHealth { binding: &self.binding, context: self.context, failed: &self.failed };
|
||||
consume(buffers, &health, source)
|
||||
}
|
||||
|
||||
@@ -4,16 +4,18 @@
|
||||
use super::*;
|
||||
|
||||
impl MtpFrame {
|
||||
fn within_bounds(&self) -> Result<bool> {
|
||||
Ok(self.token == TokenId::new(u64::from(self.token.get()), Dimension::new(248320)?)?
|
||||
&& self.position.get() < crate::qwen_forward::contract::serving_cells()
|
||||
&& self.depth < 4)
|
||||
}
|
||||
pub(in super::super) fn validate(&self, binding: &ModelBinding, session: &QwenSession<'_>) -> Result<()> {
|
||||
self.origin.validate(session)?;
|
||||
if !self.binding.matches(&binding.identity()) || self.epoch.get() != self.generation {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
binding.mtp_weights().map_err(binding_error)?.validate_binding(binding).map_err(binding_error)?;
|
||||
if self.token != TokenId::new(u64::from(self.token.get()), Dimension::new(248320)?)?
|
||||
|| self.position.get() >= crate::qwen_forward::contract::serving_cells()
|
||||
|| self.depth >= 4
|
||||
{
|
||||
if !self.within_bounds()? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
@@ -105,23 +107,23 @@ impl MtpInput {
|
||||
if cache.has_mtp_input_workspace() {
|
||||
return Self::compute_queued(binding, session, frame, streams, &embedding, cache);
|
||||
}
|
||||
let en = norm(context, binding, MtpRole::EmbeddingNorm, &embedding, false, cache)?;
|
||||
Self::compute_host(binding, session, frame, (streams, &embedding), (context, cache))
|
||||
}
|
||||
fn compute_host(
|
||||
binding: &ModelBinding,
|
||||
session: &QwenSession<'_>,
|
||||
frame: MtpFrame,
|
||||
(streams, embedding): (&[f32], &[f32]),
|
||||
(context, cache): (&Context<'_>, &MoeWeightCache<'_>),
|
||||
) -> Result<Self> {
|
||||
let en = norm(context, binding, MtpRole::EmbeddingNorm, embedding, false, cache)?;
|
||||
let e2 = project(context, binding, MtpRole::FcEmbedding, &en, cache)?;
|
||||
let hn = norm(context, binding, MtpRole::HiddenNorm, streams, true, cache)?;
|
||||
let mut h2 = reserve(10240)?;
|
||||
for chunk in hn.as_chunks::<2560>().0 {
|
||||
h2.extend_from_slice(&project(context, binding, MtpRole::FcHidden, chunk, cache)?);
|
||||
}
|
||||
let hidden = upload(context, &h2)?;
|
||||
let emb = upload(context, &e2)?;
|
||||
let mut out = allocate(context, 10240)?;
|
||||
context.mtp_broadcast_f32(&hidden, &emb, &mut out).map_err(driver_error)?;
|
||||
let result = download(&out, 10240)?;
|
||||
release([hidden, emb, out])?;
|
||||
let h2 = project_hidden_chunks(context, binding, &hn, cache)?;
|
||||
let result = broadcast_streams(context, &h2, &e2)?;
|
||||
frame.validate(binding, session)?;
|
||||
Ok(Self { frame, streams: result })
|
||||
}
|
||||
// Each role is acquired at the original stage. Scratch is exclusively
|
||||
} // Each role is acquired at the original stage. Scratch is exclusively
|
||||
// borrowed from a separate owner while actual dense weights stay immutable.
|
||||
pub(super) fn compute_queued(
|
||||
binding: &ModelBinding,
|
||||
@@ -139,51 +141,117 @@ impl MtpInput {
|
||||
let owner = cache.mtp_input_workspace_owner(binding, context)?;
|
||||
owner.with_workspace(|workspace| {
|
||||
let mut prefix = workspace.begin(embedding, streams).map_err(driver_error)?;
|
||||
let admitted: Result<()> = (|| {
|
||||
prefix.embedding_norm(en_weights).map_err(driver_error)?;
|
||||
let (kind, rows, columns, weights) = cache.mtp_matrix(binding, context, MtpRole::FcEmbedding)?;
|
||||
queued_fc_shape(kind, rows, columns)?;
|
||||
preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?;
|
||||
prefix.embedding_projection(weights).map_err(driver_error)?;
|
||||
let hn_gamma = f32_weights(binding, MtpRole::HiddenNorm, cache)?;
|
||||
validate_values(streams, 10240)?;
|
||||
validate_values(&hn_gamma, 10240)?;
|
||||
let (_, _, _, hn_weights) = cache.mtp_matrix(binding, context, MtpRole::HiddenNorm)?;
|
||||
prefix.hidden_norm(hn_weights).map_err(driver_error)?;
|
||||
// The original host H assembly allocation remains at its role
|
||||
// point; this queue changes only numerical transport storage.
|
||||
let _h2 = reserve::<f32>(10240)?;
|
||||
for _ in 0..4 {
|
||||
let (kind, rows, columns, weights) = cache.mtp_matrix(binding, context, MtpRole::FcHidden)?;
|
||||
queued_fc_shape(kind, rows, columns)?;
|
||||
preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?;
|
||||
prefix.hidden_projection(weights).map_err(driver_error)?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(primary) = admitted {
|
||||
// A fully completed earlier numerical refusal retains its old
|
||||
// priority over a later cache/source/shape admission refusal.
|
||||
// CUDA uncertainty keeps conservative transport precedence.
|
||||
return match prefix.drain_prefix().map_err(driver_error)? {
|
||||
Some(refusal) => Err(input_refusal(refusal)),
|
||||
None => Err(primary),
|
||||
};
|
||||
if let Err(primary) = admit_queued_prefix(&mut prefix, binding, context, cache, (streams, en_weights)) {
|
||||
return refuse_queued(prefix, primary);
|
||||
}
|
||||
let completion = prefix.finish().map_err(driver_error)?;
|
||||
#[cfg(test)]
|
||||
if let Some(stage) = completion.refusal_stage() {
|
||||
eprintln!("PUBLIC MTP input queued numeric stage={stage}");
|
||||
}
|
||||
let result = completion.into_streams().map_err(input_refusal)?;
|
||||
validate_values(&result, 10240)?;
|
||||
frame.validate(binding, session)?;
|
||||
cache.validate(binding, context)?;
|
||||
#[cfg(test)]
|
||||
cache.note_mtp_input_completed();
|
||||
Ok(Self { frame, streams: result })
|
||||
Self::complete_queued(prefix, (binding, session, context), cache, frame)
|
||||
})
|
||||
}
|
||||
fn complete_queued(
|
||||
prefix: leleka_cuda_driver::MtpInputPrefix<'_, '_>,
|
||||
(binding, session, context): (&ModelBinding, &QwenSession<'_>, &Context<'_>),
|
||||
cache: &MoeWeightCache<'_>,
|
||||
frame: MtpFrame,
|
||||
) -> Result<Self> {
|
||||
let completion = prefix.finish().map_err(driver_error)?;
|
||||
#[cfg(test)]
|
||||
if let Some(stage) = completion.refusal_stage() {
|
||||
eprintln!("PUBLIC MTP input queued numeric stage={stage}");
|
||||
}
|
||||
let result = completion.into_streams().map_err(input_refusal)?;
|
||||
validate_values(&result, 10240)?;
|
||||
frame.validate(binding, session)?;
|
||||
cache.validate(binding, context)?;
|
||||
#[cfg(test)]
|
||||
cache.note_mtp_input_completed();
|
||||
Ok(Self { frame, streams: result })
|
||||
}
|
||||
}
|
||||
/// The original host H assembly: the hidden stream projected in four 2560-wide chunks.
|
||||
fn project_hidden_chunks(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
hn: &[f32],
|
||||
cache: &MoeWeightCache<'_>,
|
||||
) -> Result<Vec<f32>> {
|
||||
let mut h2 = reserve(10240)?;
|
||||
for chunk in hn.as_chunks::<2560>().0 {
|
||||
h2.extend_from_slice(&project(context, binding, MtpRole::FcHidden, chunk, cache)?);
|
||||
}
|
||||
Ok(h2)
|
||||
}
|
||||
fn broadcast_streams(context: &Context<'_>, h2: &[f32], e2: &[f32]) -> Result<Box<[f32]>> {
|
||||
let hidden = upload(context, h2)?;
|
||||
let emb = upload(context, e2)?;
|
||||
let mut out = allocate(context, 10240)?;
|
||||
context.mtp_broadcast_f32(&hidden, &emb, &mut out).map_err(driver_error)?;
|
||||
let result = download(&out, 10240)?;
|
||||
release([hidden, emb, out])?;
|
||||
Ok(result)
|
||||
}
|
||||
fn queued_embedding<'lease, 'ctx: 'lease>(
|
||||
prefix: &mut leleka_cuda_driver::MtpInputPrefix<'lease, 'ctx>,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
cache: &'lease MoeWeightCache<'ctx>,
|
||||
en_weights: &'lease DeviceBuffer<'ctx>,
|
||||
) -> Result<()> {
|
||||
prefix.embedding_norm(en_weights).map_err(driver_error)?;
|
||||
let (kind, rows, columns, weights) = cache.mtp_matrix(binding, context, MtpRole::FcEmbedding)?;
|
||||
queued_fc_shape(kind, rows, columns)?;
|
||||
preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?;
|
||||
prefix.embedding_projection(weights).map_err(driver_error)
|
||||
}
|
||||
fn queued_hidden_norm<'lease, 'ctx: 'lease>(
|
||||
prefix: &mut leleka_cuda_driver::MtpInputPrefix<'lease, 'ctx>,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
cache: &'lease MoeWeightCache<'ctx>,
|
||||
streams: &[f32],
|
||||
) -> Result<()> {
|
||||
let hn_gamma = f32_weights(binding, MtpRole::HiddenNorm, cache)?;
|
||||
validate_values(streams, 10240)?;
|
||||
validate_values(&hn_gamma, 10240)?;
|
||||
let (_, _, _, hn_weights) = cache.mtp_matrix(binding, context, MtpRole::HiddenNorm)?;
|
||||
prefix.hidden_norm(hn_weights).map_err(driver_error)
|
||||
}
|
||||
fn queued_hidden_projections<'lease, 'ctx: 'lease>(
|
||||
prefix: &mut leleka_cuda_driver::MtpInputPrefix<'lease, 'ctx>,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
cache: &'lease MoeWeightCache<'ctx>,
|
||||
) -> Result<()> {
|
||||
// The original host H assembly allocation remains at its role
|
||||
// point; this queue changes only numerical transport storage.
|
||||
let _h2 = reserve::<f32>(10240)?;
|
||||
for _ in 0..4 {
|
||||
let (kind, rows, columns, weights) = cache.mtp_matrix(binding, context, MtpRole::FcHidden)?;
|
||||
queued_fc_shape(kind, rows, columns)?;
|
||||
preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?;
|
||||
prefix.hidden_projection(weights).map_err(driver_error)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Every queued stage of the prefix is admitted in the original order before the prefix may finish.
|
||||
fn admit_queued_prefix<'lease, 'ctx: 'lease>(
|
||||
prefix: &mut leleka_cuda_driver::MtpInputPrefix<'lease, 'ctx>,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
cache: &'lease MoeWeightCache<'ctx>,
|
||||
(streams, en_weights): (&[f32], &'lease DeviceBuffer<'ctx>),
|
||||
) -> Result<()> {
|
||||
queued_embedding(prefix, binding, context, cache, en_weights)?;
|
||||
queued_hidden_norm(prefix, binding, context, cache, streams)?;
|
||||
queued_hidden_projections(prefix, binding, context, cache)
|
||||
}
|
||||
/// A fully completed earlier numerical refusal retains its old
|
||||
/// priority over a later cache/source/shape admission refusal.
|
||||
/// CUDA uncertainty keeps conservative transport precedence.
|
||||
fn refuse_queued<T>(prefix: leleka_cuda_driver::MtpInputPrefix<'_, '_>, primary: Error) -> Result<T> {
|
||||
match prefix.drain_prefix().map_err(driver_error)? {
|
||||
Some(refusal) => Err(input_refusal(refusal)),
|
||||
None => Err(primary),
|
||||
}
|
||||
}
|
||||
// Only the actual loaded Q8_0 pack opts in; old BF16/unsupported paths stay None.
|
||||
pub(super) fn queued_fc_shape(kind: MtpKind, rows: usize, columns: usize) -> Result<()> {
|
||||
|
||||
+21
-13
@@ -3,29 +3,37 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
const ROWS: usize = 2560;
|
||||
const COLUMNS: usize = 6144;
|
||||
|
||||
fn project_gated(
|
||||
context: &Context<'_>,
|
||||
weights: &DeviceBuffer<'_>,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
y: &mut DeviceBuffer<'_>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
context
|
||||
.project_q8_1(
|
||||
weights,
|
||||
activation,
|
||||
y,
|
||||
ProjectionSpec { rows: ROWS, columns: COLUMNS, kind: ProjectionKind::Dense(DenseFormat::Q8_0) },
|
||||
)
|
||||
.map_err(driver_error)?;
|
||||
download(y, ROWS)
|
||||
}
|
||||
|
||||
pub(in super::super) fn project_attention_out_numeric(
|
||||
context: &Context<'_>,
|
||||
weights: &DeviceBuffer<'_>,
|
||||
input: &super::super::mtp_attention::RetainedGated<'_>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
const ROWS: usize = 2560;
|
||||
const COLUMNS: usize = 6144;
|
||||
let activation = input.buffer(context)?;
|
||||
// Activation is already charged by Context. Reserve the same remaining
|
||||
// output/quantizer/status increment as the original upload-based path.
|
||||
preflight(context, ROWS * 4 + COLUMNS / 32 * 36 + 4)?;
|
||||
let mut y = allocate(context, ROWS)?;
|
||||
let result = (|| {
|
||||
context
|
||||
.project_q8_1(
|
||||
weights,
|
||||
activation,
|
||||
&mut y,
|
||||
ProjectionSpec { rows: ROWS, columns: COLUMNS, kind: ProjectionKind::Dense(DenseFormat::Q8_0) },
|
||||
)
|
||||
.map_err(driver_error)?;
|
||||
download(&y, ROWS)
|
||||
})();
|
||||
let result = project_gated(context, weights, activation, &mut y);
|
||||
if result.as_ref().is_err_and(|e| *e == Error::CudaExecution) {
|
||||
input.failure_flag().set(true);
|
||||
}
|
||||
|
||||
@@ -52,6 +52,66 @@ pub(in super::super) fn warm_chunk_row(
|
||||
stage.validate_anchor(binding, target)
|
||||
})
|
||||
}
|
||||
/// The five numerical stage products of one draft step. They stay alive until the step is committed and synchronized,
|
||||
/// and drop in the reverse order the stages produced them.
|
||||
struct MtpBlocks {
|
||||
final_mixed: super::super::mtp_gr::MtpDraftFinal,
|
||||
block: super::super::mtp_experts::MtpBlock,
|
||||
mlp: super::super::mtp_gr::MtpMlpReady,
|
||||
attention: super::super::mtp_attention::MtpAttentionReady,
|
||||
read: super::super::mtp_gr::MtpAttentionRead,
|
||||
}
|
||||
fn run_blocks(
|
||||
binding: &ModelBinding,
|
||||
input: &MtpInput,
|
||||
(session, draft): (&QwenSession<'_>, &MtpSession),
|
||||
cache: &MoeWeightCache<'_>,
|
||||
transport_failed: &Rc<Cell<bool>>,
|
||||
) -> Result<MtpBlocks> {
|
||||
let read = super::super::mtp_gr::attention_read(binding, input, session, cache)?;
|
||||
let attention = super::super::mtp_attention::MtpAttentionStage::run(
|
||||
binding,
|
||||
&read,
|
||||
draft,
|
||||
session,
|
||||
cache,
|
||||
Rc::clone(transport_failed),
|
||||
)?;
|
||||
let mlp = super::super::mtp_gr::mlp_read(binding, &attention, session, cache)?;
|
||||
let block =
|
||||
super::super::mtp_experts::MtpExpertStage::run(binding, &mlp, session, cache, Rc::clone(transport_failed))?;
|
||||
let final_mixed = super::super::mtp_gr::finalize(binding, &block, &mlp, session, cache)?;
|
||||
if !input.frame.same(final_mixed.frame()) || !input.frame.same(attention.frame()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(MtpBlocks { final_mixed, block, mlp, attention, read })
|
||||
}
|
||||
fn copy_streams(values: &[f32]) -> Result<(Vec<f32>, Vec<f32>)> {
|
||||
let mut streams = reserve(10240)?;
|
||||
streams.extend_from_slice(values);
|
||||
let mut retained = reserve(10240)?;
|
||||
retained.extend_from_slice(&streams);
|
||||
Ok((streams, retained))
|
||||
}
|
||||
fn step_run(
|
||||
binding: &ModelBinding,
|
||||
session: &mut QwenSession<'_>,
|
||||
draft: &mut MtpSession,
|
||||
input: MtpInput,
|
||||
output: Option<&super::super::output::OutputStage<'_, '_>>,
|
||||
(cache, transport_failed): (&MoeWeightCache<'_>, &Rc<Cell<bool>>),
|
||||
) -> Result<Option<MtpStepProduct>> {
|
||||
input.frame.validate(binding, session)?;
|
||||
draft.prior(&input.frame)?;
|
||||
let blocks = run_blocks(binding, &input, (session, draft), cache, transport_failed)?;
|
||||
let predicted = output.map(|head| head.mtp_greedy(binding, blocks.final_mixed.mixed(), session)).transpose()?;
|
||||
let (streams, retained) = copy_streams(blocks.final_mixed.streams())?;
|
||||
// Teardown/synchronization ambiguity is sticky, never erased by rewind.
|
||||
session.finish_mtp_device()?;
|
||||
input.frame.validate(binding, session)?;
|
||||
draft.commit(&input.frame, blocks.attention.into_pending_kv(), retained.into_boxed_slice())?;
|
||||
Ok(predicted.map(|predicted| MtpStepProduct { frame: input.frame, predicted, streams: streams.into_boxed_slice() }))
|
||||
}
|
||||
pub(super) fn step_core(
|
||||
binding: &ModelBinding,
|
||||
session: &mut QwenSession<'_>,
|
||||
@@ -61,45 +121,7 @@ pub(super) fn step_core(
|
||||
cache: &MoeWeightCache<'_>,
|
||||
) -> Result<Option<MtpStepProduct>> {
|
||||
let transport_failed = Rc::new(Cell::new(false));
|
||||
let result = (|| {
|
||||
input.frame.validate(binding, session)?;
|
||||
draft.prior(&input.frame)?;
|
||||
let read = super::super::mtp_gr::attention_read(binding, &input, session, cache)?;
|
||||
let attention = super::super::mtp_attention::MtpAttentionStage::run(
|
||||
binding,
|
||||
&read,
|
||||
draft,
|
||||
session,
|
||||
cache,
|
||||
Rc::clone(&transport_failed),
|
||||
)?;
|
||||
let mlp = super::super::mtp_gr::mlp_read(binding, &attention, session, cache)?;
|
||||
let block = super::super::mtp_experts::MtpExpertStage::run(
|
||||
binding,
|
||||
&mlp,
|
||||
session,
|
||||
cache,
|
||||
Rc::clone(&transport_failed),
|
||||
)?;
|
||||
let final_mixed = super::super::mtp_gr::finalize(binding, &block, &mlp, session, cache)?;
|
||||
if !input.frame.same(final_mixed.frame()) || !input.frame.same(attention.frame()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let predicted = output.map(|head| head.mtp_greedy(binding, final_mixed.mixed(), session)).transpose()?;
|
||||
let mut streams = reserve(10240)?;
|
||||
streams.extend_from_slice(final_mixed.streams());
|
||||
let mut retained = reserve(10240)?;
|
||||
retained.extend_from_slice(&streams);
|
||||
// Teardown/synchronization ambiguity is sticky, never erased by rewind.
|
||||
session.finish_mtp_device()?;
|
||||
input.frame.validate(binding, session)?;
|
||||
draft.commit(&input.frame, attention.into_pending_kv(), retained.into_boxed_slice())?;
|
||||
Ok(predicted.map(|predicted| MtpStepProduct {
|
||||
frame: input.frame,
|
||||
predicted,
|
||||
streams: streams.into_boxed_slice(),
|
||||
}))
|
||||
})();
|
||||
let result = step_run(binding, session, draft, input, output, (cache, &transport_failed));
|
||||
if transport_failed.get() {
|
||||
session.note_mtp_failure(&Error::CudaExecution);
|
||||
}
|
||||
@@ -142,6 +164,17 @@ pub(in super::super) fn f32_weights(
|
||||
out.extend_from_slice(values);
|
||||
Ok(out.into_boxed_slice())
|
||||
}
|
||||
fn norm_launch(
|
||||
context: &Context<'_>,
|
||||
hidden: bool,
|
||||
(x, w, y): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &mut DeviceBuffer<'_>),
|
||||
) -> Result<()> {
|
||||
if hidden { context.mtp_hidden_norm_f32(x, w, y) } else { context.mtp_embedding_norm_f32(x, w, y) }
|
||||
.map_err(driver_error)
|
||||
}
|
||||
fn norm_width(hidden: bool) -> usize {
|
||||
if hidden { 10240 } else { 2560 }
|
||||
}
|
||||
pub(super) fn norm(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
@@ -151,18 +184,36 @@ pub(super) fn norm(
|
||||
cache: &MoeWeightCache<'_>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let gamma = f32_weights(binding, role, cache)?;
|
||||
let n = if hidden { 10240 } else { 2560 };
|
||||
let n = norm_width(hidden);
|
||||
validate_values(values, n)?;
|
||||
validate_values(&gamma, n)?;
|
||||
let x = upload(context, values)?;
|
||||
let (_, _, _, w) = cache.mtp_matrix(binding, context, role)?;
|
||||
let mut y = allocate(context, n)?;
|
||||
if hidden { context.mtp_hidden_norm_f32(&x, w, &mut y) } else { context.mtp_embedding_norm_f32(&x, w, &mut y) }
|
||||
.map_err(driver_error)?;
|
||||
norm_launch(context, hidden, (&x, w, &mut y))?;
|
||||
let result = download(&y, n)?;
|
||||
release([x, y])?;
|
||||
Ok(result)
|
||||
}
|
||||
fn project_kernel(
|
||||
context: &Context<'_>,
|
||||
kind: MtpKind,
|
||||
weights: &DeviceBuffer<'_>,
|
||||
(x, y): (&DeviceBuffer<'_>, &mut DeviceBuffer<'_>),
|
||||
(rows, columns): (usize, usize),
|
||||
) -> Result<()> {
|
||||
match kind {
|
||||
MtpKind::Bf16 => context.bf16_f32(weights, x, y, Bf16ProjectionShape { rows, columns }),
|
||||
MtpKind::Q8_0 => context.project_q8_1(
|
||||
weights,
|
||||
x,
|
||||
y,
|
||||
ProjectionSpec { rows, columns, kind: ProjectionKind::Dense(DenseFormat::Q8_0) },
|
||||
),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
.map_err(driver_error)
|
||||
}
|
||||
/// Bounded exact row tiles of the separately pinned MTP pack. Every numerical
|
||||
/// projection uses the already qualified native CUDA format dispatcher.
|
||||
/// Whole immutable dense role; each original row's projection schedule is unchanged.
|
||||
@@ -181,20 +232,8 @@ pub(in super::super) fn project(
|
||||
preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?;
|
||||
let x = upload(context, input)?;
|
||||
let mut y = allocate(context, rows)?;
|
||||
let result = (|| {
|
||||
match kind {
|
||||
MtpKind::Bf16 => context.bf16_f32(weights, &x, &mut y, Bf16ProjectionShape { rows, columns }),
|
||||
MtpKind::Q8_0 => context.project_q8_1(
|
||||
weights,
|
||||
&x,
|
||||
&mut y,
|
||||
ProjectionSpec { rows, columns, kind: ProjectionKind::Dense(DenseFormat::Q8_0) },
|
||||
),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
.map_err(driver_error)?;
|
||||
download(&y, rows)
|
||||
})();
|
||||
let result =
|
||||
project_kernel(context, kind, weights, (&x, &mut y), (rows, columns)).and_then(|()| download(&y, rows));
|
||||
let cleanup = release([x, y]);
|
||||
let output = result?;
|
||||
cleanup?;
|
||||
|
||||
@@ -39,6 +39,20 @@ pub(super) fn validate_window(keys: &[u8], values: &[u8], geometry: &DenseGeomet
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn norm_rope_launch(
|
||||
context: &Context<'_>,
|
||||
(x, gamma_device): (&DeviceBuffer<'_>, &DeviceBuffer<'_>),
|
||||
(norm, rope): (&mut DeviceBuffer<'_>, &mut DeviceBuffer<'_>),
|
||||
(position, query): (u32, bool),
|
||||
) -> Result<Box<[f32]>> {
|
||||
let count = if query { Q } else { KV };
|
||||
if query { context.qsa_norm_q(x, gamma_device, norm) } else { context.qsa_norm_k(x, gamma_device, norm) }
|
||||
.map_err(attention_driver_error)?;
|
||||
download(norm, count)?;
|
||||
if query { context.qsa_rope_q(norm, position, rope) } else { context.qsa_rope_k(norm, position, rope) }
|
||||
.map_err(attention_driver_error)?;
|
||||
download(rope, count)
|
||||
}
|
||||
pub(super) fn norm_rope(
|
||||
context: &Context<'_>,
|
||||
values: &[f32],
|
||||
@@ -53,27 +67,29 @@ pub(super) fn norm_rope(
|
||||
let x = upload(context, values)?;
|
||||
let mut norm = allocate(context, count)?;
|
||||
let mut rope = allocate(context, count)?;
|
||||
let result: Result<Box<[f32]>> = (|| {
|
||||
if query {
|
||||
context.qsa_norm_q(&x, gamma_device, &mut norm)
|
||||
} else {
|
||||
context.qsa_norm_k(&x, gamma_device, &mut norm)
|
||||
}
|
||||
.map_err(attention_driver_error)?;
|
||||
download(&norm, count)?;
|
||||
if query {
|
||||
context.qsa_rope_q(&norm, position, &mut rope)
|
||||
} else {
|
||||
context.qsa_rope_k(&norm, position, &mut rope)
|
||||
}
|
||||
.map_err(attention_driver_error)?;
|
||||
download(&rope, count)
|
||||
})();
|
||||
let result = norm_rope_launch(context, (&x, gamma_device), (&mut norm, &mut rope), (position, query));
|
||||
let cleanup = release([x, norm, rope]);
|
||||
let result = result?;
|
||||
cleanup?;
|
||||
Ok(result)
|
||||
}
|
||||
fn attend_launch(
|
||||
context: &Context<'_>,
|
||||
(q, keys, values): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>),
|
||||
out: &mut DeviceBuffer<'_>,
|
||||
position: u32,
|
||||
) -> Result<Box<[f32]>> {
|
||||
context.mtp_dense_attend_f16(q, keys, values, out, position).map_err(attention_driver_error)?;
|
||||
download(out, Q)
|
||||
}
|
||||
fn pack_kv_launch(
|
||||
context: &Context<'_>,
|
||||
(k, v): (&DeviceBuffer<'_>, &DeviceBuffer<'_>),
|
||||
(key, value): (&mut DeviceBuffer<'_>, &mut DeviceBuffer<'_>),
|
||||
) -> Result<PackedKv> {
|
||||
context.qsa_pack_kv(k, v, key, value).map_err(attention_driver_error)?;
|
||||
Ok((download_bytes(key, HALF_CELL)?, download_bytes(value, HALF_CELL)?))
|
||||
}
|
||||
pub(super) fn pack_kv(context: &Context<'_>, k: &[f32], v: &[f32]) -> Result<PackedKv> {
|
||||
validate_values(k, KV)?;
|
||||
validate_values(v, KV)?;
|
||||
@@ -81,10 +97,7 @@ pub(super) fn pack_kv(context: &Context<'_>, k: &[f32], v: &[f32]) -> Result<Pac
|
||||
let v = upload(context, v)?;
|
||||
let mut key = context.allocate(HALF_CELL).map_err(attention_driver_error)?;
|
||||
let mut value = context.allocate(HALF_CELL).map_err(attention_driver_error)?;
|
||||
let result: Result<PackedKv> = (|| {
|
||||
context.qsa_pack_kv(&k, &v, &mut key, &mut value).map_err(attention_driver_error)?;
|
||||
Ok((download_bytes(&key, HALF_CELL)?, download_bytes(&value, HALF_CELL)?))
|
||||
})();
|
||||
let result = pack_kv_launch(context, (&k, &v), (&mut key, &mut value));
|
||||
let cleanup = release([k, v, key, value]);
|
||||
let result = result?;
|
||||
cleanup?;
|
||||
@@ -120,12 +133,7 @@ pub(super) fn attend(
|
||||
let keys = upload_bytes(context, keys)?;
|
||||
let values = upload_bytes(context, values)?;
|
||||
let mut out = allocate(context, Q)?;
|
||||
let result: Result<Box<[f32]>> = (|| {
|
||||
context
|
||||
.mtp_dense_attend_f16(&q, &keys, &values, &mut out, geometry.position)
|
||||
.map_err(attention_driver_error)?;
|
||||
download(&out, Q)
|
||||
})();
|
||||
let result = attend_launch(context, (&q, &keys, &values), &mut out, geometry.position);
|
||||
let cleanup = release([q, keys, values, out]);
|
||||
let result = result?;
|
||||
cleanup?;
|
||||
|
||||
+152
-91
@@ -23,6 +23,139 @@ impl MtpAttentionReady {
|
||||
self.pending
|
||||
}
|
||||
}
|
||||
fn validate_read_values(input: &MtpAttentionRead) -> Result<()> {
|
||||
validate_values(input.mixed(), N)?;
|
||||
validate_values(input.streams(), 4 * N)?;
|
||||
validate_values(input.inject(), 4)
|
||||
}
|
||||
/// Every exact descriptor of the pinned pack admitted before row access/CUDA.
|
||||
fn check_roles(binding: &ModelBinding, expected: &[(MtpRole, (MtpKind, usize, usize))]) -> Result<()> {
|
||||
let pack = binding.mtp_weights().map_err(binding_error)?;
|
||||
for (role, expected) in expected {
|
||||
if pack.dense_shape(binding, *role).map_err(binding_error)? != *expected {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The K/V projections, K norm/rope and the packed half-precision cell of one row; the source K/V-before-query
|
||||
/// sequence. No indexer, sparse selection, rotation/INT8/Q4 cache, or target QSA state is substituted.
|
||||
fn packed_kv(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
input: &MtpAttentionRead,
|
||||
(position, cache): (u32, &MoeWeightCache<'_>),
|
||||
) -> Result<PackedKv> {
|
||||
let k = project(context, binding, MtpRole::KeyProjection, input.mixed(), cache)?;
|
||||
let v = project(context, binding, MtpRole::ValueProjection, input.mixed(), cache)?;
|
||||
let kgamma = f32_weights(binding, MtpRole::KeyNorm, cache)?;
|
||||
let (_, _, _, kw) = cache.mtp_matrix(binding, context, MtpRole::KeyNorm)?;
|
||||
let k = norm_rope(context, &k, &kgamma, kw, position, false)?;
|
||||
pack_kv(context, &k, &v)
|
||||
}
|
||||
/// Q and its gate: the query projection split, then the Q norm/rope.
|
||||
fn query_gate(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
input: &MtpAttentionRead,
|
||||
(position, cache): (u32, &MoeWeightCache<'_>),
|
||||
) -> Result<QGate> {
|
||||
let full = project(context, binding, MtpRole::QueryProjection, input.mixed(), cache)?;
|
||||
let (q, gate) = split(context, &full)?;
|
||||
let qgamma = f32_weights(binding, MtpRole::QueryNorm, cache)?;
|
||||
let (_, _, _, qw) = cache.mtp_matrix(binding, context, MtpRole::QueryNorm)?;
|
||||
Ok((norm_rope(context, &q, &qgamma, qw, position, true)?, gate))
|
||||
}
|
||||
/// Frame, prior and descriptor admission, then the context and the budget of the temporary buffers.
|
||||
fn admit_run<'a, 'd>(
|
||||
binding: &ModelBinding,
|
||||
input: &MtpAttentionRead,
|
||||
(draft, session): (&'a MtpSession, &'a QwenSession<'d>),
|
||||
cache: &MoeWeightCache<'_>,
|
||||
) -> Result<(&'a DenseKv, DenseGeometry, &'a Context<'d>, bool)> {
|
||||
input.frame().validate(binding, session)?;
|
||||
let prior = draft.prior(input.frame())?;
|
||||
validate_read_values(input)?;
|
||||
let geometry = geometry(input.frame().position().get())?;
|
||||
check_roles(
|
||||
binding,
|
||||
&[
|
||||
(MtpRole::KeyProjection, (MtpKind::Q8_0, KV, N)),
|
||||
(MtpRole::ValueProjection, (MtpKind::Q8_0, KV, N)),
|
||||
(MtpRole::QueryProjection, (MtpKind::Q8_0, 2 * Q, N)),
|
||||
(MtpRole::AttentionOutput, (MtpKind::Q8_0, N, Q)),
|
||||
(MtpRole::KeyNorm, (MtpKind::F32, 1, 256)),
|
||||
(MtpRole::QueryNorm, (MtpKind::F32, 1, 256)),
|
||||
],
|
||||
)?;
|
||||
let context = session.mtp_context()?;
|
||||
let ring_enabled = cache.has_mtp_kv_ring()?;
|
||||
preflight(context, temporary_bytes(&geometry, ring_enabled)?)?;
|
||||
Ok((prior, geometry, context, ring_enabled))
|
||||
}
|
||||
fn temporary_bytes(geometry: &DenseGeometry, ring_enabled: bool) -> Result<usize> {
|
||||
if ring_enabled {
|
||||
geometry.device_bytes.checked_sub(2 * geometry.half_bytes).ok_or(Error::Overflow)
|
||||
} else {
|
||||
Ok(geometry.device_bytes)
|
||||
}
|
||||
}
|
||||
/// The host half windows of the candidate, or none when the actor's bounded ring mirrors them.
|
||||
fn host_window(
|
||||
(binding, context, cache): (&ModelBinding, &Context<'_>, &MoeWeightCache<'_>),
|
||||
(pending, frame, geometry): (&DenseKv, &MtpFrame, &DenseGeometry),
|
||||
ring_enabled: bool,
|
||||
) -> Result<Option<PackedKv>> {
|
||||
if ring_enabled {
|
||||
cache.prepare_mtp_kv(binding, context, pending, frame)?;
|
||||
return Ok(None);
|
||||
}
|
||||
let window = pending.window(frame)?;
|
||||
validate_window(&window.0, &window.1, geometry)?;
|
||||
Ok(Some(window))
|
||||
}
|
||||
/// Attention output through the closed AttentionOutput consumer; the gated owner is closed after use.
|
||||
fn gated_output<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
(binding, session, cache): (&ModelBinding, &QwenSession<'_>, &MoeWeightCache<'_>),
|
||||
frame: &MtpFrame,
|
||||
(attention, gate): (RetainedAttended<'ctx>, &[f32]),
|
||||
) -> Result<Box<[f32]>> {
|
||||
let gated = MtpGated { frame: frame.clone(), numeric: gate_retained(context, attention, gate)? };
|
||||
let result = project_attention_output(context, binding, session, &gated, cache);
|
||||
let cleanup = gated.close();
|
||||
let output = result?;
|
||||
cleanup?;
|
||||
validate_values(&output, N)?;
|
||||
Ok(output)
|
||||
}
|
||||
fn attend_selected<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
q: &[f32],
|
||||
window: Option<PackedKv>,
|
||||
(geometry, failed): (&DenseGeometry, Rc<Cell<bool>>),
|
||||
(binding, cache, pending, frame): (&ModelBinding, &MoeWeightCache<'_>, &DenseKv, &MtpFrame),
|
||||
) -> Result<RetainedAttended<'ctx>> {
|
||||
match window {
|
||||
Some((keys, values)) => attend_retained(context, q, &keys, &values, geometry, failed),
|
||||
None => attend_ring_retained(context, q, geometry, failed, binding, cache, pending, frame),
|
||||
}
|
||||
}
|
||||
fn revalidate(
|
||||
binding: &ModelBinding,
|
||||
input: &MtpAttentionRead,
|
||||
(draft, session): (&MtpSession, &QwenSession<'_>),
|
||||
) -> Result<()> {
|
||||
input.frame().validate(binding, session)?;
|
||||
draft.prior(input.frame())?;
|
||||
Ok(())
|
||||
}
|
||||
fn ready(input: &MtpAttentionRead, output: Box<[f32]>, pending: DenseKv) -> Result<MtpAttentionReady> {
|
||||
let mut streams = reserve(4 * N)?;
|
||||
streams.extend_from_slice(input.streams());
|
||||
let inject = input.inject().try_into().map_err(|_| Error::InvalidDimension)?;
|
||||
Ok(MtpAttentionReady { frame: input.frame().clone(), output, streams: streams.into_boxed_slice(), inject, pending })
|
||||
}
|
||||
impl MtpAttentionStage {
|
||||
pub(in super::super) fn run(
|
||||
binding: &ModelBinding,
|
||||
@@ -32,79 +165,16 @@ impl MtpAttentionStage {
|
||||
cache: &MoeWeightCache<'_>,
|
||||
failed: Rc<Cell<bool>>,
|
||||
) -> Result<MtpAttentionReady> {
|
||||
input.frame().validate(binding, session)?;
|
||||
let prior = draft.prior(input.frame())?;
|
||||
validate_values(input.mixed(), N)?;
|
||||
validate_values(input.streams(), 4 * N)?;
|
||||
validate_values(input.inject(), 4)?;
|
||||
let geometry = geometry(input.frame().position().get())?;
|
||||
let pack = binding.mtp_weights().map_err(binding_error)?;
|
||||
// All exact descriptors and opaque prior admitted before row access/CUDA.
|
||||
for (role, expected) in [
|
||||
(MtpRole::KeyProjection, (MtpKind::Q8_0, KV, N)),
|
||||
(MtpRole::ValueProjection, (MtpKind::Q8_0, KV, N)),
|
||||
(MtpRole::QueryProjection, (MtpKind::Q8_0, 2 * Q, N)),
|
||||
(MtpRole::AttentionOutput, (MtpKind::Q8_0, N, Q)),
|
||||
(MtpRole::KeyNorm, (MtpKind::F32, 1, 256)),
|
||||
(MtpRole::QueryNorm, (MtpKind::F32, 1, 256)),
|
||||
] {
|
||||
if pack.dense_shape(binding, role).map_err(binding_error)? != expected {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
}
|
||||
let context = session.mtp_context()?;
|
||||
let ring_enabled = cache.has_mtp_kv_ring()?;
|
||||
let temporary_bytes = if ring_enabled {
|
||||
geometry.device_bytes.checked_sub(2 * geometry.half_bytes).ok_or(Error::Overflow)?
|
||||
} else {
|
||||
geometry.device_bytes
|
||||
};
|
||||
preflight(context, temporary_bytes)?;
|
||||
// Preserve the source K/V-before-query sequence. No indexer, sparse
|
||||
// selection, rotation/INT8/Q4 cache, or target QSA state is substituted.
|
||||
let k = project(context, binding, MtpRole::KeyProjection, input.mixed(), cache)?;
|
||||
let v = project(context, binding, MtpRole::ValueProjection, input.mixed(), cache)?;
|
||||
let kgamma = f32_weights(binding, MtpRole::KeyNorm, cache)?;
|
||||
let (_, _, _, kw) = cache.mtp_matrix(binding, context, MtpRole::KeyNorm)?;
|
||||
let k = norm_rope(context, &k, &kgamma, kw, geometry.position, false)?;
|
||||
let (key, value) = pack_kv(context, &k, &v)?;
|
||||
let (prior, geometry, context, ring_enabled) = admit_run(binding, input, (draft, session), cache)?;
|
||||
let (key, value) = packed_kv(context, binding, input, (geometry.position, cache))?;
|
||||
let pending = prior.append(input.frame(), key, value)?;
|
||||
let host_window = if ring_enabled {
|
||||
cache.prepare_mtp_kv(binding, context, &pending, input.frame())?;
|
||||
None
|
||||
} else {
|
||||
let window = pending.window(input.frame())?;
|
||||
validate_window(&window.0, &window.1, &geometry)?;
|
||||
Some(window)
|
||||
};
|
||||
let full = project(context, binding, MtpRole::QueryProjection, input.mixed(), cache)?;
|
||||
let (q, gate) = split(context, &full)?;
|
||||
let qgamma = f32_weights(binding, MtpRole::QueryNorm, cache)?;
|
||||
let (_, _, _, qw) = cache.mtp_matrix(binding, context, MtpRole::QueryNorm)?;
|
||||
let q = norm_rope(context, &q, &qgamma, qw, geometry.position, true)?;
|
||||
let attention = if let Some((keys, values)) = host_window {
|
||||
attend_retained(context, &q, &keys, &values, &geometry, failed)?
|
||||
} else {
|
||||
attend_ring_retained(context, &q, &geometry, failed, binding, cache, &pending, input.frame())?
|
||||
};
|
||||
let gated = MtpGated { frame: input.frame().clone(), numeric: gate_retained(context, attention, &gate)? };
|
||||
let result = project_attention_output(context, binding, session, &gated, cache);
|
||||
let cleanup = gated.close();
|
||||
let output = result?;
|
||||
cleanup?;
|
||||
validate_values(&output, N)?;
|
||||
input.frame().validate(binding, session)?;
|
||||
draft.prior(input.frame())?;
|
||||
let mut streams = reserve(4 * N)?;
|
||||
streams.extend_from_slice(input.streams());
|
||||
let inject = input.inject().try_into().map_err(|_| Error::InvalidDimension)?;
|
||||
Ok(MtpAttentionReady {
|
||||
frame: input.frame().clone(),
|
||||
output,
|
||||
streams: streams.into_boxed_slice(),
|
||||
inject,
|
||||
pending,
|
||||
})
|
||||
let window = host_window((binding, context, cache), (&pending, input.frame(), &geometry), ring_enabled)?;
|
||||
let (q, gate) = query_gate(context, binding, input, (geometry.position, cache))?;
|
||||
let attended = (&geometry, failed);
|
||||
let attention = attend_selected(context, &q, window, attended, (binding, cache, &pending, input.frame()))?;
|
||||
let output = gated_output(context, (binding, session, cache), input.frame(), (attention, &gate))?;
|
||||
revalidate(binding, input, (draft, session))?;
|
||||
ready(input, output, pending)
|
||||
}
|
||||
}
|
||||
/// Actual scalar K/V cell, reusable by the closed prefill coverage owner.
|
||||
@@ -116,28 +186,19 @@ pub(in super::super) fn produce_kv_cell(
|
||||
cache: &MoeWeightCache<'_>,
|
||||
) -> Result<PackedKv> {
|
||||
input.frame().validate(binding, session)?;
|
||||
validate_values(input.mixed(), N)?;
|
||||
validate_values(input.streams(), 4 * N)?;
|
||||
validate_values(input.inject(), 4)?;
|
||||
validate_read_values(input)?;
|
||||
let geometry = geometry(input.frame().position().get())?;
|
||||
let pack = binding.mtp_weights().map_err(binding_error)?;
|
||||
for (role, expected) in [
|
||||
(MtpRole::KeyProjection, (MtpKind::Q8_0, KV, N)),
|
||||
(MtpRole::ValueProjection, (MtpKind::Q8_0, KV, N)),
|
||||
(MtpRole::KeyNorm, (MtpKind::F32, 1, 256)),
|
||||
] {
|
||||
if pack.dense_shape(binding, role).map_err(binding_error)? != expected {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
}
|
||||
check_roles(
|
||||
binding,
|
||||
&[
|
||||
(MtpRole::KeyProjection, (MtpKind::Q8_0, KV, N)),
|
||||
(MtpRole::ValueProjection, (MtpKind::Q8_0, KV, N)),
|
||||
(MtpRole::KeyNorm, (MtpKind::F32, 1, 256)),
|
||||
],
|
||||
)?;
|
||||
let context = session.mtp_context()?;
|
||||
preflight(context, 2 * 1024 * 1024)?;
|
||||
let k = project(context, binding, MtpRole::KeyProjection, input.mixed(), cache)?;
|
||||
let v = project(context, binding, MtpRole::ValueProjection, input.mixed(), cache)?;
|
||||
let kgamma = f32_weights(binding, MtpRole::KeyNorm, cache)?;
|
||||
let (_, _, _, kw) = cache.mtp_matrix(binding, context, MtpRole::KeyNorm)?;
|
||||
let k = norm_rope(context, &k, &kgamma, kw, geometry.position, false)?;
|
||||
let result = pack_kv(context, &k, &v)?;
|
||||
let result = packed_kv(context, binding, input, (geometry.position, cache))?;
|
||||
input.frame().validate(binding, session)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -54,6 +54,75 @@ pub(super) fn upload_transport_f32<'ctx>(
|
||||
}
|
||||
upload_transport(context, &bytes, failed)
|
||||
}
|
||||
/// The step-local device buffers of one attention launch; each is released explicitly, whatever failed.
|
||||
#[derive(Default)]
|
||||
struct AttendBuffers<'ctx> {
|
||||
q: Option<DeviceBuffer<'ctx>>,
|
||||
k: Option<DeviceBuffer<'ctx>>,
|
||||
v: Option<DeviceBuffer<'ctx>>,
|
||||
y: Option<DeviceBuffer<'ctx>>,
|
||||
}
|
||||
impl<'ctx> AttendBuffers<'ctx> {
|
||||
fn upload_window(
|
||||
&mut self,
|
||||
context: &'ctx Context<'ctx>,
|
||||
(query, keys, values): (&[f32], &[u8], &[u8]),
|
||||
failed: &Cell<bool>,
|
||||
) -> Result<()> {
|
||||
self.q = Some(upload_transport_f32(context, query, failed)?);
|
||||
self.k = Some(upload_transport(context, keys, failed)?);
|
||||
self.v = Some(upload_transport(context, values, failed)?);
|
||||
self.y = Some(allocate(context, Q)?);
|
||||
Ok(())
|
||||
}
|
||||
fn attend(&mut self, context: &Context<'_>, position: u32) -> Result<Box<[f32]>> {
|
||||
context
|
||||
.mtp_dense_attend_f16(
|
||||
self.q.as_ref().ok_or(Error::CudaExecution)?,
|
||||
self.k.as_ref().ok_or(Error::CudaExecution)?,
|
||||
self.v.as_ref().ok_or(Error::CudaExecution)?,
|
||||
self.y.as_mut().ok_or(Error::CudaExecution)?,
|
||||
position,
|
||||
)
|
||||
.map_err(attention_driver_error)?;
|
||||
download(self.y.as_ref().ok_or(Error::CudaExecution)?, Q)
|
||||
}
|
||||
fn attend_ring(
|
||||
&mut self,
|
||||
context: &'ctx Context<'ctx>,
|
||||
query: &[f32],
|
||||
failed: &Cell<bool>,
|
||||
(binding, cache, pending, frame): (&ModelBinding, &MoeWeightCache<'_>, &DenseKv, &MtpFrame),
|
||||
) -> Result<Box<[f32]>> {
|
||||
self.q = Some(upload_transport_f32(context, query, failed)?);
|
||||
self.y = Some(allocate(context, Q)?);
|
||||
cache.attend_mtp_kv(
|
||||
binding,
|
||||
context,
|
||||
pending,
|
||||
frame,
|
||||
self.q.as_ref().ok_or(Error::CudaExecution)?,
|
||||
self.y.as_mut().ok_or(Error::CudaExecution)?,
|
||||
)?;
|
||||
download(self.y.as_ref().ok_or(Error::CudaExecution)?, Q)
|
||||
}
|
||||
}
|
||||
/// A failed launch or release withholds the readback; the output buffer is still released first-class.
|
||||
fn finish_retained<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
(result, cleanup): (Result<Box<[f32]>>, Result<()>),
|
||||
y: Option<DeviceBuffer<'ctx>>,
|
||||
failed: Rc<Cell<bool>>,
|
||||
) -> Result<RetainedAttended<'ctx>> {
|
||||
if result.is_err() || cleanup.is_err() {
|
||||
let y_cleanup = release_transport([y], &failed);
|
||||
let _ = result?;
|
||||
cleanup?;
|
||||
y_cleanup?;
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
Ok(RetainedAttended { context, buffer: y, values: result?, failed })
|
||||
}
|
||||
pub(super) fn attend_retained<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
query: &[f32],
|
||||
@@ -68,33 +137,13 @@ pub(super) fn attend_retained<'ctx>(
|
||||
validate_values(query, Q)?;
|
||||
validate_window(keys, values, geometry)?;
|
||||
preflight(context, geometry.device_bytes)?;
|
||||
let (mut q, mut k, mut v, mut y) = (None, None, None, None);
|
||||
let result = (|| {
|
||||
q = Some(upload_transport_f32(context, query, &failed)?);
|
||||
k = Some(upload_transport(context, keys, &failed)?);
|
||||
v = Some(upload_transport(context, values, &failed)?);
|
||||
y = Some(allocate(context, Q)?);
|
||||
context
|
||||
.mtp_dense_attend_f16(
|
||||
q.as_ref().ok_or(Error::CudaExecution)?,
|
||||
k.as_ref().ok_or(Error::CudaExecution)?,
|
||||
v.as_ref().ok_or(Error::CudaExecution)?,
|
||||
y.as_mut().ok_or(Error::CudaExecution)?,
|
||||
geometry.position,
|
||||
)
|
||||
.map_err(attention_driver_error)?;
|
||||
download(y.as_ref().ok_or(Error::CudaExecution)?, Q)
|
||||
})();
|
||||
let mut buffers = AttendBuffers::default();
|
||||
let result = buffers
|
||||
.upload_window(context, (query, keys, values), &failed)
|
||||
.and_then(|()| buffers.attend(context, geometry.position));
|
||||
note_transport(&result, &failed);
|
||||
let cleanup = release_transport([q, k, v], &failed);
|
||||
if result.is_err() || cleanup.is_err() {
|
||||
let y_cleanup = release_transport([y], &failed);
|
||||
let _ = result?;
|
||||
cleanup?;
|
||||
y_cleanup?;
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
Ok(RetainedAttended { context, buffer: y, values: result?, failed })
|
||||
let cleanup = release_transport([buffers.q, buffers.k, buffers.v], &failed);
|
||||
finish_retained(context, (result, cleanup), buffers.y, failed)
|
||||
}
|
||||
// Numeric query/attend/gate/output remains the existing sequence. Only the
|
||||
// canonical K/V ownership moves to the actor's bounded transport mirror.
|
||||
@@ -114,30 +163,57 @@ pub(super) fn attend_ring_retained<'ctx>(
|
||||
}
|
||||
validate_values(query, Q)?;
|
||||
preflight(context, geometry.device_bytes.checked_sub(2 * geometry.half_bytes).ok_or(Error::Overflow)?)?;
|
||||
let (mut q, mut y) = (None, None);
|
||||
let result = (|| {
|
||||
q = Some(upload_transport_f32(context, query, &failed)?);
|
||||
y = Some(allocate(context, Q)?);
|
||||
cache.attend_mtp_kv(
|
||||
binding,
|
||||
context,
|
||||
pending,
|
||||
frame,
|
||||
q.as_ref().ok_or(Error::CudaExecution)?,
|
||||
y.as_mut().ok_or(Error::CudaExecution)?,
|
||||
)?;
|
||||
download(y.as_ref().ok_or(Error::CudaExecution)?, Q)
|
||||
})();
|
||||
let mut buffers = AttendBuffers::default();
|
||||
let result = buffers.attend_ring(context, query, &failed, (binding, cache, pending, frame));
|
||||
note_transport(&result, &failed);
|
||||
let cleanup = release_transport([q], &failed);
|
||||
if result.is_err() || cleanup.is_err() {
|
||||
let y_cleanup = release_transport([y], &failed);
|
||||
let _ = result?;
|
||||
cleanup?;
|
||||
y_cleanup?;
|
||||
let cleanup = release_transport([buffers.q], &failed);
|
||||
finish_retained(context, (result, cleanup), buffers.y, failed)
|
||||
}
|
||||
/// The step-local device buffers of one gate launch.
|
||||
#[derive(Default)]
|
||||
struct GateBuffers<'ctx> {
|
||||
gate: Option<DeviceBuffer<'ctx>>,
|
||||
gated: Option<DeviceBuffer<'ctx>>,
|
||||
}
|
||||
/// The attended buffer, admitted to be this context's, healthy and exactly Q floats.
|
||||
fn gate_source<'a, 'ctx>(
|
||||
context: &Context<'_>,
|
||||
attended: &'a RetainedAttended<'ctx>,
|
||||
gate: &[f32],
|
||||
) -> Result<&'a DeviceBuffer<'ctx>> {
|
||||
if !std::ptr::eq(attended.context, context) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if attended.failed.get() {
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
Ok(RetainedAttended { context, buffer: y, values: result?, failed })
|
||||
validate_values(attended.values(), Q)?;
|
||||
validate_values(gate, Q)?;
|
||||
let source = attended.buffer.as_ref().ok_or(Error::CudaExecution)?;
|
||||
if source.len() != Q * 4 {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
Ok(source)
|
||||
}
|
||||
impl<'ctx> GateBuffers<'ctx> {
|
||||
fn apply(
|
||||
&mut self,
|
||||
context: &'ctx Context<'ctx>,
|
||||
attended: &RetainedAttended<'ctx>,
|
||||
gate: &[f32],
|
||||
) -> Result<Box<[f32]>> {
|
||||
let source = gate_source(context, attended, gate)?;
|
||||
self.gate = Some(upload_transport_f32(context, gate, &attended.failed)?);
|
||||
self.gated = Some(allocate(context, Q)?);
|
||||
context
|
||||
.qsa_gate_f32(
|
||||
source,
|
||||
self.gate.as_ref().ok_or(Error::CudaExecution)?,
|
||||
self.gated.as_mut().ok_or(Error::CudaExecution)?,
|
||||
)
|
||||
.map_err(attention_driver_error)?;
|
||||
download(self.gated.as_ref().ok_or(Error::CudaExecution)?, Q)
|
||||
}
|
||||
}
|
||||
pub(super) fn gate_retained<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
@@ -145,43 +221,19 @@ pub(super) fn gate_retained<'ctx>(
|
||||
gate: &[f32],
|
||||
) -> Result<RetainedGated<'ctx>> {
|
||||
let failed = Rc::clone(&attended.failed);
|
||||
let (mut gate_buffer, mut gated) = (None, None);
|
||||
let result = (|| {
|
||||
if !std::ptr::eq(attended.context, context) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if failed.get() {
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
validate_values(attended.values(), Q)?;
|
||||
validate_values(gate, Q)?;
|
||||
let source = attended.buffer.as_ref().ok_or(Error::CudaExecution)?;
|
||||
if source.len() != Q * 4 {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
gate_buffer = Some(upload_transport_f32(context, gate, &failed)?);
|
||||
gated = Some(allocate(context, Q)?);
|
||||
context
|
||||
.qsa_gate_f32(
|
||||
source,
|
||||
gate_buffer.as_ref().ok_or(Error::CudaExecution)?,
|
||||
gated.as_mut().ok_or(Error::CudaExecution)?,
|
||||
)
|
||||
.map_err(attention_driver_error)?;
|
||||
download(gated.as_ref().ok_or(Error::CudaExecution)?, Q)
|
||||
})();
|
||||
let mut buffers = GateBuffers::default();
|
||||
let result = buffers.apply(context, &attended, gate);
|
||||
note_transport(&result, &failed);
|
||||
let cleanup = release_transport([attended.buffer.take(), gate_buffer], &failed);
|
||||
let cleanup = release_transport([attended.buffer.take(), buffers.gate], &failed);
|
||||
if result.is_err() || cleanup.is_err() {
|
||||
let gated_cleanup = release_transport([gated], &failed);
|
||||
let gated_cleanup = release_transport([buffers.gated], &failed);
|
||||
let _ = result?;
|
||||
cleanup?;
|
||||
gated_cleanup?;
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
Ok(RetainedGated { context, buffer: gated, values: result?, failed })
|
||||
Ok(RetainedGated { context, buffer: buffers.gated, values: result?, failed })
|
||||
}
|
||||
|
||||
pub(super) fn attention_driver_error(error: leleka_cuda_driver::Error) -> Error {
|
||||
match driver_error(error) {
|
||||
Error::Unsupported(_) => Error::Unsupported(Stage::QsaAttention),
|
||||
|
||||
@@ -42,6 +42,34 @@ fn half_kv(width: usize, zero: bool) -> (Vec<u8>, Vec<u8>) {
|
||||
}
|
||||
|
||||
type Legacy = (Box<[f32]>, Box<[f32]>, Box<[f32]>);
|
||||
fn transfer_attend(context: &Context<'_>, query: &[f32], (keys, values): (&[u8], &[u8]), position: u32) -> Box<[f32]> {
|
||||
let q = upload(context, query).unwrap();
|
||||
let k = upload_bytes(context, keys).unwrap();
|
||||
let v = upload_bytes(context, values).unwrap();
|
||||
let mut y = allocate(context, Q).unwrap();
|
||||
context.mtp_dense_attend_f16(&q, &k, &v, &mut y, position).unwrap();
|
||||
let attended = download(&y, Q).unwrap();
|
||||
release([q, k, v, y]).unwrap();
|
||||
attended
|
||||
}
|
||||
fn transfer_gate(context: &Context<'_>, attended: &[f32], gate: &[f32]) -> Box<[f32]> {
|
||||
let a = upload(context, attended).unwrap();
|
||||
let g = upload(context, gate).unwrap();
|
||||
let mut y = allocate(context, Q).unwrap();
|
||||
context.qsa_gate_f32(&a, &g, &mut y).unwrap();
|
||||
let gated = download(&y, Q).unwrap();
|
||||
release([a, g, y]).unwrap();
|
||||
gated
|
||||
}
|
||||
fn transfer_out(context: &Context<'_>, gated: &[f32], matrix: &DeviceBuffer<'_>) -> Box<[f32]> {
|
||||
let a = upload(context, gated).unwrap();
|
||||
let mut y = allocate(context, 2560).unwrap();
|
||||
let spec = ProjectionSpec { rows: 2560, columns: Q, kind: ProjectionKind::Dense(DenseFormat::Q8_0) };
|
||||
context.project_q8_1(matrix, &a, &mut y, spec).unwrap();
|
||||
let out = download(&y, 2560).unwrap();
|
||||
release([a, y]).unwrap();
|
||||
out
|
||||
}
|
||||
fn original_transfer_chain(
|
||||
context: &Context<'_>,
|
||||
query: &[f32],
|
||||
@@ -51,192 +79,27 @@ fn original_transfer_chain(
|
||||
position: u32,
|
||||
matrix: &DeviceBuffer<'_>,
|
||||
) -> Legacy {
|
||||
let q = upload(context, query).unwrap();
|
||||
let k = upload_bytes(context, keys).unwrap();
|
||||
let v = upload_bytes(context, values).unwrap();
|
||||
let mut y = allocate(context, Q).unwrap();
|
||||
context.mtp_dense_attend_f16(&q, &k, &v, &mut y, position).unwrap();
|
||||
let attended = download(&y, Q).unwrap();
|
||||
release([q, k, v, y]).unwrap();
|
||||
let a = upload(context, &attended).unwrap();
|
||||
let g = upload(context, gate).unwrap();
|
||||
let mut y = allocate(context, Q).unwrap();
|
||||
context.qsa_gate_f32(&a, &g, &mut y).unwrap();
|
||||
let gated = download(&y, Q).unwrap();
|
||||
release([a, g, y]).unwrap();
|
||||
let a = upload(context, &gated).unwrap();
|
||||
let mut y = allocate(context, 2560).unwrap();
|
||||
context
|
||||
.project_q8_1(
|
||||
matrix,
|
||||
&a,
|
||||
&mut y,
|
||||
ProjectionSpec { rows: 2560, columns: Q, kind: ProjectionKind::Dense(DenseFormat::Q8_0) },
|
||||
)
|
||||
.unwrap();
|
||||
let out = download(&y, 2560).unwrap();
|
||||
release([a, y]).unwrap();
|
||||
let attended = transfer_attend(context, query, (keys, values), position);
|
||||
let gated = transfer_gate(context, &attended, gate);
|
||||
let out = transfer_out(context, &gated, matrix);
|
||||
(attended, gated, out)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "root schedules one changed MTP attended/gated/Out transport proof"]
|
||||
fn retained_mtp_attention_gate_out_matches_legacy_transfers_and_cleans_refusals() {
|
||||
let driver = Driver::load().unwrap();
|
||||
let device = driver.device(0).unwrap();
|
||||
let context = device.create_context(160 * 1024 * 1024).unwrap();
|
||||
let failed = Rc::new(Cell::new(false));
|
||||
let weights = out_weights();
|
||||
let matrix = upload_bytes(&context, &weights).unwrap();
|
||||
for (position, zero) in [(0u32, false), (64, true)] {
|
||||
let shape = geometry(u64::from(position)).unwrap();
|
||||
let width = shape.width;
|
||||
let query: Vec<f32> = (0..Q)
|
||||
.map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { (i % 17) as f32 / 64. - 8. / 64. })
|
||||
.collect();
|
||||
let gate: Vec<f32> = (0..Q)
|
||||
.map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { (i % 13) as f32 / 8. - 6. / 8. })
|
||||
.collect();
|
||||
let query_bits: Vec<u32> = query.iter().map(|v| v.to_bits()).collect();
|
||||
let gate_bits: Vec<u32> = gate.iter().map(|v| v.to_bits()).collect();
|
||||
let (keys, values) = half_kv(width, zero);
|
||||
let legacy = original_transfer_chain(&context, &query, &keys, &values, &gate, position, &matrix);
|
||||
let charged = context.allocated_bytes();
|
||||
let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap();
|
||||
exact(attended.values(), &legacy.0);
|
||||
assert_eq!(context.allocated_bytes(), charged + Q * 4);
|
||||
let gated = gate_retained(&context, attended, &gate).unwrap();
|
||||
exact(gated.values(), &legacy.1);
|
||||
assert_eq!(context.allocated_bytes(), charged + Q * 4);
|
||||
let mut actual_bytes = vec![0; Q * 4];
|
||||
gated.buffer(&context).unwrap().copy_to(&mut actual_bytes).unwrap();
|
||||
assert_eq!(actual_bytes, legacy.1.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
|
||||
let actual = super::super::mtp::project_attention_out_numeric(&context, &matrix, &gated).unwrap();
|
||||
exact(&actual, &legacy.2);
|
||||
gated.close().unwrap();
|
||||
assert_eq!(context.allocated_bytes(), charged);
|
||||
assert_eq!(query.iter().map(|v| v.to_bits()).collect::<Vec<_>>(), query_bits);
|
||||
assert_eq!(gate.iter().map(|v| v.to_bits()).collect::<Vec<_>>(), gate_bits);
|
||||
println!("MTP_RETAINED PAIR width={width} zero={zero} exact_words=14848");
|
||||
}
|
||||
let mut unchanged = vec![0; weights.len()];
|
||||
matrix.copy_to(&mut unchanged).unwrap();
|
||||
assert_eq!(unchanged, weights);
|
||||
matrix.release().unwrap();
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
|
||||
let query = vec![0.125; Q];
|
||||
let gate = vec![0.25; Q];
|
||||
let (keys, values) = half_kv(1, false);
|
||||
let shape = geometry(0).unwrap();
|
||||
assert_eq!(
|
||||
attend_retained(&context, &query[..Q - 1], &keys, &values, &shape, failed.clone()).err(),
|
||||
Some(Error::InvalidDimension)
|
||||
);
|
||||
let mut bad_query = query.clone();
|
||||
bad_query[Q - 1] = f32::from_bits(0x7fc00001);
|
||||
assert_eq!(
|
||||
attend_retained(&context, &bad_query, &keys, &values, &shape, failed.clone()).err(),
|
||||
Some(Error::NonFinite)
|
||||
);
|
||||
assert_eq!(
|
||||
attend_retained(&context, &query, &keys[..1022], &values, &shape, failed.clone()).err(),
|
||||
Some(Error::InvalidDimension)
|
||||
);
|
||||
let mut bad_keys = keys.clone();
|
||||
bad_keys[1022..].copy_from_slice(&0x7c00u16.to_le_bytes());
|
||||
assert_eq!(
|
||||
attend_retained(&context, &query, &bad_keys, &values, &shape, failed.clone()).err(),
|
||||
Some(Error::NonFinite)
|
||||
);
|
||||
let mut bad_values = values.clone();
|
||||
bad_values[1022..].copy_from_slice(&0x7e01u16.to_le_bytes());
|
||||
assert_eq!(
|
||||
attend_retained(&context, &query, &keys, &bad_values, &shape, failed.clone()).err(),
|
||||
Some(Error::NonFinite)
|
||||
);
|
||||
// All operands are finite, but the original F32 dot overflows. The actual
|
||||
// retained attention's full D2H rejects before a gate can mask the failure.
|
||||
assert_eq!(
|
||||
attend_retained(
|
||||
&context,
|
||||
&vec![f32::MAX; Q],
|
||||
&0x7bffu16.to_le_bytes().repeat(512),
|
||||
&values,
|
||||
&shape,
|
||||
failed.clone()
|
||||
)
|
||||
.err(),
|
||||
Some(Error::NonFinite)
|
||||
);
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
assert!(!failed.get());
|
||||
|
||||
// Successful abandoned owners exercise the new Drop fallback. This is
|
||||
// ownership/abort evidence only, not an additional numeric oracle pair.
|
||||
let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap();
|
||||
attended.close().unwrap();
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap();
|
||||
let abandoned = gate_retained(&context, attended, &gate).unwrap();
|
||||
assert_eq!(context.allocated_bytes(), Q * 4);
|
||||
drop(abandoned);
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
assert!(!failed.get());
|
||||
|
||||
let env = Env { context: &context, failed: Rc::new(Cell::new(false)) };
|
||||
env.pair_cases();
|
||||
let tiny = Tiny::new();
|
||||
env.attend_shape_refusals(&tiny);
|
||||
env.attend_overflow_refusal(&tiny);
|
||||
env.abandoned_owners(&tiny);
|
||||
let foreign = device.create_context(160 * 1024 * 1024).unwrap();
|
||||
let mut bad_gate = gate.clone();
|
||||
bad_gate[Q - 1] = f32::NAN;
|
||||
for malformed in [&bad_gate[..], &gate[..Q - 1]] {
|
||||
let expected = if malformed.len() == Q { Error::NonFinite } else { Error::InvalidDimension };
|
||||
let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap();
|
||||
assert_eq!(gate_retained(&context, attended, malformed).err(), Some(expected));
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
}
|
||||
let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap();
|
||||
assert_eq!(gate_retained(&foreign, attended, &gate).err(), Some(Error::IdentityMismatch));
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
assert_eq!(foreign.allocated_bytes(), 0);
|
||||
|
||||
let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap();
|
||||
let gated = gate_retained(&context, attended, &gate).unwrap();
|
||||
assert_eq!(gated.buffer(&foreign).err(), Some(Error::IdentityMismatch));
|
||||
let malformed = upload_bytes(&context, &[0; 2]).unwrap();
|
||||
let charged = context.allocated_bytes();
|
||||
assert_eq!(
|
||||
super::super::mtp::project_attention_out_numeric(&context, &malformed, &gated).err(),
|
||||
Some(Error::InvalidDimension)
|
||||
);
|
||||
assert_eq!(context.allocated_bytes(), charged);
|
||||
malformed.release().unwrap();
|
||||
let mut bad_weights = out_weights();
|
||||
let end = bad_weights.len();
|
||||
bad_weights[end - 34..end - 32].copy_from_slice(&0x7c00u16.to_le_bytes());
|
||||
let matrix = upload_bytes(&context, &bad_weights).unwrap();
|
||||
let charged = context.allocated_bytes();
|
||||
assert_eq!(
|
||||
super::super::mtp::project_attention_out_numeric(&context, &matrix, &gated).err(),
|
||||
Some(Error::NonFinite)
|
||||
);
|
||||
assert_eq!(context.allocated_bytes(), charged);
|
||||
assert!(!failed.get());
|
||||
// Explicit shared-policy flag, not injected device failure. No operation
|
||||
// may clear it; teardown still frees the actual successful owner and matrix.
|
||||
failed.set(true);
|
||||
assert_eq!(
|
||||
attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).err(),
|
||||
Some(Error::CudaExecution)
|
||||
);
|
||||
assert_eq!(gated.buffer(&context).err(), Some(Error::CudaExecution));
|
||||
assert_eq!(
|
||||
super::super::mtp::project_attention_out_numeric(&context, &matrix, &gated).err(),
|
||||
Some(Error::CudaExecution)
|
||||
);
|
||||
assert_eq!(context.allocated_bytes(), charged);
|
||||
assert_eq!(gated.close(), Err(Error::CudaExecution));
|
||||
matrix.release().unwrap();
|
||||
assert!(failed.get());
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
env.gate_refusals(&tiny, &foreign);
|
||||
let (gated, matrix) = env.out_refusals(&tiny, &foreign);
|
||||
env.failed_policy(&tiny, gated, matrix);
|
||||
context.synchronize().unwrap();
|
||||
context.close().unwrap();
|
||||
foreign.close().unwrap();
|
||||
@@ -244,3 +107,7 @@ fn retained_mtp_attention_gate_out_matches_legacy_transfers_and_cleans_refusals(
|
||||
"MTP_RETAINED COMPLETE exact_words=29696 finite_cases=2 guard_refusals=15 abort_cleanup_cases=2 allocated=0"
|
||||
);
|
||||
}
|
||||
|
||||
#[path = "mtp_attention_reuse_gpu/phases_fn.rs"]
|
||||
mod phases_fn;
|
||||
use phases_fn::{Env, Tiny};
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
//! The phases of the retained attention proof (one body per phase, STRA-338).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// One context and the shared failure bit every phase works against.
|
||||
pub(super) struct Env<'c> {
|
||||
pub(super) context: &'c Context<'c>,
|
||||
pub(super) failed: Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
/// The one-cell window and the constant query/gate of the refusal phases.
|
||||
pub(super) struct Tiny {
|
||||
query: Vec<f32>,
|
||||
gate: Vec<f32>,
|
||||
keys: Vec<u8>,
|
||||
values: Vec<u8>,
|
||||
shape: DenseGeometry,
|
||||
}
|
||||
|
||||
impl Tiny {
|
||||
pub(super) fn new() -> Self {
|
||||
let (keys, values) = half_kv(1, false);
|
||||
Self { query: vec![0.125; Q], gate: vec![0.25; Q], keys, values, shape: geometry(0).unwrap() }
|
||||
}
|
||||
}
|
||||
|
||||
fn bits(values: &[f32]) -> Vec<u32> {
|
||||
values.iter().map(|v| v.to_bits()).collect()
|
||||
}
|
||||
|
||||
fn pair_inputs(zero: bool) -> (Vec<f32>, Vec<f32>) {
|
||||
let query = (0..Q)
|
||||
.map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { (i % 17) as f32 / 64. - 8. / 64. })
|
||||
.collect();
|
||||
let gate =
|
||||
(0..Q).map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { (i % 13) as f32 / 8. - 6. / 8. }).collect();
|
||||
(query, gate)
|
||||
}
|
||||
|
||||
impl<'c> Env<'c> {
|
||||
fn pair_case(&self, matrix: &DeviceBuffer<'_>, position: u32, zero: bool) {
|
||||
let context = self.context;
|
||||
let shape = geometry(u64::from(position)).unwrap();
|
||||
let width = shape.width;
|
||||
let (query, gate) = pair_inputs(zero);
|
||||
let (query_bits, gate_bits) = (bits(&query), bits(&gate));
|
||||
let (keys, values) = half_kv(width, zero);
|
||||
let legacy = original_transfer_chain(context, &query, &keys, &values, &gate, position, matrix);
|
||||
let charged = context.allocated_bytes();
|
||||
let attended = attend_retained(context, &query, &keys, &values, &shape, self.failed.clone()).unwrap();
|
||||
exact(attended.values(), &legacy.0);
|
||||
assert_eq!(context.allocated_bytes(), charged + Q * 4);
|
||||
let gated = gate_retained(context, attended, &gate).unwrap();
|
||||
exact(gated.values(), &legacy.1);
|
||||
assert_eq!(context.allocated_bytes(), charged + Q * 4);
|
||||
let mut actual_bytes = vec![0; Q * 4];
|
||||
gated.buffer(context).unwrap().copy_to(&mut actual_bytes).unwrap();
|
||||
assert_eq!(actual_bytes, legacy.1.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
|
||||
let actual = crate::qwen_forward::mtp::project_attention_out_numeric(context, matrix, &gated).unwrap();
|
||||
exact(&actual, &legacy.2);
|
||||
gated.close().unwrap();
|
||||
assert_eq!(context.allocated_bytes(), charged);
|
||||
assert_eq!(bits(&query), query_bits);
|
||||
assert_eq!(bits(&gate), gate_bits);
|
||||
println!("MTP_RETAINED PAIR width={width} zero={zero} exact_words=14848");
|
||||
}
|
||||
pub(super) fn pair_cases(&self) {
|
||||
let weights = out_weights();
|
||||
let matrix = upload_bytes(self.context, &weights).unwrap();
|
||||
for (position, zero) in [(0u32, false), (64, true)] {
|
||||
self.pair_case(&matrix, position, zero);
|
||||
}
|
||||
let mut unchanged = vec![0; weights.len()];
|
||||
matrix.copy_to(&mut unchanged).unwrap();
|
||||
assert_eq!(unchanged, weights);
|
||||
matrix.release().unwrap();
|
||||
assert_eq!(self.context.allocated_bytes(), 0);
|
||||
}
|
||||
pub(super) fn attend_shape_refusals(&self, t: &Tiny) {
|
||||
let (context, shape, failed) = (self.context, &t.shape, &self.failed);
|
||||
let attend = |query: &[f32], keys: &[u8], values: &[u8]| {
|
||||
attend_retained(context, query, keys, values, shape, failed.clone()).err()
|
||||
};
|
||||
assert_eq!(attend(&t.query[..Q - 1], &t.keys, &t.values), Some(Error::InvalidDimension));
|
||||
let mut bad_query = t.query.clone();
|
||||
bad_query[Q - 1] = f32::from_bits(0x7fc00001);
|
||||
assert_eq!(attend(&bad_query, &t.keys, &t.values), Some(Error::NonFinite));
|
||||
assert_eq!(attend(&t.query, &t.keys[..1022], &t.values), Some(Error::InvalidDimension));
|
||||
let mut bad_keys = t.keys.clone();
|
||||
bad_keys[1022..].copy_from_slice(&0x7c00u16.to_le_bytes());
|
||||
assert_eq!(attend(&t.query, &bad_keys, &t.values), Some(Error::NonFinite));
|
||||
let mut bad_values = t.values.clone();
|
||||
bad_values[1022..].copy_from_slice(&0x7e01u16.to_le_bytes());
|
||||
assert_eq!(attend(&t.query, &t.keys, &bad_values), Some(Error::NonFinite));
|
||||
}
|
||||
pub(super) fn attend_overflow_refusal(&self, t: &Tiny) {
|
||||
// All operands are finite, but the original F32 dot overflows. The actual
|
||||
// retained attention's full D2H rejects before a gate can mask the failure.
|
||||
assert_eq!(
|
||||
attend_retained(
|
||||
self.context,
|
||||
&vec![f32::MAX; Q],
|
||||
&0x7bffu16.to_le_bytes().repeat(512),
|
||||
&t.values,
|
||||
&t.shape,
|
||||
self.failed.clone()
|
||||
)
|
||||
.err(),
|
||||
Some(Error::NonFinite)
|
||||
);
|
||||
assert_eq!(self.context.allocated_bytes(), 0);
|
||||
assert!(!self.failed.get());
|
||||
}
|
||||
fn attended(&self, t: &Tiny) -> RetainedAttended<'c> {
|
||||
attend_retained(self.context, &t.query, &t.keys, &t.values, &t.shape, self.failed.clone()).unwrap()
|
||||
}
|
||||
pub(super) fn abandoned_owners(&self, t: &Tiny) {
|
||||
// Successful abandoned owners exercise the new Drop fallback. This is
|
||||
// ownership/abort evidence only, not an additional numeric oracle pair.
|
||||
let context = self.context;
|
||||
self.attended(t).close().unwrap();
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
let abandoned = gate_retained(context, self.attended(t), &t.gate).unwrap();
|
||||
assert_eq!(context.allocated_bytes(), Q * 4);
|
||||
drop(abandoned);
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
assert!(!self.failed.get());
|
||||
}
|
||||
pub(super) fn gate_refusals(&self, t: &Tiny, foreign: &Context<'_>) {
|
||||
let context = self.context;
|
||||
let mut bad_gate = t.gate.clone();
|
||||
bad_gate[Q - 1] = f32::NAN;
|
||||
for malformed in [&bad_gate[..], &t.gate[..Q - 1]] {
|
||||
let expected = if malformed.len() == Q { Error::NonFinite } else { Error::InvalidDimension };
|
||||
assert_eq!(gate_retained(context, self.attended(t), malformed).err(), Some(expected));
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
}
|
||||
assert_eq!(gate_retained(foreign, self.attended(t), &t.gate).err(), Some(Error::IdentityMismatch));
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
assert_eq!(foreign.allocated_bytes(), 0);
|
||||
}
|
||||
/// The malformed Out weights and the foreign context refuse; returns the live gated owner and the bad-weights
|
||||
/// matrix for the failure-policy phase.
|
||||
pub(super) fn out_refusals(&self, t: &Tiny, foreign: &Context<'_>) -> (RetainedGated<'c>, DeviceBuffer<'c>) {
|
||||
let context = self.context;
|
||||
let gated = gate_retained(context, self.attended(t), &t.gate).unwrap();
|
||||
assert_eq!(gated.buffer(foreign).err(), Some(Error::IdentityMismatch));
|
||||
let malformed = upload_bytes(context, &[0; 2]).unwrap();
|
||||
let charged = context.allocated_bytes();
|
||||
let refused = crate::qwen_forward::mtp::project_attention_out_numeric(context, &malformed, &gated).err();
|
||||
assert_eq!(refused, Some(Error::InvalidDimension));
|
||||
assert_eq!(context.allocated_bytes(), charged);
|
||||
malformed.release().unwrap();
|
||||
let mut bad_weights = out_weights();
|
||||
let end = bad_weights.len();
|
||||
bad_weights[end - 34..end - 32].copy_from_slice(&0x7c00u16.to_le_bytes());
|
||||
let matrix = upload_bytes(context, &bad_weights).unwrap();
|
||||
let charged = context.allocated_bytes();
|
||||
let refused = crate::qwen_forward::mtp::project_attention_out_numeric(context, &matrix, &gated).err();
|
||||
assert_eq!(refused, Some(Error::NonFinite));
|
||||
assert_eq!(context.allocated_bytes(), charged);
|
||||
assert!(!self.failed.get());
|
||||
(gated, matrix)
|
||||
}
|
||||
/// Explicit shared-policy flag, not injected device failure. No operation
|
||||
/// may clear it; teardown still frees the actual successful owner and matrix.
|
||||
pub(super) fn failed_policy(&self, t: &Tiny, gated: RetainedGated<'c>, matrix: DeviceBuffer<'c>) {
|
||||
let context = self.context;
|
||||
let charged = context.allocated_bytes();
|
||||
self.failed.set(true);
|
||||
assert_eq!(
|
||||
attend_retained(context, &t.query, &t.keys, &t.values, &t.shape, self.failed.clone()).err(),
|
||||
Some(Error::CudaExecution)
|
||||
);
|
||||
assert_eq!(gated.buffer(context).err(), Some(Error::CudaExecution));
|
||||
let refused = crate::qwen_forward::mtp::project_attention_out_numeric(context, &matrix, &gated).err();
|
||||
assert_eq!(refused, Some(Error::CudaExecution));
|
||||
assert_eq!(context.allocated_bytes(), charged);
|
||||
assert_eq!(gated.close(), Err(Error::CudaExecution));
|
||||
matrix.release().unwrap();
|
||||
assert!(self.failed.get());
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,52 @@ impl MtpDecoder {
|
||||
}
|
||||
}
|
||||
|
||||
/// The chunk's span and a private copy of its sealed rows; a chunk of an unsupported width is refused.
|
||||
fn snapshot_rows(
|
||||
txn: &QwenChunkTxn<'_, '_>,
|
||||
) -> Result<(u64, u64, Vec<crate::qwen_forward::session::chunk::ChunkRowResidual>)> {
|
||||
let start = txn.start_position();
|
||||
let end = txn.end_position();
|
||||
let count = end.checked_sub(start).ok_or(Error::InvalidPosition)?;
|
||||
if !(1..=txn.warm_row_limit() as u64).contains(&count) || txn.rows().len() as u64 != count {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut rows = reserve(txn.rows().len())?;
|
||||
rows.extend(txn.rows().iter().cloned());
|
||||
Ok((start, end, rows))
|
||||
}
|
||||
fn check_cancelled(cancelled: &mut impl FnMut() -> bool) -> Result<()> {
|
||||
if cancelled() { Err(Error::Unsupported(super::super::contract::Stage::Executor)) } else { Ok(()) }
|
||||
}
|
||||
/// Warms the draft with every row that has a known next token; only the final row may lack one.
|
||||
fn warm_rows(
|
||||
binding: &ModelBinding,
|
||||
txn: &mut QwenChunkTxn<'_, '_>,
|
||||
rows: &[crate::qwen_forward::session::chunk::ChunkRowResidual],
|
||||
stage: &mut mtp::MtpChunkStage<'_>,
|
||||
(start, cache): (u64, &MoeWeightCache<'_>),
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<usize> {
|
||||
let mut warmed = 0;
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
check_cancelled(cancelled)?;
|
||||
let (_, position, next, _) = txn.validate_row(row)?;
|
||||
if position.get() != start.checked_add(index as u64).ok_or(Error::Overflow)? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if next.is_none() {
|
||||
if index + 1 != rows.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
mtp::warm_chunk_row(binding, txn, row, stage, cache)?;
|
||||
check_cancelled(cancelled)?;
|
||||
warmed += 1;
|
||||
}
|
||||
Ok(warmed)
|
||||
}
|
||||
|
||||
impl MtpDecoder {
|
||||
pub(in crate::qwen_forward) fn stage_prefill_chunk<'draft, 'binding>(
|
||||
&'draft mut self,
|
||||
@@ -65,36 +111,9 @@ impl MtpDecoder {
|
||||
cache: &MoeWeightCache<'_>,
|
||||
mut cancelled: impl FnMut() -> bool,
|
||||
) -> Result<ReadyMtpChunk<'draft, 'binding>> {
|
||||
let start = txn.start_position();
|
||||
let end = txn.end_position();
|
||||
let count = end.checked_sub(start).ok_or(Error::InvalidPosition)?;
|
||||
if !(1..=txn.warm_row_limit() as u64).contains(&count) || txn.rows().len() as u64 != count {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut rows = reserve(txn.rows().len())?;
|
||||
rows.extend(txn.rows().iter().cloned());
|
||||
let (start, end, rows) = snapshot_rows(txn)?;
|
||||
let mut stage = self.draft.stage_chunk(binding, txn)?;
|
||||
let mut warmed = 0;
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(super::super::contract::Stage::Executor));
|
||||
}
|
||||
let (_, position, next, _) = txn.validate_row(row)?;
|
||||
if position.get() != start.checked_add(index as u64).ok_or(Error::Overflow)? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if next.is_none() {
|
||||
if index + 1 != rows.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
mtp::warm_chunk_row(binding, txn, row, &mut stage, cache)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(super::super::contract::Stage::Executor));
|
||||
}
|
||||
warmed += 1;
|
||||
}
|
||||
let warmed = warm_rows(binding, txn, &rows, &mut stage, (start, cache), &mut cancelled)?;
|
||||
let draft_end = start.checked_add(warmed as u64).ok_or(Error::Overflow)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(super::super::contract::Stage::Executor));
|
||||
@@ -105,15 +124,15 @@ impl MtpDecoder {
|
||||
}
|
||||
}
|
||||
|
||||
impl ChunkDraftPublication for ReadyMtpChunk<'_, '_> {
|
||||
fn validate(&self, txn: &QwenChunkTxn<'_, '_>) -> Result<()> {
|
||||
if txn.start_position() != self.start
|
||||
|| txn.end_position() != self.end
|
||||
|| txn.rows().is_empty()
|
||||
|| txn.rows().len() as u64 != self.end.checked_sub(self.start).ok_or(Error::Overflow)?
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
impl ReadyMtpChunk<'_, '_> {
|
||||
fn matches_span(&self, txn: &QwenChunkTxn<'_, '_>) -> Result<bool> {
|
||||
Ok(txn.start_position() == self.start
|
||||
&& txn.end_position() == self.end
|
||||
&& !txn.rows().is_empty()
|
||||
&& txn.rows().len() as u64 == self.end.checked_sub(self.start).ok_or(Error::Overflow)?)
|
||||
}
|
||||
/// The rows with a known next token; only the final row may lack one, each at its chunk position.
|
||||
fn count_warmed(&self, txn: &QwenChunkTxn<'_, '_>) -> Result<usize> {
|
||||
let mut warmed = 0;
|
||||
for (index, row) in txn.rows().iter().enumerate() {
|
||||
let (_, position, next, _) = txn.validate_row(row)?;
|
||||
@@ -126,12 +145,21 @@ impl ChunkDraftPublication for ReadyMtpChunk<'_, '_> {
|
||||
None => return Err(Error::IdentityMismatch),
|
||||
}
|
||||
}
|
||||
Ok(warmed)
|
||||
}
|
||||
}
|
||||
|
||||
impl ChunkDraftPublication for ReadyMtpChunk<'_, '_> {
|
||||
fn validate(&self, txn: &QwenChunkTxn<'_, '_>) -> Result<()> {
|
||||
if !self.matches_span(txn)? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let warmed = self.count_warmed(txn)?;
|
||||
if warmed != self.warmed || self.start.checked_add(warmed as u64) != Some(self.draft_end) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.stage.validate_completed(self.binding, txn.original_session()?, self.draft_end)
|
||||
}
|
||||
|
||||
fn publish(self) {
|
||||
self.stage.publish();
|
||||
}
|
||||
|
||||
@@ -63,10 +63,7 @@ struct Report {
|
||||
guards: usize,
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Root-only exact pinned binding/one load/changed GPU boundary; no live overlap"]
|
||||
fn authentic_scalar_first_mtp_batch_prefix_rejection_cancel_and_cleanup() {
|
||||
assert!(env::var("LELEKA_STRA169_RUN_MTP_BATCH_NUMERIC").is_ok_and(|v| v == "yes"));
|
||||
fn open_binding() -> (ModelBinding, InheritedKarArchive) {
|
||||
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("sealed FD missing").parse().unwrap();
|
||||
assert!((3..=1048576).contains(&fd));
|
||||
let shard0 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).unwrap();
|
||||
@@ -80,15 +77,24 @@ fn authentic_scalar_first_mtp_batch_prefix_rejection_cancel_and_cleanup() {
|
||||
&path("LELEKA_STRA169_MTP_STAGING"),
|
||||
)
|
||||
.unwrap();
|
||||
let driver = Driver::load().unwrap();
|
||||
let device = driver.device(0).unwrap();
|
||||
let context = Rc::new(device.create_context(28 * 1024 * 1024 * 1024).unwrap());
|
||||
let output = OutputStage::load(&binding, context.as_ref()).unwrap();
|
||||
let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap();
|
||||
let mut cache = Some(MoeWeightCache::new(&binding, context.as_ref()).unwrap());
|
||||
let dense = DenseWeightCache::new(&binding, context.as_ref()).unwrap();
|
||||
let numerical =
|
||||
catch_unwind(AssertUnwindSafe(|| check_loaded(&binding, &context, &output, &mut kar, &mut cache, &dense)));
|
||||
(binding, inherited)
|
||||
}
|
||||
|
||||
/// What the teardown of the loaded stages established; the context itself is closed by the caller afterwards.
|
||||
struct Teardown {
|
||||
disabled: Result<()>,
|
||||
cache_closed: Option<Result<()>>,
|
||||
dense_closed: Result<()>,
|
||||
sync: std::result::Result<(), leleka_cuda_driver::Error>,
|
||||
allocated: usize,
|
||||
}
|
||||
|
||||
fn teardown(
|
||||
context: &Rc<leleka_cuda_driver::Context<'_>>,
|
||||
output: OutputStage<'_, '_>,
|
||||
kar: KarPleCache<'_>,
|
||||
(cache, dense): (Option<MoeWeightCache<'_>>, DenseWeightCache<'_>),
|
||||
) -> Teardown {
|
||||
COLLECTOR.with(|s| {
|
||||
s.borrow_mut().take();
|
||||
});
|
||||
@@ -98,6 +104,7 @@ fn authentic_scalar_first_mtp_batch_prefix_rejection_cancel_and_cleanup() {
|
||||
let drained = output.test_reset_replay_take_logits();
|
||||
drop(drained);
|
||||
let disabled = output.test_reset_replay_record(false);
|
||||
let mut cache = cache;
|
||||
let cache_closed = cache.take().map(MoeWeightCache::close);
|
||||
drop(cache);
|
||||
let dense_closed = dense.close();
|
||||
@@ -105,17 +112,13 @@ fn authentic_scalar_first_mtp_batch_prefix_rejection_cancel_and_cleanup() {
|
||||
drop(output);
|
||||
let sync = context.synchronize();
|
||||
let allocated = context.allocated_bytes();
|
||||
let closed = Rc::try_unwrap(context).ok().map(|c| c.close());
|
||||
drop(binding);
|
||||
drop(inherited);
|
||||
let report = match numerical {
|
||||
Ok(r) => r,
|
||||
Err(primary) => resume_unwind(primary),
|
||||
};
|
||||
assert!(disabled.is_ok() && matches!(cache_closed, Some(Ok(()))) && dense_closed.is_ok());
|
||||
assert!(sync.is_ok() && allocated == 0 && matches!(closed, Some(Ok(()))));
|
||||
Teardown { disabled, cache_closed, dense_closed, sync, allocated }
|
||||
}
|
||||
|
||||
fn print_report(report: &Report) {
|
||||
eprintln!(
|
||||
"MTP_BATCH_OBSERVATION compared_head_residual_words={} predicates={} guards={} allocated_bytes=0 context_closed=true speed_claim=false",
|
||||
"MTP_BATCH_OBSERVATION compared_head_residual_words={} predicates={} guards={} allocated_bytes=0 \
|
||||
context_closed=true speed_claim=false",
|
||||
report.words,
|
||||
report.predicates.len(),
|
||||
report.guards
|
||||
@@ -124,6 +127,32 @@ fn authentic_scalar_first_mtp_batch_prefix_rejection_cancel_and_cleanup() {
|
||||
eprintln!("MTP_BATCH_COMPLETE exact=true allocated_bytes=0 context_closed=true speed_claim=false");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Root-only exact pinned binding/one load/changed GPU boundary; no live overlap"]
|
||||
fn authentic_scalar_first_mtp_batch_prefix_rejection_cancel_and_cleanup() {
|
||||
assert!(env::var("LELEKA_STRA169_RUN_MTP_BATCH_NUMERIC").is_ok_and(|v| v == "yes"));
|
||||
let (binding, inherited) = open_binding();
|
||||
let driver = Driver::load().unwrap();
|
||||
let device = driver.device(0).unwrap();
|
||||
let context = Rc::new(device.create_context(28 * 1024 * 1024 * 1024).unwrap());
|
||||
let output = OutputStage::load(&binding, context.as_ref()).unwrap();
|
||||
let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap();
|
||||
let mut cache = Some(MoeWeightCache::new(&binding, context.as_ref()).unwrap());
|
||||
let dense = DenseWeightCache::new(&binding, context.as_ref()).unwrap();
|
||||
let numerical =
|
||||
catch_unwind(AssertUnwindSafe(|| check_loaded(&binding, &context, &output, &mut kar, &mut cache, &dense)));
|
||||
let down = teardown(&context, output, kar, (cache, dense));
|
||||
let closed = Rc::try_unwrap(context).ok().map(|c| c.close());
|
||||
drop(binding);
|
||||
drop(inherited);
|
||||
let report = match numerical {
|
||||
Ok(r) => r,
|
||||
Err(primary) => resume_unwind(primary),
|
||||
};
|
||||
assert!(down.disabled.is_ok() && matches!(down.cache_closed, Some(Ok(()))) && down.dense_closed.is_ok());
|
||||
assert!(down.sync.is_ok() && down.allocated == 0 && matches!(closed, Some(Ok(()))));
|
||||
print_report(&report);
|
||||
}
|
||||
#[path = "mtp_decoder_batch_gpu/impl_collection.rs"]
|
||||
mod impl_collection;
|
||||
#[allow(unused_imports)]
|
||||
|
||||
+444
-380
@@ -1,9 +1,437 @@
|
||||
//! Moved out of the parent module by STRA-338: fn check_loaded.
|
||||
//! Moved out of the parent module by STRA-338: fn check_loaded (one body per phase of the authentic boundary).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::mtp_decode::MtpVerifiedWindow;
|
||||
|
||||
fn position_at(position: u64) -> Position {
|
||||
Position::new(position, crate::qwen_forward::contract::position_dimension()).unwrap()
|
||||
}
|
||||
|
||||
/// The window preparation of one flow against the candidate cache. The prepared window borrows the target session
|
||||
/// alone, so the call is spelled out where the session and the report must stay separately borrowable.
|
||||
macro_rules! prepare_window {
|
||||
($flow:expr, $candidate:expr, ($source:expr, $proposals:expr, $eos:expr)) => {
|
||||
QwenForward::prepare_mtp_target_window(
|
||||
$flow.shared.binding,
|
||||
$source,
|
||||
$proposals,
|
||||
$eos,
|
||||
&mut $flow.target,
|
||||
$flow.shared.output,
|
||||
Some(&mut *$flow.shared.kar),
|
||||
$candidate,
|
||||
$flow.shared.dense,
|
||||
TRANSACTION_CAP,
|
||||
|| false,
|
||||
)
|
||||
};
|
||||
}
|
||||
/// Ten complete snapshots + transaction peak and draft copies stay below
|
||||
/// this explicit host cap; production transaction remains exactly512MiB.
|
||||
fn admit_binding(binding: &ModelBinding) {
|
||||
assert!(ROW_CAP.checked_mul(10).unwrap() + TRANSACTION_CAP + 4 * 1024 * 1024 <= SNAPSHOT_CAP);
|
||||
assert_eq!(binding.layer_count(), 48);
|
||||
let disposition = binding.ordered_layers().iter().fold((0, 0), |(g, q), d| match d.kind() {
|
||||
crate::model_binding::qwen4exp_input::BoundLayerKind::Gdn => (g + 1, q),
|
||||
crate::model_binding::qwen4exp_input::BoundLayerKind::Qsa => (g, q + 1),
|
||||
});
|
||||
assert_eq!(disposition, (36, 12));
|
||||
}
|
||||
|
||||
/// The loan of the loaded stages every scalar step, window preparation and decoder window runs against.
|
||||
struct Shared<'a, 'o, 'p, 'k, 'd> {
|
||||
binding: &'a ModelBinding,
|
||||
output: &'a OutputStage<'o, 'p>,
|
||||
dense: &'a DenseWeightCache<'d>,
|
||||
kar: &'a mut KarPleCache<'k>,
|
||||
}
|
||||
|
||||
impl Shared<'_, '_, '_, '_, '_> {
|
||||
fn step<'ctx>(
|
||||
&mut self,
|
||||
target: &mut QwenSession<'ctx>,
|
||||
native: &mut MoeWeightCache<'ctx>,
|
||||
(token, position): (TokenId, u64),
|
||||
) -> Result<TargetStepProduct> {
|
||||
QwenForward::step_for_mtp_cached(
|
||||
self.binding,
|
||||
token,
|
||||
position_at(position),
|
||||
target,
|
||||
self.output,
|
||||
Some(&mut *self.kar),
|
||||
Some(native),
|
||||
Some(self.dense),
|
||||
)
|
||||
}
|
||||
fn window<'ctx>(
|
||||
&mut self,
|
||||
decoder: &mut MtpDecoder,
|
||||
(target, cache): (&mut QwenSession<'ctx>, &mut MoeWeightCache<'ctx>),
|
||||
(source, spec): (TargetStepProduct, MtpWindowSpec),
|
||||
cancelled: impl FnMut() -> bool,
|
||||
) -> std::result::Result<MtpVerifiedWindow, MtpWindowError> {
|
||||
decoder.window(
|
||||
self.binding,
|
||||
source,
|
||||
target,
|
||||
self.output,
|
||||
Some(&mut *self.kar),
|
||||
cache,
|
||||
self.dense,
|
||||
spec,
|
||||
cancelled,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The tokens and draft snapshots every later phase compares against.
|
||||
struct Refs {
|
||||
seed: TokenId,
|
||||
next: TokenId,
|
||||
wrong: TokenId,
|
||||
true_next: TokenId,
|
||||
expected_draft: mtp::MtpChunkNumericSnapshot,
|
||||
continued_draft: mtp::MtpChunkNumericSnapshot,
|
||||
}
|
||||
/// The scalar references; the single-use ones are consumed (and dropped) by the phase that last needs them.
|
||||
struct Chain {
|
||||
refs: Refs,
|
||||
seed_expected: Expected,
|
||||
expected0: Expected,
|
||||
expected1: Expected,
|
||||
expected_tail: Expected,
|
||||
expected_continued: Expected,
|
||||
}
|
||||
/// The actual scalar seed, first and second rows and the draft warmed over them.
|
||||
struct Prefix {
|
||||
source: TargetStepProduct,
|
||||
row0: TargetStepProduct,
|
||||
row1: TargetStepProduct,
|
||||
draft: MtpDecoder,
|
||||
seed_expected: Expected,
|
||||
expected0: Expected,
|
||||
expected1: Expected,
|
||||
expected_draft: mtp::MtpChunkNumericSnapshot,
|
||||
tokens: (TokenId, TokenId, TokenId, TokenId),
|
||||
}
|
||||
struct Flow<'a, 'ctx, 'o, 'p, 'k, 'd> {
|
||||
shared: Shared<'a, 'o, 'p, 'k, 'd>,
|
||||
context: &'ctx Rc<leleka_cuda_driver::Context<'ctx>>,
|
||||
cache_slot: &'a mut Option<MoeWeightCache<'ctx>>,
|
||||
target: QwenSession<'ctx>,
|
||||
report: Report,
|
||||
fresh: ResetReplaySnapshot,
|
||||
zero: TokenId,
|
||||
}
|
||||
|
||||
impl<'a, 'ctx, 'o, 'p, 'k, 'd> Flow<'a, 'ctx, 'o, 'p, 'k, 'd> {
|
||||
fn open(
|
||||
shared: Shared<'a, 'o, 'p, 'k, 'd>,
|
||||
context: &'ctx Rc<leleka_cuda_driver::Context<'ctx>>,
|
||||
cache_slot: &'a mut Option<MoeWeightCache<'ctx>>,
|
||||
) -> Self {
|
||||
let binding = shared.binding;
|
||||
let zero = TokenId::new(0, Dimension::new(VOCAB as u64).unwrap()).unwrap();
|
||||
let target = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
|
||||
let fresh = target.test_reset_replay_snapshot(binding).unwrap();
|
||||
let mut report = Report::default();
|
||||
report.predicates.try_reserve_exact(40).unwrap();
|
||||
shared.output.test_reset_replay_record(true).unwrap();
|
||||
Self { shared, context, cache_slot, target, report, fresh, zero }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> {
|
||||
fn step(&mut self, token: TokenId, position: u64) -> Result<TargetStepProduct> {
|
||||
let native = self.cache_slot.as_mut().unwrap();
|
||||
self.shared.step(&mut self.target, native, (token, position))
|
||||
}
|
||||
fn warm(&mut self, draft: &mut MtpDecoder, source: &TargetStepProduct, token: TokenId) -> Result<()> {
|
||||
let native = self.cache_slot.as_mut().unwrap();
|
||||
draft.warm_retained(self.shared.binding, &mut self.target, source, token, native)
|
||||
}
|
||||
fn observe(&self, source: &TargetStepProduct) -> Expected {
|
||||
observe(self.shared.binding, &self.target, self.shared.output, source)
|
||||
}
|
||||
fn matches_state(&self, expected: &ResetReplaySnapshot) -> bool {
|
||||
self.target.test_reset_replay_snapshot(self.shared.binding).unwrap().numeric_eq(expected)
|
||||
}
|
||||
fn reset_to_fresh(&mut self) {
|
||||
QwenForward::reset(&mut self.target).unwrap();
|
||||
let ok = self.matches_state(&self.fresh);
|
||||
self.report.check(ok);
|
||||
}
|
||||
/// The scalar seed and the first two rows with the draft warmed over them.
|
||||
fn reference_prefix(&mut self) -> Prefix {
|
||||
let (zero, binding) = (self.zero, self.shared.binding);
|
||||
let source = self.step(zero, 0).expect("scalar seed refused");
|
||||
let seed_expected = self.observe(&source);
|
||||
let seed = source.predicted(&self.target).unwrap();
|
||||
let mut draft = MtpDecoder::new(binding).unwrap();
|
||||
self.warm(&mut draft, &source, seed).expect("actual seed draft warm refused");
|
||||
let row0 = self.step(seed, 1).expect("scalar row0 refused");
|
||||
let expected0 = self.observe(&row0);
|
||||
let next = row0.predicted(&self.target).unwrap();
|
||||
self.warm(&mut draft, &row0, next).expect("actual row0 draft warm refused");
|
||||
let row1 = self.step(next, 2).expect("scalar row1 refused");
|
||||
let expected1 = self.observe(&row1);
|
||||
let expected_draft = draft.test_chunk_snapshot();
|
||||
let true_next = row1.predicted(&self.target).unwrap();
|
||||
let wrong = different_token(&[seed, next, true_next]);
|
||||
let tokens = (seed, next, wrong, true_next);
|
||||
Prefix { source, row0, row1, draft, seed_expected, expected0, expected1, expected_draft, tokens }
|
||||
}
|
||||
/// The continuation and the rejected-tail reference after a restore; every scalar product is then released.
|
||||
fn reference_tail(&mut self, prefix: Prefix) -> Chain {
|
||||
let Prefix { source, row0, row1, mut draft, seed_expected, expected0, expected1, expected_draft, tokens } =
|
||||
prefix;
|
||||
let (seed, next, wrong, true_next) = tokens;
|
||||
let prior = self.target.checkpoint().unwrap();
|
||||
self.warm(&mut draft, &row1, true_next).expect("continuation draft warm refused");
|
||||
let continued = self.step(true_next, 3).expect("scalar continuation refused");
|
||||
let expected_continued = self.observe(&continued);
|
||||
let continued_draft = draft.test_chunk_snapshot();
|
||||
self.target.restore_checkpoint(&prior).unwrap();
|
||||
let tail = self.step(wrong, 3).expect("scalar rejected-tail reference refused");
|
||||
let expected_tail = self.observe(&tail);
|
||||
drop(tail);
|
||||
drop(continued);
|
||||
drop(row1);
|
||||
drop(row0);
|
||||
drop(source);
|
||||
drop(prior);
|
||||
drop(draft);
|
||||
self.shared.output.test_reset_replay_record(false).unwrap();
|
||||
let refs = Refs { seed, next, wrong, true_next, expected_draft, continued_draft };
|
||||
Chain { refs, seed_expected, expected0, expected1, expected_tail, expected_continued }
|
||||
}
|
||||
/// Closes the legacy cache, opens the explicit candidate cache and proves its seed identical to the scalar seed.
|
||||
fn candidate_seed(&mut self, seed_expected: Expected) -> TargetStepProduct {
|
||||
let old = self.cache_slot.take().unwrap();
|
||||
self.report.check(old.close().is_ok());
|
||||
*self.cache_slot = Some(
|
||||
MoeWeightCache::new_native_integer_iq3_mmq(self.shared.binding, self.context.as_ref())
|
||||
.expect("explicit candidate cache refused"),
|
||||
);
|
||||
self.reset_to_fresh();
|
||||
self.shared.output.test_reset_replay_record(true).unwrap();
|
||||
let zero = self.zero;
|
||||
let source = self.step(zero, 0).expect("candidate seed refused");
|
||||
let seed_actual = self.observe(&source);
|
||||
self.report.check(
|
||||
seed_actual.logits == seed_expected.logits
|
||||
&& seed_actual.residual == seed_expected.residual
|
||||
&& seed_actual.state.numeric_eq(&seed_expected.state),
|
||||
);
|
||||
self.report.words += VOCAB + 10240;
|
||||
drop(seed_actual);
|
||||
drop(seed_expected);
|
||||
self.shared.output.test_reset_replay_record(false).unwrap();
|
||||
source
|
||||
}
|
||||
/// Refuse T4 and actual authoritative EOS before producer mutation.
|
||||
fn refuse_windows(
|
||||
&mut self,
|
||||
source: &TargetStepProduct,
|
||||
refs: &Refs,
|
||||
decoder: &MtpDecoder,
|
||||
(target_before, draft_before): (&ResetReplaySnapshot, &mtp::MtpChunkNumericSnapshot),
|
||||
) {
|
||||
let candidate = self.cache_slot.as_mut().unwrap();
|
||||
let four = [refs.seed, refs.next, refs.wrong, self.zero];
|
||||
let too_many = prepare_window!(self, candidate, (source, &four, None));
|
||||
self.report.check(matches!(too_many, Err(Error::InputAllocation)));
|
||||
drop(too_many);
|
||||
self.report.guards += 1;
|
||||
let at_eos = prepare_window!(self, candidate, (source, &[refs.seed], Some(refs.seed)));
|
||||
self.report.check(matches!(at_eos, Err(Error::IdentityMismatch)));
|
||||
drop(at_eos);
|
||||
self.report.guards += 1;
|
||||
let unchanged = self.matches_state(target_before) && decoder.test_chunk_eq(draft_before);
|
||||
self.report.check(unchanged);
|
||||
}
|
||||
/// ONE actual completed T3 transaction. Cancellation is at the private
|
||||
/// draft stage boundary after one real causal warm, before joint publish.
|
||||
fn cancelled_publish(
|
||||
&mut self,
|
||||
source: &TargetStepProduct,
|
||||
(refs, expected0, expected1): (&Refs, &Expected, &Expected),
|
||||
expected_tail: Expected,
|
||||
decoder: &mut MtpDecoder,
|
||||
(target_before, draft_before): (&ResetReplaySnapshot, &mtp::MtpChunkNumericSnapshot),
|
||||
) {
|
||||
let collection = Collection::begin(3).unwrap();
|
||||
let candidate = self.cache_slot.as_mut().unwrap();
|
||||
let proposals = [refs.seed, refs.next, refs.wrong];
|
||||
let pending = prepare_window!(self, candidate, (source, &proposals, None)).expect("real T3 target refused");
|
||||
self.report.check(pending.accepted_rows() == 2);
|
||||
let rows = collection.finish().unwrap();
|
||||
self.report.check(row_matches(&rows[0], expected0));
|
||||
self.report.check(row_matches(&rows[1], expected1));
|
||||
self.report.check(row_matches(&rows[2], &expected_tail));
|
||||
self.report.words += 3 * (VOCAB + 10240);
|
||||
drop(rows);
|
||||
drop(expected_tail);
|
||||
let mut phase_calls = 0;
|
||||
let cancelled = pending.publish_joint(self.shared.binding, &mut decoder.draft, candidate, || {
|
||||
phase_calls += 1;
|
||||
phase_calls == 3
|
||||
});
|
||||
self.report.check(matches!(cancelled, Err(Error::Unsupported(Stage::Executor))) && phase_calls == 3);
|
||||
self.report.guards += 1;
|
||||
let unchanged = self.matches_state(target_before) && decoder.test_chunk_eq(draft_before);
|
||||
self.report.check(unchanged);
|
||||
}
|
||||
/// The first decoder warmed over the seed, the T4/EOS refusals, the cancelled T3 transaction and the restore.
|
||||
fn first_window(
|
||||
&mut self,
|
||||
source: &TargetStepProduct,
|
||||
(refs, expected0, expected1): (&Refs, &Expected, &Expected),
|
||||
expected_tail: Expected,
|
||||
) -> (MtpDecoder, ResetReplaySnapshot, mtp::MtpChunkNumericSnapshot) {
|
||||
let binding = self.shared.binding;
|
||||
let mut decoder = MtpDecoder::new(binding).unwrap();
|
||||
self.warm(&mut decoder, source, refs.seed).unwrap();
|
||||
let target_before = self.target.test_reset_replay_snapshot(binding).unwrap();
|
||||
let draft_before = decoder.test_chunk_snapshot();
|
||||
let target_prior = self.target.checkpoint().unwrap();
|
||||
let draft_prior = decoder.draft.checkpoint().unwrap();
|
||||
self.refuse_windows(source, refs, &decoder, (&target_before, &draft_before));
|
||||
let before = (&target_before, &draft_before);
|
||||
self.cancelled_publish(source, (refs, expected0, expected1), expected_tail, &mut decoder, before);
|
||||
self.report.check(self.target.restore_checkpoint(&target_prior).is_ok());
|
||||
self.report.check(decoder.draft.restore(&draft_prior).is_ok());
|
||||
drop(target_prior);
|
||||
drop(draft_prior);
|
||||
(decoder, target_before, draft_before)
|
||||
}
|
||||
/// The old product was invalidated by real rollback. Reset and recompute
|
||||
/// the seed; never relabel that product as a fresh origin. Existing caller publishes a real prefix, then its
|
||||
/// existing cancellation check fires from this exact event. No guessed global callback ordinal.
|
||||
fn automatic_cancel(
|
||||
&mut self,
|
||||
source: TargetStepProduct,
|
||||
expected0: &Expected,
|
||||
target_before: &ResetReplaySnapshot,
|
||||
) {
|
||||
drop(source);
|
||||
self.reset_to_fresh();
|
||||
let zero = self.zero;
|
||||
let source = self.step(zero, 0).expect("recovery seed refused");
|
||||
let mut decoder = MtpDecoder::new(self.shared.binding).unwrap();
|
||||
let automatic_draft_before = decoder.test_chunk_snapshot();
|
||||
let event = PostcommitCancellation::arm().unwrap();
|
||||
let collection = Collection::begin(1).unwrap();
|
||||
let spec = MtpWindowSpec::new(4, 1, None).unwrap();
|
||||
let candidate = self.cache_slot.as_mut().unwrap();
|
||||
let cancelled =
|
||||
self.shared.window(&mut decoder, (&mut self.target, candidate), (source, spec), || event.cancelled());
|
||||
self.report.check(event.cancelled() && matches!(cancelled, Err(MtpWindowError::Cancelled)));
|
||||
drop(cancelled);
|
||||
let actual = collection.finish().unwrap();
|
||||
self.report.check(row_matches(&actual[0], expected0));
|
||||
self.report.words += VOCAB + 10240;
|
||||
self.report.guards += 1;
|
||||
let unchanged = self.matches_state(target_before) && decoder.test_chunk_eq(&automatic_draft_before);
|
||||
self.report.check(unchanged);
|
||||
drop((actual, event, automatic_draft_before, decoder));
|
||||
}
|
||||
/// Automatic full restore invalidates the consumed source. Recover via
|
||||
/// genuine reset/forward, never a clone/remint of that stale capability; then verify a SomeEOS prefix.
|
||||
fn eos_prefix(
|
||||
&mut self,
|
||||
refs: &Refs,
|
||||
(expected0, expected1): (Expected, Expected),
|
||||
(target_before, draft_before): (ResetReplaySnapshot, mtp::MtpChunkNumericSnapshot),
|
||||
) -> (MtpDecoder, TargetStepProduct) {
|
||||
let binding = self.shared.binding;
|
||||
self.reset_to_fresh();
|
||||
let zero = self.zero;
|
||||
let source = self.step(zero, 0).expect("automatic caller cancellation recovery refused");
|
||||
let mut decoder = MtpDecoder::new(binding).unwrap();
|
||||
self.warm(&mut decoder, &source, refs.seed).unwrap();
|
||||
let candidate = self.cache_slot.as_mut().unwrap();
|
||||
let proposals = [refs.seed, refs.next, refs.wrong];
|
||||
let pending = prepare_window!(self, candidate, (&source, &proposals, Some(refs.wrong)))
|
||||
.expect("SomeEOS accepted prefix refused");
|
||||
self.report.check(pending.accepted_rows() == 2);
|
||||
let latest =
|
||||
pending.publish_joint(binding, &mut decoder.draft, candidate, || false).expect("real jointprefix refused");
|
||||
let state_ok = self.matches_state(&expected1.state);
|
||||
self.report.check(state_ok);
|
||||
self.report.check(decoder.test_chunk_eq(&refs.expected_draft));
|
||||
let (_, _, streams, _) = latest.mtp_source(binding, &self.target).unwrap();
|
||||
self.report.check(
|
||||
latest.predicted(&self.target).unwrap() == expected1.head
|
||||
&& streams.iter().map(|v| v.to_bits()).eq(expected1.residual.iter().copied()),
|
||||
);
|
||||
drop((expected0, expected1, target_before, draft_before));
|
||||
(decoder, latest)
|
||||
}
|
||||
/// Actual wired caller: remaining=1 must not consume more than one true
|
||||
/// target token; this also exercises speculative rewind + head-free catchup.
|
||||
fn max_one(
|
||||
&mut self,
|
||||
refs: &Refs,
|
||||
expected_continued: Expected,
|
||||
decoder: &mut MtpDecoder,
|
||||
latest: TargetStepProduct,
|
||||
) -> TargetStepProduct {
|
||||
let collection = Collection::begin(1).unwrap();
|
||||
let spec = MtpWindowSpec::new(4, 1, None).unwrap();
|
||||
let candidate = self.cache_slot.as_mut().unwrap();
|
||||
let window = self
|
||||
.shared
|
||||
.window(decoder, (&mut self.target, candidate), (latest, spec), || false)
|
||||
.expect("actual max1 decoder caller refused");
|
||||
let observed = collection.finish().unwrap();
|
||||
self.report.check(row_matches(&observed[0], &expected_continued));
|
||||
let (tokens, latest, stopped) = window.into_parts();
|
||||
self.report.check(tokens == vec![refs.true_next] && !stopped);
|
||||
let state_ok = self.matches_state(&expected_continued.state);
|
||||
self.report.check(state_ok);
|
||||
self.report.check(decoder.test_chunk_eq(&refs.continued_draft));
|
||||
self.report.words += VOCAB + 10240;
|
||||
drop(observed);
|
||||
drop(expected_continued);
|
||||
latest
|
||||
}
|
||||
/// A window with nothing to advance (`remaining` zero or an authoritative EOS) does no draft work and returns
|
||||
/// the same genuine committed source.
|
||||
fn idle_window(
|
||||
&mut self,
|
||||
decoder: &mut MtpDecoder,
|
||||
latest: TargetStepProduct,
|
||||
(remaining, eos, stopped_expected): (usize, Option<TokenId>, bool),
|
||||
) -> TargetStepProduct {
|
||||
let spec = MtpWindowSpec::new(4, remaining, eos).unwrap();
|
||||
let candidate = self.cache_slot.as_mut().unwrap();
|
||||
let window = self.shared.window(decoder, (&mut self.target, candidate), (latest, spec), || false).unwrap();
|
||||
self.report.check(window.tokens().is_empty() && window.draft_steps() == 0);
|
||||
let (_, latest, stopped) = window.into_parts();
|
||||
self.report.check(stopped == stopped_expected);
|
||||
self.report.guards += 1;
|
||||
latest
|
||||
}
|
||||
/// Zero remaining and authoritative EOS require no advance, draft work or publication.
|
||||
fn no_advance(&mut self, mut decoder: MtpDecoder, latest: TargetStepProduct) {
|
||||
let before = self.target.test_reset_replay_snapshot(self.shared.binding).unwrap();
|
||||
let draft_before = decoder.test_chunk_snapshot();
|
||||
let latest = self.idle_window(&mut decoder, latest, (0, None, false));
|
||||
let eos = latest.predicted(&self.target).unwrap();
|
||||
let latest = self.idle_window(&mut decoder, latest, (4, Some(eos), true));
|
||||
let unchanged = self.matches_state(&before) && decoder.test_chunk_eq(&draft_before);
|
||||
self.report.check(unchanged);
|
||||
drop(latest);
|
||||
drop(decoder);
|
||||
drop(before);
|
||||
drop(draft_before);
|
||||
self.reset_to_fresh();
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn check_loaded<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
context: &'ctx Rc<leleka_cuda_driver::Context<'ctx>>,
|
||||
@@ -12,382 +440,18 @@ pub(super) fn check_loaded<'ctx>(
|
||||
cache_slot: &mut Option<MoeWeightCache<'ctx>>,
|
||||
dense: &DenseWeightCache<'_>,
|
||||
) -> Report {
|
||||
// Ten complete snapshots + transaction peak and draft copies stay below
|
||||
// this explicit host cap; production transaction remains exactly512MiB.
|
||||
assert!(ROW_CAP.checked_mul(10).unwrap() + TRANSACTION_CAP + 4 * 1024 * 1024 <= SNAPSHOT_CAP);
|
||||
assert_eq!(binding.layer_count(), 48);
|
||||
let disposition = binding.ordered_layers().iter().fold((0, 0), |(g, q), d| match d.kind() {
|
||||
crate::model_binding::qwen4exp_input::BoundLayerKind::Gdn => (g + 1, q),
|
||||
crate::model_binding::qwen4exp_input::BoundLayerKind::Qsa => (g, q + 1),
|
||||
});
|
||||
assert_eq!(disposition, (36, 12));
|
||||
let bounds = crate::qwen_forward::contract::position_dimension();
|
||||
let vocab = Dimension::new(VOCAB as u64).unwrap();
|
||||
let zero = TokenId::new(0, vocab).unwrap();
|
||||
let mut target = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
|
||||
let fresh = target.test_reset_replay_snapshot(binding).unwrap();
|
||||
let mut report = Report::default();
|
||||
report.predicates.try_reserve_exact(40).unwrap();
|
||||
output.test_reset_replay_record(true).unwrap();
|
||||
let native = cache_slot.as_mut().unwrap();
|
||||
let source = QwenForward::step_for_mtp_cached(
|
||||
binding,
|
||||
zero,
|
||||
Position::new(0, bounds).unwrap(),
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
Some(&mut *native),
|
||||
Some(dense),
|
||||
)
|
||||
.expect("scalar seed refused");
|
||||
let seed_expected = observe(binding, &target, output, &source);
|
||||
let seed = source.predicted(&target).unwrap();
|
||||
let mut draft = MtpDecoder::new(binding).unwrap();
|
||||
draft.warm_retained(binding, &mut target, &source, seed, native).expect("actual seed draft warm refused");
|
||||
let row0 = QwenForward::step_for_mtp_cached(
|
||||
binding,
|
||||
seed,
|
||||
Position::new(1, bounds).unwrap(),
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
Some(&mut *native),
|
||||
Some(dense),
|
||||
)
|
||||
.expect("scalar row0 refused");
|
||||
let expected0 = observe(binding, &target, output, &row0);
|
||||
let next = row0.predicted(&target).unwrap();
|
||||
draft.warm_retained(binding, &mut target, &row0, next, native).expect("actual row0 draft warm refused");
|
||||
let row1 = QwenForward::step_for_mtp_cached(
|
||||
binding,
|
||||
next,
|
||||
Position::new(2, bounds).unwrap(),
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
Some(&mut *native),
|
||||
Some(dense),
|
||||
)
|
||||
.expect("scalar row1 refused");
|
||||
let expected1 = observe(binding, &target, output, &row1);
|
||||
let expected_draft = draft.test_chunk_snapshot();
|
||||
let true_next = row1.predicted(&target).unwrap();
|
||||
let wrong = different_token(&[seed, next, true_next]);
|
||||
let prior = target.checkpoint().unwrap();
|
||||
draft.warm_retained(binding, &mut target, &row1, true_next, native).expect("continuation draft warm refused");
|
||||
let continued = QwenForward::step_for_mtp_cached(
|
||||
binding,
|
||||
true_next,
|
||||
Position::new(3, bounds).unwrap(),
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
Some(&mut *native),
|
||||
Some(dense),
|
||||
)
|
||||
.expect("scalar continuation refused");
|
||||
let expected_continued = observe(binding, &target, output, &continued);
|
||||
let continued_draft = draft.test_chunk_snapshot();
|
||||
target.restore_checkpoint(&prior).unwrap();
|
||||
let tail = QwenForward::step_for_mtp_cached(
|
||||
binding,
|
||||
wrong,
|
||||
Position::new(3, bounds).unwrap(),
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
Some(&mut *native),
|
||||
Some(dense),
|
||||
)
|
||||
.expect("scalar rejected-tail reference refused");
|
||||
let expected_tail = observe(binding, &target, output, &tail);
|
||||
drop(tail);
|
||||
drop(continued);
|
||||
drop(row1);
|
||||
drop(row0);
|
||||
drop(source);
|
||||
drop(prior);
|
||||
drop(draft);
|
||||
output.test_reset_replay_record(false).unwrap();
|
||||
let old = cache_slot.take().unwrap();
|
||||
report.check(old.close().is_ok());
|
||||
*cache_slot = Some(
|
||||
MoeWeightCache::new_native_integer_iq3_mmq(binding, context.as_ref())
|
||||
.expect("explicit candidate cache refused"),
|
||||
);
|
||||
let candidate = cache_slot.as_mut().unwrap();
|
||||
QwenForward::reset(&mut target).unwrap();
|
||||
report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&fresh));
|
||||
output.test_reset_replay_record(true).unwrap();
|
||||
let source = QwenForward::step_for_mtp_cached(
|
||||
binding,
|
||||
zero,
|
||||
Position::new(0, bounds).unwrap(),
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
Some(&mut *candidate),
|
||||
Some(dense),
|
||||
)
|
||||
.expect("candidate seed refused");
|
||||
let seed_actual = observe(binding, &target, output, &source);
|
||||
report.check(
|
||||
seed_actual.logits == seed_expected.logits
|
||||
&& seed_actual.residual == seed_expected.residual
|
||||
&& seed_actual.state.numeric_eq(&seed_expected.state),
|
||||
);
|
||||
report.words += VOCAB + 10240;
|
||||
drop(seed_actual);
|
||||
drop(seed_expected);
|
||||
output.test_reset_replay_record(false).unwrap();
|
||||
let mut decoder = MtpDecoder::new(binding).unwrap();
|
||||
decoder.warm_retained(binding, &mut target, &source, seed, candidate).unwrap();
|
||||
let target_before = target.test_reset_replay_snapshot(binding).unwrap();
|
||||
let draft_before = decoder.test_chunk_snapshot();
|
||||
let target_prior = target.checkpoint().unwrap();
|
||||
let draft_prior = decoder.draft.checkpoint().unwrap();
|
||||
// Refuse T4 and actual authoritative EOS before producer mutation.
|
||||
let too_many = QwenForward::prepare_mtp_target_window(
|
||||
binding,
|
||||
&source,
|
||||
&[seed, next, wrong, zero],
|
||||
None,
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
candidate,
|
||||
dense,
|
||||
TRANSACTION_CAP,
|
||||
|| false,
|
||||
);
|
||||
report.check(matches!(too_many, Err(Error::InputAllocation)));
|
||||
drop(too_many);
|
||||
report.guards += 1;
|
||||
let at_eos = QwenForward::prepare_mtp_target_window(
|
||||
binding,
|
||||
&source,
|
||||
&[seed],
|
||||
Some(seed),
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
candidate,
|
||||
dense,
|
||||
TRANSACTION_CAP,
|
||||
|| false,
|
||||
);
|
||||
report.check(matches!(at_eos, Err(Error::IdentityMismatch)));
|
||||
drop(at_eos);
|
||||
report.guards += 1;
|
||||
report.check(
|
||||
target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&target_before)
|
||||
&& decoder.test_chunk_eq(&draft_before),
|
||||
);
|
||||
// ONE actual completed T3 transaction. Cancellation is at the private
|
||||
// draft stage boundary after one real causal warm, before joint publish.
|
||||
let collection = Collection::begin(3).unwrap();
|
||||
let pending = QwenForward::prepare_mtp_target_window(
|
||||
binding,
|
||||
&source,
|
||||
&[seed, next, wrong],
|
||||
None,
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
candidate,
|
||||
dense,
|
||||
TRANSACTION_CAP,
|
||||
|| false,
|
||||
)
|
||||
.expect("real T3 target refused");
|
||||
report.check(pending.accepted_rows() == 2);
|
||||
let rows = collection.finish().unwrap();
|
||||
report.check(row_matches(&rows[0], &expected0));
|
||||
report.check(row_matches(&rows[1], &expected1));
|
||||
report.check(row_matches(&rows[2], &expected_tail));
|
||||
report.words += 3 * (VOCAB + 10240);
|
||||
drop(rows);
|
||||
drop(expected_tail);
|
||||
let mut phase_calls = 0;
|
||||
let cancelled = pending.publish_joint(binding, &mut decoder.draft, candidate, || {
|
||||
phase_calls += 1;
|
||||
phase_calls == 3
|
||||
});
|
||||
report.check(matches!(cancelled, Err(Error::Unsupported(Stage::Executor))) && phase_calls == 3);
|
||||
report.guards += 1;
|
||||
report.check(
|
||||
target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&target_before)
|
||||
&& decoder.test_chunk_eq(&draft_before),
|
||||
);
|
||||
report.check(target.restore_checkpoint(&target_prior).is_ok());
|
||||
report.check(decoder.draft.restore(&draft_prior).is_ok());
|
||||
drop(target_prior);
|
||||
drop(draft_prior);
|
||||
// The old product was invalidated by real rollback. Reset and recompute
|
||||
// the seed; never relabel that product as a fresh origin.
|
||||
drop(source);
|
||||
QwenForward::reset(&mut target).unwrap();
|
||||
report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&fresh));
|
||||
let source = QwenForward::step_for_mtp_cached(
|
||||
binding,
|
||||
zero,
|
||||
Position::new(0, bounds).unwrap(),
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
Some(&mut *candidate),
|
||||
Some(dense),
|
||||
)
|
||||
.expect("recovery seed refused");
|
||||
let mut decoder = MtpDecoder::new(binding).unwrap();
|
||||
let automatic_draft_before = decoder.test_chunk_snapshot();
|
||||
let event = PostcommitCancellation::arm().unwrap();
|
||||
let collection = Collection::begin(1).unwrap();
|
||||
// Existing caller publishes a real prefix, then its existing cancellation
|
||||
// check fires from this exact event. No guessed global callback ordinal.
|
||||
let cancelled = decoder.window(
|
||||
binding,
|
||||
source,
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
candidate,
|
||||
dense,
|
||||
MtpWindowSpec::new(4, 1, None).unwrap(),
|
||||
|| event.cancelled(),
|
||||
);
|
||||
report.check(event.cancelled() && matches!(cancelled, Err(MtpWindowError::Cancelled)));
|
||||
drop(cancelled);
|
||||
let actual = collection.finish().unwrap();
|
||||
report.check(row_matches(&actual[0], &expected0));
|
||||
report.words += VOCAB + 10240;
|
||||
report.guards += 1;
|
||||
report.check(
|
||||
target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&target_before)
|
||||
&& decoder.test_chunk_eq(&automatic_draft_before),
|
||||
);
|
||||
drop(actual);
|
||||
drop(event);
|
||||
drop(automatic_draft_before);
|
||||
drop(decoder);
|
||||
// Automatic full restore invalidates the consumed source. Recover via
|
||||
// genuine reset/forward, never a clone/remint of that stale capability.
|
||||
QwenForward::reset(&mut target).unwrap();
|
||||
report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&fresh));
|
||||
let source = QwenForward::step_for_mtp_cached(
|
||||
binding,
|
||||
zero,
|
||||
Position::new(0, bounds).unwrap(),
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
Some(&mut *candidate),
|
||||
Some(dense),
|
||||
)
|
||||
.expect("automatic caller cancellation recovery refused");
|
||||
let mut decoder = MtpDecoder::new(binding).unwrap();
|
||||
decoder.warm_retained(binding, &mut target, &source, seed, candidate).unwrap();
|
||||
let pending = QwenForward::prepare_mtp_target_window(
|
||||
binding,
|
||||
&source,
|
||||
&[seed, next, wrong],
|
||||
Some(wrong),
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
candidate,
|
||||
dense,
|
||||
TRANSACTION_CAP,
|
||||
|| false,
|
||||
)
|
||||
.expect("SomeEOS accepted prefix refused");
|
||||
report.check(pending.accepted_rows() == 2);
|
||||
let latest =
|
||||
pending.publish_joint(binding, &mut decoder.draft, candidate, || false).expect("real jointprefix refused");
|
||||
report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&expected1.state));
|
||||
report.check(decoder.test_chunk_eq(&expected_draft));
|
||||
let (_, _, streams, _) = latest.mtp_source(binding, &target).unwrap();
|
||||
report.check(
|
||||
latest.predicted(&target).unwrap() == expected1.head
|
||||
&& streams.iter().map(|v| v.to_bits()).eq(expected1.residual.iter().copied()),
|
||||
);
|
||||
drop(expected0);
|
||||
drop(expected1);
|
||||
drop(target_before);
|
||||
drop(draft_before);
|
||||
// Actual wired caller: remaining=1 must not consume more than one true
|
||||
// target token; this also exercises speculative rewind + head-free catchup.
|
||||
let collection = Collection::begin(1).unwrap();
|
||||
let window = decoder
|
||||
.window(
|
||||
binding,
|
||||
latest,
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
candidate,
|
||||
dense,
|
||||
MtpWindowSpec::new(4, 1, None).unwrap(),
|
||||
|| false,
|
||||
)
|
||||
.expect("actual max1 decoder caller refused");
|
||||
let observed = collection.finish().unwrap();
|
||||
report.check(row_matches(&observed[0], &expected_continued));
|
||||
let (tokens, latest, stopped) = window.into_parts();
|
||||
report.check(tokens == vec![true_next] && !stopped);
|
||||
report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&expected_continued.state));
|
||||
report.check(decoder.test_chunk_eq(&continued_draft));
|
||||
report.words += VOCAB + 10240;
|
||||
drop(observed);
|
||||
drop(expected_continued);
|
||||
// Zero remaining and authoritative EOS require no advance, draft work or
|
||||
// publication. They return the same genuine committed source.
|
||||
let before = target.test_reset_replay_snapshot(binding).unwrap();
|
||||
let draft_before = decoder.test_chunk_snapshot();
|
||||
let window = decoder
|
||||
.window(
|
||||
binding,
|
||||
latest,
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
candidate,
|
||||
dense,
|
||||
MtpWindowSpec::new(4, 0, None).unwrap(),
|
||||
|| false,
|
||||
)
|
||||
.unwrap();
|
||||
report.check(window.tokens().is_empty() && window.draft_steps() == 0);
|
||||
let (_, latest, stopped) = window.into_parts();
|
||||
report.check(!stopped);
|
||||
report.guards += 1;
|
||||
let eos = latest.predicted(&target).unwrap();
|
||||
let window = decoder
|
||||
.window(
|
||||
binding,
|
||||
latest,
|
||||
&mut target,
|
||||
output,
|
||||
Some(&mut *kar),
|
||||
candidate,
|
||||
dense,
|
||||
MtpWindowSpec::new(4, 4, Some(eos)).unwrap(),
|
||||
|| false,
|
||||
)
|
||||
.unwrap();
|
||||
report.check(window.tokens().is_empty() && window.draft_steps() == 0);
|
||||
let (_, latest, stopped) = window.into_parts();
|
||||
report.check(stopped);
|
||||
report.guards += 1;
|
||||
report.check(
|
||||
target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&before) && decoder.test_chunk_eq(&draft_before),
|
||||
);
|
||||
drop(latest);
|
||||
drop(decoder);
|
||||
drop(before);
|
||||
drop(draft_before);
|
||||
QwenForward::reset(&mut target).unwrap();
|
||||
report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&fresh));
|
||||
report
|
||||
admit_binding(binding);
|
||||
let mut flow = Flow::open(Shared { binding, output, dense, kar }, context, cache_slot);
|
||||
let prefix = flow.reference_prefix();
|
||||
let Chain { refs, seed_expected, expected0, expected1, expected_tail, expected_continued } =
|
||||
flow.reference_tail(prefix);
|
||||
let source = flow.candidate_seed(seed_expected);
|
||||
let (first_decoder, target_before, draft_before) =
|
||||
flow.first_window(&source, (&refs, &expected0, &expected1), expected_tail);
|
||||
flow.automatic_cancel(source, &expected0, &target_before);
|
||||
let (mut decoder, latest) = flow.eos_prefix(&refs, (expected0, expected1), (target_before, draft_before));
|
||||
let latest = flow.max_one(&refs, expected_continued, &mut decoder, latest);
|
||||
flow.no_advance(decoder, latest);
|
||||
drop(first_decoder);
|
||||
flow.report
|
||||
}
|
||||
|
||||
+36
-20
@@ -74,6 +74,40 @@ pub(in crate::qwen_forward) fn collecting() -> bool {
|
||||
COLLECTOR.with(|slot| slot.borrow().is_some())
|
||||
}
|
||||
|
||||
/// The full finite head of one row: exactly VOCAB words, none non-finite.
|
||||
fn head_words(words: impl Iterator<Item = u32>) -> Result<Vec<u32>> {
|
||||
let mut logits = Vec::new();
|
||||
logits.try_reserve_exact(VOCAB).map_err(|_| Error::InputAllocation)?;
|
||||
for word in words {
|
||||
if logits.len() == VOCAB || !f32::from_bits(word).is_finite() {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
logits.push(word);
|
||||
}
|
||||
if logits.len() != VOCAB {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
Ok(logits)
|
||||
}
|
||||
/// The row being completed is the one its head opened, still without a state, and its residual and state fit the cap.
|
||||
fn admit_row(
|
||||
row: &RowObservation,
|
||||
(token, position): (TokenId, Position),
|
||||
residual: &[f32],
|
||||
state: &ResetReplaySnapshot,
|
||||
) -> Result<()> {
|
||||
if row.token != token
|
||||
|| row.position != position
|
||||
|| row.state.is_some()
|
||||
|| residual.len() != 10240
|
||||
|| residual.iter().any(|v| !v.is_finite())
|
||||
|| state.retained_bytes().ok_or(Error::InputAllocation)? > ROW_CAP
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::qwen_forward) fn collect_head(
|
||||
token: TokenId,
|
||||
position: Position,
|
||||
@@ -87,17 +121,7 @@ pub(in crate::qwen_forward) fn collect_head(
|
||||
if c.rows.len() >= c.count {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let mut logits = Vec::new();
|
||||
logits.try_reserve_exact(VOCAB).map_err(|_| Error::InputAllocation)?;
|
||||
for word in words {
|
||||
if logits.len() == VOCAB || !f32::from_bits(word).is_finite() {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
logits.push(word);
|
||||
}
|
||||
if logits.len() != VOCAB {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let logits = head_words(words)?;
|
||||
c.rows.push(RowObservation {
|
||||
token,
|
||||
position,
|
||||
@@ -122,15 +146,7 @@ pub(in crate::qwen_forward) fn collect_row(
|
||||
return Ok(());
|
||||
};
|
||||
let row = c.rows.last_mut().ok_or(Error::IdentityMismatch)?;
|
||||
if row.token != token
|
||||
|| row.position != position
|
||||
|| row.state.is_some()
|
||||
|| residual.len() != 10240
|
||||
|| residual.iter().any(|v| !v.is_finite())
|
||||
|| state.retained_bytes().ok_or(Error::InputAllocation)? > ROW_CAP
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
admit_row(row, (token, position), residual, &state)?;
|
||||
let mut bits = Vec::new();
|
||||
bits.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?;
|
||||
bits.extend(residual.iter().map(|v| v.to_bits()));
|
||||
|
||||
@@ -140,30 +140,42 @@ impl<'ctx> Transport<'ctx> {
|
||||
// Exact original FP32-scale/half-away quantizers; caller inspects every
|
||||
// completed scale before any original grouped dot consumes the pair.
|
||||
pub(super) fn quantize(&mut self, input: usize, hidden: bool) -> Result<(usize, usize)> {
|
||||
let q = self.allocate(if hidden { 680 } else { 2720 })?;
|
||||
let scales = self.allocate(if hidden { 80 } else { 320 })?;
|
||||
let (q_bytes, scale_bytes, scale_words) = quantizer_extents(hidden);
|
||||
let q = self.allocate(q_bytes)?;
|
||||
let scales = self.allocate(scale_bytes)?;
|
||||
let (inputs, outputs) = self.buffers.split_at_mut(q);
|
||||
let (quant, scale) = outputs.split_at_mut(1);
|
||||
let result = if hidden {
|
||||
self.context.mtp_quantize_scaled_640(
|
||||
let result = quantize_launch(
|
||||
self.context,
|
||||
hidden,
|
||||
(
|
||||
at(inputs, input)?,
|
||||
quant[0].as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
scale[0].as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
)
|
||||
} else {
|
||||
self.context.mtp_quantize_scaled_2560(
|
||||
at(inputs, input)?,
|
||||
quant[0].as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
scale[0].as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
)
|
||||
}
|
||||
),
|
||||
)
|
||||
.map_err(moe_driver_error)
|
||||
.and_then(|()| download(at(&self.buffers, scales)?, if hidden { 20 } else { 80 }).map(|_| ()));
|
||||
.and_then(|()| download(at(&self.buffers, scales)?, scale_words).map(|_| ()));
|
||||
self.note(&result);
|
||||
result?;
|
||||
Ok((q, scales))
|
||||
}
|
||||
}
|
||||
/// Quantized bytes, scale bytes and scale words read back, of the hidden (640) or the input (2560) quantizer.
|
||||
fn quantizer_extents(hidden: bool) -> (usize, usize, usize) {
|
||||
if hidden { (680, 80, 20) } else { (2720, 320, 80) }
|
||||
}
|
||||
fn quantize_launch(
|
||||
context: &Context<'_>,
|
||||
hidden: bool,
|
||||
(input, quant, scale): (&DeviceBuffer<'_>, &mut DeviceBuffer<'_>, &mut DeviceBuffer<'_>),
|
||||
) -> std::result::Result<(), leleka_cuda_driver::Error> {
|
||||
if hidden {
|
||||
context.mtp_quantize_scaled_640(input, quant, scale)
|
||||
} else {
|
||||
context.mtp_quantize_scaled_2560(input, quant, scale)
|
||||
}
|
||||
}
|
||||
impl Drop for Transport<'_> {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.close();
|
||||
@@ -172,6 +184,40 @@ impl Drop for Transport<'_> {
|
||||
pub(super) fn at<'a, 'ctx>(buffers: &'a [Option<DeviceBuffer<'ctx>>], index: usize) -> Result<&'a DeviceBuffer<'ctx>> {
|
||||
buffers.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)
|
||||
}
|
||||
fn routed_hidden(
|
||||
transport: &mut Transport<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
(slot, expert): (usize, u32),
|
||||
(q, scales): (usize, usize),
|
||||
) -> Result<usize> {
|
||||
let context = transport.context;
|
||||
let gateup = transport.produce(Role::RoutedGu(slot, expert), |inputs, out| {
|
||||
context.mtp_s2_gate_up_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error)
|
||||
})?;
|
||||
let gateup_index = transport.validate(&gateup, Role::RoutedGu(slot, expert))?;
|
||||
let hidden = transport.produce(Role::RoutedHidden(slot, expert), |inputs, out| {
|
||||
context.mtp_swiglu_640(at(inputs, gateup_index)?, out).map_err(moe_driver_error)
|
||||
})?;
|
||||
transport.release(gateup_index)?;
|
||||
transport.validate(&hidden, Role::RoutedHidden(slot, expert))
|
||||
}
|
||||
fn routed_down(
|
||||
transport: &mut Transport<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
(slot, expert): (usize, u32),
|
||||
hidden_index: usize,
|
||||
) -> Result<Finite> {
|
||||
let context = transport.context;
|
||||
let (q, scales) = transport.quantize(hidden_index, true)?;
|
||||
transport.release(hidden_index)?;
|
||||
let result = transport.produce(Role::RoutedDown(slot, expert), |inputs, out| {
|
||||
context.mtp_s2_down_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error)
|
||||
});
|
||||
let cleanup = transport.release_all(&[q, scales]);
|
||||
let output = result?;
|
||||
cleanup?;
|
||||
Ok(output)
|
||||
}
|
||||
pub(super) fn routed(
|
||||
transport: &mut Transport<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
@@ -183,23 +229,6 @@ pub(super) fn routed(
|
||||
if slot >= K || expert >= 512 {
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
let context = transport.context;
|
||||
let gateup = transport.produce(Role::RoutedGu(slot, expert), |inputs, out| {
|
||||
context.mtp_s2_gate_up_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error)
|
||||
})?;
|
||||
let gateup_index = transport.validate(&gateup, Role::RoutedGu(slot, expert))?;
|
||||
let hidden = transport.produce(Role::RoutedHidden(slot, expert), |inputs, out| {
|
||||
context.mtp_swiglu_640(at(inputs, gateup_index)?, out).map_err(moe_driver_error)
|
||||
})?;
|
||||
transport.release(gateup_index)?;
|
||||
let hidden_index = transport.validate(&hidden, Role::RoutedHidden(slot, expert))?;
|
||||
let (q, scales) = transport.quantize(hidden_index, true)?;
|
||||
transport.release(hidden_index)?;
|
||||
let result = transport.produce(Role::RoutedDown(slot, expert), |inputs, out| {
|
||||
context.mtp_s2_down_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error)
|
||||
});
|
||||
let cleanup = transport.release_all(&[q, scales]);
|
||||
let output = result?;
|
||||
cleanup?;
|
||||
Ok(output)
|
||||
let hidden_index = routed_hidden(transport, bank, (slot, expert), (q, scales))?;
|
||||
routed_down(transport, bank, (slot, expert), hidden_index)
|
||||
}
|
||||
|
||||
+48
-16
@@ -27,7 +27,7 @@ pub(super) fn shared_project(
|
||||
.map_err(moe_driver_error)
|
||||
})
|
||||
}
|
||||
pub(super) fn shared(transport: &mut Transport<'_>, weights: [&DeviceBuffer<'_>; 4], input: usize) -> Result<Finite> {
|
||||
fn shared_hidden(transport: &mut Transport<'_>, weights: [&DeviceBuffer<'_>; 4], input: usize) -> Result<usize> {
|
||||
let gate = shared_project(transport, Role::SharedGate, weights[0], input)?;
|
||||
let up = shared_project(transport, Role::SharedUp, weights[1], input)?;
|
||||
let gate_index = transport.validate(&gate, Role::SharedGate)?;
|
||||
@@ -39,27 +39,42 @@ pub(super) fn shared(transport: &mut Transport<'_>, weights: [&DeviceBuffer<'_>;
|
||||
let cleanup = transport.release_all(&[gate_index, up_index]);
|
||||
let hidden = result?;
|
||||
cleanup?;
|
||||
let hidden_index = transport.validate(&hidden, Role::SharedHidden)?;
|
||||
let result = shared_project(transport, Role::SharedDown, weights[2], hidden_index);
|
||||
transport.validate(&hidden, Role::SharedHidden)
|
||||
}
|
||||
fn shared_down(transport: &mut Transport<'_>, weights: &DeviceBuffer<'_>, hidden_index: usize) -> Result<usize> {
|
||||
let result = shared_project(transport, Role::SharedDown, weights, hidden_index);
|
||||
let cleanup = transport.release(hidden_index);
|
||||
let down = result?;
|
||||
cleanup?;
|
||||
let down_index = transport.validate(&down, Role::SharedDown)?;
|
||||
transport.validate(&down, Role::SharedDown)
|
||||
}
|
||||
fn shared_scaled(
|
||||
transport: &mut Transport<'_>,
|
||||
scalar_weights: &DeviceBuffer<'_>,
|
||||
input: usize,
|
||||
down: usize,
|
||||
) -> Result<Finite> {
|
||||
let context = transport.context;
|
||||
let scalar = transport.produce(Role::Scalar, |inputs, out| {
|
||||
context.moe_shared_scalar_f32_bf16(at(inputs, input)?, weights[3], out).map_err(moe_driver_error)
|
||||
context.moe_shared_scalar_f32_bf16(at(inputs, input)?, scalar_weights, out).map_err(moe_driver_error)
|
||||
})?;
|
||||
if !(0.0..=1.0).contains(&scalar.values[0]) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
let scalar_index = transport.validate(&scalar, Role::Scalar)?;
|
||||
let result = transport.produce(Role::Scaled, |inputs, out| {
|
||||
context.moe_shared_scale_f32(at(inputs, down_index)?, at(inputs, scalar_index)?, out).map_err(moe_driver_error)
|
||||
context.moe_shared_scale_f32(at(inputs, down)?, at(inputs, scalar_index)?, out).map_err(moe_driver_error)
|
||||
});
|
||||
let cleanup = transport.release_all(&[down_index, scalar_index]);
|
||||
let cleanup = transport.release_all(&[down, scalar_index]);
|
||||
let scaled = result?;
|
||||
cleanup?;
|
||||
Ok(scaled)
|
||||
}
|
||||
pub(super) fn shared(transport: &mut Transport<'_>, weights: [&DeviceBuffer<'_>; 4], input: usize) -> Result<Finite> {
|
||||
let hidden_index = shared_hidden(transport, weights, input)?;
|
||||
let down_index = shared_down(transport, weights[2], hidden_index)?;
|
||||
shared_scaled(transport, weights[3], input, down_index)
|
||||
}
|
||||
impl Packed {
|
||||
pub(super) fn new(transport: &mut Transport<'_>, ids: [u32; K]) -> Result<Self> {
|
||||
for (slot, id) in ids.iter().enumerate() {
|
||||
@@ -93,17 +108,23 @@ impl Packed {
|
||||
self.next += 1;
|
||||
Ok(())
|
||||
}
|
||||
/// Test-only: the packed destination is read back and recorded before the combine consumes it.
|
||||
#[cfg(test)]
|
||||
fn observe_packed(&self, transport: &mut Transport<'_>) -> Result<()> {
|
||||
if transport.observations.is_some() {
|
||||
let result = download(transport.buffer(self.index)?, K * N);
|
||||
transport.note(&result);
|
||||
transport.observe(Role::Packed, &result?)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn combine(&self, transport: &mut Transport<'_>, weights: usize, shared: &Finite) -> Result<Finite> {
|
||||
if self.next != K || !Rc::ptr_eq(&self.invocation, &transport.invocation) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let shared = transport.validate(shared, Role::Scaled)?;
|
||||
#[cfg(test)]
|
||||
if transport.observations.is_some() {
|
||||
let result = download(transport.buffer(self.index)?, K * N);
|
||||
transport.note(&result);
|
||||
transport.observe(Role::Packed, &result?)?;
|
||||
}
|
||||
self.observe_packed(transport)?;
|
||||
let context = transport.context;
|
||||
transport.produce(Role::Combined, |inputs, out| {
|
||||
context
|
||||
@@ -128,6 +149,20 @@ pub(in super::super) fn compose(
|
||||
let result = compose_inner(&mut transport, bank, shared_weights, mixed, ids, weights);
|
||||
transport.finish(result)
|
||||
}
|
||||
/// Every routed expert's Down, packed in slot order; the first failure stops before any later expert runs.
|
||||
fn pack_routed(
|
||||
transport: &mut Transport<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
ids: [u32; K],
|
||||
packed: &mut Packed,
|
||||
(q, scales): (usize, usize),
|
||||
) -> Result<()> {
|
||||
for (slot, expert) in ids.into_iter().enumerate() {
|
||||
let down = routed(transport, bank, slot, expert, q, scales)?;
|
||||
packed.pack(transport, down)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn compose_inner(
|
||||
transport: &mut Transport<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
@@ -139,10 +174,7 @@ pub(super) fn compose_inner(
|
||||
let input = transport.upload(mixed)?;
|
||||
let mut packed = Packed::new(transport, ids)?;
|
||||
let (q, scales) = transport.quantize(input, false)?;
|
||||
for (slot, expert) in ids.into_iter().enumerate() {
|
||||
let down = routed(transport, bank, slot, expert, q, scales)?;
|
||||
packed.pack(transport, down)?;
|
||||
}
|
||||
pack_routed(transport, bank, ids, &mut packed, (q, scales))?;
|
||||
transport.release_all(&[q, scales])?;
|
||||
let scaled = shared(transport, shared_weights, input)?;
|
||||
let route_weights = transport.upload(&weights)?;
|
||||
|
||||
@@ -27,155 +27,53 @@ fn retained_mtp_experts_match_original_s2_shared_and_combine_and_clean_abort() {
|
||||
let driver = Driver::load().unwrap();
|
||||
let device = driver.device(0).unwrap();
|
||||
let ctx = device.create_context(1024 * 1024 * 1024).unwrap();
|
||||
let failed = Rc::new(Cell::new(false));
|
||||
let refusals = Cell::new(0);
|
||||
let mut bank_bytes = bank_fixture();
|
||||
let mut bank = bytes(&ctx, &bank_bytes);
|
||||
let shared_bytes = [matrix(FF, N, 0x0c00, 0), matrix(FF, N, 0x0c00, 1), matrix(N, FF, 0x1c00, 2), scalar_matrix()];
|
||||
let shared_buffers = shared_bytes.each_ref().map(|b| bytes(&ctx, b));
|
||||
let w = shared_buffers.each_ref();
|
||||
let charge = ctx.allocated_bytes();
|
||||
assert_eq!(charge, 713_016_320);
|
||||
for zero in [false, true] {
|
||||
let mixed: Vec<f32> = (0..N)
|
||||
.map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { ((i % 17) as f32 - 8.) / 2048. })
|
||||
.collect();
|
||||
let expected = original(&ctx, &bank, w, &mixed);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
// DEV provides test-only observation of actual serving-produced finite
|
||||
// witnesses; no unverified host/device pair enters the serving path.
|
||||
compare_observed(&ctx, &bank, w, &mixed, &expected, failed.clone());
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
assert!(!failed.get());
|
||||
println!("MTP_EXPERT_RETAINED PAIR zero={zero} observed_words=80001 returned_words=2560 unique_words=54401");
|
||||
}
|
||||
let mut fixture = Fixture::new(&ctx);
|
||||
let w = fixture.shared_buffers.each_ref();
|
||||
let env = Env { ctx: &ctx, failed: Rc::new(Cell::new(false)), refusals: Cell::new(0), charge: fixture.charge };
|
||||
env.pair_cases(&fixture.bank, w);
|
||||
let mixed = vec![0.125 / 64.; N];
|
||||
refusal(
|
||||
compose(&ctx, &bank, w, &mixed[..N - 1], IDS, ROUTE, failed.clone()),
|
||||
Error::InvalidDimension,
|
||||
&ctx,
|
||||
charge,
|
||||
&refusals,
|
||||
);
|
||||
let mut bad_mixed = mixed.clone();
|
||||
bad_mixed[N - 1] = f32::NAN;
|
||||
refusal(compose(&ctx, &bank, w, &bad_mixed, IDS, ROUTE, failed.clone()), Error::NonFinite, &ctx, charge, &refusals);
|
||||
for (slot, id) in [(K - 1, 512), (K - 1, IDS[0])] {
|
||||
let mut bad = IDS;
|
||||
bad[slot] = id;
|
||||
refusal(
|
||||
compose(&ctx, &bank, w, &mixed, bad, ROUTE, failed.clone()),
|
||||
Error::InvalidExpert,
|
||||
&ctx,
|
||||
charge,
|
||||
&refusals,
|
||||
);
|
||||
}
|
||||
for value in [f32::NAN, -0.01, 1.01] {
|
||||
let mut bad = ROUTE;
|
||||
bad[K - 1] = value;
|
||||
refusal(compose(&ctx, &bank, w, &mixed, IDS, bad, failed.clone()), Error::NonFinite, &ctx, charge, &refusals);
|
||||
}
|
||||
let malformed = bytes(&ctx, &[0; 4]);
|
||||
let with_bad = ctx.allocated_bytes();
|
||||
refusal(
|
||||
compose(&ctx, &malformed, w, &mixed, IDS, ROUTE, failed.clone()),
|
||||
Error::InvalidDimension,
|
||||
&ctx,
|
||||
with_bad,
|
||||
&refusals,
|
||||
);
|
||||
let mut bad_w = w;
|
||||
bad_w[0] = &malformed;
|
||||
refusal(
|
||||
compose(&ctx, &bank, bad_w, &mixed, IDS, ROUTE, failed.clone()),
|
||||
Error::InvalidDimension,
|
||||
&ctx,
|
||||
with_bad,
|
||||
&refusals,
|
||||
);
|
||||
malformed.release().unwrap();
|
||||
// Last routed expert's last Down scale refuses after earlier slots copied;
|
||||
// failure must discard the invocation's partial actual packed destination.
|
||||
let last = IDS[K - 1] as usize * BLOB_BYTES + 1_331_200 + (N * 10 - 1) * 2;
|
||||
let old = [bank_bytes[last], bank_bytes[last + 1]];
|
||||
bank_bytes[last..last + 2].copy_from_slice(&0x7e00u16.to_le_bytes());
|
||||
bank.copy_from(&bank_bytes).unwrap();
|
||||
refusal(compose(&ctx, &bank, w, &mixed, IDS, ROUTE, failed.clone()), Error::NonFinite, &ctx, charge, &refusals);
|
||||
bank_bytes[last..last + 2].copy_from_slice(&old);
|
||||
bank.copy_from(&bank_bytes).unwrap();
|
||||
let mut bad_down = shared_bytes[2].clone();
|
||||
let end = bad_down.len();
|
||||
bad_down[end - 34..end - 32].copy_from_slice(&0x7c00u16.to_le_bytes());
|
||||
let bad = bytes(&ctx, &bad_down);
|
||||
let mut bad_w = w;
|
||||
bad_w[2] = &bad;
|
||||
let with_bad = ctx.allocated_bytes();
|
||||
refusal(
|
||||
compose(&ctx, &bank, bad_w, &mixed, IDS, ROUTE, failed.clone()),
|
||||
Error::NonFinite,
|
||||
&ctx,
|
||||
with_bad,
|
||||
&refusals,
|
||||
);
|
||||
bad.release().unwrap();
|
||||
let mut bad_scalar = shared_bytes[3].clone();
|
||||
let end = bad_scalar.len();
|
||||
bad_scalar[end - 2..].copy_from_slice(&0x7fc0u16.to_le_bytes());
|
||||
let bad = bytes(&ctx, &bad_scalar);
|
||||
let mut bad_w = w;
|
||||
bad_w[3] = &bad;
|
||||
let with_bad = ctx.allocated_bytes();
|
||||
refusal(
|
||||
compose(&ctx, &bank, bad_w, &mixed, IDS, ROUTE, failed.clone()),
|
||||
Error::NonFinite,
|
||||
&ctx,
|
||||
with_bad,
|
||||
&refusals,
|
||||
);
|
||||
bad.release().unwrap();
|
||||
assert!(!failed.get());
|
||||
private_owner_guards(&ctx, &bank, w, &mixed, failed.clone(), &refusals);
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
let foreign = device.create_context(144 * 1024 * 1024).unwrap();
|
||||
refusal(
|
||||
compose(&foreign, &bank, w, &mixed, IDS, ROUTE, Rc::new(Cell::new(false))),
|
||||
Error::IdentityMismatch,
|
||||
&foreign,
|
||||
0,
|
||||
&refusals,
|
||||
);
|
||||
foreign.close().unwrap();
|
||||
let low = device.create_context(DEVICE_PEAK - 1).unwrap();
|
||||
refusal(
|
||||
compose(&low, &bank, w, &mixed, IDS, ROUTE, Rc::new(Cell::new(false))),
|
||||
Error::InputAllocation,
|
||||
&low,
|
||||
0,
|
||||
&refusals,
|
||||
);
|
||||
low.close().unwrap();
|
||||
unchanged(&bank, &bank_bytes);
|
||||
for (buffer, expected) in shared_buffers.iter().zip(&shared_bytes) {
|
||||
unchanged(buffer, expected);
|
||||
}
|
||||
failed.set(true); // Explicit shared policy, not physical CUDA fault injection.
|
||||
refusal(compose(&ctx, &bank, w, &mixed, IDS, ROUTE, failed.clone()), Error::CudaExecution, &ctx, charge, &refusals);
|
||||
for buffer in shared_buffers {
|
||||
buffer.release().unwrap();
|
||||
}
|
||||
bank.release().unwrap();
|
||||
assert!(failed.get());
|
||||
assert_eq!(ctx.allocated_bytes(), 0);
|
||||
assert_eq!(refusals.get(), 21);
|
||||
env.input_refusals(&fixture.bank, w, &mixed);
|
||||
env.malformed_refusals(&fixture.bank, w, &mixed);
|
||||
env.corrupt_last_scale((&mut fixture.bank, &mut fixture.bank_bytes), w, &mixed);
|
||||
env.corrupt_shared(&fixture.bank, (w, 2), (&mixed, fixture.shared_bytes[2].clone()), (34, 0x7c00u16.to_le_bytes()));
|
||||
env.corrupt_shared(&fixture.bank, (w, 3), (&mixed, fixture.shared_bytes[3].clone()), (2, 0x7fc0u16.to_le_bytes()));
|
||||
assert!(!env.failed.get());
|
||||
private_owner_guards(&ctx, &fixture.bank, w, &mixed, env.failed.clone(), &env.refusals);
|
||||
assert_eq!(ctx.allocated_bytes(), fixture.charge);
|
||||
env.foreign_and_low(&device, &fixture.bank, w, &mixed);
|
||||
let refusals = env.conclude(fixture, &mixed);
|
||||
ctx.synchronize().unwrap();
|
||||
ctx.close().unwrap();
|
||||
println!(
|
||||
"MTP_EXPERT_RETAINED COMPLETE finite_cases=2 exact_words=165122 unique_words=108802 refusals={} abort_cleanup=2 allocated=0",
|
||||
refusals.get()
|
||||
"MTP_EXPERT_RETAINED COMPLETE finite_cases=2 exact_words=165122 unique_words=108802 refusals={} \
|
||||
abort_cleanup=2 allocated=0",
|
||||
refusals
|
||||
);
|
||||
}
|
||||
|
||||
/// The resident bank and the four shared weights with the host bytes they were uploaded from.
|
||||
pub(super) struct Fixture<'c> {
|
||||
bank_bytes: Vec<u8>,
|
||||
bank: DeviceBuffer<'c>,
|
||||
shared_bytes: [Vec<u8>; 4],
|
||||
shared_buffers: [DeviceBuffer<'c>; 4],
|
||||
charge: usize,
|
||||
}
|
||||
impl<'c> Fixture<'c> {
|
||||
fn new(ctx: &'c Context<'c>) -> Self {
|
||||
let bank_bytes = bank_fixture();
|
||||
let bank = bytes(ctx, &bank_bytes);
|
||||
let shared_bytes =
|
||||
[matrix(FF, N, 0x0c00, 0), matrix(FF, N, 0x0c00, 1), matrix(N, FF, 0x1c00, 2), scalar_matrix()];
|
||||
let shared_buffers = shared_bytes.each_ref().map(|b| bytes(ctx, b));
|
||||
let charge = ctx.allocated_bytes();
|
||||
assert_eq!(charge, 713_016_320);
|
||||
Self { bank_bytes, bank, shared_bytes, shared_buffers, charge }
|
||||
}
|
||||
}
|
||||
#[path = "mtp_expert_transport_gpu/phases_fn.rs"]
|
||||
mod phases_fn;
|
||||
use phases_fn::Env;
|
||||
#[path = "mtp_expert_transport_gpu/exact_fn.rs"]
|
||||
mod exact_fn;
|
||||
#[allow(unused_imports)]
|
||||
|
||||
@@ -15,26 +15,32 @@ pub(super) fn bytes<'ctx>(ctx: &'ctx Context<'ctx>, values: &[u8]) -> DeviceBuff
|
||||
out.copy_from(values).unwrap();
|
||||
out
|
||||
}
|
||||
/// One matrix of an expert blob: palette codes per row and alternating-sign scales per chunk.
|
||||
fn fill_blob_part(
|
||||
blob: &mut [u8],
|
||||
expert: usize,
|
||||
(rows, columns, codes, scales, chunks): (usize, usize, usize, usize, usize),
|
||||
) {
|
||||
let palette = [0xe4, 0x39, 0x4e, 0x93];
|
||||
for row in 0..rows {
|
||||
for col in 0..columns {
|
||||
blob[codes + row * columns + col] = palette[(expert + row * 3 + col * 5 + col / 8) % 4];
|
||||
}
|
||||
for chunk in 0..chunks {
|
||||
// Literal half 2^-10, alternating sign with distinct rows.
|
||||
let half = 0x1400u16 | if (row + chunk + expert).is_multiple_of(2) { 0 } else { 0x8000 };
|
||||
let at = scales + (row * chunks + chunk) * 2;
|
||||
blob[at..at + 2].copy_from_slice(&half.to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn bank_fixture() -> Vec<u8> {
|
||||
let mut bank = vec![0; BANK_BYTES];
|
||||
let palette = [0xe4, 0x39, 0x4e, 0x93];
|
||||
for expert in IDS {
|
||||
let base = expert as usize * BLOB_BYTES;
|
||||
let blob = &mut bank[base..base + BLOB_BYTES];
|
||||
for (rows, columns, codes, scales, chunks) in
|
||||
[(1280, 640, 0, 1_228_800, 40), (2560, 160, 819_200, 1_331_200, 10)]
|
||||
{
|
||||
for row in 0..rows {
|
||||
for col in 0..columns {
|
||||
blob[codes + row * columns + col] = palette[(expert as usize + row * 3 + col * 5 + col / 8) % 4];
|
||||
}
|
||||
for chunk in 0..chunks {
|
||||
// Literal half 2^-10, alternating sign with distinct rows.
|
||||
let half = 0x1400u16 | if (row + chunk + expert as usize).is_multiple_of(2) { 0 } else { 0x8000 };
|
||||
let at = scales + (row * chunks + chunk) * 2;
|
||||
blob[at..at + 2].copy_from_slice(&half.to_le_bytes());
|
||||
}
|
||||
}
|
||||
for part in [(1280, 640, 0, 1_228_800, 40), (2560, 160, 819_200, 1_331_200, 10)] {
|
||||
fill_blob_part(blob, expert as usize, part);
|
||||
}
|
||||
}
|
||||
bank
|
||||
@@ -74,39 +80,62 @@ pub(super) fn original_project(
|
||||
release([x, out]).unwrap();
|
||||
result
|
||||
}
|
||||
pub(super) fn original(
|
||||
/// One expert's original S2 chain: gate/up, swiglu, hidden quantizer, down; each stage read back.
|
||||
fn routed_expert(
|
||||
ctx: &Context<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
w: [&DeviceBuffer<'_>; 4],
|
||||
mixed: &[f32],
|
||||
) -> Original {
|
||||
let x = upload(ctx, mixed).unwrap();
|
||||
expert: u32,
|
||||
(q, scales): (&DeviceBuffer<'_>, &DeviceBuffer<'_>),
|
||||
) -> (Box<[f32]>, Box<[f32]>, Box<[f32]>) {
|
||||
let mut gu = allocate(ctx, 2 * FF).unwrap();
|
||||
ctx.mtp_s2_gate_up_full(bank, expert, q, scales, &mut gu).unwrap();
|
||||
let gu_values = download(&gu, 2 * FF).unwrap();
|
||||
let mut hidden = allocate(ctx, FF).unwrap();
|
||||
ctx.mtp_swiglu_640(&gu, &mut hidden).unwrap();
|
||||
let hidden_values = download(&hidden, FF).unwrap();
|
||||
gu.release().unwrap();
|
||||
let mut hq = ctx.allocate(680).unwrap();
|
||||
let mut hs = allocate(ctx, 20).unwrap();
|
||||
ctx.mtp_quantize_scaled_640(&hidden, &mut hq, &mut hs).unwrap();
|
||||
download(&hs, 20).unwrap();
|
||||
hidden.release().unwrap();
|
||||
let mut down = allocate(ctx, N).unwrap();
|
||||
ctx.mtp_s2_down_full(bank, expert, &hq, &hs, &mut down).unwrap();
|
||||
let down_values = download(&down, N).unwrap();
|
||||
release([hq, hs, down]).unwrap();
|
||||
(gu_values, hidden_values, down_values)
|
||||
}
|
||||
fn routed_originals(
|
||||
ctx: &Context<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
x: &DeviceBuffer<'_>,
|
||||
) -> (Vec<Box<[f32]>>, Vec<Box<[f32]>>, Vec<Box<[f32]>>) {
|
||||
let mut q = ctx.allocate(2720).unwrap();
|
||||
let mut scales = allocate(ctx, 80).unwrap();
|
||||
ctx.mtp_quantize_scaled_2560(&x, &mut q, &mut scales).unwrap();
|
||||
ctx.mtp_quantize_scaled_2560(x, &mut q, &mut scales).unwrap();
|
||||
download(&scales, 80).unwrap();
|
||||
let mut routed_gu = Vec::new();
|
||||
let mut routed_hidden = Vec::new();
|
||||
let mut routed = Vec::new();
|
||||
let (mut routed_gu, mut routed_hidden, mut routed) = (Vec::new(), Vec::new(), Vec::new());
|
||||
for expert in IDS {
|
||||
let mut gu = allocate(ctx, 2 * FF).unwrap();
|
||||
ctx.mtp_s2_gate_up_full(bank, expert, &q, &scales, &mut gu).unwrap();
|
||||
routed_gu.push(download(&gu, 2 * FF).unwrap());
|
||||
let mut hidden = allocate(ctx, FF).unwrap();
|
||||
ctx.mtp_swiglu_640(&gu, &mut hidden).unwrap();
|
||||
routed_hidden.push(download(&hidden, FF).unwrap());
|
||||
gu.release().unwrap();
|
||||
let mut hq = ctx.allocate(680).unwrap();
|
||||
let mut hs = allocate(ctx, 20).unwrap();
|
||||
ctx.mtp_quantize_scaled_640(&hidden, &mut hq, &mut hs).unwrap();
|
||||
download(&hs, 20).unwrap();
|
||||
hidden.release().unwrap();
|
||||
let mut down = allocate(ctx, N).unwrap();
|
||||
ctx.mtp_s2_down_full(bank, expert, &hq, &hs, &mut down).unwrap();
|
||||
routed.push(download(&down, N).unwrap());
|
||||
release([hq, hs, down]).unwrap();
|
||||
let (gu, hidden, down) = routed_expert(ctx, bank, expert, (&q, &scales));
|
||||
routed_gu.push(gu);
|
||||
routed_hidden.push(hidden);
|
||||
routed.push(down);
|
||||
}
|
||||
release([q, scales]).unwrap();
|
||||
(routed_gu, routed_hidden, routed)
|
||||
}
|
||||
/// Original shared expert chain: gate/up projections, swiglu, down projection, scalar and scale; the device
|
||||
/// products the combine still needs stay alive.
|
||||
struct SharedStage<'c> {
|
||||
gate: Box<[f32]>,
|
||||
up: Box<[f32]>,
|
||||
hidden: Box<[f32]>,
|
||||
down: Box<[f32]>,
|
||||
scalar_values: Box<[f32]>,
|
||||
scaled_values: Box<[f32]>,
|
||||
devices: [DeviceBuffer<'c>; 3],
|
||||
}
|
||||
fn shared_hidden_values(ctx: &Context<'_>, w: [&DeviceBuffer<'_>; 2], mixed: &[f32]) -> [Box<[f32]>; 3] {
|
||||
let gate = original_project(ctx, w[0], mixed, FF, N);
|
||||
let up = original_project(ctx, w[1], mixed, FF, N);
|
||||
let g = upload(ctx, &gate).unwrap();
|
||||
@@ -115,16 +144,38 @@ pub(super) fn original(
|
||||
ctx.moe_swiglu_f32(&g, &u, &mut hidden).unwrap();
|
||||
let hidden_values = download(&hidden, FF).unwrap();
|
||||
release([g, u, hidden]).unwrap();
|
||||
let down = original_project(ctx, w[2], &hidden_values, N, FF);
|
||||
[gate, up, hidden_values]
|
||||
}
|
||||
fn shared_stage<'c>(
|
||||
ctx: &'c Context<'_>,
|
||||
w: [&DeviceBuffer<'_>; 4],
|
||||
mixed: &[f32],
|
||||
x: &DeviceBuffer<'_>,
|
||||
) -> SharedStage<'c> {
|
||||
let [gate, up, hidden] = shared_hidden_values(ctx, [w[0], w[1]], mixed);
|
||||
let down = original_project(ctx, w[2], &hidden, N, FF);
|
||||
let down_gpu = upload(ctx, &down).unwrap();
|
||||
let mut scalar = allocate(ctx, 1).unwrap();
|
||||
ctx.moe_shared_scalar_f32_bf16(&x, w[3], &mut scalar).unwrap();
|
||||
ctx.moe_shared_scalar_f32_bf16(x, w[3], &mut scalar).unwrap();
|
||||
let scalar_values = download(&scalar, 1).unwrap();
|
||||
assert!((0.0..=1.0).contains(&scalar_values[0]));
|
||||
let mut scaled = allocate(ctx, N).unwrap();
|
||||
ctx.moe_shared_scale_f32(&down_gpu, &scalar, &mut scaled).unwrap();
|
||||
let scaled_values = download(&scaled, N).unwrap();
|
||||
// This upload baseline precedes every retained candidate, in router order.
|
||||
let devices = [down_gpu, scalar, scaled];
|
||||
SharedStage { gate, up, hidden, down, scalar_values, scaled_values, devices }
|
||||
}
|
||||
/// The original baseline; its combine upload precedes every retained candidate, in router order.
|
||||
pub(super) fn original(
|
||||
ctx: &Context<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
w: [&DeviceBuffer<'_>; 4],
|
||||
mixed: &[f32],
|
||||
) -> Original {
|
||||
let x = upload(ctx, mixed).unwrap();
|
||||
let (routed_gu, routed_hidden, routed) = routed_originals(ctx, bank, &x);
|
||||
let SharedStage { gate, up, hidden, down, scalar_values, scaled_values, devices } = shared_stage(ctx, w, mixed, &x);
|
||||
let [down_gpu, scalar, scaled] = devices;
|
||||
let parts: Vec<f32> = routed.iter().flat_map(|v| v.iter().copied()).collect();
|
||||
let parts = upload(ctx, &parts).unwrap();
|
||||
let weights = upload(ctx, &ROUTE).unwrap();
|
||||
@@ -138,14 +189,33 @@ pub(super) fn original(
|
||||
routed,
|
||||
gate,
|
||||
up,
|
||||
hidden: hidden_values,
|
||||
hidden,
|
||||
down,
|
||||
scalar: scalar_values,
|
||||
scaled: scaled_values,
|
||||
combined,
|
||||
}
|
||||
}
|
||||
|
||||
fn routed_stage(i: usize, expected: &Original) -> (Role, &[f32]) {
|
||||
let slot = i / 3;
|
||||
match i % 3 {
|
||||
0 => (Role::RoutedGu(slot, IDS[slot]), &expected.routed_gu[slot]),
|
||||
1 => (Role::RoutedHidden(slot, IDS[slot]), &expected.routed_hidden[slot]),
|
||||
_ => (Role::RoutedDown(slot, IDS[slot]), &expected.routed[slot]),
|
||||
}
|
||||
}
|
||||
fn shared_observed<'a>(i: usize, expected: &'a Original, parts: &'a [f32]) -> (Role, &'a [f32]) {
|
||||
match i {
|
||||
0 => (Role::SharedGate, &expected.gate),
|
||||
1 => (Role::SharedUp, &expected.up),
|
||||
2 => (Role::SharedHidden, &expected.hidden),
|
||||
3 => (Role::SharedDown, &expected.down),
|
||||
4 => (Role::Scalar, &expected.scalar),
|
||||
5 => (Role::Scaled, &expected.scaled),
|
||||
6 => (Role::Packed, parts),
|
||||
_ => (Role::Combined, &expected.combined),
|
||||
}
|
||||
}
|
||||
pub(super) fn compare_observed(
|
||||
ctx: &Context<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
@@ -159,36 +229,16 @@ pub(super) fn compare_observed(
|
||||
let parts: Vec<f32> = expected.routed.iter().flat_map(|v| v.iter().copied()).collect();
|
||||
let mut words = 0;
|
||||
for (i, (role, value)) in observed.iter().enumerate() {
|
||||
if i < 30 {
|
||||
let slot = i / 3;
|
||||
let (expected_role, original) = match i % 3 {
|
||||
0 => (Role::RoutedGu(slot, IDS[slot]), &expected.routed_gu[slot]),
|
||||
1 => (Role::RoutedHidden(slot, IDS[slot]), &expected.routed_hidden[slot]),
|
||||
_ => (Role::RoutedDown(slot, IDS[slot]), &expected.routed[slot]),
|
||||
};
|
||||
assert!(*role == expected_role);
|
||||
exact(value, original);
|
||||
} else {
|
||||
let (expected_role, original): (Role, &[f32]) = match i - 30 {
|
||||
0 => (Role::SharedGate, &expected.gate),
|
||||
1 => (Role::SharedUp, &expected.up),
|
||||
2 => (Role::SharedHidden, &expected.hidden),
|
||||
3 => (Role::SharedDown, &expected.down),
|
||||
4 => (Role::Scalar, &expected.scalar),
|
||||
5 => (Role::Scaled, &expected.scaled),
|
||||
6 => (Role::Packed, &parts),
|
||||
_ => (Role::Combined, &expected.combined),
|
||||
};
|
||||
assert!(*role == expected_role);
|
||||
exact(value, original);
|
||||
}
|
||||
let (expected_role, original) =
|
||||
if i < 30 { routed_stage(i, expected) } else { shared_observed(i - 30, expected, &parts) };
|
||||
assert!(*role == expected_role);
|
||||
exact(value, original);
|
||||
words += value.len();
|
||||
}
|
||||
assert_eq!(words, 80_001);
|
||||
// Also bind the externally returned finite block to the original baseline.
|
||||
exact(&output, &expected.combined);
|
||||
}
|
||||
|
||||
pub(super) fn refusal<T>(result: Result<T>, error: Error, ctx: &Context<'_>, charge: usize, count: &Cell<usize>) {
|
||||
assert_eq!(result.err(), Some(error));
|
||||
assert_eq!(ctx.allocated_bytes(), charge);
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
//! The phases of the retained MTP expert transport proof (one body per phase, STRA-338).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// One context, the shared failure bit, the refusal counter and the resident charge every phase works against.
|
||||
pub(super) struct Env<'c> {
|
||||
pub(super) ctx: &'c Context<'c>,
|
||||
pub(super) failed: Rc<Cell<bool>>,
|
||||
pub(super) refusals: Cell<usize>,
|
||||
pub(super) charge: usize,
|
||||
}
|
||||
|
||||
type Weights<'a, 'c> = [&'a DeviceBuffer<'c>; 4];
|
||||
|
||||
fn pair_mixed(zero: bool) -> Vec<f32> {
|
||||
(0..N).map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { ((i % 17) as f32 - 8.) / 2048. }).collect()
|
||||
}
|
||||
|
||||
impl<'c> Env<'c> {
|
||||
fn refuse(&self, result: Result<Box<[f32]>>, error: Error, charge: usize) {
|
||||
refusal(result, error, self.ctx, charge, &self.refusals);
|
||||
}
|
||||
fn compose(
|
||||
&self,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
w: Weights<'_, '_>,
|
||||
mixed: &[f32],
|
||||
(ids, route): ([u32; K], [f32; K]),
|
||||
) -> Result<Box<[f32]>> {
|
||||
compose(self.ctx, bank, w, mixed, ids, route, self.failed.clone())
|
||||
}
|
||||
pub(super) fn pair_cases(&self, bank: &DeviceBuffer<'_>, w: Weights<'_, '_>) {
|
||||
let ctx = self.ctx;
|
||||
for zero in [false, true] {
|
||||
let mixed = pair_mixed(zero);
|
||||
let expected = original(ctx, bank, w, &mixed);
|
||||
assert_eq!(ctx.allocated_bytes(), self.charge);
|
||||
// DEV provides test-only observation of actual serving-produced finite
|
||||
// witnesses; no unverified host/device pair enters the serving path.
|
||||
compare_observed(ctx, bank, w, &mixed, &expected, self.failed.clone());
|
||||
assert_eq!(ctx.allocated_bytes(), self.charge);
|
||||
assert!(!self.failed.get());
|
||||
println!(
|
||||
"MTP_EXPERT_RETAINED PAIR zero={zero} observed_words=80001 returned_words=2560 unique_words=54401"
|
||||
);
|
||||
}
|
||||
}
|
||||
pub(super) fn input_refusals(&self, bank: &DeviceBuffer<'_>, w: Weights<'_, '_>, mixed: &[f32]) {
|
||||
let charge = self.charge;
|
||||
self.refuse(self.compose(bank, w, &mixed[..N - 1], (IDS, ROUTE)), Error::InvalidDimension, charge);
|
||||
let mut bad_mixed = mixed.to_vec();
|
||||
bad_mixed[N - 1] = f32::NAN;
|
||||
self.refuse(self.compose(bank, w, &bad_mixed, (IDS, ROUTE)), Error::NonFinite, charge);
|
||||
for (slot, id) in [(K - 1, 512), (K - 1, IDS[0])] {
|
||||
let mut bad = IDS;
|
||||
bad[slot] = id;
|
||||
self.refuse(self.compose(bank, w, mixed, (bad, ROUTE)), Error::InvalidExpert, charge);
|
||||
}
|
||||
for value in [f32::NAN, -0.01, 1.01] {
|
||||
let mut bad = ROUTE;
|
||||
bad[K - 1] = value;
|
||||
self.refuse(self.compose(bank, w, mixed, (IDS, bad)), Error::NonFinite, charge);
|
||||
}
|
||||
}
|
||||
pub(super) fn malformed_refusals(&self, bank: &DeviceBuffer<'_>, w: Weights<'_, '_>, mixed: &[f32]) {
|
||||
let malformed = bytes(self.ctx, &[0; 4]);
|
||||
let with_bad = self.ctx.allocated_bytes();
|
||||
self.refuse(self.compose(&malformed, w, mixed, (IDS, ROUTE)), Error::InvalidDimension, with_bad);
|
||||
let mut bad_w = w;
|
||||
bad_w[0] = &malformed;
|
||||
self.refuse(self.compose(bank, bad_w, mixed, (IDS, ROUTE)), Error::InvalidDimension, with_bad);
|
||||
malformed.release().unwrap();
|
||||
}
|
||||
/// Last routed expert's last Down scale refuses after earlier slots copied;
|
||||
/// failure must discard the invocation's partial actual packed destination.
|
||||
pub(super) fn corrupt_last_scale(
|
||||
&self,
|
||||
(bank, bank_bytes): (&mut DeviceBuffer<'_>, &mut [u8]),
|
||||
w: Weights<'_, '_>,
|
||||
mixed: &[f32],
|
||||
) {
|
||||
let last = IDS[K - 1] as usize * BLOB_BYTES + 1_331_200 + (N * 10 - 1) * 2;
|
||||
let old = [bank_bytes[last], bank_bytes[last + 1]];
|
||||
bank_bytes[last..last + 2].copy_from_slice(&0x7e00u16.to_le_bytes());
|
||||
bank.copy_from(bank_bytes).unwrap();
|
||||
self.refuse(self.compose(bank, w, mixed, (IDS, ROUTE)), Error::NonFinite, self.charge);
|
||||
bank_bytes[last..last + 2].copy_from_slice(&old);
|
||||
bank.copy_from(bank_bytes).unwrap();
|
||||
}
|
||||
/// Replaces shared weight `index` by `corrupt`ed bytes and expects the non-finite refusal.
|
||||
pub(super) fn corrupt_shared(
|
||||
&self,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
(w, index): (Weights<'_, '_>, usize),
|
||||
(mixed, mut corrupted): (&[f32], Vec<u8>),
|
||||
word: (usize, [u8; 2]),
|
||||
) {
|
||||
let end = corrupted.len();
|
||||
corrupted[end - word.0..end - word.0 + 2].copy_from_slice(&word.1);
|
||||
let bad = bytes(self.ctx, &corrupted);
|
||||
let mut bad_w = w;
|
||||
bad_w[index] = &bad;
|
||||
let with_bad = self.ctx.allocated_bytes();
|
||||
self.refuse(self.compose(bank, bad_w, mixed, (IDS, ROUTE)), Error::NonFinite, with_bad);
|
||||
bad.release().unwrap();
|
||||
}
|
||||
pub(super) fn foreign_and_low(
|
||||
&self,
|
||||
device: &leleka_cuda_driver::Device<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
w: Weights<'_, '_>,
|
||||
mixed: &[f32],
|
||||
) {
|
||||
let foreign = device.create_context(144 * 1024 * 1024).unwrap();
|
||||
let result = compose(&foreign, bank, w, mixed, IDS, ROUTE, Rc::new(Cell::new(false)));
|
||||
refusal(result, Error::IdentityMismatch, &foreign, 0, &self.refusals);
|
||||
foreign.close().unwrap();
|
||||
let low = device.create_context(DEVICE_PEAK - 1).unwrap();
|
||||
let result = compose(&low, bank, w, mixed, IDS, ROUTE, Rc::new(Cell::new(false)));
|
||||
refusal(result, Error::InputAllocation, &low, 0, &self.refusals);
|
||||
low.close().unwrap();
|
||||
}
|
||||
/// The inputs are byte-identical after every refusal; then the explicit shared failure policy fences the
|
||||
/// context and everything is released. Returns the number of refusals.
|
||||
pub(super) fn conclude(&self, fixture: Fixture<'c>, mixed: &[f32]) -> usize {
|
||||
let Fixture { bank_bytes, bank, shared_bytes, shared_buffers, charge } = fixture;
|
||||
let w = shared_buffers.each_ref();
|
||||
unchanged(&bank, &bank_bytes);
|
||||
for (buffer, expected) in shared_buffers.iter().zip(&shared_bytes) {
|
||||
unchanged(buffer, expected);
|
||||
}
|
||||
self.failed.set(true); // Explicit shared policy, not physical CUDA fault injection.
|
||||
self.refuse(self.compose(&bank, w, mixed, (IDS, ROUTE)), Error::CudaExecution, charge);
|
||||
for buffer in shared_buffers {
|
||||
buffer.release().unwrap();
|
||||
}
|
||||
bank.release().unwrap();
|
||||
assert!(self.failed.get());
|
||||
assert_eq!(self.ctx.allocated_bytes(), 0);
|
||||
assert_eq!(self.refusals.get(), 21);
|
||||
self.refusals.get()
|
||||
}
|
||||
}
|
||||
+36
-15
@@ -3,6 +3,40 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
type Count<'a> = &'a Cell<usize>;
|
||||
|
||||
/// A released or foreign-invocation product is never accepted by another transport.
|
||||
fn gate_guards(
|
||||
ctx: &Context<'_>,
|
||||
(t, rival): (&mut Transport<'_>, &mut Transport<'_>),
|
||||
(weights, input): (&DeviceBuffer<'_>, usize),
|
||||
count: Count<'_>,
|
||||
) {
|
||||
let gate = shared_project(t, Role::SharedGate, weights, input).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refusal(t.validate(&gate, Role::SharedUp), Error::IdentityMismatch, ctx, charge, count);
|
||||
refusal(rival.validate(&gate, Role::SharedGate), Error::IdentityMismatch, ctx, charge, count);
|
||||
t.release(gate.index).unwrap();
|
||||
refusal(t.validate(&gate, Role::SharedGate), Error::IdentityMismatch, ctx, ctx.allocated_bytes(), count);
|
||||
}
|
||||
/// A Down product of the wrong slot cannot be packed, and the packed destination cannot combine early.
|
||||
fn slot_guards(
|
||||
ctx: &Context<'_>,
|
||||
t: &mut Transport<'_>,
|
||||
packed: &mut Packed,
|
||||
(bank, w, input): (&DeviceBuffer<'_>, [&DeviceBuffer<'_>; 4], usize),
|
||||
count: Count<'_>,
|
||||
) {
|
||||
let (q, scales) = t.quantize(input, false).unwrap();
|
||||
let wrong_slot = routed(t, bank, 1, IDS[1], q, scales).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refusal(packed.pack(t, wrong_slot), Error::IdentityMismatch, ctx, charge, count);
|
||||
assert_eq!(packed.next, 0);
|
||||
let scaled = shared(t, w, input).unwrap();
|
||||
let weights = t.upload(&ROUTE).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refusal(packed.combine(t, weights, &scaled), Error::IdentityMismatch, ctx, charge, count);
|
||||
}
|
||||
pub(super) fn private_owner_guards(
|
||||
ctx: &Context<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
@@ -16,21 +50,8 @@ pub(super) fn private_owner_guards(
|
||||
let mut rival = Transport::new(ctx, failed).unwrap();
|
||||
let input = t.upload(mixed).unwrap();
|
||||
let mut packed = Packed::new(&mut t, IDS).unwrap();
|
||||
let gate = shared_project(&mut t, Role::SharedGate, w[0], input).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refusal(t.validate(&gate, Role::SharedUp), Error::IdentityMismatch, ctx, charge, count);
|
||||
refusal(rival.validate(&gate, Role::SharedGate), Error::IdentityMismatch, ctx, charge, count);
|
||||
t.release(gate.index).unwrap();
|
||||
refusal(t.validate(&gate, Role::SharedGate), Error::IdentityMismatch, ctx, ctx.allocated_bytes(), count);
|
||||
let (q, scales) = t.quantize(input, false).unwrap();
|
||||
let wrong_slot = routed(&mut t, bank, 1, IDS[1], q, scales).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refusal(packed.pack(&mut t, wrong_slot), Error::IdentityMismatch, ctx, charge, count);
|
||||
assert_eq!(packed.next, 0);
|
||||
let scaled = shared(&mut t, w, input).unwrap();
|
||||
let weights = t.upload(&ROUTE).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refusal(packed.combine(&mut t, weights, &scaled), Error::IdentityMismatch, ctx, charge, count);
|
||||
gate_guards(ctx, (&mut t, &mut rival), (w[0], input), count);
|
||||
slot_guards(ctx, &mut t, &mut packed, (bank, w, input), count);
|
||||
let rival_input = rival.upload(mixed).unwrap();
|
||||
let (rq, rs) = rival.quantize(rival_input, false).unwrap();
|
||||
let foreign_invocation = routed(&mut rival, bank, 0, IDS[0], rq, rs).unwrap();
|
||||
|
||||
+88
-39
@@ -11,6 +11,40 @@ impl Drop for Transport<'_, '_> {
|
||||
pub(super) fn at<'a, 'ctx>(buffers: &'a [Option<DeviceBuffer<'ctx>>], index: usize) -> Result<&'a DeviceBuffer<'ctx>> {
|
||||
buffers.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)
|
||||
}
|
||||
fn routed_hidden(
|
||||
transport: &mut Transport<'_, '_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
(slot, expert): (usize, u32),
|
||||
(q, scales): (usize, usize),
|
||||
) -> Result<usize> {
|
||||
let context = transport.context;
|
||||
let gateup = transport.produce(Role::RoutedGu(slot, expert), |inputs, out| {
|
||||
context.mtp_s2_gate_up_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error)
|
||||
})?;
|
||||
let gateup_index = transport.validate(&gateup, Role::RoutedGu(slot, expert))?;
|
||||
let hidden = transport.produce(Role::RoutedHidden(slot, expert), |inputs, out| {
|
||||
context.mtp_swiglu_640(at(inputs, gateup_index)?, out).map_err(moe_driver_error)
|
||||
})?;
|
||||
transport.release(gateup_index)?;
|
||||
transport.validate(&hidden, Role::RoutedHidden(slot, expert))
|
||||
}
|
||||
fn routed_down(
|
||||
transport: &mut Transport<'_, '_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
(slot, expert): (usize, u32),
|
||||
hidden_index: usize,
|
||||
) -> Result<Finite> {
|
||||
let context = transport.context;
|
||||
let (q, scales) = transport.quantize(hidden_index, true)?;
|
||||
transport.release(hidden_index)?;
|
||||
let result = transport.produce(Role::RoutedDown(slot, expert), |inputs, out| {
|
||||
context.mtp_s2_down_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error)
|
||||
});
|
||||
let cleanup = transport.release_all(&[q, scales]);
|
||||
let output = result?;
|
||||
cleanup?;
|
||||
Ok(output)
|
||||
}
|
||||
pub(super) fn routed(
|
||||
transport: &mut Transport<'_, '_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
@@ -22,25 +56,8 @@ pub(super) fn routed(
|
||||
if slot >= K || expert >= 512 {
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
let context = transport.context;
|
||||
let gateup = transport.produce(Role::RoutedGu(slot, expert), |inputs, out| {
|
||||
context.mtp_s2_gate_up_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error)
|
||||
})?;
|
||||
let gateup_index = transport.validate(&gateup, Role::RoutedGu(slot, expert))?;
|
||||
let hidden = transport.produce(Role::RoutedHidden(slot, expert), |inputs, out| {
|
||||
context.mtp_swiglu_640(at(inputs, gateup_index)?, out).map_err(moe_driver_error)
|
||||
})?;
|
||||
transport.release(gateup_index)?;
|
||||
let hidden_index = transport.validate(&hidden, Role::RoutedHidden(slot, expert))?;
|
||||
let (q, scales) = transport.quantize(hidden_index, true)?;
|
||||
transport.release(hidden_index)?;
|
||||
let result = transport.produce(Role::RoutedDown(slot, expert), |inputs, out| {
|
||||
context.mtp_s2_down_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error)
|
||||
});
|
||||
let cleanup = transport.release_all(&[q, scales]);
|
||||
let output = result?;
|
||||
cleanup?;
|
||||
Ok(output)
|
||||
let hidden_index = routed_hidden(transport, bank, (slot, expert), (q, scales))?;
|
||||
routed_down(transport, bank, (slot, expert), hidden_index)
|
||||
}
|
||||
pub(super) fn shared_project(
|
||||
transport: &mut Transport<'_, '_>,
|
||||
@@ -66,11 +83,7 @@ pub(super) fn shared_project(
|
||||
.map_err(moe_driver_error)
|
||||
})
|
||||
}
|
||||
pub(super) fn shared(
|
||||
transport: &mut Transport<'_, '_>,
|
||||
weights: [&DeviceBuffer<'_>; 4],
|
||||
input: usize,
|
||||
) -> Result<Finite> {
|
||||
fn shared_hidden(transport: &mut Transport<'_, '_>, weights: [&DeviceBuffer<'_>; 4], input: usize) -> Result<usize> {
|
||||
let gate = shared_project(transport, Role::SharedGate, weights[0], input)?;
|
||||
let up = shared_project(transport, Role::SharedUp, weights[1], input)?;
|
||||
let gate_index = transport.validate(&gate, Role::SharedGate)?;
|
||||
@@ -82,27 +95,46 @@ pub(super) fn shared(
|
||||
let cleanup = transport.release_all(&[gate_index, up_index]);
|
||||
let hidden = result?;
|
||||
cleanup?;
|
||||
let hidden_index = transport.validate(&hidden, Role::SharedHidden)?;
|
||||
let result = shared_project(transport, Role::SharedDown, weights[2], hidden_index);
|
||||
transport.validate(&hidden, Role::SharedHidden)
|
||||
}
|
||||
fn shared_down(transport: &mut Transport<'_, '_>, weights: &DeviceBuffer<'_>, hidden_index: usize) -> Result<usize> {
|
||||
let result = shared_project(transport, Role::SharedDown, weights, hidden_index);
|
||||
let cleanup = transport.release(hidden_index);
|
||||
let down = result?;
|
||||
cleanup?;
|
||||
let down_index = transport.validate(&down, Role::SharedDown)?;
|
||||
transport.validate(&down, Role::SharedDown)
|
||||
}
|
||||
fn shared_scaled(
|
||||
transport: &mut Transport<'_, '_>,
|
||||
scalar_weights: &DeviceBuffer<'_>,
|
||||
input: usize,
|
||||
down: usize,
|
||||
) -> Result<Finite> {
|
||||
let context = transport.context;
|
||||
let scalar = transport.produce(Role::Scalar, |inputs, out| {
|
||||
context.moe_shared_scalar_f32_bf16(at(inputs, input)?, weights[3], out).map_err(moe_driver_error)
|
||||
context.moe_shared_scalar_f32_bf16(at(inputs, input)?, scalar_weights, out).map_err(moe_driver_error)
|
||||
})?;
|
||||
if !(0.0..=1.0).contains(&scalar.values[0]) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
let scalar_index = transport.validate(&scalar, Role::Scalar)?;
|
||||
let result = transport.produce(Role::Scaled, |inputs, out| {
|
||||
context.moe_shared_scale_f32(at(inputs, down_index)?, at(inputs, scalar_index)?, out).map_err(moe_driver_error)
|
||||
context.moe_shared_scale_f32(at(inputs, down)?, at(inputs, scalar_index)?, out).map_err(moe_driver_error)
|
||||
});
|
||||
let cleanup = transport.release_all(&[down_index, scalar_index]);
|
||||
let cleanup = transport.release_all(&[down, scalar_index]);
|
||||
let scaled = result?;
|
||||
cleanup?;
|
||||
Ok(scaled)
|
||||
}
|
||||
pub(super) fn shared(
|
||||
transport: &mut Transport<'_, '_>,
|
||||
weights: [&DeviceBuffer<'_>; 4],
|
||||
input: usize,
|
||||
) -> Result<Finite> {
|
||||
let hidden_index = shared_hidden(transport, weights, input)?;
|
||||
let down_index = shared_down(transport, weights[2], hidden_index)?;
|
||||
shared_scaled(transport, weights[3], input, down_index)
|
||||
}
|
||||
impl Packed {
|
||||
pub(super) fn new(transport: &mut Transport<'_, '_>, ids: [u32; K]) -> Result<Self> {
|
||||
for (slot, id) in ids.iter().enumerate() {
|
||||
@@ -141,17 +173,23 @@ impl Packed {
|
||||
self.next += 1;
|
||||
Ok(())
|
||||
}
|
||||
/// Test-only: the packed destination is read back and recorded before the combine consumes it.
|
||||
#[cfg(test)]
|
||||
fn observe_packed(&self, transport: &mut Transport<'_, '_>) -> Result<()> {
|
||||
if transport.observations.is_some() {
|
||||
let result = download(transport.buffer(self.index)?, K * N);
|
||||
transport.note(&result);
|
||||
transport.observe(Role::Packed, &result?)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn combine(&self, transport: &mut Transport<'_, '_>, weights: usize, shared: &Finite) -> Result<Finite> {
|
||||
if self.next != K || !Rc::ptr_eq(&self.invocation, &transport.invocation) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let shared = transport.validate(shared, Role::Scaled)?;
|
||||
#[cfg(test)]
|
||||
if transport.observations.is_some() {
|
||||
let result = download(transport.buffer(self.index)?, K * N);
|
||||
transport.note(&result);
|
||||
transport.observe(Role::Packed, &result?)?;
|
||||
}
|
||||
self.observe_packed(transport)?;
|
||||
let context = transport.context;
|
||||
transport.produce(Role::Combined, |inputs, out| {
|
||||
context
|
||||
@@ -176,6 +214,20 @@ pub(super) fn compose(
|
||||
let result = compose_inner(&mut transport, bank, shared_weights, mixed, ids, weights);
|
||||
transport.finish(result)
|
||||
}
|
||||
/// Every routed expert's Down, packed in slot order; the first failure stops before any later expert runs.
|
||||
fn pack_routed(
|
||||
transport: &mut Transport<'_, '_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
ids: [u32; K],
|
||||
packed: &mut Packed,
|
||||
(q, scales): (usize, usize),
|
||||
) -> Result<()> {
|
||||
for (slot, expert) in ids.into_iter().enumerate() {
|
||||
let down = routed(transport, bank, slot, expert, q, scales)?;
|
||||
packed.pack(transport, down)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn compose_inner(
|
||||
transport: &mut Transport<'_, '_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
@@ -187,10 +239,7 @@ pub(super) fn compose_inner(
|
||||
let input = transport.upload(mixed, Slot::Input)?;
|
||||
let mut packed = Packed::new(transport, ids)?;
|
||||
let (q, scales) = transport.quantize(input, false)?;
|
||||
for (slot, expert) in ids.into_iter().enumerate() {
|
||||
let down = routed(transport, bank, slot, expert, q, scales)?;
|
||||
packed.pack(transport, down)?;
|
||||
}
|
||||
pack_routed(transport, bank, ids, &mut packed, (q, scales))?;
|
||||
transport.release_all(&[q, scales])?;
|
||||
let scaled = shared(transport, shared_weights, input)?;
|
||||
let route_weights = transport.upload(&weights, Slot::Weights)?;
|
||||
|
||||
Reference in New Issue
Block a user