cortex-hybrid 0.2.0

Backend-neutral ANN stage layer and deterministic Vec reference backend for hybrid ANN/SNN systems.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
// SPDX-License-Identifier: MIT OR Apache-2.0

use super::finite::{layer_norm_row, rms_norm_row, validate_norm_eps};
use super::{Tensor, try_alloc_filled};
use crate::error::{CortexError, Result, unwrap_compat};

/// Matrix multiply: [M×K] × [K×N] → [M×N]
///
/// Uses a cache-friendly tiled CPU loop. This crate has no GPU backend and
/// no `gpu` feature; consume the resulting [`Tensor`] into your own kernels if
/// you need device acceleration.
///
/// # Panics
///
/// Panics on rank or inner-dimension mismatch, or if the output size
/// overflows `usize`. Prefer [`try_matmul`] in new code. This wrapper is
/// retained for pre-1.0 source compatibility.
pub fn matmul(a: &Tensor, b: &Tensor) -> Tensor {
    unwrap_compat(try_matmul(a, b), "matmul")
}

/// Fallible matrix multiply: [M×K] × [K×N] → [M×N].
///
/// Validates ranks, inner dimensions, and output size before allocating.
pub fn try_matmul(a: &Tensor, b: &Tensor) -> Result<Tensor> {
    a.check_storage()?;
    b.check_storage()?;
    expect_rank(a, 2)?;
    expect_rank(b, 2)?;
    let (m, k1) = (a.shape()[0], a.shape()[1]);
    let (k2, n) = (b.shape()[0], b.shape()[1]);
    if k1 != k2 {
        return Err(CortexError::MatmulDim { m, k1, k2, n });
    }
    let out_shape = [m, n];
    let mut out = alloc_zeros(&out_shape)?;
    if out.is_empty() {
        return Tensor::try_from_vec(out, &out_shape);
    }

    let ad = a.data();
    let bd = b.data();

    // Tiled matmul for better cache behaviour
    const TILE: usize = 32;
    for i0 in (0..m).step_by(TILE) {
        for j0 in (0..n).step_by(TILE) {
            for p0 in (0..k1).step_by(TILE) {
                let i_end = (i0 + TILE).min(m);
                let j_end = (j0 + TILE).min(n);
                let p_end = (p0 + TILE).min(k1);
                for i in i0..i_end {
                    // Hoist the row slices out of the j-loop so the inner
                    // loop has no per-element bounds checks and can
                    // auto-vectorise. Summation order is unchanged, so the
                    // result is bit-identical to the indexed form.
                    let orow = &mut out[i * n + j0..i * n + j_end];
                    let arow = &ad[i * k1 + p0..i * k1 + p_end];
                    for (p, &a_ip) in (p0..p_end).zip(arow) {
                        let brow = &bd[p * n + j0..p * n + j_end];
                        for (o, &b_pj) in orow.iter_mut().zip(brow) {
                            *o += a_ip * b_pj;
                        }
                    }
                }
            }
        }
    }
    Tensor::try_from_vec(out, &out_shape)
}

/// Batched matmul: [B×M×K] × [B×K×N] → [B×M×N]
///
/// This is the crate's **only** broadcasting rule, and it is deliberately
/// narrow — there is no NumPy-style elementwise broadcasting anywhere else:
///
/// * `a` rank-3 `[B, M, K]`, `b` rank-3 `[B, K, N]`: per-batch matmul; the
///   batch extents must match exactly.
/// * `a` rank-3 `[B, M, K]`, `b` rank-2 `[K, N]`: `b` is reused for every
///   batch of `a` (broadcast across the batch axis).
/// * `a` rank-2 and `b` rank-2: delegates to [`try_matmul`].
///
/// Any other rank combination is a [`CortexError::RankMismatch`]. No axis of
/// size `1` is expanded, and `a` is never broadcast against a batched `b`.
///
/// # Panics
///
/// Panics on rank, batch, or inner-dimension mismatch, or if the output size
/// overflows `usize`. Prefer [`try_batched_matmul`] in new code.
pub fn batched_matmul(a: &Tensor, b: &Tensor) -> Tensor {
    unwrap_compat(try_batched_matmul(a, b), "batched_matmul")
}

