STRA-338 size2 en4: moe_activation, moe_down and moe_down_reuse functions split into phases
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user