1use alloc::format;
8use alloc::string::{String, ToString};
9use alloc::vec::Vec;
10
11use crate::humanize::humanize_diagnostic;
12use crate::typenum::matching_bracket;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct MatMulMismatch {
19 pub lhs: Vec<String>,
21 pub rhs: Vec<String>,
23 pub lhs_inner_index: usize,
26 pub rhs_inner_index: usize,
30}
31
32impl MatMulMismatch {
33 pub fn render(&self) -> String {
37 const INDENT: &str = " ";
38 let lhs_inner = &self.lhs[self.lhs_inner_index];
39 let rhs_inner = &self.rhs[self.rhs_inner_index];
40
41 let lhs_label = format!("{INDENT}lhs shape = (");
42 let rhs_label = format!("{INDENT}rhs shape = (");
43 let lhs_caret_width =
47 lhs_label.len() + joined_prefix_len(&self.lhs, self.lhs_inner_index) + 1;
48 let rhs_caret_width =
49 rhs_label.len() + joined_prefix_len(&self.rhs, self.rhs_inner_index) + 1;
50
51 format!(
52 "{lhs_label}{lhs_shape})\n\
53 {lhs_caret:>lhs_caret_width$} inner dim = {lhs_inner}\n\
54 {rhs_label}{rhs_shape})\n\
55 {rhs_caret:>rhs_caret_width$} inner dim = {rhs_inner}\n\
56 {INDENT}{lhs_inner} \u{2260} {rhs_inner} \u{2192} change the lhs inner dim from {lhs_inner} to {rhs_inner}, or the rhs inner dim from {rhs_inner} to {lhs_inner}.",
57 lhs_shape = self.lhs.join(", "),
58 rhs_shape = self.rhs.join(", "),
59 lhs_caret = "^",
60 rhs_caret = "^",
61 )
62 }
63}
64
65fn joined_prefix_len(elements: &[String], index: usize) -> usize {
69 elements[..index].iter().map(|e| e.len() + 2).sum()
70}
71
72pub fn parse_matmul_mismatch(text: &str) -> Option<MatMulMismatch> {
80 let start = text.find("Cannot matrix-multiply shape `")?;
85 let after_prefix = &text[start + "Cannot matrix-multiply shape `".len()..];
86 let (lhs_raw, after_lhs) = after_prefix.split_once('`')?;
87 let after_lhs = after_lhs.strip_prefix(" with `")?;
88 let (rhs_raw, _) = after_lhs.split_once('`')?;
89
90 let lhs_inner_text = lhs_raw.strip_prefix('(')?.strip_suffix(')')?;
91 let rhs_inner_text = rhs_raw.strip_prefix('(')?.strip_suffix(')')?;
92
93 let lhs_elems: Vec<&str> = split_top_level_commas(lhs_inner_text);
94 let rhs_elems: Vec<&str> = split_top_level_commas(rhs_inner_text);
95 if lhs_elems.is_empty() || rhs_elems.len() < 2 {
96 return None;
97 }
98
99 let lhs_inner_index = lhs_elems.len() - 1;
100 let rhs_inner_index = rhs_elems.len() - 2;
101
102 let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
103 let lhs: Vec<String> = lhs_elems.iter().map(|e| humanize(e)).collect();
104 let rhs: Vec<String> = rhs_elems.iter().map(|e| humanize(e)).collect();
105
106 if lhs[lhs_inner_index] == rhs[rhs_inner_index] {
107 return None; }
109
110 Some(MatMulMismatch {
111 lhs,
112 rhs,
113 lhs_inner_index,
114 rhs_inner_index,
115 })
116}
117
118fn split_top_level_commas(s: &str) -> Vec<&str> {
122 let mut parts = Vec::new();
123 let mut depth = 0i32;
124 let mut start = 0;
125 for (i, ch) in s.char_indices() {
126 match ch {
127 '<' => depth += 1,
128 '>' => depth -= 1,
129 ',' if depth == 0 => {
130 parts.push(s[start..i].trim());
131 start = i + 1;
132 }
133 _ => {}
134 }
135 }
136 let last = s[start..].trim();
137 if !last.is_empty() || !parts.is_empty() {
138 parts.push(last);
139 }
140 parts
141}
142
143#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct ConcatMismatch {
146 pub lhs: Vec<String>,
148 pub rhs: Vec<String>,
150 pub axis: usize,
152 pub mismatch_index: usize,
154}
155
156impl ConcatMismatch {
157 pub fn render(&self) -> String {
159 const INDENT: &str = " ";
160 let lhs_val = &self.lhs[self.mismatch_index];
161 let rhs_val = &self.rhs[self.mismatch_index];
162
163 let lhs_label = format!("{INDENT}lhs shape = (");
164 let rhs_label = format!("{INDENT}rhs shape = (");
165 let lhs_caret_width =
166 lhs_label.len() + joined_prefix_len(&self.lhs, self.mismatch_index) + 1;
167 let rhs_caret_width =
168 rhs_label.len() + joined_prefix_len(&self.rhs, self.mismatch_index) + 1;
169
170 format!(
171 "{lhs_label}{lhs_shape})\n\
172 {lhs_caret:>lhs_caret_width$} non-concat dim = {lhs_val}\n\
173 {rhs_label}{rhs_shape})\n\
174 {rhs_caret:>rhs_caret_width$} non-concat dim = {rhs_val}\n\
175 {INDENT}{lhs_val} \u{2260} {rhs_val} \u{2192} concatenating along axis {axis} requires all other dimensions to match exactly.",
176 lhs_shape = self.lhs.join(", "),
177 rhs_shape = self.rhs.join(", "),
178 lhs_caret = "^",
179 rhs_caret = "^",
180 axis = self.axis,
181 )
182 }
183}
184
185pub fn parse_concat_mismatch(text: &str) -> Option<ConcatMismatch> {
187 let start = text.find("Cannot concatenate shape `")?;
188 let after_prefix = &text[start + "Cannot concatenate shape `".len()..];
189 let (lhs_raw, after_lhs) = after_prefix.split_once('`')?;
190 let after_lhs = after_lhs.strip_prefix(" with `")?;
191 let (rhs_raw, after_rhs) = after_lhs.split_once('`')?;
192 let axis_str = after_rhs.strip_prefix(" along axis `")?.split_once('`')?.0;
193
194 let axis: usize = axis_str.trim().parse().ok()?;
195
196 let lhs_inner_text = lhs_raw.strip_prefix('(')?.strip_suffix(')')?;
197 let rhs_inner_text = rhs_raw.strip_prefix('(')?.strip_suffix(')')?;
198
199 let lhs_elems: Vec<&str> = split_top_level_commas(lhs_inner_text);
200 let rhs_elems: Vec<&str> = split_top_level_commas(rhs_inner_text);
201
202 if lhs_elems.len() != rhs_elems.len() {
203 return None;
204 }
205
206 let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
207 let lhs: Vec<String> = lhs_elems.iter().map(|e| humanize(e)).collect();
208 let rhs: Vec<String> = rhs_elems.iter().map(|e| humanize(e)).collect();
209
210 for i in 0..lhs.len() {
211 if i != axis && lhs[i] != rhs[i] {
212 return Some(ConcatMismatch {
213 lhs,
214 rhs,
215 axis,
216 mismatch_index: i,
217 });
218 }
219 }
220
221 None
222}
223
224#[derive(Debug, Clone, PartialEq, Eq)]
226pub struct BroadcastMismatch {
227 pub lhs: Vec<String>,
229 pub rhs: Vec<String>,
231 pub lhs_mismatch_index: usize,
233 pub rhs_mismatch_index: usize,
235}
236
237impl BroadcastMismatch {
238 pub fn render(&self) -> String {
240 const INDENT: &str = " ";
241 let lhs_val = &self.lhs[self.lhs_mismatch_index];
242 let rhs_val = &self.rhs[self.rhs_mismatch_index];
243
244 let lhs_label = format!("{INDENT}lhs shape = (");
245 let rhs_label = format!("{INDENT}rhs shape = (");
246 let lhs_caret_width =
247 lhs_label.len() + joined_prefix_len(&self.lhs, self.lhs_mismatch_index) + 1;
248 let rhs_caret_width =
249 rhs_label.len() + joined_prefix_len(&self.rhs, self.rhs_mismatch_index) + 1;
250
251 format!(
252 "{lhs_label}{lhs_shape})\n\
253 {lhs_caret:>lhs_caret_width$} dim = {lhs_val}\n\
254 {rhs_label}{rhs_shape})\n\
255 {rhs_caret:>rhs_caret_width$} dim = {rhs_val}\n\
256 {INDENT}{lhs_val} \u{2260} {rhs_val} \u{2192} broadcast requires corresponding dimensions to be equal, or one of them to be 1.",
257 lhs_shape = self.lhs.join(", "),
258 rhs_shape = self.rhs.join(", "),
259 lhs_caret = "^",
260 rhs_caret = "^",
261 )
262 }
263}
264
265pub fn parse_broadcast_mismatch(text: &str) -> Option<BroadcastMismatch> {
267 let start = text.find("Cannot broadcast shape `")?;
268 let after_prefix = &text[start + "Cannot broadcast shape `".len()..];
269 let (lhs_raw, after_lhs) = after_prefix.split_once('`')?;
270 let after_lhs = after_lhs.strip_prefix(" to `")?;
271 let (rhs_raw, _) = after_lhs.split_once('`')?;
272
273 let lhs_inner_text = lhs_raw.strip_prefix('(')?.strip_suffix(')')?;
274 let rhs_inner_text = rhs_raw.strip_prefix('(')?.strip_suffix(')')?;
275
276 let lhs_elems: Vec<&str> = split_top_level_commas(lhs_inner_text);
277 let rhs_elems: Vec<&str> = split_top_level_commas(rhs_inner_text);
278
279 let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
280 let lhs: Vec<String> = lhs_elems.iter().map(|e| humanize(e)).collect();
281 let rhs: Vec<String> = rhs_elems.iter().map(|e| humanize(e)).collect();
282
283 let min_rank = lhs.len().min(rhs.len());
284 for i in 1..=min_rank {
285 let l_idx = lhs.len() - i;
286 let r_idx = rhs.len() - i;
287 let l_val = &lhs[l_idx];
288 let r_val = &rhs[r_idx];
289 if l_val != r_val && l_val != "1" && r_val != "1" {
290 return Some(BroadcastMismatch {
291 lhs,
292 rhs,
293 lhs_mismatch_index: l_idx,
294 rhs_mismatch_index: r_idx,
295 });
296 }
297 }
298
299 None
300}
301
302#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct ReshapeMismatch {
305 pub src: Vec<String>,
307 pub target: Vec<String>,
309 pub src_count: usize,
311 pub target_count: usize,
313}
314
315impl ReshapeMismatch {
316 pub fn render(&self) -> String {
318 const INDENT: &str = " ";
319 format!(
320 "{INDENT}src shape = ({src_shape}) [total elements = {src_count}]\n\
321 {INDENT}target shape = ({target_shape}) [total elements = {target_count}]\n\
322 {INDENT}{src_count} \u{2260} {target_count} \u{2192} reshape requires the product of dimensions (total element count) to remain identical.",
323 src_shape = self.src.join(", "),
324 target_shape = self.target.join(", "),
325 src_count = self.src_count,
326 target_count = self.target_count,
327 )
328 }
329}
330
331pub fn parse_reshape_mismatch(text: &str) -> Option<ReshapeMismatch> {
333 let start = text.find("Cannot reshape from `")?;
334 let after_prefix = &text[start + "Cannot reshape from `".len()..];
335 let (src_raw, after_src) = after_prefix.split_once('`')?;
336 let after_src = after_src.strip_prefix(" to `")?;
337 let (target_raw, _) = after_src.split_once('`')?;
338
339 let src_inner_text = src_raw.strip_prefix('(')?.strip_suffix(')')?;
340 let target_inner_text = target_raw.strip_prefix('(')?.strip_suffix(')')?;
341
342 let src_elems: Vec<&str> = split_top_level_commas(src_inner_text);
343 let target_elems: Vec<&str> = split_top_level_commas(target_inner_text);
344
345 let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
346 let src: Vec<String> = src_elems.iter().map(|e| humanize(e)).collect();
347 let target: Vec<String> = target_elems.iter().map(|e| humanize(e)).collect();
348
349 let mut src_count = 1;
350 for s in &src {
351 src_count *= s.parse::<usize>().ok()?;
352 }
353 let mut target_count = 1;
354 for t in &target {
355 target_count *= t.parse::<usize>().ok()?;
356 }
357
358 if src_count != target_count {
359 Some(ReshapeMismatch {
360 src,
361 target,
362 src_count,
363 target_count,
364 })
365 } else {
366 None
367 }
368}
369
370#[derive(Debug, Clone, PartialEq, Eq)]
372pub struct Conv2dMismatch {
373 pub input: Vec<String>,
375 pub kernel: Vec<String>,
377 pub input_channel_idx: usize,
379 pub kernel_channel_idx: usize,
381}
382
383impl Conv2dMismatch {
384 pub fn render(&self) -> String {
386 const INDENT: &str = " ";
387 let in_c = &self.input[self.input_channel_idx];
388 let k_c = &self.kernel[self.kernel_channel_idx];
389
390 let in_label = format!("{INDENT}input shape = (");
391 let k_label = format!("{INDENT}kernel shape = (");
392 let in_caret_width =
393 in_label.len() + joined_prefix_len(&self.input, self.input_channel_idx) + 1;
394 let k_caret_width =
395 k_label.len() + joined_prefix_len(&self.kernel, self.kernel_channel_idx) + 1;
396
397 format!(
398 "{in_label}{in_shape})\n\
399 {in_caret:>in_caret_width$} input channels = {in_c}\n\
400 {k_label}{k_shape})\n\
401 {k_caret:>k_caret_width$} kernel in_channels = {k_c}\n\
402 {INDENT}{in_c} \u{2260} {k_c} \u{2192} Conv2D input channels must match kernel input channels.",
403 in_shape = self.input.join(", "),
404 k_shape = self.kernel.join(", "),
405 in_caret = "^",
406 k_caret = "^",
407 )
408 }
409}
410
411pub fn parse_conv2d_mismatch(text: &str) -> Option<Conv2dMismatch> {
413 let start = text.find("Cannot apply Conv2D: input shape `")?;
414 let after_prefix = &text[start + "Cannot apply Conv2D: input shape `".len()..];
415 let (in_raw, after_in) = after_prefix.split_once('`')?;
416 let after_in = after_in.strip_prefix(" is incompatible with kernel shape `")?;
417 let (k_raw, _) = after_in.split_once('`')?;
418
419 let in_inner_text = in_raw.strip_prefix('(')?.strip_suffix(')')?;
420 let k_inner_text = k_raw.strip_prefix('(')?.strip_suffix(')')?;
421
422 let in_elems: Vec<&str> = split_top_level_commas(in_inner_text);
423 let k_elems: Vec<&str> = split_top_level_commas(k_inner_text);
424
425 if in_elems.len() < 2 || k_elems.len() < 2 {
426 return None;
427 }
428
429 let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
430 let input: Vec<String> = in_elems.iter().map(|e| humanize(e)).collect();
431 let kernel: Vec<String> = k_elems.iter().map(|e| humanize(e)).collect();
432
433 if input[1] != kernel[1] {
434 Some(Conv2dMismatch {
435 input,
436 kernel,
437 input_channel_idx: 1,
438 kernel_channel_idx: 1,
439 })
440 } else {
441 None
442 }
443}
444
445#[derive(Debug, Clone, PartialEq, Eq)]
447pub struct TransposeMismatch {
448 pub shape: Vec<String>,
450 pub d1: usize,
452 pub d2: usize,
454 pub rank: usize,
456}
457
458impl TransposeMismatch {
459 pub fn render(&self) -> String {
461 const INDENT: &str = " ";
462 format!(
463 "{INDENT}shape = ({shape}) [rank = {rank}]\n\
464 {INDENT}transpose indices = ({d1}, {d2})\n\
465 {INDENT}invalid dimension index \u{2192} both transpose indices must be < rank ({rank}).",
466 shape = self.shape.join(", "),
467 rank = self.rank,
468 d1 = self.d1,
469 d2 = self.d2,
470 )
471 }
472}
473
474pub fn parse_transpose_mismatch(text: &str) -> Option<TransposeMismatch> {
476 let start = text.find("Cannot transpose dimensions `")?;
477 let after_prefix = &text[start + "Cannot transpose dimensions `".len()..];
478 let (d1_str, after_d1) = after_prefix.split_once('`')?;
479 let after_d1 = after_d1.strip_prefix(" and `")?;
480 let (d2_str, after_d2) = after_d1.split_once('`')?;
481 let after_d2 = after_d2.strip_prefix(" on shape `")?;
482 let (shape_raw, _) = after_d2.split_once('`')?;
483
484 let d1: usize = d1_str.trim().parse().ok()?;
485 let d2: usize = d2_str.trim().parse().ok()?;
486
487 let shape_inner = shape_raw.strip_prefix('(')?.strip_suffix(')')?;
488 let elems: Vec<&str> = split_top_level_commas(shape_inner);
489
490 let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
491 let shape: Vec<String> = elems.iter().map(|e| humanize(e)).collect();
492 let rank = shape.len();
493
494 if d1 >= rank || d2 >= rank {
495 Some(TransposeMismatch {
496 shape,
497 d1,
498 d2,
499 rank,
500 })
501 } else {
502 None
503 }
504}
505
506#[derive(Debug, Clone, PartialEq, Eq)]
508pub struct ReduceDimMismatch {
509 pub shape: Vec<String>,
511 pub dim: usize,
513 pub rank: usize,
515}
516
517impl ReduceDimMismatch {
518 pub fn render(&self) -> String {
520 const INDENT: &str = " ";
521 format!(
522 "{INDENT}shape = ({shape}) [rank = {rank}]\n\
523 {INDENT}reduce dim = {dim}\n\
524 {INDENT}{dim} \u{2265} {rank} \u{2192} reduction dimension must be < rank ({rank}).",
525 shape = self.shape.join(", "),
526 rank = self.rank,
527 dim = self.dim,
528 )
529 }
530}
531
532pub fn parse_reduce_dim_mismatch(text: &str) -> Option<ReduceDimMismatch> {
534 let start = text.find("Cannot reduce dimension `")?;
535 let after_prefix = &text[start + "Cannot reduce dimension `".len()..];
536 let (dim_str, after_dim) = after_prefix.split_once('`')?;
537 let after_dim = after_dim
538 .find("on shape `")
539 .map(|p| &after_dim[p + "on shape `".len()..])?;
540 let (shape_raw, _) = after_dim.split_once('`')?;
541
542 let dim: usize = dim_str.trim().parse().ok()?;
543
544 let shape_inner = shape_raw.strip_prefix('(')?.strip_suffix(')')?;
545 let elems: Vec<&str> = split_top_level_commas(shape_inner);
546
547 let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
548 let shape: Vec<String> = elems.iter().map(|e| humanize(e)).collect();
549 let rank = shape.len();
550
551 if dim >= rank {
552 Some(ReduceDimMismatch { shape, dim, rank })
553 } else {
554 None
555 }
556}
557
558#[derive(Debug, Clone, PartialEq, Eq)]
560pub struct FlattenMismatch {
561 pub shape: Vec<String>,
563 pub start_dim: usize,
565 pub end_dim: usize,
567 pub rank: usize,
569}
570
571impl FlattenMismatch {
572 pub fn render(&self) -> String {
574 const INDENT: &str = " ";
575 format!(
576 "{INDENT}shape = ({shape}) [rank = {rank}]\n\
577 {INDENT}flatten range = [{start_dim}, {end_dim}]\n\
578 {INDENT}invalid range \u{2192} flatten requires start <= end and end < rank ({rank}).",
579 shape = self.shape.join(", "),
580 rank = self.rank,
581 start_dim = self.start_dim,
582 end_dim = self.end_dim,
583 )
584 }
585}
586
587pub fn parse_flatten_mismatch(text: &str) -> Option<FlattenMismatch> {
589 let start = text.find("Cannot flatten shape `")?;
590 let after_prefix = &text[start + "Cannot flatten shape `".len()..];
591 let (shape_raw, after_shape) = after_prefix.split_once('`')?;
592 let after_shape = after_shape.strip_prefix(" from dimension `")?;
593 let (start_str, after_start) = after_shape.split_once('`')?;
594 let after_start = after_start.strip_prefix(" to `")?;
595 let (end_str, _) = after_start.split_once('`')?;
596
597 let start_dim: usize = start_str.trim().parse().ok()?;
598 let end_dim: usize = end_str.trim().parse().ok()?;
599
600 let shape_inner = shape_raw.strip_prefix('(')?.strip_suffix(')')?;
601 let elems: Vec<&str> = split_top_level_commas(shape_inner);
602
603 let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
604 let shape: Vec<String> = elems.iter().map(|e| humanize(e)).collect();
605 let rank = shape.len();
606
607 if start_dim > end_dim || end_dim >= rank {
608 Some(FlattenMismatch {
609 shape,
610 start_dim,
611 end_dim,
612 rank,
613 })
614 } else {
615 None
616 }
617}
618
619#[derive(Debug, Clone, PartialEq, Eq)]
621pub struct ModuleForwardMismatch {
622 pub actual_input: String,
624 pub expected_input: String,
626}
627
628impl ModuleForwardMismatch {
629 pub fn render(&self) -> String {
631 const INDENT: &str = " ";
632 format!(
633 "{INDENT}provided input shape = {actual}\n\
634 {INDENT}expected input shape = {expected}\n\
635 {INDENT}shape mismatch \u{2192} layer forward pass expects {expected}, but received {actual}.",
636 actual = self.actual_input,
637 expected = self.expected_input,
638 )
639 }
640}
641
642pub fn parse_module_forward_mismatch(text: &str) -> Option<ModuleForwardMismatch> {
644 let mut search = text;
645 let mut actual_raw = None;
646 while let Some(start) = search.find("Module<") {
647 let after = &search[start + "Module<".len()..];
648 if let Some(close) = matching_bracket(after, '<', '>') {
649 let inner = &after[..close];
650 if inner.contains("Tensor") {
651 actual_raw = Some(inner);
652 break;
653 }
654 }
655 if after.is_empty() {
656 break;
657 }
658 search = &after[1..];
659 }
660 let actual_raw = actual_raw?;
661
662 let impl_start = text.find("implements `Module<")?;
663 let after_impl = &text[impl_start + "implements `Module<".len()..];
664 let close_impl = matching_bracket(after_impl, '<', '>')?;
665 let expected_raw = &after_impl[..close_impl];
666
667 let clean = |s: &str| {
668 let mut res = humanize_diagnostic(s.trim()).text.trim().to_string();
669 let open_count = res.chars().filter(|&c| c == '<').count();
670 let close_count = res.chars().filter(|&c| c == '>').count();
671 if open_count > close_count {
672 res.push('>');
673 }
674 res
675 };
676
677 let actual = clean(actual_raw);
678 let expected = clean(expected_raw);
679
680 if actual != expected {
681 Some(ModuleForwardMismatch {
682 actual_input: actual,
683 expected_input: expected,
684 })
685 } else {
686 None
687 }
688}
689
690#[derive(Debug, Clone, PartialEq, Eq)]
692pub struct SliceMismatch {
693 pub slice_spec: String,
695 pub in_shape: String,
697}
698
699impl SliceMismatch {
700 pub fn render(&self) -> String {
702 const INDENT: &str = " ";
703 format!(
704 "{INDENT}input shape = {in_shape}\n\
705 {INDENT}slice spec = {slice_spec}\n\
706 {INDENT}invalid slice \u{2192} slice ranges must fall within input dimension bounds.",
707 in_shape = self.in_shape,
708 slice_spec = self.slice_spec,
709 )
710 }
711}
712
713pub fn parse_slice_mismatch(text: &str) -> Option<SliceMismatch> {
715 let start = text.find("Cannot slice dimension with `")?;
716 let after = &text[start + "Cannot slice dimension with `".len()..];
717 let (spec_raw, after_spec) = after.split_once('`')?;
718
719 let in_shape_raw = if let Some(pos) = after_spec.find("for shape `") {
720 let after_for = &after_spec[pos + "for shape `".len()..];
721 after_for.split_once('`').map(|(s, _)| s)
722 } else {
723 None
724 };
725
726 let slice_spec = humanize_diagnostic(spec_raw.trim()).text;
727 let in_shape = in_shape_raw
728 .map(|s| humanize_diagnostic(s.trim()).text)
729 .unwrap_or_else(|| "unknown".to_string());
730
731 Some(SliceMismatch {
732 slice_spec,
733 in_shape,
734 })
735}
736
737#[derive(Debug, Clone, PartialEq, Eq)]
739pub struct Conv1dMismatch {
740 pub input_shape: String,
742}
743
744impl Conv1dMismatch {
745 pub fn render(&self) -> String {
747 const INDENT: &str = " ";
748 format!(
749 "{INDENT}input shape = {shape}\n\
750 {INDENT}invalid shape \u{2192} Conv1D requires a 2D or 3D tensor (C, L) or (B, C, L).",
751 shape = self.input_shape,
752 )
753 }
754}
755
756pub fn parse_conv1d_mismatch(text: &str) -> Option<Conv1dMismatch> {
758 let start = text.find("Cannot apply 1D convolution to shape `")?;
759 let after = &text[start + "Cannot apply 1D convolution to shape `".len()..];
760 let (raw_shape, _) = after.split_once('`')?;
761
762 let input_shape = humanize_diagnostic(raw_shape.trim()).text;
763 Some(Conv1dMismatch { input_shape })
764}
765
766#[derive(Debug, Clone, PartialEq, Eq)]
768pub struct Pool2dMismatch {
769 pub input_shape: String,
771}
772
773impl Pool2dMismatch {
774 pub fn render(&self) -> String {
776 const INDENT: &str = " ";
777 format!(
778 "{INDENT}input shape = {shape}\n\
779 {INDENT}invalid shape \u{2192} Pool2D requires a 3D or 4D tensor (C, H, W) or (B, C, H, W).",
780 shape = self.input_shape,
781 )
782 }
783}
784
785pub fn parse_pool2d_mismatch(text: &str) -> Option<Pool2dMismatch> {
787 let start = text.find("Cannot apply 2D pooling to shape `")?;
788 let after = &text[start + "Cannot apply 2D pooling to shape `".len()..];
789 let (raw_shape, _) = after.split_once('`')?;
790
791 let input_shape = humanize_diagnostic(raw_shape.trim()).text;
792 Some(Pool2dMismatch { input_shape })
793}
794
795#[derive(Debug, Clone, PartialEq, Eq)]
797pub struct ShapeEqMismatch {
798 pub message: String,
800}
801
802impl ShapeEqMismatch {
803 pub fn render(&self) -> String {
805 const INDENT: &str = " ";
806 format!("{INDENT}shape mismatch \u{2192} {msg}", msg = self.message,)
807 }
808}
809
810pub fn parse_shape_eq_mismatch(text: &str) -> Option<ShapeEqMismatch> {
812 if let Some(start) = text.find("Shape Mismatch:") {
813 let after = &text[start + "Shape Mismatch:".len()..];
814 let end = after.find('\n').unwrap_or(after.len());
815 let message = after[..end].trim().to_string();
816 Some(ShapeEqMismatch { message })
817 } else {
818 None
819 }
820}
821
822#[derive(Debug, Clone, PartialEq, Eq)]
824pub struct BmmMismatch {
825 pub message: String,
827}
828
829impl BmmMismatch {
830 pub fn render(&self) -> String {
832 const INDENT: &str = " ";
833 format!("{INDENT}bmm mismatch \u{2192} {msg}", msg = self.message)
834 }
835}
836
837pub fn parse_bmm_mismatch(text: &str) -> Option<BmmMismatch> {
839 if text.contains("bmm") || text.contains("batched matrix multiplication") {
840 Some(BmmMismatch {
841 message: "BMM requires 3D tensors (B, M, K) x (B, K, N)".to_string(),
842 })
843 } else {
844 None
845 }
846}
847
848#[derive(Debug, Clone, PartialEq, Eq)]
850pub struct UnfoldMismatch {
851 pub message: String,
853}
854
855impl UnfoldMismatch {
856 pub fn render(&self) -> String {
858 const INDENT: &str = " ";
859 format!("{INDENT}unfold mismatch \u{2192} {msg}", msg = self.message)
860 }
861}
862
863pub fn parse_unfold_mismatch(text: &str) -> Option<UnfoldMismatch> {
865 if text.contains("unfold size cannot exceed dimension length") {
866 Some(UnfoldMismatch {
867 message: "unfold size exceeds target dimension length".to_string(),
868 })
869 } else {
870 None
871 }
872}
873
874#[derive(Debug, Clone, PartialEq, Eq)]
876pub struct PixelShuffleMismatch {
877 pub message: String,
879}
880
881impl PixelShuffleMismatch {
882 pub fn render(&self) -> String {
884 const INDENT: &str = " ";
885 format!(
886 "{INDENT}pixel_shuffle mismatch \u{2192} {msg}",
887 msg = self.message
888 )
889 }
890}
891
892pub fn parse_pixel_shuffle_mismatch(text: &str) -> Option<PixelShuffleMismatch> {
894 if text.contains("pixel_shuffle channels must be divisible") {
895 Some(PixelShuffleMismatch {
896 message: "channel count must be divisible by upscale_factor^2".to_string(),
897 })
898 } else {
899 None
900 }
901}
902
903#[derive(Debug, Clone, PartialEq, Eq)]
905pub struct GroupNormMismatch {
906 pub message: String,
908}
909
910impl GroupNormMismatch {
911 pub fn render(&self) -> String {
913 const INDENT: &str = " ";
914 format!(
915 "{INDENT}group_norm mismatch \u{2192} {msg}",
916 msg = self.message
917 )
918 }
919}
920
921pub fn parse_group_norm_mismatch(text: &str) -> Option<GroupNormMismatch> {
923 if text.contains("group_norm: channels must be divisible by groups") {
924 Some(GroupNormMismatch {
925 message: "channels count must be divisible by groups".to_string(),
926 })
927 } else {
928 None
929 }
930}
931
932#[derive(Debug, Clone, PartialEq, Eq)]
934pub struct MathDomainError {
935 pub message: String,
937}
938
939impl MathDomainError {
940 pub fn render(&self) -> String {
942 const INDENT: &str = " ";
943 format!(
944 "{INDENT}math domain error \u{2192} {msg}",
945 msg = self.message
946 )
947 }
948}
949
950pub fn parse_math_domain_error(text: &str) -> Option<MathDomainError> {
952 if text.contains("out of domain")
953 || text.contains("NaN domain")
954 || text.contains("domain error")
955 {
956 Some(MathDomainError {
957 message: "argument value is outside the real domain of the function".to_string(),
958 })
959 } else {
960 None
961 }
962}
963
964#[derive(Debug, Clone, PartialEq, Eq)]
966pub struct InPlaceShapeMismatch {
967 pub message: String,
969}
970
971impl InPlaceShapeMismatch {
972 pub fn render(&self) -> String {
974 const INDENT: &str = " ";
975 format!(
976 "{INDENT}in-place shape mismatch \u{2192} {msg}",
977 msg = self.message
978 )
979 }
980}
981
982pub fn parse_inplace_shape_mismatch(text: &str) -> Option<InPlaceShapeMismatch> {
984 if text.contains("in-place operand shape mismatch") || text.contains("cannot mutate in-place") {
985 Some(InPlaceShapeMismatch {
986 message:
987 "target tensor and operand tensor must have identical shapes for in-place mutation"
988 .to_string(),
989 })
990 } else {
991 None
992 }
993}