/// Fallible batched matmul: [B×M×K] × [B×K×N] → [B×M×N].
///
/// If both operands are 2-D, this is equivalent to [`try_matmul`]. If `b` is
/// 2-D, it is broadcast across the batch of `a`. Validates every dimension
/// and the output size before allocating.
pub fn try_batched_matmul(a: &Tensor, b: &Tensor) -> Result<Tensor> {
    a.check_storage()?;
    b.check_storage()?;
    if a.ndim() == 2 && b.ndim() == 2 {
        return try_matmul(a, b);
    }
    if a.ndim() != 3 {
        return Err(CortexError::RankMismatch {
            expected: 3,
            got: a.ndim(),
        });
    }

    let batch = a.shape()[0];
    let m = a.shape()[1];
    let k = a.shape()[2];

    let (b_is_batched, n) = match b.ndim() {
        3 => {
            expect_dim("batched_matmul", 0, batch, b.shape()[0])?;
            expect_dim("batched_matmul", 1, k, b.shape()[1])?;
            (true, b.shape()[2])
        }
        2 => {
            expect_dim("batched_matmul", 0, k, b.shape()[0])?;
            (false, b.shape()[1])
        }
        got => {
            return Err(CortexError::RankMismatch { expected: 3, got });
        }
    };

    let out_shape = [batch, m, n];
    let mut out = alloc_zeros(&out_shape)?;
    if out.is_empty() {
        return Tensor::try_from_vec(out, &out_shape);
    }
    let ad = a.data();
    let bd = b.data();

    for bi in 0..batch {
        // Output numel being representable does not imply `bi * m * k` is:
        // a zero axis can make `batch * m * n` fit while a leading product
        // of the other extents overflows (debug panic / release wrap).
        let a_off = checked_mul3(bi, m, k, a.shape())?;
        let b_off = if b_is_batched {
            checked_mul3(bi, k, n, b.shape())?
        } else {
            0
        };
        let o_off = checked_mul3(bi, m, n, &out_shape)?;
        // Same slice-hoisting as `try_matmul`: bounds checks happen once per
        // row, not per element, and the summation order is unchanged.
        for i in 0..m {
            let orow = &mut out[o_off + i * n..o_off + (i + 1) * n];
            let arow = &ad[a_off + i * k..a_off + (i + 1) * k];
            for (p, &a_ip) in arow.iter().enumerate() {
                let brow = &bd[b_off + p * n..b_off + (p + 1) * n];
                for (o, &b_pj) in orow.iter_mut().zip(brow) {
                    *o += a_ip * b_pj;
                }
            }
        }
    }
    Tensor::try_from_vec(out, &out_shape)
}

/// Layer normalization over the last axis of a rank-2 `[batch, dim]` tensor.
///
/// # Panics
///
/// Panics if `x` is not rank-2, the last axis is zero-width, `eps` is not
/// positive and finite, or `weight`/`bias` lengths do not match the last
/// axis. Prefer [`try_layer_norm`] in new code.
///
/// See [`super::finite`] for the finite-value policy.
pub fn layer_norm(x: &Tensor, weight: &Tensor, bias: &Tensor, eps: f32) -> Tensor {
    unwrap_compat(try_layer_norm(x, weight, bias, eps), "layer_norm")
}

/// Fallible layer normalization over the last axis of a rank-2 tensor.
pub fn try_layer_norm(x: &Tensor, weight: &Tensor, bias: &Tensor, eps: f32) -> Result<Tensor> {
    x.check_storage()?;
    weight.check_storage()?;
    bias.check_storage()?;
    expect_rank(x, 2)?;
    let (rows, cols) = (x.shape()[0], x.shape()[1]);
    if cols == 0 {
        return Err(CortexError::ZeroWidth {
            op: "layer_norm",
            axis: 1,
        });
    }
    let eps64 = validate_norm_eps(eps)?;
    expect_dim("layer_norm", 0, cols, weight.numel())?;
    expect_dim("layer_norm", 0, cols, bias.numel())?;

    let out_shape = [rows, cols];
    let mut out = alloc_zeros(&out_shape)?;
    let xd = x.data();
    let wd = weight.data();
    let bd = bias.data();

    for r in 0..rows {
        let off = r * cols;
        layer_norm_row(
            &xd[off..off + cols],
            wd,
            bd,
            eps64,
            &mut out[off..off + cols],
        );
    }
    Tensor::try_from_vec(out, &out_shape)
}

