pub const TAG_SAME_AS: u8 = 0x01;
pub const TAG_EXTENT: u8 = 0x02;
pub const TAG_CONST: u8 = 0x03;
pub const TAG_PARAM: u8 = 0x04;
pub const TAG_ADD: u8 = 0x05;
pub const TAG_SUB: u8 = 0x06;
pub const TAG_MUL: u8 = 0x07;
pub const TAG_DIV: u8 = 0x08;
pub const TAG_REDUCE: u8 = 0x09; pub const TAG_WITH_DIM: u8 = 0x0A; pub const TAG_DIMS: u8 = 0x0B;
pub const SYMBOLIC: i64 = i64::MIN;
pub const LAST: u8 = 0xFF;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Dim {
Extent {
operand: u8,
axis: u8,
},
Const(i64),
Param(u8),
Add(Box<Dim>, Box<Dim>),
Sub(Box<Dim>, Box<Dim>),
Mul(Box<Dim>, Box<Dim>),
Div(Box<Dim>, Box<Dim>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ShapeExpr {
SameAs { operand: u8 },
WithDim {
operand: u8,
axis: u8,
dim: Box<Dim>,
},
Dims(Vec<Dim>),
}
impl ShapeExpr {
pub fn encode(&self) -> Vec<u8> {
match self {
ShapeExpr::SameAs { operand } => vec![TAG_SAME_AS, *operand],
ShapeExpr::WithDim { operand, axis, dim } => {
let child = dim.encode();
let mut v = vec![TAG_WITH_DIM, *operand, *axis];
v.extend_from_slice(&(child.len() as u16).to_le_bytes());
v.extend_from_slice(&child);
v
}
ShapeExpr::Dims(dims) => {
let mut v = vec![TAG_DIMS, dims.len() as u8];
for d in dims {
let child = d.encode();
v.extend_from_slice(&(child.len() as u16).to_le_bytes());
v.extend_from_slice(&child);
}
v
}
}
}
}
impl Dim {
pub fn encode(&self) -> Vec<u8> {
match self {
Dim::Extent { operand, axis } => vec![TAG_EXTENT, *operand, *axis],
Dim::Const(c) => {
let mut v = vec![TAG_CONST];
v.extend_from_slice(&c.to_le_bytes());
v
}
Dim::Param(f) => vec![TAG_PARAM, *f],
Dim::Add(a, b) => encode_binary(TAG_ADD, a, b),
Dim::Sub(a, b) => encode_binary(TAG_SUB, a, b),
Dim::Mul(a, b) => encode_binary(TAG_MUL, a, b),
Dim::Div(a, b) => encode_binary(TAG_DIV, a, b),
}
}
}
fn encode_binary(tag: u8, a: &Dim, b: &Dim) -> Vec<u8> {
let (ca, cb) = (a.encode(), b.encode());
let mut v = vec![tag];
v.extend_from_slice(&(ca.len() as u16).to_le_bytes());
v.extend_from_slice(&ca);
v.extend_from_slice(&(cb.len() as u16).to_le_bytes());
v.extend_from_slice(&cb);
v
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShapeExprError {
ZeroTag,
ReservedTag { tag: u8 },
TruncatedBlob { need: usize, got: usize },
TrailingBytes { extra: usize },
AxisOutOfRange { axis: u8, rank: usize },
OperandOutOfRange { operand: u8, operands: usize },
ParamOutOfRange { field: u8, params: usize },
DivideByZero,
}
pub fn decode_dim(blob: &[u8]) -> Result<Dim, ShapeExprError> {
let (d, consumed) = decode_dim_at(blob, 0)?;
if consumed != blob.len() {
return Err(ShapeExprError::TrailingBytes {
extra: blob.len() - consumed,
});
}
Ok(d)
}
fn decode_dim_at(blob: &[u8], pos: usize) -> Result<(Dim, usize), ShapeExprError> {
let tag = *blob.get(pos).ok_or(ShapeExprError::TruncatedBlob {
need: pos + 1,
got: blob.len(),
})?;
match tag {
0x00 => Err(ShapeExprError::ZeroTag),
TAG_EXTENT => {
need(blob, pos, 3)?;
Ok((
Dim::Extent {
operand: blob[pos + 1],
axis: blob[pos + 2],
},
pos + 3,
))
}
TAG_CONST => {
need(blob, pos, 9)?;
let mut a = [0u8; 8];
a.copy_from_slice(&blob[pos + 1..pos + 9]);
Ok((Dim::Const(i64::from_le_bytes(a)), pos + 9))
}
TAG_PARAM => {
need(blob, pos, 2)?;
Ok((Dim::Param(blob[pos + 1]), pos + 2))
}
TAG_ADD | TAG_SUB | TAG_MUL | TAG_DIV => {
let (c1, p1) = read_child(blob, pos + 1)?;
let (c2, p2) = read_child(blob, p1)?;
let (a, b) = (Box::new(c1), Box::new(c2));
let d = match tag {
TAG_ADD => Dim::Add(a, b),
TAG_SUB => Dim::Sub(a, b),
TAG_MUL => Dim::Mul(a, b),
_ => Dim::Div(a, b),
};
Ok((d, p2))
}
TAG_REDUCE | TAG_WITH_DIM | TAG_DIMS => Err(ShapeExprError::ReservedTag { tag }),
other => Err(ShapeExprError::ReservedTag { tag: other }),
}
}
fn read_child(blob: &[u8], pos: usize) -> Result<(Dim, usize), ShapeExprError> {
if blob.len() < pos + 2 {
return Err(ShapeExprError::TruncatedBlob {
need: 2,
got: blob.len().saturating_sub(pos),
});
}
let len = u16::from_le_bytes([blob[pos], blob[pos + 1]]) as usize;
let start = pos + 2;
if blob.len() < start + len {
return Err(ShapeExprError::TruncatedBlob {
need: len,
got: blob.len().saturating_sub(start),
});
}
let child = decode_dim(&blob[start..start + len])?; Ok((child, start + len))
}
fn need(blob: &[u8], pos: usize, n: usize) -> Result<(), ShapeExprError> {
if blob.len() < pos + n {
Err(ShapeExprError::TruncatedBlob {
need: n,
got: blob.len().saturating_sub(pos),
})
} else {
Ok(())
}
}
pub fn decode_shape(blob: &[u8]) -> Result<ShapeExpr, ShapeExprError> {
let (s, consumed) = decode_shape_at(blob, 0)?;
if consumed != blob.len() {
return Err(ShapeExprError::TrailingBytes {
extra: blob.len() - consumed,
});
}
Ok(s)
}
fn decode_shape_at(blob: &[u8], pos: usize) -> Result<(ShapeExpr, usize), ShapeExprError> {
let tag = *blob.get(pos).ok_or(ShapeExprError::TruncatedBlob {
need: pos + 1,
got: blob.len(),
})?;
match tag {
0x00 => Err(ShapeExprError::ZeroTag),
TAG_SAME_AS => {
need(blob, pos, 2)?;
Ok((
ShapeExpr::SameAs {
operand: blob[pos + 1],
},
pos + 2,
))
}
TAG_WITH_DIM => {
need(blob, pos, 3)?;
let operand = blob[pos + 1];
let axis = blob[pos + 2];
let (child, next) = read_child(blob, pos + 3)?;
Ok((
ShapeExpr::WithDim {
operand,
axis,
dim: Box::new(child),
},
next,
))
}
TAG_DIMS => {
need(blob, pos, 2)?;
let count = blob[pos + 1] as usize;
let mut dims = Vec::with_capacity(count);
let mut p = pos + 2;
for _ in 0..count {
let (child, next) = read_child(blob, p)?;
dims.push(child);
p = next;
}
Ok((ShapeExpr::Dims(dims), p))
}
other => Err(ShapeExprError::ReservedTag { tag: other }),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DimValue {
Concrete(i64),
Gap,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShapeValue {
Concrete(Vec<i64>),
Gap,
}
pub fn resolve_axis(axis: u8, rank: usize) -> Result<usize, ShapeExprError> {
if axis == LAST {
return rank
.checked_sub(1)
.ok_or(ShapeExprError::AxisOutOfRange { axis, rank });
}
let a = axis as usize;
if a >= rank {
return Err(ShapeExprError::AxisOutOfRange { axis, rank });
}
Ok(a)
}
fn floordiv(a: i64, b: i64) -> i64 {
let (q, r) = (a / b, a % b);
if r != 0 && ((r < 0) != (b < 0)) {
q - 1
} else {
q
}
}
fn eval_binary(
a: DimValue,
b: DimValue,
f: impl Fn(i64, i64) -> Result<i64, ShapeExprError>,
) -> Result<DimValue, ShapeExprError> {
match (a, b) {
(DimValue::Concrete(x), DimValue::Concrete(y)) => Ok(DimValue::Concrete(f(x, y)?)),
_ => Ok(DimValue::Gap), }
}
pub fn eval_dim(
d: &Dim,
operands: &[Vec<i64>],
params: &[i64],
) -> Result<DimValue, ShapeExprError> {
match d {
Dim::Extent { operand, axis } => {
let op = *operand as usize;
let shape = operands.get(op).ok_or(ShapeExprError::OperandOutOfRange {
operand: *operand,
operands: operands.len(),
})?;
let idx = resolve_axis(*axis, shape.len())?;
let ext = shape[idx];
Ok(if ext == SYMBOLIC {
DimValue::Gap
} else {
DimValue::Concrete(ext)
})
}
Dim::Const(c) => Ok(DimValue::Concrete(*c)),
Dim::Param(f) => {
let fi = *f as usize;
let v = params.get(fi).ok_or(ShapeExprError::ParamOutOfRange {
field: *f,
params: params.len(),
})?;
Ok(DimValue::Concrete(*v))
}
Dim::Add(a, b) => eval_binary(
eval_dim(a, operands, params)?,
eval_dim(b, operands, params)?,
|x, y| Ok(x + y),
),
Dim::Sub(a, b) => eval_binary(
eval_dim(a, operands, params)?,
eval_dim(b, operands, params)?,
|x, y| Ok(x - y),
),
Dim::Mul(a, b) => eval_binary(
eval_dim(a, operands, params)?,
eval_dim(b, operands, params)?,
|x, y| Ok(x * y),
),
Dim::Div(a, b) => eval_binary(
eval_dim(a, operands, params)?,
eval_dim(b, operands, params)?,
|x, y| {
if y == 0 {
Err(ShapeExprError::DivideByZero)
} else {
Ok(floordiv(x, y))
}
},
),
}
}
pub fn eval_shape(
s: &ShapeExpr,
operands: &[Vec<i64>],
params: &[i64],
) -> Result<ShapeValue, ShapeExprError> {
match s {
ShapeExpr::SameAs { operand } => {
let op = *operand as usize;
let shape = operands.get(op).ok_or(ShapeExprError::OperandOutOfRange {
operand: *operand,
operands: operands.len(),
})?;
if shape.contains(&SYMBOLIC) {
Ok(ShapeValue::Gap)
} else {
Ok(ShapeValue::Concrete(shape.clone()))
}
}
ShapeExpr::WithDim { operand, axis, dim } => {
let op = *operand as usize;
let shape = operands.get(op).ok_or(ShapeExprError::OperandOutOfRange {
operand: *operand,
operands: operands.len(),
})?;
let idx = resolve_axis(*axis, shape.len())?;
let replacement = eval_dim(dim, operands, params)?;
let mut out = shape.clone();
let mut gap = false;
for (i, e) in out.iter_mut().enumerate() {
if i == idx {
match &replacement {
DimValue::Concrete(v) => *e = *v,
DimValue::Gap => gap = true,
}
} else if *e == SYMBOLIC {
gap = true;
}
}
if gap {
Ok(ShapeValue::Gap)
} else {
Ok(ShapeValue::Concrete(out))
}
}
ShapeExpr::Dims(dims) => {
let mut out = Vec::with_capacity(dims.len());
let mut gap = false;
for d in dims {
match eval_dim(d, operands, params)? {
DimValue::Concrete(v) => out.push(v),
DimValue::Gap => gap = true,
}
}
if gap {
Ok(ShapeValue::Gap)
} else {
Ok(ShapeValue::Concrete(out))
}
}
}
}
pub fn reduce_shape(input: &[i64], reduce_axes: &[usize], keepdim: bool) -> Vec<i64> {
let set: std::collections::BTreeSet<usize> = reduce_axes.iter().copied().collect();
let mut out = Vec::new();
for (i, &e) in input.iter().enumerate() {
if set.contains(&i) {
if keepdim {
out.push(1);
}
} else {
out.push(e);
}
}
out
}
pub fn gather_shape(data: &[i64], index: &[i64], axis: usize) -> Vec<i64> {
let mut out = Vec::with_capacity(data.len() - 1 + index.len());
out.extend_from_slice(&data[..axis]);
out.extend_from_slice(index);
out.extend_from_slice(&data[axis + 1..]);
out
}
pub fn matmul_shape(lhs: &[i64], rhs: &[i64]) -> Vec<i64> {
let r = lhs.len();
let mut out = lhs[..r - 2].to_vec(); out.push(lhs[r - 2]); out.push(rhs[r - 1]); out
}
pub fn shape_consistent(declared: &[i64], computed: &ShapeValue) -> bool {
match computed {
ShapeValue::Concrete(c) => declared == c.as_slice(),
ShapeValue::Gap => true,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialization_golden() {
assert_eq!(ShapeExpr::SameAs { operand: 0 }.encode(), vec![0x01, 0x00]);
assert_eq!(
Dim::Extent {
operand: 0,
axis: LAST
}
.encode(),
vec![0x02, 0x00, 0xFF]
);
assert_eq!(
Dim::Const(2).encode(),
vec![0x03, 0x02, 0, 0, 0, 0, 0, 0, 0]
);
assert_eq!(Dim::Param(0).encode(), vec![0x04, 0x00]);
let half = Dim::Div(
Box::new(Dim::Extent {
operand: 0,
axis: LAST,
}),
Box::new(Dim::Const(2)),
);
assert_eq!(
half.encode(),
vec![
0x08, 0x03, 0x00, 0x02, 0x00, 0xFF, 0x09, 0x00, 0x03, 0x02, 0, 0, 0, 0, 0, 0, 0
]
);
}
#[test]
fn decode_round_trip_and_declines() {
let half = Dim::Div(
Box::new(Dim::Extent {
operand: 0,
axis: LAST,
}),
Box::new(Dim::Const(2)),
);
assert_eq!(decode_dim(&half.encode()).unwrap(), half); assert_eq!(decode_dim(&[0x00]), Err(ShapeExprError::ZeroTag));
assert_eq!(
decode_dim(&[0x09, 0x00]),
Err(ShapeExprError::ReservedTag { tag: 0x09 })
);
assert_eq!(
decode_dim(&[0x03, 0x02, 0x00]),
Err(ShapeExprError::TruncatedBlob { need: 9, got: 3 })
);
assert_eq!(
decode_dim(&[0x04, 0x00, 0xAB]),
Err(ShapeExprError::TrailingBytes { extra: 1 })
);
}
#[test]
fn reserved_extension_tags_decline_by_name() {
assert_eq!(TAG_REDUCE, 0x09);
assert_eq!(TAG_WITH_DIM, 0x0A);
assert_eq!(TAG_DIMS, 0x0B);
for tag in [TAG_REDUCE, TAG_WITH_DIM, TAG_DIMS] {
assert_eq!(decode_dim(&[tag]), Err(ShapeExprError::ReservedTag { tag }));
assert_eq!(
decode_dim(&[tag, 0x00, 0x01]),
Err(ShapeExprError::ReservedTag { tag })
);
}
assert_eq!(
decode_dim(&[TAG_ADD, 1, 0, TAG_WITH_DIM, 1, 0, TAG_DIMS]),
Err(ShapeExprError::ReservedTag { tag: TAG_WITH_DIM })
);
assert_eq!(
decode_dim(&[0x0C]),
Err(ShapeExprError::ReservedTag { tag: 0x0C })
);
}
#[test]
fn with_dim_extension_golden_roundtrip_eval() {
let wd = ShapeExpr::WithDim {
operand: 0,
axis: 1,
dim: Box::new(Dim::Const(7)),
};
assert_eq!(
wd.encode(),
vec![
0x0A, 0x00, 0x01, 0x09, 0x00, 0x03, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
]
);
let wd_last = ShapeExpr::WithDim {
operand: 1,
axis: LAST,
dim: Box::new(Dim::Param(0)),
};
assert_eq!(
wd_last.encode(),
vec![0x0A, 0x01, 0xFF, 0x02, 0x00, 0x04, 0x00]
);
assert_eq!(decode_shape(&wd.encode()).unwrap(), wd);
assert_eq!(decode_shape(&wd_last.encode()).unwrap(), wd_last);
assert_eq!(
decode_shape(&[0x0A, 0x00]),
Err(ShapeExprError::TruncatedBlob { need: 3, got: 2 })
);
assert_eq!(
decode_shape(&[0x0A, 0x00, 0x01, 0x09, 0x00]),
Err(ShapeExprError::TruncatedBlob { need: 9, got: 0 })
);
let ops = vec![vec![2i64, 3, 5]];
assert_eq!(
eval_shape(
&ShapeExpr::WithDim {
operand: 0,
axis: 1,
dim: Box::new(Dim::Const(9))
},
&ops,
&[]
)
.unwrap(),
ShapeValue::Concrete(vec![2, 9, 5])
);
assert_eq!(
eval_shape(
&ShapeExpr::WithDim {
operand: 0,
axis: LAST,
dim: Box::new(Dim::Const(9))
},
&ops,
&[]
)
.unwrap(),
ShapeValue::Concrete(vec![2, 3, 9])
);
let sym = vec![vec![4i64, SYMBOLIC]];
assert_eq!(
eval_shape(
&ShapeExpr::WithDim {
operand: 0,
axis: 0,
dim: Box::new(Dim::Const(7))
},
&sym,
&[]
)
.unwrap(),
ShapeValue::Gap
);
assert_eq!(
eval_shape(
&ShapeExpr::WithDim {
operand: 0,
axis: LAST,
dim: Box::new(Dim::Const(7))
},
&sym,
&[]
)
.unwrap(),
ShapeValue::Concrete(vec![4, 7])
);
assert_eq!(
eval_shape(
&ShapeExpr::WithDim {
operand: 0,
axis: 0,
dim: Box::new(Dim::Extent {
operand: 0,
axis: LAST
}),
},
&sym,
&[]
)
.unwrap(),
ShapeValue::Gap
);
assert_eq!(
eval_shape(
&ShapeExpr::WithDim {
operand: 0,
axis: 5,
dim: Box::new(Dim::Const(1))
},
&[vec![2i64, 3]],
&[]
),
Err(ShapeExprError::AxisOutOfRange { axis: 5, rank: 2 })
);
assert_eq!(
eval_shape(
&ShapeExpr::WithDim {
operand: 0,
axis: 1,
dim: Box::new(Dim::Param(0))
},
&ops,
&[42]
)
.unwrap(),
ShapeValue::Concrete(vec![2, 42, 5])
);
}
#[test]
fn dims_extension_golden_roundtrip_eval() {
let dims = ShapeExpr::Dims(vec![
Dim::Extent {
operand: 0,
axis: 0,
},
Dim::Const(2),
]);
assert_eq!(
dims.encode(),
vec![
0x0B, 0x02, 0x03, 0x00, 0x02, 0x00, 0x00, 0x09, 0x00, 0x03, 0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
]
);
let scalar = ShapeExpr::Dims(vec![]);
assert_eq!(scalar.encode(), vec![0x0B, 0x00]);
assert_eq!(decode_shape(&dims.encode()).unwrap(), dims);
assert_eq!(decode_shape(&scalar.encode()).unwrap(), scalar);
assert_eq!(
decode_shape(&[0x0B, 0x02]),
Err(ShapeExprError::TruncatedBlob { need: 2, got: 0 })
);
assert_eq!(
decode_shape(&[0x09, 0x00]),
Err(ShapeExprError::ReservedTag { tag: 0x09 })
);
assert_eq!(
decode_shape(&[0x0B, 0x00, 0xAB]),
Err(ShapeExprError::TrailingBytes { extra: 1 })
);
let ops = vec![vec![8i64, 16, 32, 64], vec![1i64, 1, 1, 128]];
assert_eq!(
eval_shape(
&ShapeExpr::Dims(vec![
Dim::Extent {
operand: 0,
axis: 0
},
Dim::Extent {
operand: 0,
axis: 2
},
Dim::Extent {
operand: 0,
axis: 3
},
Dim::Extent {
operand: 1,
axis: 3
},
]),
&ops,
&[]
)
.unwrap(),
ShapeValue::Concrete(vec![8, 32, 64, 128])
);
assert_eq!(
eval_shape(&ShapeExpr::Dims(vec![]), &ops, &[]).unwrap(),
ShapeValue::Concrete(vec![])
);
let sym = vec![vec![4i64, SYMBOLIC]];
assert_eq!(
eval_shape(
&ShapeExpr::Dims(vec![
Dim::Extent {
operand: 0,
axis: 0
},
Dim::Extent {
operand: 0,
axis: LAST
},
]),
&sym,
&[]
)
.unwrap(),
ShapeValue::Gap
);
}
#[test]
fn decode_shape_core_and_grammar_level_declines() {
assert_eq!(
decode_shape(&[0x01, 0x00]).unwrap(),
ShapeExpr::SameAs { operand: 0 }
);
assert_eq!(
decode_shape(&[0x03, 0x02, 0, 0, 0, 0, 0, 0, 0]),
Err(ShapeExprError::ReservedTag { tag: 0x03 })
);
assert_eq!(
decode_dim(&[TAG_WITH_DIM, 0x00, 0x01, 0x02, 0x00, 0x04, 0x00]),
Err(ShapeExprError::ReservedTag { tag: TAG_WITH_DIM })
);
assert_eq!(
decode_dim(&[TAG_DIMS, 0x00]),
Err(ShapeExprError::ReservedTag { tag: TAG_DIMS })
);
assert_eq!(
decode_shape(&[0x09, 0x00]),
Err(ShapeExprError::ReservedTag { tag: 0x09 })
);
assert_eq!(
decode_dim(&[0x09, 0x00]),
Err(ShapeExprError::ReservedTag { tag: 0x09 })
);
}
#[test]
fn eval_vocabulary_axis_floordiv_gap() {
let ops = vec![vec![2i64, 3, 4]];
let params = vec![7i64];
assert_eq!(
eval_shape(&ShapeExpr::SameAs { operand: 0 }, &ops, ¶ms).unwrap(),
ShapeValue::Concrete(vec![2, 3, 4])
);
assert_eq!(
eval_dim(
&Dim::Extent {
operand: 0,
axis: 1
},
&ops,
¶ms
)
.unwrap(),
DimValue::Concrete(3)
);
assert_eq!(
eval_dim(&Dim::Const(5), &ops, ¶ms).unwrap(),
DimValue::Concrete(5)
);
assert_eq!(
eval_dim(&Dim::Param(0), &ops, ¶ms).unwrap(),
DimValue::Concrete(7)
);
let e = Dim::Add(
Box::new(Dim::Mul(
Box::new(Dim::Extent {
operand: 0,
axis: 0,
}),
Box::new(Dim::Const(3)),
)),
Box::new(Dim::Param(0)),
);
assert_eq!(eval_dim(&e, &ops, ¶ms).unwrap(), DimValue::Concrete(13));
let r3 = vec![vec![2i64, 3, 5]];
assert_eq!(
eval_dim(
&Dim::Extent {
operand: 0,
axis: LAST
},
&r3,
&[]
)
.unwrap(),
DimValue::Concrete(5)
);
assert_eq!(
eval_dim(
&Dim::Extent {
operand: 0,
axis: 2
},
&r3,
&[]
)
.unwrap(),
DimValue::Concrete(5)
);
assert_eq!(
eval_dim(
&Dim::Extent {
operand: 0,
axis: 3
},
&r3,
&[]
),
Err(ShapeExprError::AxisOutOfRange { axis: 3, rank: 3 })
);
let fd = |a, b| {
eval_dim(
&Dim::Div(Box::new(Dim::Const(a)), Box::new(Dim::Const(b))),
&r3,
&[],
)
};
assert_eq!(fd(7, 2).unwrap(), DimValue::Concrete(3));
assert_eq!(fd(-7, 2).unwrap(), DimValue::Concrete(-4)); assert_eq!(fd(1, 0), Err(ShapeExprError::DivideByZero));
let sym = vec![vec![4i64, SYMBOLIC]];
assert_eq!(
eval_dim(
&Dim::Extent {
operand: 0,
axis: LAST
},
&sym,
&[]
)
.unwrap(),
DimValue::Gap
);
let half = Dim::Div(
Box::new(Dim::Extent {
operand: 0,
axis: LAST,
}),
Box::new(Dim::Const(2)),
);
assert_eq!(eval_dim(&half, &sym, &[]).unwrap(), DimValue::Gap);
assert_eq!(
eval_shape(&ShapeExpr::SameAs { operand: 0 }, &sym, &[]).unwrap(),
ShapeValue::Gap
);
assert_eq!(
eval_dim(
&Dim::Extent {
operand: 0,
axis: 0
},
&sym,
&[]
)
.unwrap(),
DimValue::Concrete(4)
);
}
#[test]
fn reduce_shape_rule() {
assert_eq!(reduce_shape(&[2, 3, 5], &[2], false), vec![2, 3]); assert_eq!(reduce_shape(&[2, 3, 5], &[2], true), vec![2, 3, 1]); assert_eq!(reduce_shape(&[2, 3, 5], &[0, 2], false), vec![3]); assert_eq!(reduce_shape(&[8, 4096], &[1], false), vec![8]); }
#[test]
fn out_differs_from_operands() {
assert_eq!(gather_shape(&[8, 4096], &[16], 0), vec![16, 4096]);
assert_eq!(gather_shape(&[1000, 64], &[2, 5], 0), vec![2, 5, 64]); assert_eq!(matmul_shape(&[8, 4096], &[4096, 1024]), vec![8, 1024]);
assert_eq!(matmul_shape(&[4, 8, 16], &[4, 16, 32]), vec![4, 8, 32]);
let g = gather_shape(&[8, 4096], &[16], 0);
assert!(!shape_consistent(&[8, 4096], &ShapeValue::Concrete(g)));
let m = matmul_shape(&[8, 4096], &[4096, 1024]);
assert!(!shape_consistent(
&[8, 4096],
&ShapeValue::Concrete(m.clone())
));
assert!(!shape_consistent(&[4096, 1024], &ShapeValue::Concrete(m)));
}
#[test]
fn contract_output_shape_consistency() {
let computed = ShapeValue::Concrete(reduce_shape(&[8, 4096], &[1], false));
assert!(shape_consistent(&[8], &computed)); assert!(!shape_consistent(&[8, 4096], &computed)); assert!(shape_consistent(&[8], &ShapeValue::Gap)); }
}