1pub const TAG_SAME_AS: u8 = 0x01;
15pub const TAG_EXTENT: u8 = 0x02;
16pub const TAG_CONST: u8 = 0x03;
17pub const TAG_PARAM: u8 = 0x04;
18pub const TAG_ADD: u8 = 0x05;
19pub const TAG_SUB: u8 = 0x06;
20pub const TAG_MUL: u8 = 0x07;
21pub const TAG_DIV: u8 = 0x08;
22pub const TAG_REDUCE: u8 = 0x09; pub const TAG_WITH_DIM: u8 = 0x0A; pub const TAG_DIMS: u8 = 0x0B; pub const SYMBOLIC: i64 = i64::MIN;
28
29pub const LAST: u8 = 0xFF;
34
35#[derive(Debug, Clone, PartialEq, Eq, Hash)]
37pub enum Dim {
38 Extent {
40 operand: u8,
41 axis: u8,
42 },
43 Const(i64),
44 Param(u8),
46 Add(Box<Dim>, Box<Dim>),
47 Sub(Box<Dim>, Box<Dim>),
48 Mul(Box<Dim>, Box<Dim>),
49 Div(Box<Dim>, Box<Dim>),
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Hash)]
58pub enum ShapeExpr {
59 SameAs { operand: u8 },
61 WithDim {
65 operand: u8,
66 axis: u8,
67 dim: Box<Dim>,
68 },
69 Dims(Vec<Dim>),
73}
74
75impl ShapeExpr {
76 pub fn encode(&self) -> Vec<u8> {
79 match self {
80 ShapeExpr::SameAs { operand } => vec![TAG_SAME_AS, *operand],
81 ShapeExpr::WithDim { operand, axis, dim } => {
84 let child = dim.encode();
85 let mut v = vec![TAG_WITH_DIM, *operand, *axis];
86 v.extend_from_slice(&(child.len() as u16).to_le_bytes());
87 v.extend_from_slice(&child);
88 v
89 }
90 ShapeExpr::Dims(dims) => {
93 let mut v = vec![TAG_DIMS, dims.len() as u8];
94 for d in dims {
95 let child = d.encode();
96 v.extend_from_slice(&(child.len() as u16).to_le_bytes());
97 v.extend_from_slice(&child);
98 }
99 v
100 }
101 }
102 }
103}
104
105impl Dim {
106 pub fn encode(&self) -> Vec<u8> {
108 match self {
109 Dim::Extent { operand, axis } => vec![TAG_EXTENT, *operand, *axis],
110 Dim::Const(c) => {
111 let mut v = vec![TAG_CONST];
112 v.extend_from_slice(&c.to_le_bytes());
113 v
114 }
115 Dim::Param(f) => vec![TAG_PARAM, *f],
116 Dim::Add(a, b) => encode_binary(TAG_ADD, a, b),
117 Dim::Sub(a, b) => encode_binary(TAG_SUB, a, b),
118 Dim::Mul(a, b) => encode_binary(TAG_MUL, a, b),
119 Dim::Div(a, b) => encode_binary(TAG_DIV, a, b),
120 }
121 }
122}
123
124fn encode_binary(tag: u8, a: &Dim, b: &Dim) -> Vec<u8> {
125 let (ca, cb) = (a.encode(), b.encode());
126 let mut v = vec![tag];
127 v.extend_from_slice(&(ca.len() as u16).to_le_bytes());
128 v.extend_from_slice(&ca);
129 v.extend_from_slice(&(cb.len() as u16).to_le_bytes());
130 v.extend_from_slice(&cb);
131 v
132}
133
134#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum ShapeExprError {
138 ZeroTag,
139 ReservedTag { tag: u8 },
140 TruncatedBlob { need: usize, got: usize },
141 TrailingBytes { extra: usize },
142 AxisOutOfRange { axis: u8, rank: usize },
143 OperandOutOfRange { operand: u8, operands: usize },
144 ParamOutOfRange { field: u8, params: usize },
145 DivideByZero,
146}
147
148pub fn decode_dim(blob: &[u8]) -> Result<Dim, ShapeExprError> {
151 let (d, consumed) = decode_dim_at(blob, 0)?;
152 if consumed != blob.len() {
153 return Err(ShapeExprError::TrailingBytes {
154 extra: blob.len() - consumed,
155 });
156 }
157 Ok(d)
158}
159
160fn decode_dim_at(blob: &[u8], pos: usize) -> Result<(Dim, usize), ShapeExprError> {
161 let tag = *blob.get(pos).ok_or(ShapeExprError::TruncatedBlob {
162 need: pos + 1,
163 got: blob.len(),
164 })?;
165 match tag {
166 0x00 => Err(ShapeExprError::ZeroTag),
167 TAG_EXTENT => {
168 need(blob, pos, 3)?;
169 Ok((
170 Dim::Extent {
171 operand: blob[pos + 1],
172 axis: blob[pos + 2],
173 },
174 pos + 3,
175 ))
176 }
177 TAG_CONST => {
178 need(blob, pos, 9)?;
179 let mut a = [0u8; 8];
180 a.copy_from_slice(&blob[pos + 1..pos + 9]);
181 Ok((Dim::Const(i64::from_le_bytes(a)), pos + 9))
182 }
183 TAG_PARAM => {
184 need(blob, pos, 2)?;
185 Ok((Dim::Param(blob[pos + 1]), pos + 2))
186 }
187 TAG_ADD | TAG_SUB | TAG_MUL | TAG_DIV => {
188 let (c1, p1) = read_child(blob, pos + 1)?;
189 let (c2, p2) = read_child(blob, p1)?;
190 let (a, b) = (Box::new(c1), Box::new(c2));
191 let d = match tag {
192 TAG_ADD => Dim::Add(a, b),
193 TAG_SUB => Dim::Sub(a, b),
194 TAG_MUL => Dim::Mul(a, b),
195 _ => Dim::Div(a, b),
196 };
197 Ok((d, p2))
198 }
199 TAG_REDUCE | TAG_WITH_DIM | TAG_DIMS => Err(ShapeExprError::ReservedTag { tag }),
205 other => Err(ShapeExprError::ReservedTag { tag: other }),
206 }
207}
208
209fn read_child(blob: &[u8], pos: usize) -> Result<(Dim, usize), ShapeExprError> {
211 if blob.len() < pos + 2 {
212 return Err(ShapeExprError::TruncatedBlob {
213 need: 2,
214 got: blob.len().saturating_sub(pos),
215 });
216 }
217 let len = u16::from_le_bytes([blob[pos], blob[pos + 1]]) as usize;
218 let start = pos + 2;
219 if blob.len() < start + len {
220 return Err(ShapeExprError::TruncatedBlob {
221 need: len,
222 got: blob.len().saturating_sub(start),
223 });
224 }
225 let child = decode_dim(&blob[start..start + len])?; Ok((child, start + len))
227}
228
229fn need(blob: &[u8], pos: usize, n: usize) -> Result<(), ShapeExprError> {
230 if blob.len() < pos + n {
231 Err(ShapeExprError::TruncatedBlob {
232 need: n,
233 got: blob.len().saturating_sub(pos),
234 })
235 } else {
236 Ok(())
237 }
238}
239
240pub fn decode_shape(blob: &[u8]) -> Result<ShapeExpr, ShapeExprError> {
248 let (s, consumed) = decode_shape_at(blob, 0)?;
249 if consumed != blob.len() {
250 return Err(ShapeExprError::TrailingBytes {
251 extra: blob.len() - consumed,
252 });
253 }
254 Ok(s)
255}
256
257fn decode_shape_at(blob: &[u8], pos: usize) -> Result<(ShapeExpr, usize), ShapeExprError> {
258 let tag = *blob.get(pos).ok_or(ShapeExprError::TruncatedBlob {
259 need: pos + 1,
260 got: blob.len(),
261 })?;
262 match tag {
263 0x00 => Err(ShapeExprError::ZeroTag),
264 TAG_SAME_AS => {
265 need(blob, pos, 2)?;
266 Ok((
267 ShapeExpr::SameAs {
268 operand: blob[pos + 1],
269 },
270 pos + 2,
271 ))
272 }
273 TAG_WITH_DIM => {
275 need(blob, pos, 3)?;
276 let operand = blob[pos + 1];
277 let axis = blob[pos + 2];
278 let (child, next) = read_child(blob, pos + 3)?;
279 Ok((
280 ShapeExpr::WithDim {
281 operand,
282 axis,
283 dim: Box::new(child),
284 },
285 next,
286 ))
287 }
288 TAG_DIMS => {
290 need(blob, pos, 2)?;
291 let count = blob[pos + 1] as usize;
292 let mut dims = Vec::with_capacity(count);
293 let mut p = pos + 2;
294 for _ in 0..count {
295 let (child, next) = read_child(blob, p)?;
296 dims.push(child);
297 p = next;
298 }
299 Ok((ShapeExpr::Dims(dims), p))
300 }
301 other => Err(ShapeExprError::ReservedTag { tag: other }),
304 }
305}
306
307#[derive(Debug, Clone, PartialEq, Eq)]
309pub enum DimValue {
310 Concrete(i64),
311 Gap,
312}
313
314#[derive(Debug, Clone, PartialEq, Eq)]
316pub enum ShapeValue {
317 Concrete(Vec<i64>),
318 Gap,
319}
320
321pub fn resolve_axis(axis: u8, rank: usize) -> Result<usize, ShapeExprError> {
326 if axis == LAST {
327 return rank
328 .checked_sub(1)
329 .ok_or(ShapeExprError::AxisOutOfRange { axis, rank });
330 }
331 let a = axis as usize;
332 if a >= rank {
333 return Err(ShapeExprError::AxisOutOfRange { axis, rank });
334 }
335 Ok(a)
336}
337
338fn floordiv(a: i64, b: i64) -> i64 {
340 let (q, r) = (a / b, a % b);
341 if r != 0 && ((r < 0) != (b < 0)) {
342 q - 1
343 } else {
344 q
345 }
346}
347
348fn eval_binary(
349 a: DimValue,
350 b: DimValue,
351 f: impl Fn(i64, i64) -> Result<i64, ShapeExprError>,
352) -> Result<DimValue, ShapeExprError> {
353 match (a, b) {
354 (DimValue::Concrete(x), DimValue::Concrete(y)) => Ok(DimValue::Concrete(f(x, y)?)),
355 _ => Ok(DimValue::Gap), }
357}
358
359pub fn eval_dim(
361 d: &Dim,
362 operands: &[Vec<i64>],
363 params: &[i64],
364) -> Result<DimValue, ShapeExprError> {
365 match d {
366 Dim::Extent { operand, axis } => {
367 let op = *operand as usize;
368 let shape = operands.get(op).ok_or(ShapeExprError::OperandOutOfRange {
369 operand: *operand,
370 operands: operands.len(),
371 })?;
372 let idx = resolve_axis(*axis, shape.len())?;
373 let ext = shape[idx];
374 Ok(if ext == SYMBOLIC {
375 DimValue::Gap
376 } else {
377 DimValue::Concrete(ext)
378 })
379 }
380 Dim::Const(c) => Ok(DimValue::Concrete(*c)),
381 Dim::Param(f) => {
382 let fi = *f as usize;
383 let v = params.get(fi).ok_or(ShapeExprError::ParamOutOfRange {
384 field: *f,
385 params: params.len(),
386 })?;
387 Ok(DimValue::Concrete(*v))
388 }
389 Dim::Add(a, b) => eval_binary(
390 eval_dim(a, operands, params)?,
391 eval_dim(b, operands, params)?,
392 |x, y| Ok(x + y),
393 ),
394 Dim::Sub(a, b) => eval_binary(
395 eval_dim(a, operands, params)?,
396 eval_dim(b, operands, params)?,
397 |x, y| Ok(x - y),
398 ),
399 Dim::Mul(a, b) => eval_binary(
400 eval_dim(a, operands, params)?,
401 eval_dim(b, operands, params)?,
402 |x, y| Ok(x * y),
403 ),
404 Dim::Div(a, b) => eval_binary(
405 eval_dim(a, operands, params)?,
406 eval_dim(b, operands, params)?,
407 |x, y| {
408 if y == 0 {
409 Err(ShapeExprError::DivideByZero)
410 } else {
411 Ok(floordiv(x, y))
412 }
413 },
414 ),
415 }
416}
417
418pub fn eval_shape(
420 s: &ShapeExpr,
421 operands: &[Vec<i64>],
422 params: &[i64],
423) -> Result<ShapeValue, ShapeExprError> {
424 match s {
425 ShapeExpr::SameAs { operand } => {
426 let op = *operand as usize;
427 let shape = operands.get(op).ok_or(ShapeExprError::OperandOutOfRange {
428 operand: *operand,
429 operands: operands.len(),
430 })?;
431 if shape.contains(&SYMBOLIC) {
432 Ok(ShapeValue::Gap)
433 } else {
434 Ok(ShapeValue::Concrete(shape.clone()))
435 }
436 }
437 ShapeExpr::WithDim { operand, axis, dim } => {
442 let op = *operand as usize;
443 let shape = operands.get(op).ok_or(ShapeExprError::OperandOutOfRange {
444 operand: *operand,
445 operands: operands.len(),
446 })?;
447 let idx = resolve_axis(*axis, shape.len())?;
448 let replacement = eval_dim(dim, operands, params)?;
449 let mut out = shape.clone();
450 let mut gap = false;
451 for (i, e) in out.iter_mut().enumerate() {
452 if i == idx {
453 match &replacement {
454 DimValue::Concrete(v) => *e = *v,
455 DimValue::Gap => gap = true,
456 }
457 } else if *e == SYMBOLIC {
458 gap = true;
459 }
460 }
461 if gap {
462 Ok(ShapeValue::Gap)
463 } else {
464 Ok(ShapeValue::Concrete(out))
465 }
466 }
467 ShapeExpr::Dims(dims) => {
471 let mut out = Vec::with_capacity(dims.len());
472 let mut gap = false;
473 for d in dims {
474 match eval_dim(d, operands, params)? {
475 DimValue::Concrete(v) => out.push(v),
476 DimValue::Gap => gap = true,
477 }
478 }
479 if gap {
480 Ok(ShapeValue::Gap)
481 } else {
482 Ok(ShapeValue::Concrete(out))
483 }
484 }
485 }
486}
487
488pub fn reduce_shape(input: &[i64], reduce_axes: &[usize], keepdim: bool) -> Vec<i64> {
495 let set: std::collections::BTreeSet<usize> = reduce_axes.iter().copied().collect();
496 let mut out = Vec::new();
497 for (i, &e) in input.iter().enumerate() {
498 if set.contains(&i) {
499 if keepdim {
500 out.push(1);
501 }
502 } else {
503 out.push(e);
504 }
505 }
506 out
507}
508
509pub fn gather_shape(data: &[i64], index: &[i64], axis: usize) -> Vec<i64> {
514 let mut out = Vec::with_capacity(data.len() - 1 + index.len());
515 out.extend_from_slice(&data[..axis]);
516 out.extend_from_slice(index);
517 out.extend_from_slice(&data[axis + 1..]);
518 out
519}
520
521pub fn matmul_shape(lhs: &[i64], rhs: &[i64]) -> Vec<i64> {
526 let r = lhs.len();
527 let mut out = lhs[..r - 2].to_vec(); out.push(lhs[r - 2]); out.push(rhs[r - 1]); out
531}
532
533pub fn shape_consistent(declared: &[i64], computed: &ShapeValue) -> bool {
539 match computed {
540 ShapeValue::Concrete(c) => declared == c.as_slice(),
541 ShapeValue::Gap => true,
542 }
543}
544
545#[cfg(test)]
546mod tests {
547 use super::*;
548
549 #[test]
551 fn serialization_golden() {
552 assert_eq!(ShapeExpr::SameAs { operand: 0 }.encode(), vec![0x01, 0x00]);
553 assert_eq!(
554 Dim::Extent {
555 operand: 0,
556 axis: LAST
557 }
558 .encode(),
559 vec![0x02, 0x00, 0xFF]
560 );
561 assert_eq!(
562 Dim::Const(2).encode(),
563 vec![0x03, 0x02, 0, 0, 0, 0, 0, 0, 0]
564 );
565 assert_eq!(Dim::Param(0).encode(), vec![0x04, 0x00]);
566 let half = Dim::Div(
568 Box::new(Dim::Extent {
569 operand: 0,
570 axis: LAST,
571 }),
572 Box::new(Dim::Const(2)),
573 );
574 assert_eq!(
575 half.encode(),
576 vec![
577 0x08, 0x03, 0x00, 0x02, 0x00, 0xFF, 0x09, 0x00, 0x03, 0x02, 0, 0, 0, 0, 0, 0, 0
578 ]
579 );
580 }
581
582 #[test]
583 fn decode_round_trip_and_declines() {
584 let half = Dim::Div(
585 Box::new(Dim::Extent {
586 operand: 0,
587 axis: LAST,
588 }),
589 Box::new(Dim::Const(2)),
590 );
591 assert_eq!(decode_dim(&half.encode()).unwrap(), half); assert_eq!(decode_dim(&[0x00]), Err(ShapeExprError::ZeroTag));
594 assert_eq!(
595 decode_dim(&[0x09, 0x00]),
596 Err(ShapeExprError::ReservedTag { tag: 0x09 })
597 );
598 assert_eq!(
599 decode_dim(&[0x03, 0x02, 0x00]),
600 Err(ShapeExprError::TruncatedBlob { need: 9, got: 3 })
601 );
602 assert_eq!(
603 decode_dim(&[0x04, 0x00, 0xAB]),
604 Err(ShapeExprError::TrailingBytes { extra: 1 })
605 );
606 }
607
608 #[test]
614 fn reserved_extension_tags_decline_by_name() {
615 assert_eq!(TAG_REDUCE, 0x09);
617 assert_eq!(TAG_WITH_DIM, 0x0A);
618 assert_eq!(TAG_DIMS, 0x0B);
619 for tag in [TAG_REDUCE, TAG_WITH_DIM, TAG_DIMS] {
620 assert_eq!(decode_dim(&[tag]), Err(ShapeExprError::ReservedTag { tag }));
622 assert_eq!(
624 decode_dim(&[tag, 0x00, 0x01]),
625 Err(ShapeExprError::ReservedTag { tag })
626 );
627 }
628 assert_eq!(
630 decode_dim(&[TAG_ADD, 1, 0, TAG_WITH_DIM, 1, 0, TAG_DIMS]),
631 Err(ShapeExprError::ReservedTag { tag: TAG_WITH_DIM })
632 );
633 assert_eq!(
636 decode_dim(&[0x0C]),
637 Err(ShapeExprError::ReservedTag { tag: 0x0C })
638 );
639 }
640
641 #[test]
648 fn with_dim_extension_golden_roundtrip_eval() {
649 let wd = ShapeExpr::WithDim {
652 operand: 0,
653 axis: 1,
654 dim: Box::new(Dim::Const(7)),
655 };
656 assert_eq!(
657 wd.encode(),
658 vec![
659 0x0A, 0x00, 0x01, 0x09, 0x00, 0x03, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
660 ]
661 );
662 let wd_last = ShapeExpr::WithDim {
664 operand: 1,
665 axis: LAST,
666 dim: Box::new(Dim::Param(0)),
667 };
668 assert_eq!(
669 wd_last.encode(),
670 vec![0x0A, 0x01, 0xFF, 0x02, 0x00, 0x04, 0x00]
671 );
672
673 assert_eq!(decode_shape(&wd.encode()).unwrap(), wd);
675 assert_eq!(decode_shape(&wd_last.encode()).unwrap(), wd_last);
676
677 assert_eq!(
680 decode_shape(&[0x0A, 0x00]),
681 Err(ShapeExprError::TruncatedBlob { need: 3, got: 2 })
682 );
683 assert_eq!(
684 decode_shape(&[0x0A, 0x00, 0x01, 0x09, 0x00]),
685 Err(ShapeExprError::TruncatedBlob { need: 9, got: 0 })
686 );
687
688 let ops = vec![vec![2i64, 3, 5]];
690 assert_eq!(
691 eval_shape(
692 &ShapeExpr::WithDim {
693 operand: 0,
694 axis: 1,
695 dim: Box::new(Dim::Const(9))
696 },
697 &ops,
698 &[]
699 )
700 .unwrap(),
701 ShapeValue::Concrete(vec![2, 9, 5])
702 );
703 assert_eq!(
705 eval_shape(
706 &ShapeExpr::WithDim {
707 operand: 0,
708 axis: LAST,
709 dim: Box::new(Dim::Const(9))
710 },
711 &ops,
712 &[]
713 )
714 .unwrap(),
715 ShapeValue::Concrete(vec![2, 3, 9])
716 );
717 let sym = vec![vec![4i64, SYMBOLIC]];
720 assert_eq!(
721 eval_shape(
722 &ShapeExpr::WithDim {
723 operand: 0,
724 axis: 0,
725 dim: Box::new(Dim::Const(7))
726 },
727 &sym,
728 &[]
729 )
730 .unwrap(),
731 ShapeValue::Gap
732 );
733 assert_eq!(
734 eval_shape(
735 &ShapeExpr::WithDim {
736 operand: 0,
737 axis: LAST,
738 dim: Box::new(Dim::Const(7))
739 },
740 &sym,
741 &[]
742 )
743 .unwrap(),
744 ShapeValue::Concrete(vec![4, 7])
745 );
746 assert_eq!(
748 eval_shape(
749 &ShapeExpr::WithDim {
750 operand: 0,
751 axis: 0,
752 dim: Box::new(Dim::Extent {
753 operand: 0,
754 axis: LAST
755 }),
756 },
757 &sym,
758 &[]
759 )
760 .unwrap(),
761 ShapeValue::Gap
762 );
763 assert_eq!(
765 eval_shape(
766 &ShapeExpr::WithDim {
767 operand: 0,
768 axis: 5,
769 dim: Box::new(Dim::Const(1))
770 },
771 &[vec![2i64, 3]],
772 &[]
773 ),
774 Err(ShapeExprError::AxisOutOfRange { axis: 5, rank: 2 })
775 );
776 assert_eq!(
778 eval_shape(
779 &ShapeExpr::WithDim {
780 operand: 0,
781 axis: 1,
782 dim: Box::new(Dim::Param(0))
783 },
784 &ops,
785 &[42]
786 )
787 .unwrap(),
788 ShapeValue::Concrete(vec![2, 42, 5])
789 );
790 }
791
792 #[test]
793 fn dims_extension_golden_roundtrip_eval() {
794 let dims = ShapeExpr::Dims(vec![
797 Dim::Extent {
798 operand: 0,
799 axis: 0,
800 },
801 Dim::Const(2),
802 ]);
803 assert_eq!(
804 dims.encode(),
805 vec![
806 0x0B, 0x02, 0x03, 0x00, 0x02, 0x00, 0x00, 0x09, 0x00, 0x03, 0x02, 0x00, 0x00, 0x00,
807 0x00, 0x00, 0x00, 0x00
808 ]
809 );
810 let scalar = ShapeExpr::Dims(vec![]);
812 assert_eq!(scalar.encode(), vec![0x0B, 0x00]);
813
814 assert_eq!(decode_shape(&dims.encode()).unwrap(), dims);
816 assert_eq!(decode_shape(&scalar.encode()).unwrap(), scalar);
817
818 assert_eq!(
821 decode_shape(&[0x0B, 0x02]),
822 Err(ShapeExprError::TruncatedBlob { need: 2, got: 0 })
823 );
824 assert_eq!(
825 decode_shape(&[0x09, 0x00]),
826 Err(ShapeExprError::ReservedTag { tag: 0x09 })
827 );
828 assert_eq!(
829 decode_shape(&[0x0B, 0x00, 0xAB]),
830 Err(ShapeExprError::TrailingBytes { extra: 1 })
831 );
832
833 let ops = vec![vec![8i64, 16, 32, 64], vec![1i64, 1, 1, 128]];
835 assert_eq!(
836 eval_shape(
837 &ShapeExpr::Dims(vec![
838 Dim::Extent {
839 operand: 0,
840 axis: 0
841 },
842 Dim::Extent {
843 operand: 0,
844 axis: 2
845 },
846 Dim::Extent {
847 operand: 0,
848 axis: 3
849 },
850 Dim::Extent {
851 operand: 1,
852 axis: 3
853 },
854 ]),
855 &ops,
856 &[]
857 )
858 .unwrap(),
859 ShapeValue::Concrete(vec![8, 32, 64, 128])
860 );
861 assert_eq!(
863 eval_shape(&ShapeExpr::Dims(vec![]), &ops, &[]).unwrap(),
864 ShapeValue::Concrete(vec![])
865 );
866 let sym = vec![vec![4i64, SYMBOLIC]];
869 assert_eq!(
870 eval_shape(
871 &ShapeExpr::Dims(vec![
872 Dim::Extent {
873 operand: 0,
874 axis: 0
875 },
876 Dim::Extent {
877 operand: 0,
878 axis: LAST
879 },
880 ]),
881 &sym,
882 &[]
883 )
884 .unwrap(),
885 ShapeValue::Gap
886 );
887 }
888
889 #[test]
894 fn decode_shape_core_and_grammar_level_declines() {
895 assert_eq!(
896 decode_shape(&[0x01, 0x00]).unwrap(),
897 ShapeExpr::SameAs { operand: 0 }
898 );
899 assert_eq!(
901 decode_shape(&[0x03, 0x02, 0, 0, 0, 0, 0, 0, 0]),
902 Err(ShapeExprError::ReservedTag { tag: 0x03 })
903 );
904 assert_eq!(
907 decode_dim(&[TAG_WITH_DIM, 0x00, 0x01, 0x02, 0x00, 0x04, 0x00]),
908 Err(ShapeExprError::ReservedTag { tag: TAG_WITH_DIM })
909 );
910 assert_eq!(
911 decode_dim(&[TAG_DIMS, 0x00]),
912 Err(ShapeExprError::ReservedTag { tag: TAG_DIMS })
913 );
914 assert_eq!(
916 decode_shape(&[0x09, 0x00]),
917 Err(ShapeExprError::ReservedTag { tag: 0x09 })
918 );
919 assert_eq!(
920 decode_dim(&[0x09, 0x00]),
921 Err(ShapeExprError::ReservedTag { tag: 0x09 })
922 );
923 }
924
925 #[test]
926 fn eval_vocabulary_axis_floordiv_gap() {
927 let ops = vec![vec![2i64, 3, 4]];
929 let params = vec![7i64];
930 assert_eq!(
931 eval_shape(&ShapeExpr::SameAs { operand: 0 }, &ops, ¶ms).unwrap(),
932 ShapeValue::Concrete(vec![2, 3, 4])
933 );
934 assert_eq!(
935 eval_dim(
936 &Dim::Extent {
937 operand: 0,
938 axis: 1
939 },
940 &ops,
941 ¶ms
942 )
943 .unwrap(),
944 DimValue::Concrete(3)
945 );
946 assert_eq!(
947 eval_dim(&Dim::Const(5), &ops, ¶ms).unwrap(),
948 DimValue::Concrete(5)
949 );
950 assert_eq!(
951 eval_dim(&Dim::Param(0), &ops, ¶ms).unwrap(),
952 DimValue::Concrete(7)
953 );
954 let e = Dim::Add(
956 Box::new(Dim::Mul(
957 Box::new(Dim::Extent {
958 operand: 0,
959 axis: 0,
960 }),
961 Box::new(Dim::Const(3)),
962 )),
963 Box::new(Dim::Param(0)),
964 );
965 assert_eq!(eval_dim(&e, &ops, ¶ms).unwrap(), DimValue::Concrete(13));
966
967 let r3 = vec![vec![2i64, 3, 5]];
969 assert_eq!(
970 eval_dim(
971 &Dim::Extent {
972 operand: 0,
973 axis: LAST
974 },
975 &r3,
976 &[]
977 )
978 .unwrap(),
979 DimValue::Concrete(5)
980 );
981 assert_eq!(
982 eval_dim(
983 &Dim::Extent {
984 operand: 0,
985 axis: 2
986 },
987 &r3,
988 &[]
989 )
990 .unwrap(),
991 DimValue::Concrete(5)
992 );
993 assert_eq!(
994 eval_dim(
995 &Dim::Extent {
996 operand: 0,
997 axis: 3
998 },
999 &r3,
1000 &[]
1001 ),
1002 Err(ShapeExprError::AxisOutOfRange { axis: 3, rank: 3 })
1003 );
1004 let fd = |a, b| {
1005 eval_dim(
1006 &Dim::Div(Box::new(Dim::Const(a)), Box::new(Dim::Const(b))),
1007 &r3,
1008 &[],
1009 )
1010 };
1011 assert_eq!(fd(7, 2).unwrap(), DimValue::Concrete(3));
1012 assert_eq!(fd(-7, 2).unwrap(), DimValue::Concrete(-4)); assert_eq!(fd(1, 0), Err(ShapeExprError::DivideByZero));
1014
1015 let sym = vec![vec![4i64, SYMBOLIC]];
1017 assert_eq!(
1018 eval_dim(
1019 &Dim::Extent {
1020 operand: 0,
1021 axis: LAST
1022 },
1023 &sym,
1024 &[]
1025 )
1026 .unwrap(),
1027 DimValue::Gap
1028 );
1029 let half = Dim::Div(
1030 Box::new(Dim::Extent {
1031 operand: 0,
1032 axis: LAST,
1033 }),
1034 Box::new(Dim::Const(2)),
1035 );
1036 assert_eq!(eval_dim(&half, &sym, &[]).unwrap(), DimValue::Gap);
1037 assert_eq!(
1038 eval_shape(&ShapeExpr::SameAs { operand: 0 }, &sym, &[]).unwrap(),
1039 ShapeValue::Gap
1040 );
1041 assert_eq!(
1042 eval_dim(
1043 &Dim::Extent {
1044 operand: 0,
1045 axis: 0
1046 },
1047 &sym,
1048 &[]
1049 )
1050 .unwrap(),
1051 DimValue::Concrete(4)
1052 );
1053 }
1054
1055 #[test]
1057 fn reduce_shape_rule() {
1058 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]); }
1063
1064 #[test]
1066 fn out_differs_from_operands() {
1067 assert_eq!(gather_shape(&[8, 4096], &[16], 0), vec![16, 4096]);
1069 assert_eq!(gather_shape(&[1000, 64], &[2, 5], 0), vec![2, 5, 64]); assert_eq!(matmul_shape(&[8, 4096], &[4096, 1024]), vec![8, 1024]);
1072 assert_eq!(matmul_shape(&[4, 8, 16], &[4, 16, 32]), vec![4, 8, 32]);
1073 let g = gather_shape(&[8, 4096], &[16], 0);
1075 assert!(!shape_consistent(&[8, 4096], &ShapeValue::Concrete(g)));
1076 let m = matmul_shape(&[8, 4096], &[4096, 1024]);
1077 assert!(!shape_consistent(
1078 &[8, 4096],
1079 &ShapeValue::Concrete(m.clone())
1080 ));
1081 assert!(!shape_consistent(&[4096, 1024], &ShapeValue::Concrete(m)));
1082 }
1083
1084 #[test]
1086 fn contract_output_shape_consistency() {
1087 let computed = ShapeValue::Concrete(reduce_shape(&[8, 4096], &[1], false));
1088 assert!(shape_consistent(&[8], &computed)); assert!(!shape_consistent(&[8, 4096], &computed)); assert!(shape_consistent(&[8], &ShapeValue::Gap)); }
1092}