/// RMS normalization (used by LLaMA-family models).
///
/// # Panics
///
/// Panics if `x` is not rank-2, the last axis is zero-width, `eps` is not
/// positive and finite, or `weight` length does not match the last axis.
/// Prefer [`try_rms_norm`] in new code.
///
/// See [`super::finite`] for the finite-value policy.
pub fn rms_norm(x: &Tensor, weight: &Tensor, eps: f32) -> Tensor {
    unwrap_compat(try_rms_norm(x, weight, eps), "rms_norm")
}

/// Fallible RMS normalization over the last axis of a rank-2 tensor.
pub fn try_rms_norm(x: &Tensor, weight: &Tensor, eps: f32) -> Result<Tensor> {
    x.check_storage()?;
    weight.check_storage()?;
    expect_rank(x, 2)?;
    let (rows, cols) = (x.shape()[0], x.shape()[1]);
    if cols == 0 {
        return Err(CortexError::ZeroWidth {
            op: "rms_norm",
            axis: 1,
        });
    }
    let eps64 = validate_norm_eps(eps)?;
    expect_dim("rms_norm", 0, cols, weight.numel())?;

    let out_shape = [rows, cols];
    let mut out = alloc_zeros(&out_shape)?;
    let xd = x.data();
    let wd = weight.data();

    for r in 0..rows {
        let off = r * cols;
        rms_norm_row(&xd[off..off + cols], wd, eps64, &mut out[off..off + cols]);
    }
    Tensor::try_from_vec(out, &out_shape)
}

/// Softmax along the last axis of a rank-0, rank-1, or rank-2 tensor (each
/// row independently for rank 2).
///
/// See [`super::finite`] for the NaN / `±Inf` / all-masked policy.
///
/// # Panics
///
/// Panics if the rank is greater than 2. Prefer [`try_softmax`] in new code.
pub fn softmax(x: &Tensor) -> Tensor {
    unwrap_compat(try_softmax(x), "softmax")
}

/// Fallible softmax along the last axis.
///
/// Returns [`CortexError::RankMismatch`] with `expected: 2` when the rank is
/// greater than 2, matching the other rank-checked ops.
pub fn try_softmax(x: &Tensor) -> Result<Tensor> {
    x.try_softmax_last()
}

/// Embedding lookup: [vocab_size, dim] indexed by token ids → [seq_len, dim]
///
/// # Panics
///
/// Panics if `table` is not rank-2, a token id is out of vocabulary, or the
/// output size overflows `usize`. Prefer [`try_embedding`] in new code.
pub fn embedding(table: &Tensor, ids: &[u32]) -> Tensor {
    unwrap_compat(try_embedding(table, ids), "embedding")
}

/// Fallible embedding lookup: [vocab_size, dim] indexed by token ids → [seq_len, dim].
///
/// Out-of-vocabulary ids return [`CortexError::TokenIndex`] without slicing.
pub fn try_embedding(table: &Tensor, ids: &[u32]) -> Result<Tensor> {
    table.check_storage()?;
    expect_rank(table, 2)?;
    let vocab = table.shape()[0];
    let dim = table.shape()[1];
    for &id in ids {
        let index = id as usize;
        if index >= vocab {
            return Err(CortexError::TokenIndex {
                index,
                vocab_size: vocab,
            });
        }
    }

    let seq_len = ids.len();
    let out_shape = [seq_len, dim];
    let mut out = alloc_zeros(&out_shape)?;
    let td = table.data();
    for (i, &id) in ids.iter().enumerate() {
        let src_off = id as usize * dim;
        out[i * dim..(i + 1) * dim].copy_from_slice(&td[src_off..src_off + dim]);
    }
    Tensor::try_from_vec(out, &out_shape)
}

