use memra_engine::Engine;
use memra_engine::kda::{KdaAttnLayer, kda_attn};
use memra_engine::model::GpuTensor;
use memra_gguf::GgmlType;
use memra_gguf::config::ModelConfig;
use memra_gguf::model_plan::{
ActivationPlan, AttentionPlan, DenseMlpPlan, DraftSourcePlan, KimiDeltaNetPlan, LayerPlan,
MlpPlan, ModelPlan, NormKind, NormPlan, ResidualTopology, StatePlan, WeightTransform,
};
use memra_gguf::source::{TensorSource, TensorView};
use memra_gguf::tensor_contract::{
CheckpointDialect, ContractOptions, OutputHead, TensorContract, TensorId, TensorMatch,
};
use memra_reference::{ReferenceTensor, deterministic_fixture};
use std::borrow::Cow;
use std::collections::BTreeMap;
const HIDDEN: usize = 256;
const HEADS: u32 = 2;
const HEAD_DIM: u32 = 128;
const CONV_KERNEL: u32 = 4;
const GATE_LOWER_BOUND: f32 = -5.0;
const EPS: f32 = 1e-5;
const QKV: usize = (HEADS * HEAD_DIM) as usize;
const CONV_WIDTH: usize = 3 * QKV;
const STATE_WIDTH: usize = (HEADS * HEAD_DIM * HEAD_DIM) as usize;
const QUANTIZED_SUFFIXES: [&str; 9] = [
"kda_q.weight",
"kda_k.weight",
"kda_v.weight",
"kda_f_a.weight",
"kda_f_b.weight",
"kda_g_a.weight",
"kda_g_b.weight",
"kda_b.weight",
"kda_out.weight",
];
const QUANT_TOL: f32 = 5e-2;
fn gpu_guard() -> std::sync::MutexGuard<'static, ()> {
static GPU: std::sync::Mutex<()> = std::sync::Mutex::new(());
GPU.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn force_true_f32() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
if std::env::var("NVIDIA_TF32_OVERRIDE").as_deref() != Ok("0") {
unsafe { std::env::set_var("NVIDIA_TF32_OVERRIDE", "0") };
}
});
}
fn kda_plan() -> KimiDeltaNetPlan {
KimiDeltaNetPlan {
num_heads: HEADS,
head_dim: HEAD_DIM,
conv_kernel: CONV_KERNEL,
gate_lower_bound: GATE_LOWER_BOUND,
}
}
fn one_kda_layer_plan() -> ModelPlan {
let norm = NormPlan {
kind: NormKind::Rms,
epsilon: EPS,
weight_transform: WeightTransform::Identity,
};
ModelPlan {
arch: memra_gguf::config::Arch::Glm5Next,
hidden_size: HIDDEN as u32,
vocab_size: 32,
context_length: 512,
embedding_scale: 1.0,
vision: None,
multimodal: None,
layers: vec![LayerPlan {
index: 0,
pre_attention_norm: norm,
attention: AttentionPlan::KimiDeltaNet(kda_plan()),
pre_mlp_norm: norm,
mlp: MlpPlan::Dense(DenseMlpPlan {
intermediate_size: 32,
activation: ActivationPlan::Silu,
}),
residual: ResidualTopology::Serial,
ple: None,
sparse_overlay: None,
state: StatePlan::Recurrent {
conv_width: CONV_WIDTH as u32,
conv_kernel: CONV_KERNEL,
state_width: STATE_WIDTH as u32,
},
}],
output_norm: norm,
logits: Vec::new(),
mtp_blocks: Vec::new(),
drafter: None,
exit_mixer: None,
draft_source: DraftSourcePlan::Embedded,
sampling_defaults: None,
partition_boundaries: Vec::new(),
}
}
struct OwnedTensor {
bytes: Vec<u8>,
ne: Vec<u64>,
ty: GgmlType,
}
struct FixtureSource {
tensors: BTreeMap<String, OwnedTensor>,
}
impl TensorSource for FixtureSource {
fn config(&self) -> ModelConfig {
unreachable!("the KDA fixture source is tensor-only; nothing in the load path reads config")
}
fn find(&self, name: &str) -> Option<TensorView<'_>> {
let t = self.tensors.get(name)?;
Some(TensorView {
bytes: Cow::Borrowed(&t.bytes),
ggml_type: t.ty,
ne: t.ne.clone(),
})
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Arm {
Float,
Q8_0,
Q8_0StrideTooLong,
Q8_0RowRotated,
}
fn fixture_source(
plan: &ModelPlan,
weights: &BTreeMap<TensorId, ReferenceTensor>,
arm: Arm,
) -> FixtureSource {
let contract = TensorContract::for_plan(
plan,
CheckpointDialect::Gguf,
ContractOptions {
output_head: OutputHead::TiedToEmbedding,
},
)
.expect("contract for the one-KDA-layer plan");
let mut tensors = BTreeMap::new();
for req in contract
.requirements
.iter()
.filter(|r| r.required || weights.contains_key(&r.id))
{
let tensor = weights
.get(&req.id)
.unwrap_or_else(|| panic!("reference fixture is missing {:?}", req.id));
let elements: usize = req.shape.iter().map(|&d| d as usize).product();
assert_eq!(
elements,
tensor.data.len(),
"fixture {:?} has {} elements, contract requires {elements}",
req.id,
tensor.data.len()
);
let names = match req.match_mode {
TensorMatch::OneOf => &req.names[..1],
TensorMatch::All => req.names.as_slice(),
};
for name in names {
let quantize = arm != Arm::Float
&& QUANTIZED_SUFFIXES
.iter()
.any(|s| name == &format!("blk.0.{s}"));
let (bytes, ty) = if quantize {
let in_f = req.shape[0] as usize;
let out_f = req.shape[1] as usize;
assert_eq!(
in_f % 32,
0,
"{name}: Q8_0 needs in_features % 32 == 0, got {in_f}"
);
let mut bytes = memra_gguf::nvfp4_repack::f32_to_q8_0(&tensor.data);
if arm == Arm::Q8_0StrideTooLong {
let row_bytes = in_f / 32 * 34;
assert_eq!(bytes.len(), out_f * row_bytes);
let target = out_f * row_bytes * HEADS as usize;
let src = bytes.clone();
while bytes.len() < target {
let take = (target - bytes.len()).min(src.len());
bytes.extend_from_slice(&src[..take]);
}
}
if arm == Arm::Q8_0RowRotated {
let row_bytes = in_f / 32 * 34;
bytes.rotate_left(row_bytes);
}
(bytes, GgmlType::Q8_0)
} else {
(
tensor.data.iter().flat_map(|v| v.to_le_bytes()).collect(),
GgmlType::F32,
)
};
tensors.insert(
name.clone(),
OwnedTensor {
bytes,
ne: req.shape.clone(),
ty,
},
);
}
}
FixtureSource { tensors }
}
fn hidden_states(tokens: usize, seed: u64) -> Vec<f32> {
let mut s = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
(0..tokens * HIDDEN)
.map(|_| {
s = s
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
((s >> 33) as f32 / (1u64 << 31) as f32 - 0.5) * 0.6
})
.collect()
}
fn maxdiff(a: &[f32], b: &[f32]) -> f32 {
assert_eq!(a.len(), b.len(), "compared slices differ in length");
a.iter()
.zip(b)
.map(|(x, y)| (x - y).abs())
.fold(0.0f32, f32::max)
}
fn scale_of(v: &[f32]) -> f32 {
v.iter().fold(0.0f32, |m, x| m.max(x.abs())).max(1e-6)
}
fn rel(got: &[f32], want: &[f32]) -> f32 {
maxdiff(got, want) / scale_of(want)
}
struct Harness {
engine: Engine,
float: KdaAttnLayer,
quant: KdaAttnLayer,
}
impl Harness {
fn new() -> Self {
force_true_f32();
let model_plan = one_kda_layer_plan();
let fixture = deterministic_fixture(&model_plan).expect("deterministic KDA fixture");
let engine = Engine::new(0).expect("CUDA engine on device 0");
let plan = kda_plan();
let float = KdaAttnLayer::load(
&engine,
&fixture_source(&model_plan, &fixture.weights, Arm::Float),
0,
&plan,
)
.expect("KDA mixer loads with F32 operands");
let quant = KdaAttnLayer::load(
&engine,
&fixture_source(&model_plan, &fixture.weights, Arm::Q8_0),
0,
&plan,
)
.expect("KDA mixer loads with Q8_0 operands");
Self {
engine,
float,
quant,
}
}
fn run(&self, layer: &KdaAttnLayer, x: &[f32], tokens: usize) -> Vec<f32> {
let x_d = self.engine.htod(x).unwrap();
let out = kda_attn(&self.engine, layer, &x_d, tokens, EPS).expect("GPU KDA prefill");
self.engine.dtoh(&out).unwrap()
}
}
#[test]
#[ignore = "needs a CUDA device — run under flock /tmp/memra-5090.lock"]
fn kda_quant_arm_is_actually_quantized() {
let _gpu = gpu_guard();
let h = Harness::new();
let pairs: [(&str, &GpuTensor, &GpuTensor); 9] = [
("kda_q", &h.float.wq, &h.quant.wq),
("kda_k", &h.float.wk, &h.quant.wk),
("kda_v", &h.float.wv, &h.quant.wv),
("kda_f_a", &h.float.f_a, &h.quant.f_a),
("kda_f_b", &h.float.f_b, &h.quant.f_b),
("kda_g_a", &h.float.g_a, &h.quant.g_a),
("kda_g_b", &h.float.g_b, &h.quant.g_b),
("kda_b", &h.float.b_proj, &h.quant.b_proj),
("kda_out", &h.float.wo, &h.quant.wo),
];
for (name, f, q) in pairs {
assert!(
matches!(f, GpuTensor::Float { .. }),
"{name}: the control arm must be Float, got a quantized tensor"
);
assert!(
matches!(q, GpuTensor::Quant { .. }),
"{name}: the arm under test loaded Float — the Q8_0 fixture bytes did not reach the \
quantized loader path, so this whole gate would compare a layer with itself"
);
}
}
#[test]
#[ignore = "needs a CUDA device — run under flock /tmp/memra-5090.lock"]
fn kda_q8_0_operands_match_the_float_twin_within_the_quantization_floor() {
let _gpu = gpu_guard();
let h = Harness::new();
let mut worst = 0.0f32;
let mut worst_at = 0usize;
for &tokens in &[1usize, 7, 16, 65, 130] {
#[allow(clippy::unusual_byte_groupings)]
let x = hidden_states(tokens, 0x9_11A_57 ^ tokens as u64);
let want = h.run(&h.float, &x, tokens);
let got = h.run(&h.quant, &x, tokens);
assert!(
got.iter().all(|v| v.is_finite()),
"T={tokens}: the quantized arm produced non-finite values"
);
let r = rel(&got, &want);
eprintln!("[kda-quant] T={tokens} rel {r:.3e}");
if r > worst {
worst = r;
worst_at = tokens;
}
assert!(
r <= QUANT_TOL,
"T={tokens}: Q8_0 vs Float relative maxdiff {r:.3e} exceeds the quantization floor \
{QUANT_TOL:.1e}"
);
}
eprintln!(
"[kda-quant] worst relative maxdiff {worst:.3e} at T={worst_at} (tol {QUANT_TOL:.1e})"
);
}
#[test]
#[ignore = "needs a CUDA device — run under flock /tmp/memra-5090.lock"]
fn a_mis_strided_quantized_operand_fails_the_gate() {
let _gpu = gpu_guard();
force_true_f32();
let model_plan = one_kda_layer_plan();
let fixture = deterministic_fixture(&model_plan).expect("deterministic KDA fixture");
let engine = Engine::new(0).expect("CUDA engine on device 0");
let plan = kda_plan();
let load = |arm: Arm| {
KdaAttnLayer::load(
&engine,
&fixture_source(&model_plan, &fixture.weights, arm),
0,
&plan,
)
.expect("the mutated fixture still LOADS — that is the point of the mutation")
};
let float = load(Arm::Float);
let tokens = 16usize;
let x = hidden_states(tokens, 0xBAD_5721DE);
let x_d = engine.htod(&x).unwrap();
let want = engine
.dtoh(&kda_attn(&engine, &float, &x_d, tokens, EPS).expect("float arm"))
.unwrap();
for (label, arm) in [
("stride-too-long", Arm::Q8_0StrideTooLong),
("row-rotated", Arm::Q8_0RowRotated),
] {
let bad = load(arm);
let got = engine
.dtoh(&kda_attn(&engine, &bad, &x_d, tokens, EPS).expect("mutated arm"))
.unwrap();
assert!(
got.iter().all(|v| v.is_finite()),
"{label}: the mutation produced non-finite values — it is failing loudly for the \
wrong reason, which proves nothing about the bar"
);
let r = rel(&got, &want);
eprintln!(
"[kda-quant mutation] {label} relative maxdiff {r:.3e} vs tol {QUANT_TOL:.1e} \
({:.3e}x the bar)",
r / QUANT_TOL
);
assert!(
r > QUANT_TOL,
"the {label} Q8_0 operand produced {r:.3e} relative error, INSIDE the \
{QUANT_TOL:.1e} bar — gate 2 does not bind and would pass a corrupted weight"
);
}
}
#[test]
#[ignore = "needs a CUDA device — run under flock /tmp/memra-5090.lock"]
fn a_quantized_3d_operand_is_refused_by_name_not_mis_strided() {
let _gpu = gpu_guard();
force_true_f32();
let engine = Engine::new(0).expect("CUDA engine on device 0");
let (nope, rank, heads) = (64usize, 32usize, 4usize);
let elements = nope * rank * heads;
let data = vec![0.25f32; elements];
let bytes = memra_gguf::nvfp4_repack::f32_to_q8_0(&data);
let true_row_bytes = nope / 32 * 34;
let rows = rank * heads;
assert_eq!(true_row_bytes, 68);
assert_eq!(bytes.len(), rows * true_row_bytes);
assert_eq!(bytes.len(), 8704);
let mis_derived = bytes.len() / rank; assert_eq!(mis_derived, 272);
assert_eq!(
mis_derived,
true_row_bytes * heads,
"the mis-derivation is exactly a factor of the head count"
);
struct One {
name: String,
bytes: Vec<u8>,
ne: Vec<u64>,
}
impl TensorSource for One {
fn config(&self) -> ModelConfig {
unreachable!("rank-guard fixture is tensor-only")
}
fn find(&self, name: &str) -> Option<TensorView<'_>> {
(name == self.name).then(|| TensorView {
bytes: Cow::Borrowed(&self.bytes),
ggml_type: GgmlType::Q8_0,
ne: self.ne.clone(),
})
}
}
let name = "blk.0.attn_k_b.weight";
let src = One {
name: name.into(),
bytes,
ne: vec![nope as u64, rank as u64, heads as u64],
};
let err = GpuTensor::load_from_source(&engine, &src, name)
.err()
.expect("a quantized 3-D tensor must be refused, not loaded with a derived stride");
let msg = err.to_string();
assert!(
msg.contains(name),
"the refusal must NAME the tensor; got: {msg}"
);
assert!(
msg.contains("3-D") && msg.contains("2-D"),
"the refusal must say what the constraint is; got: {msg}"
);
let src_1d = One {
name: name.into(),
bytes: memra_gguf::nvfp4_repack::f32_to_q8_0(&vec![0.25f32; 64]),
ne: vec![64],
};
let err = GpuTensor::load_from_source(&engine, &src_1d, name)
.err()
.expect("a quantized 1-D tensor must be refused, not panic on ne[1]");
assert!(err.to_string().contains(name));
}