mod canonical;
pub use canonical::UnresolvedAttr;
pub mod shape_expr;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OpTag {
Add,
Sub,
Mul,
Div,
Maximum,
Minimum,
Pow,
Rem,
Neg,
Abs,
Sqr,
Sqrt,
Rsqrt,
Recip,
Exp,
Log,
Sin,
Cos,
Tanh,
Sigmoid,
Silu,
GeluTanh,
Gelu,
Relu,
Erf,
Step,
Floor,
Ceil,
Round,
Sign,
AddScalar,
MulScalar,
PowI,
Clamp,
Equal,
Ne,
Lt,
Le,
Gt,
Ge,
Where,
MaskedFill,
SumAll,
MaxAll,
MinAll,
MeanAll,
SumDim,
MaxDim,
MeanDim,
ReduceSumTo,
ReduceMaxTo,
CumSum,
MatMul,
Transpose,
Permute,
Reshape,
BroadcastTo,
Unsqueeze,
Squeeze,
Cast,
Slice,
Concat,
Flip,
Roll,
Pad,
Triu,
Tril,
IndexSelect,
Gather,
IndexAdd,
ScatterAdd,
LogSoftmaxLastDim,
Iota,
Const,
RuntimeScalar,
ReducedCount,
ScanPlaceholder,
Scan,
View,
Fused,
}
pub const SCAN_ROLE_CARRY: u8 = 0;
pub const SCAN_ROLE_ELEM: u8 = 1;
pub fn const_bits_narrow(storage: u64, width_bits: u32) -> u64 {
if width_bits == 0 {
return 0;
}
if width_bits >= 64 {
return storage;
}
storage & ((1u64 << width_bits) - 1)
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct OpAttrs {
pub scalars: Vec<f64>,
pub axis: Option<i64>,
pub perm: Vec<u8>,
pub target_shape: Vec<i64>,
pub dims: Vec<u8>,
pub cast_dtype: Option<String>,
pub slice_start: Option<u64>,
pub slice_len: Option<u64>,
pub roll_shift: Option<i64>,
pub pad_amounts: Vec<(u64, u64)>,
pub pad_mode: Option<u8>,
pub pad_value: Option<f64>,
pub keepdim: Option<bool>,
pub target_shape_rel: Option<shape_expr::ShapeExpr>,
pub slice_start_rel: Option<shape_expr::Dim>,
pub slice_len_rel: Option<shape_expr::Dim>,
pub axis_last: bool,
pub scalar_rel: Option<shape_expr::Dim>,
pub lhs_roles: Vec<u8>,
pub rhs_roles: Vec<u8>,
pub const_bits: Option<u64>,
pub slot_index: Option<u32>,
pub scan_role: Option<u8>,
pub scan_index: Option<u32>,
pub scan_n_carries: Option<u32>,
pub scan_n_xs: Option<u32>,
pub scan_bound: Option<u32>,
pub scan_emit: Option<u8>,
pub scan_early_exit: Option<bool>,
pub view_slot: Option<u32>,
pub rank0_target: bool,
pub fused_op: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct RegionKey {
axis: Option<i64>,
perm: Vec<u8>,
target_shape: Vec<i64>,
dims: Vec<u8>,
cast_dtype: Option<String>,
slice_start: Option<u64>,
slice_len: Option<u64>,
roll_shift: Option<i64>,
pad_amounts: Vec<(u64, u64)>,
pad_mode: Option<u8>,
pad_value_bits: Option<u64>,
keepdim: Option<bool>,
target_shape_rel: Option<shape_expr::ShapeExpr>,
slice_start_rel: Option<shape_expr::Dim>,
slice_len_rel: Option<shape_expr::Dim>,
axis_last: bool,
scalar_rel: Option<shape_expr::Dim>,
lhs_roles: Vec<u8>,
rhs_roles: Vec<u8>,
const_bits: Option<u64>,
slot_index: Option<u32>,
scan_role: Option<u8>,
scan_index: Option<u32>,
scan_n_carries: Option<u32>,
scan_n_xs: Option<u32>,
scan_bound: Option<u32>,
scan_emit: Option<u8>,
scan_early_exit: Option<bool>,
view_slot: Option<u32>,
rank0_target: bool,
fused_op: Option<String>,
}
impl OpAttrs {
pub fn region_key(&self) -> RegionKey {
let OpAttrs {
scalars: _, axis,
perm,
target_shape,
dims,
cast_dtype,
slice_start,
slice_len,
roll_shift,
pad_amounts,
pad_mode,
pad_value,
keepdim,
target_shape_rel,
slice_start_rel,
slice_len_rel,
axis_last,
scalar_rel,
lhs_roles,
rhs_roles,
const_bits,
slot_index,
scan_role,
scan_index,
scan_n_carries,
scan_n_xs,
scan_bound,
scan_emit,
scan_early_exit,
view_slot,
rank0_target,
fused_op,
} = self;
RegionKey {
axis: *axis,
perm: perm.clone(),
target_shape: target_shape.clone(),
dims: dims.clone(),
cast_dtype: cast_dtype.clone(),
slice_start: *slice_start,
slice_len: *slice_len,
roll_shift: *roll_shift,
pad_amounts: pad_amounts.clone(),
pad_mode: *pad_mode,
pad_value_bits: (*pad_value).map(f64::to_bits),
keepdim: *keepdim,
target_shape_rel: target_shape_rel.clone(),
slice_start_rel: slice_start_rel.clone(),
slice_len_rel: slice_len_rel.clone(),
axis_last: *axis_last,
scalar_rel: scalar_rel.clone(),
lhs_roles: lhs_roles.clone(),
rhs_roles: rhs_roles.clone(),
const_bits: *const_bits,
slot_index: *slot_index,
scan_role: *scan_role,
scan_index: *scan_index,
scan_n_carries: *scan_n_carries,
scan_n_xs: *scan_n_xs,
scan_bound: *scan_bound,
scan_emit: *scan_emit,
scan_early_exit: *scan_early_exit,
view_slot: *view_slot,
rank0_target: *rank0_target,
fused_op: fused_op.clone(),
}
}
}
pub fn matmul_roles(lhs_rank: usize, rhs_rank: usize) -> (Vec<u8>, Vec<u8>) {
fn one(rank: usize, second_last: u8, last: u8) -> Vec<u8> {
let mut v = vec![0u8; rank]; if rank >= 2 {
v[rank - 2] = second_last;
v[rank - 1] = last;
}
v
}
(one(lhs_rank, 1, 3), one(rhs_rank, 3, 2))
}
#[derive(Clone, Debug, PartialEq)]
#[expect(
clippy::large_enum_variant,
reason = "Op-payload boxing deferred: ~150 cross-crate construction sites, sequenced after the in-flight rename sweep"
)]
pub enum PatternNode {
Op {
op: OpTag,
operands: Vec<PatternNode>,
attrs: OpAttrs,
},
Bind { index: u8 },
SeeThrough { then: Box<PatternNode> },
Any,
}
impl PatternNode {
pub fn bind_indices(&self) -> Vec<u8> {
let mut out = Vec::new();
self.collect_binds(&mut out);
out.sort_unstable();
out.dedup();
out
}
fn collect_binds(&self, out: &mut Vec<u8>) {
match self {
PatternNode::Bind { index } => out.push(*index),
PatternNode::Op { operands, .. } => {
for o in operands {
o.collect_binds(out);
}
}
PatternNode::SeeThrough { then } => then.collect_binds(out),
PatternNode::Any => {}
}
}
}
pub fn advisory_band_reference_cases() -> Vec<(PatternNode, Option<u64>)> {
fn bind(i: u8) -> PatternNode {
PatternNode::Bind { index: i }
}
fn op(op: OpTag, operands: Vec<PatternNode>) -> PatternNode {
PatternNode::Op {
op,
operands,
attrs: OpAttrs::default(),
}
}
vec![
(bind(0), None),
(op(OpTag::Add, vec![bind(0), bind(1)]), None),
(
op(OpTag::Relu, vec![op(OpTag::Add, vec![bind(0), bind(1)])]),
Some(1),
),
(
op(
OpTag::Relu,
vec![op(
OpTag::Relu,
vec![op(OpTag::Add, vec![bind(0), bind(1)])],
)],
),
Some(2),
),
(
op(OpTag::Sqrt, vec![op(OpTag::Add, vec![bind(0), bind(1)])]),
Some(1),
),
(op(OpTag::Exp, vec![bind(0)]), Some(4)),
(
op(OpTag::Exp, vec![op(OpTag::Add, vec![bind(0), bind(1)])]),
Some(4),
),
(
op(
OpTag::Tanh,
vec![op(OpTag::Add, vec![op(OpTag::Exp, vec![bind(0)]), bind(1)])],
),
Some(8),
),
(
op(OpTag::Exp, vec![op(OpTag::Tanh, vec![bind(0)])]),
Some(8),
),
(
op(
OpTag::Silu,
vec![op(OpTag::Add, vec![bind(0), op(OpTag::Exp, vec![bind(1)])])],
),
Some(8),
),
]
}
#[cfg(test)]
mod region_key_tests {
use super::*;
use crate::shape_expr::{Dim, ShapeExpr};
#[test]
fn every_included_field_changes_the_key() {
let base = OpAttrs::default().region_key();
macro_rules! moves {
($field:ident = $val:expr) => {{
let a = OpAttrs {
$field: $val,
..Default::default()
};
assert_ne!(
a.region_key(),
base,
concat!("region_key() ignores field `", stringify!($field), "`")
);
}};
}
moves!(axis = Some(3));
moves!(perm = vec![1u8, 0]);
moves!(target_shape = vec![2i64, 3]);
moves!(dims = vec![1u8]);
moves!(cast_dtype = Some("f32".to_string()));
moves!(slice_start = Some(5));
moves!(slice_len = Some(7));
moves!(roll_shift = Some(-1));
moves!(pad_amounts = vec![(1u64, 2u64)]);
moves!(pad_mode = Some(1u8));
moves!(pad_value = Some(1.5));
moves!(keepdim = Some(true));
moves!(target_shape_rel = Some(ShapeExpr::SameAs { operand: 0 }));
moves!(slice_start_rel = Some(Dim::Const(1)));
moves!(slice_len_rel = Some(Dim::Const(1)));
moves!(axis_last = true);
moves!(scalar_rel = Some(Dim::Const(1)));
moves!(lhs_roles = vec![1u8]);
moves!(rhs_roles = vec![2u8]);
moves!(const_bits = Some(42u64));
moves!(slot_index = Some(1u32));
moves!(scan_role = Some(1u8));
moves!(scan_index = Some(1u32));
moves!(scan_n_carries = Some(1u32));
moves!(scan_n_xs = Some(1u32));
moves!(scan_bound = Some(1u32));
moves!(scan_emit = Some(1u8));
moves!(scan_early_exit = Some(true));
moves!(view_slot = Some(1u32));
moves!(rank0_target = true);
moves!(fused_op = Some("SoftmaxLastDim".to_string()));
}
#[test]
fn scalars_length_and_values_are_excluded_from_the_key() {
let base = OpAttrs::default().region_key(); for scalars in [
vec![],
vec![0.0],
vec![9.0],
vec![1.0, 2.0],
vec![-0.0, f64::NAN, 3.5],
] {
let a = OpAttrs {
scalars,
..Default::default()
};
assert_eq!(
a.region_key(),
base,
"scalars length and values must not affect the region key (baracuda #115; \
arity is scalar_slot_arity(op), a function of OpTag)"
);
}
}
#[test]
fn none_stays_distinct_from_some_zero() {
let none = OpAttrs::default().region_key();
let a = OpAttrs {
slice_start: Some(0),
..Default::default()
};
assert_ne!(a.region_key(), none, "slice_start None vs Some(0)");
let b = OpAttrs {
pad_value: Some(0.0),
..Default::default()
};
assert_ne!(b.region_key(), none, "pad_value None vs Some(0.0)");
let c = OpAttrs {
const_bits: Some(0),
..Default::default()
};
assert_ne!(c.region_key(), none, "const_bits None vs Some(0)");
}
#[test]
fn floats_key_by_to_bits() {
let mk = |v: f64| {
OpAttrs {
pad_value: Some(v),
..Default::default()
}
.region_key()
};
assert_ne!(mk(0.0), mk(-0.0), "pad_value +0.0 vs -0.0 stay distinct");
let nan_a = f64::from_bits(0x7ff8_0000_0000_0001);
let nan_b = f64::from_bits(0x7ff8_0000_0000_0002);
assert!(nan_a.is_nan() && nan_b.is_nan());
assert_ne!(mk(nan_a), mk(nan_b), "distinct NaN payloads stay distinct");
assert_eq!(
mk(f64::NAN),
mk(f64::NAN),
"same NaN bits => equal keys (Eq reflexive)"
);
}
#[test]
fn key_buckets_kernels_by_region_ignoring_scalars() {
use std::collections::HashMap;
let mut m: HashMap<RegionKey, &str> = HashMap::new();
let add = OpAttrs::default(); let other = OpAttrs {
axis: Some(1),
..Default::default()
};
m.insert(add.region_key(), "kernel_add");
m.insert(other.region_key(), "kernel_other");
assert_eq!(
m.len(),
2,
"structurally distinct regions => distinct kernels"
);
let add_val_9 = OpAttrs {
scalars: vec![9.0],
..Default::default()
};
assert_eq!(
m.get(&add_val_9.region_key()),
Some(&"kernel_add"),
"differing scalar values reuse the same kernel (no wasted compile)"
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pattern_node_region_for_relu_a_plus_b() {
let region = PatternNode::Op {
op: OpTag::Relu,
attrs: OpAttrs::default(),
operands: vec![PatternNode::Op {
op: OpTag::Add,
attrs: OpAttrs::default(),
operands: vec![
PatternNode::Bind { index: 0 },
PatternNode::Bind { index: 1 },
],
}],
};
assert_eq!(region.bind_indices(), vec![0, 1]);
}
#[test]
fn shared_input_node_identity_guard() {
let region = PatternNode::Op {
op: OpTag::Mul,
attrs: OpAttrs::default(),
operands: vec![
PatternNode::Bind { index: 0 },
PatternNode::Bind { index: 0 },
],
};
assert_eq!(region.bind_indices(), vec![0]);
}
#[test]
fn empty_schema_op_serializes_zero_length() {
assert_eq!(
OpAttrs::default().to_canonical_bytes(OpTag::Add).unwrap(),
vec![0, 0, 0, 0]
);
assert_eq!(
OpAttrs::default()
.to_canonical_bytes(OpTag::MatMul)
.unwrap(),
vec![0, 0, 0, 0]
);
}
#[test]
fn slice_serializes_positionally() {
let a = OpAttrs {
axis: Some(1),
slice_start: Some(2),
slice_len: Some(3),
..OpAttrs::default()
};
let mut expect = Vec::new();
let body = {
let mut b = Vec::new();
b.extend_from_slice(&1u32.to_le_bytes());
b.extend_from_slice(&2u64.to_le_bytes());
b.extend_from_slice(&3u64.to_le_bytes());
b
};
expect.extend_from_slice(&(body.len() as u32).to_le_bytes());
expect.extend_from_slice(&body);
assert_eq!(a.to_canonical_bytes(OpTag::Slice).unwrap(), expect);
}
#[test]
fn cast_serializes_dtype_name_length_prefixed() {
let a = OpAttrs {
cast_dtype: Some("f16".into()),
..OpAttrs::default()
};
let mut body = Vec::new();
body.extend_from_slice(&(3u32.to_le_bytes())); body.extend_from_slice(b"f16");
let mut expect = (body.len() as u32).to_le_bytes().to_vec();
expect.extend_from_slice(&body);
assert_eq!(a.to_canonical_bytes(OpTag::Cast).unwrap(), expect);
}
#[test]
fn canonical_bytes_are_deterministic() {
let a = OpAttrs {
target_shape: vec![2, 3],
..OpAttrs::default()
};
assert_eq!(
a.to_canonical_bytes(OpTag::Reshape).unwrap(),
a.to_canonical_bytes(OpTag::Reshape).unwrap()
);
}
#[test]
fn three_carrier_width_pins_stay_distinct() {
use crate::shape_expr::{Dim, LAST};
let empty = OpAttrs::default().to_canonical_bytes(OpTag::Add).unwrap();
assert_eq!(
empty,
vec![0u8, 0, 0, 0],
"carrier (a): empty node-envelope op_attrs = u32-LE zero (4 bytes)"
);
let sliced = OpAttrs {
axis: Some(1),
slice_start: Some(2),
slice_len: Some(3),
..OpAttrs::default()
};
let blob = sliced.to_canonical_bytes(OpTag::Slice).unwrap();
let a_body_len = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]) as usize;
assert_eq!(
blob.len(),
4 + a_body_len,
"carrier (a): outer length prefix is u32-LE (4 bytes), body verbatim"
);
fn region_node_table_op_attrs_sub_block(payload: &[u8]) -> Vec<u8> {
let mut out = (payload.len() as u16).to_le_bytes().to_vec();
out.extend_from_slice(payload); out
}
assert_eq!(
region_node_table_op_attrs_sub_block(&[]),
vec![0x00, 0x00],
"carrier (b): EMPTY region-node-table op_attrs sub-block = 0x0000 (u16-LE, 2 bytes)"
);
assert_eq!(
region_node_table_op_attrs_sub_block(&[0xAB, 0xCD]),
vec![0x02, 0x00, 0xAB, 0xCD],
"carrier (b): sub-block length prefix is u16-LE (2 bytes), payload verbatim"
);
let half = Dim::Div(
Box::new(Dim::Extent {
operand: 0,
axis: LAST,
}),
Box::new(Dim::Const(2)),
);
let bytes = half.encode();
assert_eq!(
[bytes[1], bytes[2]],
3u16.to_le_bytes(),
"carrier (c): first child length prefix is u16-LE (2 bytes)"
);
assert_eq!(
[bytes[6], bytes[7]],
9u16.to_le_bytes(),
"carrier (c): second child length prefix is u16-LE (2 bytes)"
);
assert_eq!(
bytes.len(),
1 + 2 + 3 + 2 + 9,
"carrier (c): whole rope-half blob accounted for"
);
}
#[test]
fn rel_attr_fields_are_absent_from_the_6_19_wire() {
use crate::shape_expr::{Dim, LAST, ShapeExpr};
let half = Dim::Div(
Box::new(Dim::Extent {
operand: 0,
axis: LAST,
}),
Box::new(Dim::Const(2)),
);
let rel_only = OpAttrs {
target_shape_rel: Some(ShapeExpr::SameAs { operand: 0 }),
slice_start_rel: Some(half.clone()),
slice_len_rel: Some(half),
axis_last: true,
scalar_rel: Some(Dim::Extent {
operand: 0,
axis: LAST,
}),
..OpAttrs::default()
};
assert_eq!(
rel_only.to_canonical_bytes(OpTag::BroadcastTo).unwrap(),
OpAttrs::default()
.to_canonical_bytes(OpTag::BroadcastTo)
.unwrap(),
"target_shape_rel must not reach the broadcast_to wire arm"
);
let abs = OpAttrs {
axis: Some(1),
slice_start: Some(2),
slice_len: Some(3),
..OpAttrs::default()
};
let abs_plus_rel = OpAttrs {
axis: Some(1),
slice_start: Some(2),
slice_len: Some(3),
..rel_only.clone()
};
assert_eq!(
abs_plus_rel.to_canonical_bytes(OpTag::Slice).unwrap(),
abs.to_canonical_bytes(OpTag::Slice).unwrap(),
"slice_{{start,len}}_rel must not reach the slice wire arm"
);
let sd = OpAttrs {
axis: Some(1),
..OpAttrs::default()
};
let sd_plus_rel = OpAttrs {
axis: Some(1),
..rel_only.clone()
};
assert_eq!(
sd_plus_rel.to_canonical_bytes(OpTag::SumDim).unwrap(),
sd.to_canonical_bytes(OpTag::SumDim).unwrap(),
"axis_last must not reach the reduce wire row"
);
assert_eq!(
rel_only.to_canonical_bytes(OpTag::MulScalar).unwrap(),
OpAttrs::default()
.to_canonical_bytes(OpTag::MulScalar)
.unwrap(),
"scalar_rel must not reach the mul_scalar wire arm"
);
assert_eq!(
rel_only.to_canonical_bytes(OpTag::Add).unwrap(),
vec![0, 0, 0, 0]
);
}
#[test]
fn fused_nested_op_is_absent_from_the_6_19_wire() {
let fused = OpAttrs {
fused_op: Some("SoftmaxLastDim".into()),
..OpAttrs::default()
};
assert_eq!(
fused.to_canonical_bytes(OpTag::Fused).unwrap(),
vec![0, 0, 0, 0],
"OpTag::Fused must serialize to the empty canonical body"
);
assert_eq!(
fused.to_canonical_bytes(OpTag::Fused).unwrap(),
OpAttrs::default().to_canonical_bytes(OpTag::Fused).unwrap(),
"the fused_op selector must not reach any wire arm"
);
assert_eq!(
fused.to_canonical_bytes(OpTag::Add).unwrap(),
vec![0, 0, 0, 0],
"fused_op must not leak into an empty-schema arm"
);
}
#[test]
fn max_dim_serializes_the_reduce_row() {
let a = OpAttrs {
axis: Some(1),
..OpAttrs::default()
};
let mut expect = 9u32.to_le_bytes().to_vec();
expect.extend_from_slice(&1i64.to_le_bytes());
expect.push(0u8);
assert_eq!(a.to_canonical_bytes(OpTag::MaxDim).unwrap(), expect);
assert_eq!(
a.to_canonical_bytes(OpTag::MaxDim).unwrap(),
a.to_canonical_bytes(OpTag::SumDim).unwrap(),
"MaxDim must share the SumDim reduce-row schema"
);
}
#[test]
fn matmul_role_vectors_serialize_the_locked_rank2_golden() {
let a = OpAttrs {
lhs_roles: vec![1, 3],
rhs_roles: vec![3, 2],
..OpAttrs::default()
};
let golden: Vec<u8> = vec![
0x0C, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x03, 0x02, 0x00, 0x00, 0x00, 0x03, 0x02, ];
assert_eq!(
a.to_canonical_bytes(OpTag::MatMul).unwrap(),
golden,
"the rank-2 matmul role-vector golden is the shared cross-producer contract (Baracuda #68)"
);
}
#[test]
fn matmul_empty_roles_stay_the_canonical_zero_body() {
assert_eq!(
OpAttrs::default()
.to_canonical_bytes(OpTag::MatMul)
.unwrap(),
vec![0, 0, 0, 0]
);
}
#[test]
fn matmul_roles_derives_the_canonical_cell() {
assert_eq!(matmul_roles(2, 2), (vec![1u8, 3], vec![3u8, 2]));
assert_eq!(matmul_roles(4, 4), (vec![0u8, 0, 1, 3], vec![0u8, 0, 3, 2]));
}
#[test]
fn advisory_band_reference_cases_are_well_formed() {
let cases = advisory_band_reference_cases();
assert!(
cases.len() >= 8,
"fixture should cover the formula's branches"
);
for (region, _expected) in &cases {
let binds = region.bind_indices();
if let PatternNode::Op { .. } = region {
for (i, b) in binds.iter().enumerate() {
assert_eq!(*b as usize, i, "bind indices must be [0, n)");
}
}
}
assert!(
cases
.iter()
.any(|(r, e)| matches!(r, PatternNode::Bind { .. }) && e.is_none())
);
assert!(cases.iter().any(|(_, e)| *e == Some(1)));
assert!(cases.iter().any(|(_, e)| *e == Some(4)));
assert!(cases.iter().any(|(_, e)| *e == Some(8)));
}
#[test]
fn runtime_scalar_leaf_serializes_the_slot_index() {
let a = OpAttrs {
slot_index: Some(7),
..OpAttrs::default()
};
let golden: Vec<u8> = vec![
0x04, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, ];
assert_eq!(a.to_canonical_bytes(OpTag::RuntimeScalar).unwrap(), golden);
assert_eq!(
OpAttrs {
slot_index: Some(0),
..OpAttrs::default()
}
.to_canonical_bytes(OpTag::RuntimeScalar)
.unwrap(),
vec![0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
);
}
#[test]
fn reduced_count_leaf_serializes_the_fold_axis() {
let a = OpAttrs {
axis: Some(1),
..OpAttrs::default()
};
let mut golden = 8u32.to_le_bytes().to_vec();
golden.extend_from_slice(&1i64.to_le_bytes());
assert_eq!(a.to_canonical_bytes(OpTag::ReducedCount).unwrap(), golden);
let fold = a.to_canonical_bytes(OpTag::SumDim).unwrap();
let rc = a.to_canonical_bytes(OpTag::ReducedCount).unwrap();
assert_eq!(
rc[4..],
fold[4..12],
"reduced_count body = the fold's i64(axis) verbatim"
);
assert_eq!(
fold.len(),
rc.len() + 1,
"the fold row carries exactly one extra byte (keepdim)"
);
let neg = OpAttrs {
axis: Some(-1),
..OpAttrs::default()
};
let mut expect = 8u32.to_le_bytes().to_vec();
expect.extend_from_slice(&(-1i64).to_le_bytes());
assert_eq!(neg.to_canonical_bytes(OpTag::ReducedCount).unwrap(), expect);
}
#[test]
fn const_leaf_serializes_bits_with_the_mbz_narrow_dtype_rule() {
let f64_15 = OpAttrs {
const_bits: Some(1.5f64.to_bits()),
..OpAttrs::default()
};
let mut golden = 8u32.to_le_bytes().to_vec();
golden.extend_from_slice(&0x3FF8_0000_0000_0000u64.to_le_bytes());
assert_eq!(f64_15.to_canonical_bytes(OpTag::Const).unwrap(), golden);
let f32_15 = OpAttrs {
const_bits: Some(const_bits_narrow(1.5f32.to_bits() as u64, 32)),
..OpAttrs::default()
};
let blob = f32_15.to_canonical_bytes(OpTag::Const).unwrap();
assert_eq!(
blob,
vec![
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x3F, 0x00, 0x00, 0x00, 0x00
],
"f32 1.5 = 0x3FC00000 in the LOW-order bits; upper 4 bytes MBZ"
);
let f16_15 = OpAttrs {
const_bits: Some(const_bits_narrow(0x3E00, 16)),
..OpAttrs::default()
};
assert_eq!(
f16_15.to_canonical_bytes(OpTag::Const).unwrap(),
vec![
0x08, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
],
);
let bf16_15 = OpAttrs {
const_bits: Some(const_bits_narrow(0x3FC0, 16)),
..OpAttrs::default()
};
assert_eq!(
bf16_15.to_canonical_bytes(OpTag::Const).unwrap(),
vec![
0x08, 0x00, 0x00, 0x00, 0xC0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
],
);
assert_eq!(
const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 16),
0x0000_0000_0000_FFFF
);
assert_eq!(
const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 32),
0x0000_0000_FFFF_FFFF
);
assert_eq!(
const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 64),
0xFFFF_FFFF_FFFF_FFFF
);
assert_eq!(
const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 200),
0xFFFF_FFFF_FFFF_FFFF
);
assert_eq!(const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 0), 0);
for w in [1u32, 8, 16, 32, 63] {
let bits = const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, w);
assert_eq!(bits >> w, 0, "width {w}: upper bits must be zero");
}
}
#[test]
fn const_leaf_carries_a_nan_payload_verbatim() {
const F32_NAN_PAYLOAD: u32 = 0x7FC0_DEAD;
assert!(
f32::from_bits(F32_NAN_PAYLOAD).is_nan(),
"fixture must be a NaN"
);
let a = OpAttrs {
const_bits: Some(const_bits_narrow(F32_NAN_PAYLOAD as u64, 32)),
..OpAttrs::default()
};
let blob = a.to_canonical_bytes(OpTag::Const).unwrap();
assert_eq!(
blob,
vec![
0x08, 0x00, 0x00, 0x00, 0xAD, 0xDE, 0xC0, 0x7F, 0x00, 0x00, 0x00, 0x00
],
"the f32 NaN payload rides the low-order bits verbatim; upper 4 bytes MBZ"
);
let read_back = u64::from_le_bytes(blob[4..12].try_into().unwrap());
assert_eq!(
read_back, F32_NAN_PAYLOAD as u64,
"payload bits round-trip verbatim"
);
assert_eq!(
f32::from_bits(read_back as u32).to_bits(),
F32_NAN_PAYLOAD,
"bit-exact (a NaN never compares equal — compare BITS)"
);
const F64_SNAN_PAYLOAD: u64 = 0x7FF0_0000_0000_DEAD;
assert!(
f64::from_bits(F64_SNAN_PAYLOAD).is_nan(),
"fixture must be a NaN"
);
let d = OpAttrs {
const_bits: Some(F64_SNAN_PAYLOAD),
..OpAttrs::default()
};
let dblob = d.to_canonical_bytes(OpTag::Const).unwrap();
assert_eq!(
u64::from_le_bytes(dblob[4..12].try_into().unwrap()),
F64_SNAN_PAYLOAD,
"an f64 sNaN payload is NOT quieted by the serializer"
);
}
#[test]
fn scan_placeholder_leaf_serializes_role_and_index() {
assert_eq!((SCAN_ROLE_CARRY, SCAN_ROLE_ELEM), (0u8, 1u8));
let carry = OpAttrs {
scan_role: Some(SCAN_ROLE_CARRY),
scan_index: Some(0),
..OpAttrs::default()
};
assert_eq!(
carry.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
vec![0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
"carry hole: u32-LE(5) ++ u8(0) ++ u32-LE(0)"
);
let elem = OpAttrs {
scan_role: Some(SCAN_ROLE_ELEM),
scan_index: Some(2),
..OpAttrs::default()
};
assert_eq!(
elem.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
vec![0x05, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x00],
"elem hole: u32-LE(5) ++ u8(1) ++ u32-LE(2)"
);
let elem0 = OpAttrs {
scan_role: Some(SCAN_ROLE_ELEM),
scan_index: Some(0),
..OpAttrs::default()
};
assert_ne!(
carry.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
elem0.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
);
}
#[test]
fn leaf_arm_bodies_ride_carrier_a_u32_le() {
let a = OpAttrs {
slot_index: Some(7),
axis: Some(1),
const_bits: Some(0x3FC0_0000),
scan_role: Some(SCAN_ROLE_ELEM),
scan_index: Some(2),
..OpAttrs::default()
};
for (tag, body_len) in [
(OpTag::RuntimeScalar, 4usize),
(OpTag::ReducedCount, 8),
(OpTag::Const, 8),
(OpTag::ScanPlaceholder, 5),
] {
let blob = a.to_canonical_bytes(tag).unwrap();
let declared = u32::from_le_bytes(blob[..4].try_into().unwrap()) as usize;
assert_eq!(
declared, body_len,
"{tag:?}: outer u32-LE length = body length"
);
assert_eq!(
blob.len(),
4 + body_len,
"{tag:?}: 4-byte u32-LE prefix + verbatim body"
);
}
}
#[test]
fn leaf_arms_are_wire_tokens_only_no_graph_producer() {
let d = OpAttrs::default();
for (tag, field) in [
(OpTag::RuntimeScalar, "slot_index"),
(OpTag::ReducedCount, "axis"),
(OpTag::Const, "const_bits"),
(OpTag::ScanPlaceholder, "scan_role"),
] {
assert_eq!(
d.to_canonical_bytes(tag),
Err(UnresolvedAttr { op: tag, field }),
"{tag:?} must DECLINE an unset `{field}`, not emit a default"
);
}
assert_eq!(d.to_canonical_bytes(OpTag::Add).unwrap(), vec![0, 0, 0, 0]);
let filled = OpAttrs {
scan_role: Some(SCAN_ROLE_ELEM),
scan_index: Some(2),
..OpAttrs::default()
};
assert_eq!(
filled
.to_canonical_bytes(OpTag::ScanPlaceholder)
.unwrap()
.len(),
4 + 5,
"a RESOLVED ScanPlaceholder still emits the same 5-byte body"
);
}
#[test]
fn an_unresolved_axis_is_inexpressible_gap287() {
assert_eq!(
OpAttrs::default().to_canonical_bytes(OpTag::Gather),
Err(UnresolvedAttr {
op: OpTag::Gather,
field: "axis"
})
);
let a0 = OpAttrs {
axis: Some(0),
..OpAttrs::default()
};
let a2 = OpAttrs {
axis: Some(2),
..OpAttrs::default()
};
assert_ne!(
a0.to_canonical_bytes(OpTag::Gather).unwrap(),
a2.to_canonical_bytes(OpTag::Gather).unwrap(),
"axis 0 and axis 2 must differ on the wire"
);
}
#[test]
fn keepdim_still_defaults_because_the_decoder_never_reads_it() {
let axis_only = OpAttrs {
axis: Some(1),
..OpAttrs::default()
};
let bytes = axis_only
.to_canonical_bytes(OpTag::SumDim)
.expect("axis is set; keepdim is not required");
assert_eq!(bytes.len(), 4 + 8 + 1, "axis(i64) + keepdim(u8)");
assert_eq!(*bytes.last().unwrap(), 0, "keepdim defaults to false");
assert_eq!(
OpAttrs::default().to_canonical_bytes(OpTag::SumDim),
Err(UnresolvedAttr {
op: OpTag::SumDim,
field: "axis"
})
);
}
}