/// Causal attention mask: upper triangle = -inf, lower triangle + diagonal = 0.
///
/// # Panics
///
/// Panics if `seq_len * seq_len` overflows `usize`. Prefer
/// [`try_causal_mask`] in new code.
pub fn causal_mask(seq_len: usize) -> Tensor {
    unwrap_compat(try_causal_mask(seq_len), "causal_mask")
}

/// Fallible causal mask: returns [`CortexError::SizeOverflow`] when
/// `seq_len * seq_len` is not representable and
/// [`CortexError::AllocationFailed`] when the allocator refuses the buffer.
pub fn try_causal_mask(seq_len: usize) -> Result<Tensor> {
    let mut data = alloc_zeros(&[seq_len, seq_len])?;
    for i in 0..seq_len {
        for j in (i + 1)..seq_len {
            data[i * seq_len + j] = f32::NEG_INFINITY;
        }
    }
    Tensor::try_from_vec(data, &[seq_len, seq_len])
}

fn expect_rank(t: &Tensor, expected: usize) -> Result<()> {
    if t.ndim() != expected {
        Err(CortexError::RankMismatch {
            expected,
            got: t.ndim(),
        })
    } else {
        Ok(())
    }
}

fn expect_dim(op: &'static str, axis: usize, expected: usize, got: usize) -> Result<()> {
    if expected != got {
        Err(CortexError::DimMismatch {
            op,
            axis,
            expected,
            got,
        })
    } else {
        Ok(())
    }
}

/// Allocate an output buffer only after numel and strides are representable.
fn alloc_zeros(shape: &[usize]) -> Result<Vec<f32>> {
    try_alloc_filled(shape, 0.0)
}

