STRA-338 size2 en3: layer0 observation report, MoE retained fixtures and component owner split into helpers

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 23:06:28 +01:00
parent d594815eac
commit 48619e66f5
6 changed files with 210 additions and 139 deletions
@@ -27,7 +27,7 @@ impl<'ctx> GdnChunkDevice<'ctx> {
}
Ok(owner)
}
fn empty(context: &'ctx Context<'ctx>, failed: Rc<Cell<bool>>, start: GdnChunkStart) -> Self {
pub(in super::super) fn empty(context: &'ctx Context<'ctx>, failed: Rc<Cell<bool>>, start: GdnChunkStart) -> Self {
Self {
context,
failed,
@@ -67,23 +67,7 @@ pub(super) fn component_owner<'ctx>(
context: &'ctx Context<'ctx>,
start: GdnChunkStart,
) -> Result<GdnChunkDevice<'ctx>> {
let mut owner = GdnChunkDevice {
context,
failed: Rc::new(Cell::new(false)),
initial: None,
verification: None,
verified_rows: Vec::new(),
start,
state: None,
next: None,
guard: None,
history: None,
cursor: 0,
inflight: false,
valid: true,
queue: None,
queue_enabled: false,
};
let mut owner = GdnChunkDevice::empty(context, Rc::new(Cell::new(false)), start);
validate_values(owner.start.prior().values(), STATE_ELEMENTS)?;
preflight_budget(
context.budget_bytes(),
@@ -240,6 +240,24 @@ impl Report {
}
#[cfg(not(unix))]
std::fs::DirBuilder::new().create(root)?;
let (manifest, total) = self.write_raw_files(root)?;
assert_eq!(total, RAW_WORDS);
let comparisons = self.comparisons();
let complete = format!(
"layer=0 rows=4 same_input=true same_routes=true same_origin=true native_first=true \
resident_witness={:?} cache_counters={:?} raw_words={} allocated_bytes=0 txn_aborted=true \
injected=false published=false mtp=false head=false quality_pass=false speed_claim=false\n",
self.witness, self.cache, total
);
for (name, text) in [("MANIFEST.tsv", manifest), ("COMPARISON.tsv", comparisons), ("COMPLETE.txt", complete)] {
let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(root.join(name))?;
f.write_all(text.as_bytes())?;
f.sync_all()?;
}
Ok(())
}
// Every raw word file with its digest line; returns the manifest and the total word count.
fn write_raw_files(&self, root: &Path) -> std::io::Result<(String, usize)> {
let mut total = 0;
let mut manifest = String::from("file\twords\tsha256\n");
for (name, words) in [
@@ -253,70 +271,65 @@ impl Report {
("mmq.shared_scaled.f32", &self.arms[1].shared),
("mmq.final.f32", &self.arms[1].final_values),
] {
use sha2::Digest;
use std::fmt::Write as _;
total += words.len();
let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(root.join(name))?;
let mut digest = sha2::Sha256::new();
for word in words {
let b = word.to_le_bytes();
f.write_all(&b)?;
digest.update(b);
}
f.sync_all()?;
let mut hex = String::new();
for b in digest.finalize() {
write!(&mut hex, "{b:02x}").expect("String write");
}
let hex = write_raw_file(&root.join(name), words)?;
manifest.push_str(&format!("{name}\t{}\t{hex}\n", words.len()));
}
assert_eq!(total, RAW_WORDS);
Ok((manifest, total))
}
fn comparisons(&self) -> String {
let mut comparisons = String::from("role\trow\tslot\texpert\twords\tdifferent\tfirst_word\tmax_abs\n");
for row in 0..ROWS {
for slot in 0..SLOTS {
let lo = (row * SLOTS + slot) * N;
comparisons.push_str(&comparison(
"packed_down",
row,
Some(slot),
Some(self.ids[row * SLOTS + slot]),
&self.arms[0].packed[lo..lo + N],
&self.arms[1].packed[lo..lo + N],
));
}
let lo = row * N;
self.push_row_comparisons(row, &mut comparisons);
}
comparisons
}
fn push_row_comparisons(&self, row: usize, comparisons: &mut String) {
for slot in 0..SLOTS {
let lo = (row * SLOTS + slot) * N;
comparisons.push_str(&comparison(
"shared_scaled",
"packed_down",
row,
None,
None,
&self.arms[0].shared[lo..lo + N],
&self.arms[1].shared[lo..lo + N],
));
comparisons.push_str(&comparison(
"final",
row,
None,
None,
&self.arms[0].final_values[lo..lo + N],
&self.arms[1].final_values[lo..lo + N],
Some(slot),
Some(self.ids[row * SLOTS + slot]),
&self.arms[0].packed[lo..lo + N],
&self.arms[1].packed[lo..lo + N],
));
}
for (name, text) in [
("MANIFEST.tsv", manifest),
("COMPARISON.tsv", comparisons),
(
"COMPLETE.txt",
format!(
"layer=0 rows=4 same_input=true same_routes=true same_origin=true native_first=true resident_witness={:?} cache_counters={:?} raw_words={} allocated_bytes=0 txn_aborted=true injected=false published=false mtp=false head=false quality_pass=false speed_claim=false\n",
self.witness, self.cache, total
),
),
] {
let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(root.join(name))?;
f.write_all(text.as_bytes())?;
f.sync_all()?;
}
Ok(())
let lo = row * N;
comparisons.push_str(&comparison(
"shared_scaled",
row,
None,
None,
&self.arms[0].shared[lo..lo + N],
&self.arms[1].shared[lo..lo + N],
));
comparisons.push_str(&comparison(
"final",
row,
None,
None,
&self.arms[0].final_values[lo..lo + N],
&self.arms[1].final_values[lo..lo + N],
));
}
}
// One raw word file, created fresh and synced; returns the hex SHA-256 of its bytes.
fn write_raw_file(path: &Path, words: &[u32]) -> std::io::Result<String> {
use sha2::Digest;
use std::fmt::Write as _;
let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(path)?;
let mut digest = sha2::Sha256::new();
for word in words {
let b = word.to_le_bytes();
f.write_all(&b)?;
digest.update(b);
}
f.sync_all()?;
let mut hex = String::new();
for b in digest.finalize() {
write!(&mut hex, "{b:02x}").expect("String write");
}
Ok(hex)
}
@@ -26,6 +26,18 @@ fn retained_gate_up_matches_legacy_chain_and_closes_failed_candidates() {
}
}
saturation_and_refusals(&context);
small_context_refusals(&device);
context.synchronize().unwrap();
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
println!(
"MOE_RETAINED COMPLETE paired_words=54400 finite_cases=17 original_refusal_cases=6 \
domain_diagnostic_refusals=1 allocated=0"
);
}
// Budgets too small for the Down pair or the Gate/Up projection refuse before any kernel runs.
fn small_context_refusals(device: &leleka_cuda_driver::Device<'_>) {
let small = device.create_context(2 * FF * 4).unwrap();
assert_eq!(
finish_cached_mlp(&small, raw(&small, &[0.25; FF]), raw(&small, &[0.5; FF]), |_| panic!(
@@ -43,12 +55,6 @@ fn retained_gate_up_matches_legacy_chain_and_closes_failed_candidates() {
);
assert_eq!(small.allocated_bytes(), 0);
small.close().unwrap();
context.synchronize().unwrap();
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
println!(
"MOE_RETAINED COMPLETE paired_words=54400 finite_cases=17 original_refusal_cases=6 domain_diagnostic_refusals=1 allocated=0"
);
}
#[path = "moe_activation_reuse_gpu/encoded_fn.rs"]
@@ -3,9 +3,10 @@
#[allow(unused_imports)]
use super::*;
pub(super) fn encoded(kind: MoeMatrixKind, rows: usize, columns: usize, variant: usize) -> Vec<u8> {
// Elements per block and bytes per block of a fixture format.
fn block_geometry(kind: MoeMatrixKind) -> (usize, usize) {
use MoeMatrixKind as K;
let (elements, bytes) = match kind {
match kind {
K::Iq3Xxs => (256, 98),
K::Iq3S => (256, 110),
K::Iq2S => (256, 82),
@@ -16,22 +17,32 @@ pub(super) fn encoded(kind: MoeMatrixKind, rows: usize, columns: usize, variant:
K::RoutedIq4Nl => (32, 18),
K::Q8_0 => (32, 34),
_ => panic!("fixture has no other format"),
};
}
}
// One deterministic block with a literal F16 scale (and minimum) in its header.
fn fill_block(kind: MoeMatrixKind, (row, block, variant): (usize, usize, usize), chunk: &mut [u8]) {
use MoeMatrixKind as K;
for (i, byte) in chunk.iter_mut().enumerate() {
*byte = ((row * 17 + block * 29 + i * 37 + 11 + variant * 53) % 256) as u8;
}
if kind == K::Q6K {
chunk[208..210].copy_from_slice(&0x3c00u16.to_le_bytes());
} else {
chunk[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
if matches!(kind, K::Q4K | K::Q5K) {
chunk[2..4].copy_from_slice(&0x3800u16.to_le_bytes());
}
}
}
pub(super) fn encoded(kind: MoeMatrixKind, rows: usize, columns: usize, variant: usize) -> Vec<u8> {
let (elements, bytes) = block_geometry(kind);
let stride = columns / elements * bytes;
let mut values = vec![0; rows * stride];
for (row, chunk) in values.chunks_exact_mut(stride).enumerate() {
for (block, chunk) in chunk.chunks_exact_mut(bytes).enumerate() {
for (i, byte) in chunk.iter_mut().enumerate() {
*byte = ((row * 17 + block * 29 + i * 37 + 11 + variant * 53) % 256) as u8;
}
if kind == K::Q6K {
chunk[208..210].copy_from_slice(&0x3c00u16.to_le_bytes());
} else {
chunk[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
if matches!(kind, K::Q4K | K::Q5K) {
chunk[2..4].copy_from_slice(&0x3800u16.to_le_bytes());
}
}
fill_block(kind, (row, block, variant), chunk);
}
}
values
@@ -107,17 +118,16 @@ pub(super) fn down(
Ok(values)
}
pub(super) fn compare_mlp(
// Genuine retained reference chain: completed finite readback, two uploads, original SwiGLU and same actual Down
// kernel. No host numerical oracle. Returns the expected hidden activations and Down output.
fn reference_mlp(
context: &Context<'_>,
gate: DeviceBuffer<'_>,
up: DeviceBuffer<'_>,
(gate, up): (&DeviceBuffer<'_>, &DeviceBuffer<'_>),
down_kind: MoeMatrixKind,
down_matrix: &DeviceBuffer<'_>,
) {
// Genuine retained reference chain: completed finite readback, two uploads,
// original SwiGLU and same actual Down kernel. No host numerical oracle.
let gate_values = download_f32(&gate, FF).unwrap();
let up_values = download_f32(&up, FF).unwrap();
) -> (Box<[f32]>, Box<[f32]>) {
let gate_values = download_f32(gate, FF).unwrap();
let up_values = download_f32(up, FF).unwrap();
let old_gate = upload_f32(context, &gate_values).unwrap();
let old_up = upload_f32(context, &up_values).unwrap();
let mut old_hidden = context.allocate(FF * 4).unwrap();
@@ -130,6 +140,17 @@ pub(super) fn compare_mlp(
old_hidden.release().unwrap();
old_up.release().unwrap();
old_gate.release().unwrap();
(expected_hidden, expected)
}
pub(super) fn compare_mlp(
context: &Context<'_>,
gate: DeviceBuffer<'_>,
up: DeviceBuffer<'_>,
down_kind: MoeMatrixKind,
down_matrix: &DeviceBuffer<'_>,
) {
let (expected_hidden, expected) = reference_mlp(context, (&gate, &up), down_kind, down_matrix);
let retained = context.allocated_bytes();
let called = Cell::new(false);
let actual = finish_cached_mlp(context, gate, up, |hidden| {
@@ -143,10 +164,20 @@ pub(super) fn compare_mlp(
assert_eq!(context.allocated_bytes(), retained - 2 * FF * 4);
}
fn assert_matrices_unchanged(matrices: [(&DeviceBuffer<'_>, &Vec<u8>); 3]) {
for (matrix, bytes) in matrices {
let mut unchanged = vec![0; bytes.len()];
matrix.copy_to(&mut unchanged).unwrap();
assert_eq!(&unchanged, bytes);
}
}
fn format_input(zero: bool) -> Vec<f32> {
(0..N).map(|i| if zero { if i % 2 == 0 { -0.0 } else { 0.0 } } else { ((i % 31) as f32 - 15.) / 2048. }).collect()
}
pub(super) fn format_case(context: &Context<'_>, kind: MoeMatrixKind, routed: bool, zero: bool) {
let input: Vec<f32> = (0..N)
.map(|i| if zero { if i % 2 == 0 { -0.0 } else { 0.0 } } else { ((i % 31) as f32 - 15.) / 2048. })
.collect();
let input = format_input(zero);
let gate_bytes = bounded_gate_up(kind, 0);
let up_bytes = bounded_gate_up(kind, 1);
let down_kind = if routed { MoeMatrixKind::RoutedIq4Nl } else { MoeMatrixKind::Q8_0 };
@@ -166,11 +197,7 @@ pub(super) fn format_case(context: &Context<'_>, kind: MoeMatrixKind, routed: bo
}
compare_mlp(context, gate, up, down_kind, &down_matrix);
exact(&download_f32(&x, N).unwrap(), &input);
for (matrix, bytes) in [(&gate_matrix, &gate_bytes), (&up_matrix, &up_bytes), (&down_matrix, &down_bytes)] {
let mut unchanged = vec![0; bytes.len()];
matrix.copy_to(&mut unchanged).unwrap();
assert_eq!(&unchanged, bytes);
}
assert_matrices_unchanged([(&gate_matrix, &gate_bytes), (&up_matrix, &up_bytes), (&down_matrix, &down_bytes)]);
down_matrix.release().unwrap();
up_matrix.release().unwrap();
gate_matrix.release().unwrap();
@@ -3,25 +3,44 @@
#[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();
// The device owners of the former fixture: the input, the three matrices and the retained Gate/Up products.
struct FormerFixture<'c> {
x: DeviceBuffer<'c>,
gate_matrix: DeviceBuffer<'c>,
up_matrix: DeviceBuffer<'c>,
down_matrix: DeviceBuffer<'c>,
gate: DeviceBuffer<'c>,
up: DeviceBuffer<'c>,
}
impl<'c> FormerFixture<'c> {
fn build(context: &'c 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();
Self { x, gate_matrix, up_matrix, down_matrix, gate, up }
}
fn release(self) {
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();
}
}
// The largest hidden magnitude and the largest per-warp sum magnitude.
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 +48,22 @@ 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 = FormerFixture::build(context);
let mut hidden = context.allocate(FF * 4).unwrap();
context.moe_swiglu_f32(&fixture.gate, &fixture.up, &mut hidden).unwrap();
let values = download_f32(&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, &hidden, &mut output);
println!(
"MOE_RETAINED original_domain raw_down_error={result:?} hidden_abs_max={maximum} warp_sum_abs_max={maximum_sum}"
);
@@ -44,17 +74,19 @@ pub(super) fn former_fixture_domain_refusal(context: &Context<'_>) {
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<'_>) {
saturated_down_reference(context);
nonfinite_hidden_refusals(context);
late_nan_projection_refusal(context);
down_shape_refusal(context);
}
fn saturated_down_reference(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();
@@ -62,6 +94,9 @@ pub(super) fn saturation_and_refusals(context: &Context<'_>) {
compare_mlp(context, gate, up, MoeMatrixKind::RoutedIq4Nl, &matrix);
matrix.release().unwrap();
assert_eq!(context.allocated_bytes(), 0);
}
fn nonfinite_hidden_refusals(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,8 +114,11 @@ pub(super) fn saturation_and_refusals(context: &Context<'_>) {
assert!(!called.get());
assert_eq!(context.allocated_bytes(), 0);
}
// Actual projection writes a late NaN, exercising finite admission before
// the newly retained projection owner can be published.
}
// Actual projection writes a late NaN, exercising finite admission before
// the newly retained projection owner can be published.
fn late_nan_projection_refusal(context: &Context<'_>) {
let mut malformed = encoded(MoeMatrixKind::Q6K, FF, N, 0);
let end = malformed.len();
malformed[end - 2..].copy_from_slice(&0x7e01u16.to_le_bytes());
@@ -95,7 +133,10 @@ pub(super) fn saturation_and_refusals(context: &Context<'_>) {
assert_eq!(context.allocated_bytes(), initial);
x.release().unwrap();
w.release().unwrap();
// Down shape refusal is genuine native admission, not a fabricated error.
}
// Down shape refusal is genuine native admission, not a fabricated error.
fn down_shape_refusal(context: &Context<'_>) {
let w = upload_bytes(context, &encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 0)).unwrap();
let mut wrong = context.allocate(N * 4 - 4).unwrap();
let sentinel = vec![0xa5; N * 4 - 4];