fn checked_mul3(a: usize, b: usize, c: usize, err_shape: &[usize]) -> Result<usize> {
    a.checked_mul(b)
        .and_then(|v| v.checked_mul(c))
        .ok_or_else(|| CortexError::SizeOverflow {
            shape: err_shape.to_vec(),
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Largest `f32` count that passes the layout check; see the matching
    /// test in `tensor/mod.rs`.
    const UNBACKABLE_NUMEL: usize = isize::MAX as usize / std::mem::size_of::<f32>();

    #[test]
    fn unbackable_output_shapes_are_errors_not_aborts() {
        // causal_mask(n) allocates n*n: pick n so n*n passes the layout check.
        let n = UNBACKABLE_NUMEL.isqrt();
        assert!(matches!(
            try_causal_mask(n),
            Err(CortexError::AllocationFailed { .. })
        ));
        // matmul [1, 0] x [0, N] needs an [1, N] output it cannot back.
        let a = Tensor::try_from_vec(vec![], &[1, 0]).unwrap();
        let b = Tensor::try_from_vec(vec![], &[0, UNBACKABLE_NUMEL]).unwrap();
        assert!(matches!(
            try_matmul(&a, &b),
            Err(CortexError::AllocationFailed { .. })
        ));
        // The zero-numel short-circuit must survive the change: an empty id
        // slice against a zero-row table with an unbackable width allocates
        // nothing and succeeds. (A genuinely unbackable embedding output
        // needs a table whose row is itself unbackable, so that branch is
        // covered through `alloc_zeros` by the matmul case above.)
        let table = Tensor::try_from_vec(vec![], &[0, UNBACKABLE_NUMEL]).unwrap();
        assert!(matches!(
            try_embedding(&table, &[]),
            Ok(ref t) if t.shape() == [0, UNBACKABLE_NUMEL]
        ));
    }

    #[test]
    fn test_matmul_2x2() {
        let a = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
        let b = Tensor::from_vec(vec![5.0, 6.0, 7.0, 8.0], &[2, 2]);
        let c = matmul(&a, &b);
        assert_eq!(c.shape(), &[2, 2]);
        // [1*5+2*7, 1*6+2*8, 3*5+4*7, 3*6+4*8] = [19, 22, 43, 50]
        assert_eq!(c.data(), &[19.0, 22.0, 43.0, 50.0]);
        let tried = try_matmul(&a, &b).unwrap();
        assert_eq!(tried.data(), c.data());
        assert_eq!(tried.shape(), c.shape());
    }

    #[test]
    fn test_layer_norm() {
        let x = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
        let w = Tensor::ones(&[3]);
        let b = Tensor::zeros(&[3]);
        let y = layer_norm(&x, &w, &b, 1e-5);
        // Each row should have mean ≈ 0
        let row0_mean: f32 = y.data()[0..3].iter().sum::<f32>() / 3.0;
        assert!(row0_mean.abs() < 1e-4);
        let tried = try_layer_norm(&x, &w, &b, 1e-5).unwrap();
        assert_eq!(tried.data(), y.data());
    }

    #[test]
    fn test_rms_norm_matches_wrapper() {
        let x = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
        let w = Tensor::ones(&[3]);
        let y = rms_norm(&x, &w, 1e-5);
        let tried = try_rms_norm(&x, &w, 1e-5).unwrap();
        assert_eq!(y.data(), tried.data());
        assert_eq!(y.shape(), &[2, 3]);
    }

    #[test]
    fn test_softmax_op_matches_tensor_softmax_last() {
        let t = Tensor::from_vec(vec![1.0, 2.0, 3.0, 0.0], &[2, 2]);
        let a = softmax(&t);
        let b = t.softmax_last();
        assert_eq!(a.data(), b.data());
    }

    #[test]
    fn test_rms_norm_unit_weight() {
        let x = Tensor::from_vec(vec![3.0, -4.0], &[1, 2]);
        let w = Tensor::ones(&[2]);
        let y = rms_norm(&x, &w, 1e-5);
        assert!(y.data().iter().all(|v| v.is_finite()));
        let ms = (9.0f64 + 16.0) / 2.0;
        let rstd = 1.0 / (ms + 1e-5).sqrt();
        assert!((f64::from(y.data()[0]) - 3.0 * rstd).abs() < 1e-5);
        assert!((f64::from(y.data()[1]) + 4.0 * rstd).abs() < 1e-5);
    }

    #[test]
    fn test_causal_mask() {
        let m = causal_mask(3);
        assert_eq!(m.data()[0], 0.0); // [0,0]
        assert!(m.data()[1].is_infinite()); // [0,1] = -inf
        assert_eq!(m.data()[4], 0.0); // [1,1]
    }

    #[test]
    fn test_embedding() {
        let table = Tensor::from_vec(vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6], &[3, 2]);
        let ids = vec![2u32, 0u32];
        let out = embedding(&table, &ids);
        assert_eq!(out.shape(), &[2, 2]);
        assert_eq!(out.data(), &[0.5, 0.6, 0.1, 0.2]);
        assert_eq!(try_embedding(&table, &ids).unwrap().data(), out.data());
    }

    #[test]
    fn try_embedding_accepts_empty_ids() {
        let table = Tensor::from_vec(vec![0.1, 0.2, 0.3, 0.4], &[2, 2]);
        let out = try_embedding(&table, &[]).unwrap();
        assert_eq!(out.shape(), &[0, 2]);
        assert_eq!(out.numel(), 0);
    }

    #[test]
    fn try_ops_error_table() {
        let rank1 = Tensor::from_vec(vec![1.0, 2.0], &[2]);
        let a2 = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
        let b_inner = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
        let batch_a = Tensor::from_vec(vec![0.0; 2 * 2 * 3], &[2, 2, 3]);
        let batch_b_mismatch = Tensor::from_vec(vec![0.0; 3 * 3 * 4], &[3, 3, 4]);
        let table = Tensor::from_vec(vec![0.1, 0.2, 0.3, 0.4], &[2, 2]);
        let x = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
        let w = Tensor::ones(&[3]);
        let b = Tensor::zeros(&[3]);
        let zero_width = Tensor::try_from_vec(vec![], &[2, 0]).unwrap();
        let w0 = Tensor::try_from_vec(vec![], &[0]).unwrap();

        struct Case {
            name: &'static str,
            err: CortexError,
            check: fn(&CortexError) -> bool,
        }
        let cases = [
            Case {
                name: "matmul rank",
                err: try_matmul(&rank1, &a2).unwrap_err(),
                check: |e| {
                    matches!(
                        e,
                        CortexError::RankMismatch {
                            expected: 2,
                            got: 1
                        }
                    )
                },
            },
            Case {
                name: "matmul inner dim",
                err: try_matmul(&a2, &b_inner).unwrap_err(),
                check: |e| {
                    matches!(
                        e,
                        CortexError::MatmulDim {
                            m: 2,
                            k1: 2,
                            k2: 3,
                            n: 2
                        }
                    )
                },
            },
            Case {
                name: "batched rank",
                err: try_batched_matmul(&rank1, &a2).unwrap_err(),
                check: |e| {
                    matches!(
                        e,
                        CortexError::RankMismatch {
                            expected: 3,
                            got: 1
                        }
                    )
                },
            },
            Case {
                name: "batched batch mismatch",
                err: try_batched_matmul(&batch_a, &batch_b_mismatch).unwrap_err(),
                check: |e| {
                    matches!(
                        e,
                        CortexError::DimMismatch {
                            op: "batched_matmul",
                            axis: 0,
                            expected: 2,
                            got: 3
                        }
                    )
                },
            },
            Case {
                name: "oov token",
                err: try_embedding(&table, &[2]).unwrap_err(),
                check: |e| {
                    matches!(
                        e,
                        CortexError::TokenIndex {
                            index: 2,
                            vocab_size: 2
                        }
                    )
                },
            },
            Case {
                name: "oov u32::MAX",
                err: try_embedding(&table, &[u32::MAX]).unwrap_err(),
                check: |e| {
                    matches!(
                        e,
                        CortexError::TokenIndex {
                            index,
                            vocab_size: 2
                        } if *index == u32::MAX as usize
                    )
                },
            },
            Case {
                name: "layer_norm rank",
                err: try_layer_norm(&rank1, &w, &b, 1e-5).unwrap_err(),
                check: |e| {
                    matches!(
                        e,
                        CortexError::RankMismatch {
                            expected: 2,
                            got: 1
                        }
                    )
                },
            },
            Case {
                name: "layer_norm weight dim",
                err: try_layer_norm(&x, &Tensor::ones(&[2]), &b, 1e-5).unwrap_err(),
                check: |e| {
                    matches!(
                        e,
                        CortexError::DimMismatch {
                            op: "layer_norm",
                            expected: 3,
                            got: 2,
                            ..
                        }
                    )
                },
            },
            Case {
                name: "layer_norm zero width",
                err: try_layer_norm(&zero_width, &w0, &w0, 1e-5).unwrap_err(),
                check: |e| {
                    matches!(
                        e,
                        CortexError::ZeroWidth {
                            op: "layer_norm",
                            axis: 1
                        }
                    )
                },
            },
            Case {
                name: "rms_norm zero width",
                err: try_rms_norm(&zero_width, &w0, 1e-5).unwrap_err(),
                check: |e| {
                    matches!(
                        e,
                        CortexError::ZeroWidth {
                            op: "rms_norm",
                            axis: 1
                        }
                    )
                },
            },
            Case {
                name: "non-positive eps",
                err: try_layer_norm(&x, &w, &b, 0.0).unwrap_err(),
                check: |e| matches!(e, CortexError::InvalidEpsilon { eps } if *eps == 0.0),
            },
            Case {
                name: "negative eps",
                err: try_rms_norm(&x, &w, -1e-5).unwrap_err(),
                check: |e| matches!(e, CortexError::InvalidEpsilon { eps } if *eps < 0.0),
            },
            Case {
                name: "nan eps",
                err: try_layer_norm(&x, &w, &b, f32::NAN).unwrap_err(),
                check: |e| matches!(e, CortexError::InvalidEpsilon { eps } if eps.is_nan()),
            },
            Case {
                name: "inf eps",
                err: try_rms_norm(&x, &w, f32::INFINITY).unwrap_err(),
                check: |e| matches!(e, CortexError::InvalidEpsilon { eps } if eps.is_infinite()),
            },
        ];
        for case in cases {
            assert!((case.check)(&case.err), "{}: {}", case.name, case.err);
        }
    }

    #[test]
    fn try_matmul_empty_output_skips_huge_extent_loop() {
        let a = Tensor::try_from_vec(vec![], &[usize::MAX, 0]).unwrap();
        let b = Tensor::try_from_vec(vec![], &[0, 0]).unwrap();
        let out = try_matmul(&a, &b).unwrap();
        assert_eq!(out.shape(), &[usize::MAX, 0]);
        assert_eq!(out.numel(), 0);
    }

    #[test]
    fn try_batched_matmul_empty_output_uses_checked_offsets() {
        let a = Tensor::try_from_vec(vec![], &[3, usize::MAX, 0]).unwrap();
        let b = Tensor::try_from_vec(vec![], &[3, 0, 0]).unwrap();
        let out = try_batched_matmul(&a, &b).unwrap();
        assert_eq!(out.shape(), &[3, usize::MAX, 0]);
        assert_eq!(out.numel(), 0);
    }

    #[test]
    fn try_batched_matmul_zero_inner_dim_is_all_zeros() {
        let a = Tensor::try_from_vec(vec![], &[2, 2, 0]).unwrap();
        let b = Tensor::try_from_vec(vec![], &[2, 0, 3]).unwrap();
        let out = try_batched_matmul(&a, &b).unwrap();
        assert_eq!(out.shape(), &[2, 2, 3]);
        assert_eq!(out.data(), &[0.0; 12]);
    }

    #[test]
    fn try_matmul_rejects_byte_capacity_overflow() {
        // usize product fits, but `Vec<f32>` cannot hold more than
        // `isize::MAX` bytes.
        let rows = (isize::MAX as usize) / std::mem::size_of::<f32>() + 1;
        let a = Tensor::try_from_vec(vec![], &[rows, 0]).unwrap();
        let b = Tensor::try_from_vec(vec![], &[0, 1]).unwrap();
        let err = try_matmul(&a, &b).unwrap_err();
        assert!(matches!(
            err,
            CortexError::SizeOverflow { shape } if shape == [rows, 1]
        ));
    }

    #[test]
    fn try_matmul_output_overflow_without_allocation() {
        // A well-formed tensor can still request an unrepresentable product
        // when paired with another huge extent. Synthetic shapes use a zero
        // axis so the operands themselves are cheap to construct.
        let a = Tensor::try_from_vec(vec![], &[usize::MAX, 0]).unwrap();
        let b = Tensor::try_from_vec(vec![], &[0, 2]).unwrap();
        let err = try_matmul(&a, &b).unwrap_err();
        assert!(matches!(
            err,
            CortexError::SizeOverflow { shape } if shape == [usize::MAX, 2]
        ));
    }

    #[test]
    fn try_batched_matmul_broadcast_and_empty_batch() {
        let a = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], &[2, 2, 2]);
        let b = Tensor::from_vec(vec![1.0, 0.0, 0.0, 1.0], &[2, 2]);
        let out = try_batched_matmul(&a, &b).unwrap();
        assert_eq!(out.shape(), &[2, 2, 2]);
        // Identity broadcast: each batch slice is unchanged.
        assert_eq!(out.data(), a.data());

        let empty_a = Tensor::try_from_vec(vec![], &[0, 2, 3]).unwrap();
        let empty_b = Tensor::try_from_vec(vec![], &[0, 3, 4]).unwrap();
        let empty_out = try_batched_matmul(&empty_a, &empty_b).unwrap();
        assert_eq!(empty_out.shape(), &[0, 2, 4]);
        assert_eq!(empty_out.numel(), 0);
    }
}