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
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Routing math and embedding resampling for checkpoint-backed gates.
//!
//! Top-k expert selection is a pure helper with a documented total order:
//! finite scores descending, ascending expert ID on ties, typed NaN
//! rejection, and explicit ±Inf ranking. See [`top_k_indices`].

use crate::error::{HybridError, Result};
use crate::tensor::finite::{l2_normalize, softmax_vec};
use crate::types::ExtractTokenOptions;
use std::cmp::Ordering;

pub(super) fn checkpoint_gate_scores(
    dims: &[usize],
    weights: &[f32],
    model_path: &str,
    routing_tensor_name: &str,
    num_experts: usize,
    embedding: &[f32],
) -> Result<Vec<f32>> {
    if dims.len() != 2 {
        return Err(HybridError::UnsupportedFormat(format!(
            "routing tensor '{routing_tensor_name}' must be rank-2 F32 in '{model_path}', got dims={dims:?}"
        )));
    }
    let hidden_size = embedding.len();
    // Orientation is a property of the tensor, not of one element: resolve it
    // once instead of O(E·H) times inside the dot-product loop.
    let layout = resolve_gate_layout(dims, num_experts, hidden_size)?;
    // `element_count` already rejected an overflowing shape at bind time; this
    // is the local guard that lets the loop index without per-element checks.
    let required = dims[0]
        .checked_mul(dims[1])
        .ok_or_else(|| HybridError::ModelLoad {
            path: model_path.to_owned(),
            reason: format!("routing tensor '{routing_tensor_name}' dims {dims:?} overflow usize"),
        })?;
    if required > weights.len() {
        return Err(HybridError::ModelLoad {
            path: model_path.to_owned(),
            reason: format!(
                "routing tensor '{routing_tensor_name}' with dims {dims:?} needs {required} weights, payload holds {}",
                weights.len()
            ),
        });
    }
    let weights = &weights[..required];

    let mut gate_scores = Vec::with_capacity(num_experts);
    for expert_id in 0..num_experts {
        let mut score = 0.0f32;
        for (dim, &value) in embedding.iter().enumerate() {
            // Every index is in range: `expert_id < num_experts <= expert axis`
            // and `dim < hidden_size == hidden axis` were checked by `layout`.
            score += weights[layout.index(expert_id, dim)] * value;
        }
        gate_scores.push(score);
    }
    Ok(gate_scores)
}

pub(super) fn synthetic_gate_scores(num_experts: usize, embedding: &[f32]) -> Vec<f32> {
    if embedding.is_empty() {
        return vec![0.0; num_experts];
    }
    let width = embedding.len();
    let chunk = (width / num_experts.max(1)).max(1);
    let mut gate_scores = Vec::with_capacity(num_experts);
    for expert_id in 0..num_experts {
        let start = (expert_id * chunk) % width;
        let end = (start + chunk).min(width);
        gate_scores.push(embedding[start..end].iter().sum());
    }
    gate_scores
}

pub(super) fn softmax(scores: &[f32]) -> Vec<f32> {
    softmax_vec(scores)
}

/// Deterministic top-k expert selection.
///
/// # Routing policy
///
/// * **NaN:** typed rejection ([`HybridError::NanRoutingScore`]) for the lowest
///   expert ID that is NaN. NaN is never ordered through `partial_cmp`.
/// * **±Inf:** ranked, not sanitized. `+Inf` is strictly above every finite
///   score; `-Inf` is strictly below every finite score. Equal infinities
///   break ties by ascending expert ID.
/// * **Finite scores:** descending numeric order. `+0.0` and `-0.0` are
///   equal; the lowest expert ID wins the tie.
/// * **`top_k == 0` or no experts:** empty selection.
/// * **`top_k > num_experts`:** every expert is returned, unique and in range,
///   already sorted by the total order above.
///
/// This helper is pure: the same `(scores, top_k)` pair always yields the same
/// `Result`. Softmax and normalization kernels are unchanged here.
///
/// Callers must rank these raw scores *before* softmax. Softmax fills a row
/// containing NaN with NaN and collapses `+Inf` scores to an equal split, so
/// ranking its output would lose the NaN rejection and the order among the
/// finite scores.
pub(super) fn top_k_indices(scores: &[f32], top_k: usize) -> Result<Vec<usize>> {
    reject_nan_routing_scores(scores)?;

    let take = top_k.min(scores.len());
    if take == 0 {
        return Ok(Vec::new());
    }

    let mut indexed: Vec<(usize, f32)> = scores.iter().copied().enumerate().collect();
    indexed.sort_by(cmp_routing_entries);
    Ok(indexed
        .into_iter()
        .take(take)
        .map(|(expert_id, _)| expert_id)
        .collect())
}

/// Reject NaN routing scores without ranking. Used to fail closed before
/// mutating any SNN backend state.
pub(crate) fn reject_nan_routing_scores(scores: &[f32]) -> Result<()> {
    if let Some(expert_id) = scores.iter().position(|score| score.is_nan()) {
        return Err(HybridError::NanRoutingScore { expert_id });
    }
    Ok(())
}

/// Rank raw routing scores, then softmax for the returned expert weights.
pub(crate) fn route_top_k(scores: &[f32], top_k: usize) -> Result<(Vec<f32>, Vec<usize>)> {
    let selected_experts = top_k_indices(scores, top_k)?;
    Ok((softmax(scores), selected_experts))
}

/// Total order for routing: higher score first, then lower expert ID.
///
/// Precondition: neither score is NaN. After that check, IEEE `<`/`>` is a
/// total order over finite values and infinities, and treats signed zeros as
/// equal so the expert-ID tie break is the only remaining discriminator.
fn cmp_routing_entries(left: &(usize, f32), right: &(usize, f32)) -> Ordering {
    debug_assert!(!left.1.is_nan() && !right.1.is_nan());
    if left.1 > right.1 {
        Ordering::Less
    } else if left.1 < right.1 {
        Ordering::Greater
    } else {
        left.0.cmp(&right.0)
    }
}

pub(super) fn resample_embedding(input: &[f32], target_len: usize) -> Vec<f32> {
    if target_len == 0 {
        return Vec::new();
    }
    if input.len() == target_len {
        return input.to_vec();
    }
    if input.is_empty() {
        return vec![0.0; target_len];
    }
    if target_len == 1 {
        return vec![input.iter().sum::<f32>() / input.len() as f32];
    }

    let last = input.len() - 1;
    // The source position is the exact rational `idx * last / (target_len - 1)`
    // and is computed in integer space. In `f32` the scale factor loses the
    // endpoint once `last` exceeds 2^24 (the index rounds, either past the
    // end or down to the previous element), which drops the final input value
    // and shifts the interpolation towards the wrong neighbour. `u128` holds
    // `idx * last` for any `usize` pair on 64-bit targets.
    let denom = (target_len - 1) as u128;
    let mut out = Vec::with_capacity(target_len);
    for idx in 0..target_len {
        let numerator = (idx as u128) * (last as u128);
        // `numerator / denom` is the lower neighbour and never exceeds `last`.
        let lo = (numerator / denom) as usize;
        let remainder = numerator % denom;
        if remainder == 0 {
            out.push(input[lo]);
            continue;
        }
        // A non-zero remainder means the position is strictly between `lo` and
        // `lo + 1`, so the upper neighbour is still within the input.
        let hi = lo + 1;
        let t = (remainder as f64 / denom as f64) as f32;
        out.push(input[lo] * (1.0 - t) + input[hi] * t);
    }
    out
}

pub(super) fn normalize_l2(values: &mut [f32]) {
    l2_normalize(values);
}

pub(super) fn apply_extract_token_options(input: &[f32], options: ExtractTokenOptions) -> Vec<f32> {
    let mut out = if let Some(target_dim) = options.target_dim {
        resample_embedding(input, target_dim)
    } else {
        input.to_vec()
    };
    if options.l2_normalize {
        normalize_l2(&mut out);
    }
    out
}

/// Which axis of a rank-2 gate tensor is the expert axis.
///
/// `dims` is engram-parser's outermost-first shape, so `dims[1]` is the
/// contiguous on-disk axis (GGUF `ne[0]`), and `weights[r * dims[1] + c]` is
/// row `r`, column `c`. llama.cpp creates `ffn_gate_inp` as
/// `ne = [n_embd, n_expert]`, which arrives here as `[experts, hidden]`: expert
/// `e` is the contiguous row `weights[e * hidden + dim]`. The transposed
/// storage `[hidden, experts]` is also accepted; there expert `e` is the
/// strided column `weights[dim * experts + e]`. A square matrix has no shape
/// cue for which axis is which; expert rows win because that is llama.cpp's
/// layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GateLayout {
    /// `[experts, hidden]`: expert rows, `hidden` contiguous.
    ExpertRows { hidden: usize },
    /// `[hidden, experts]`: expert columns, `experts` contiguous.
    ExpertColumns { experts: usize },
}

impl GateLayout {
    #[inline]
    fn index(self, expert_id: usize, dim: usize) -> usize {
        match self {
            GateLayout::ExpertRows { hidden } => expert_id * hidden + dim,
            GateLayout::ExpertColumns { experts } => dim * experts + expert_id,
        }
    }
}

/// Resolve the gate orientation from the outermost-first shape once per call.
fn resolve_gate_layout(
    dims: &[usize],
    num_experts: usize,
    hidden_size: usize,
) -> Result<GateLayout> {
    let d0 = dims[0];
    let d1 = dims[1];

    if d1 == hidden_size && d0 >= num_experts {
        return Ok(GateLayout::ExpertRows { hidden: d1 });
    }
    if d0 == hidden_size && d1 >= num_experts {
        return Ok(GateLayout::ExpertColumns { experts: d1 });
    }

    Err(HybridError::UnsupportedFormat(format!(
        "unsupported routing tensor orientation {dims:?} for hidden_size={hidden_size}"
    )))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::HybridError;
    use std::collections::HashSet;

    #[test]
    fn resample_embedding_preserves_target_length() {
        let input = vec![0.0, 1.0, 0.0, -1.0];
        let out = resample_embedding(&input, 8);
        assert_eq!(out.len(), 8);
        assert!((out[0] - 0.0).abs() < 1e-6);
        assert!((out[7] + 1.0).abs() < 1e-6);
    }

    /// `(len - 1) as f32` rounds up to `len` for this length (2^24 + 3 is a
    /// tie that rounds to even, 2^24 + 4), so the last sample's `f32` index
    /// used to land one past the end and panic. Reachable through
    /// `MoeRouter::extract_token_embedding_with_options` on a checkpoint whose
    /// hidden size exceeds 2^24.
    #[test]
    fn resample_embedding_long_input_does_not_index_past_the_end() {
        let len = (1usize << 24) + 4;
        assert_eq!((len - 1) as f32, len as f32);
        let mut input = vec![0.0f32; len];
        input[0] = -3.0;
        input[len - 1] = 7.0;
        let out = resample_embedding(&input, 2);
        assert_eq!(out, vec![-3.0, 7.0]);
    }

    /// The mirror case: `(len - 1) as f32` rounds *down* here (2^24 + 1 is a
    /// tie that rounds to the even 2^24), so the float path sampled
    /// `input[len - 2]` for the final output and silently dropped the last
    /// embedding value.
    #[test]
    fn resample_embedding_keeps_the_last_element_when_the_float_index_rounds_down() {
        let len = (1usize << 24) + 2;
        assert_eq!((len - 1) as f32, (len - 2) as f32);
        let mut input = vec![0.0f32; len];
        input[0] = -3.0;
        input[len - 1] = 7.0;
        let out = resample_embedding(&input, 2);
        assert_eq!(out, vec![-3.0, 7.0]);
    }

    /// Both endpoints of the input survive the resample, and the samples in
    /// between are the linear interpolation of their bracketing elements.
    #[test]
    fn resample_embedding_preserves_the_endpoints() {
        let input: Vec<f32> = (0..17).map(|value| value as f32).collect();
        let out = resample_embedding(&input, 5);
        assert_eq!(out.first(), Some(&0.0));
        assert_eq!(out.last(), Some(&16.0));
        // `idx * 16 / 4` is an integer for every output index, so each sample
        // is an exact input element here.
        assert_eq!(out, vec![0.0, 4.0, 8.0, 12.0, 16.0]);
    }

    /// A non-integer source position interpolates between the bracketing
    /// input elements.
    #[test]
    fn resample_embedding_interpolates_between_neighbours() {
        let out = resample_embedding(&[0.0, 10.0], 3);
        assert!((out[0] - 0.0).abs() < 1e-6);
        assert!((out[1] - 5.0).abs() < 1e-6);
        assert!((out[2] - 10.0).abs() < 1e-6);
    }

    #[test]
    fn synthetic_gate_scores_on_empty_embedding_are_zero() {
        assert_eq!(synthetic_gate_scores(3, &[]), vec![0.0; 3]);
        assert!(synthetic_gate_scores(0, &[]).is_empty());
    }

    /// Gate value `100 * expert + dim` so every cell is distinguishable, laid
    /// out as `weights[expert * hidden + dim]` — the row-major view of a GGUF
    /// `ffn_gate_inp` with `ne = [hidden, experts]` (outermost-first
    /// `[experts, hidden]`), which is what engram-parser hands this crate.
    fn marker_gate(experts: usize, hidden: usize) -> Vec<f32> {
        let mut weights = vec![0.0f32; experts * hidden];
        for expert in 0..experts {
            for dim in 0..hidden {
                weights[expert * hidden + dim] = (100 * expert + dim) as f32;
            }
        }
        weights
    }

    fn one_hot(len: usize, hot: usize) -> Vec<f32> {
        let mut out = vec![0.0f32; len];
        out[hot] = 1.0;
        out
    }

    #[test]
    fn gate_index_follows_llama_cpp_expert_rows() {
        // GGUF ne = [n_embd=32, n_expert=8]  →  outermost-first dims [8, 32].
        let (experts, hidden) = (8usize, 32usize);
        let dims = [experts, hidden];
        let weights = marker_gate(experts, hidden);
        let layout = resolve_gate_layout(&dims, experts, hidden).unwrap();
        assert_eq!(layout, GateLayout::ExpertRows { hidden });
        for expert in 0..experts {
            for dim in 0..hidden {
                let index = layout.index(expert, dim);
                assert_eq!(
                    weights[index],
                    (100 * expert + dim) as f32,
                    "expert {expert} dim {dim} resolved to index {index}"
                );
            }
        }
        // The issue's repro: input e_7 must see expert 5's cell, not a
        // transposed read of row 7's cell.
        assert_eq!(weights[layout.index(5, 7)], 507.0);
    }

    #[test]
    fn gate_index_accepts_transposed_expert_columns() {
        // Transposed storage: ne = [n_expert=8, n_embd=32] → dims [32, 8], so
        // expert `e` is a strided column `weights[dim * experts + e]`.
        let (experts, hidden) = (8usize, 32usize);
        let dims = [hidden, experts];
        let mut weights = vec![0.0f32; experts * hidden];
        for dim in 0..hidden {
            for expert in 0..experts {
                weights[dim * experts + expert] = (100 * expert + dim) as f32;
            }
        }
        let layout = resolve_gate_layout(&dims, experts, hidden).unwrap();
        assert_eq!(layout, GateLayout::ExpertColumns { experts });
        for expert in 0..experts {
            for dim in 0..hidden {
                assert_eq!(
                    weights[layout.index(expert, dim)],
                    (100 * expert + dim) as f32
                );
            }
        }
    }

    #[test]
    fn gate_scores_pick_marked_cell_for_one_hot_input() {
        let (experts, hidden) = (8usize, 32usize);
        let dims = [experts, hidden];
        let weights = marker_gate(experts, hidden);
        for dim in [0usize, 7, 31] {
            let scores = checkpoint_gate_scores(
                &dims,
                &weights,
                "marker",
                "gate",
                experts,
                &one_hot(hidden, dim),
            )
            .unwrap();
            let expected: Vec<f32> = (0..experts).map(|e| (100 * e + dim) as f32).collect();
            assert_eq!(scores, expected, "input e_{dim}");
        }
    }

    #[test]
    fn gate_scores_select_the_expert_whose_row_matches() {
        // Issue #89 repro: H=32, E=8, expert-5 row all ones, input e_0.
        // llama.cpp semantics: logit_e = Σ_d W[e*H + d]·x[d] → expert 5 wins.
        // A transposed read yields all-zero scores and selects expert 0.
        let (experts, hidden) = (8usize, 32usize);
        let dims = [experts, hidden];
        let mut weights = vec![0.0f32; experts * hidden];
        weights[5 * hidden..6 * hidden].fill(1.0);
        let scores = checkpoint_gate_scores(
            &dims,
            &weights,
            "repro",
            "gate",
            experts,
            &one_hot(hidden, 0),
        )
        .unwrap();
        let (_, selected) = route_top_k(&scores, 1).unwrap();
        assert_eq!(selected, vec![5]);
        assert_eq!(scores[5], 1.0);
        assert!(scores.iter().enumerate().all(|(e, s)| e == 5 || *s == 0.0));
    }

    #[test]
    fn gate_scores_with_more_rows_than_experts_still_use_expert_rows() {
        // Shape cue only requires `d0 >= num_experts`: a 64-row gate routed
        // over 8 experts reads rows 0..8.
        let (rows, experts, hidden) = (64usize, 8usize, 32usize);
        let dims = [rows, hidden];
        let weights = marker_gate(rows, hidden);
        let scores = checkpoint_gate_scores(
            &dims,
            &weights,
            "wide",
            "gate",
            experts,
            &one_hot(hidden, 3),
        )
        .unwrap();
        assert_eq!(scores.len(), experts);
        assert_eq!(scores[7], 703.0);
    }

    #[test]
    fn gate_scores_reject_short_payload_and_unknown_orientation() {
        let dims = [8usize, 32usize];
        let short = vec![0.0f32; 8 * 32 - 1];
        let err =
            checkpoint_gate_scores(&dims, &short, "short", "gate", 8, &one_hot(32, 0)).unwrap_err();
        assert!(matches!(err, HybridError::ModelLoad { .. }), "{err}");

        let err = resolve_gate_layout(&[8, 16], 8, 32).unwrap_err();
        assert!(matches!(err, HybridError::UnsupportedFormat(_)), "{err}");
        let err = resolve_gate_layout(&[4, 32], 8, 32).unwrap_err();
        assert!(matches!(err, HybridError::UnsupportedFormat(_)), "{err}");
    }

    #[test]
    fn softmax_empty_scores_are_empty() {
        assert!(softmax(&[]).is_empty());
    }

    #[test]
    fn softmax_all_masked_is_uniform() {
        let y = softmax(&[f32::NEG_INFINITY, f32::NEG_INFINITY]);
        assert!((y[0] - 0.5).abs() < 1e-6);
        assert!((y[1] - 0.5).abs() < 1e-6);
    }

    #[test]
    fn softmax_two_pos_inf_split() {
        let y = softmax(&[f32::INFINITY, 0.0, f32::INFINITY]);
        assert_eq!(y, vec![0.5, 0.0, 0.5]);
    }

    #[test]
    fn l2_normalize_unit_vector() {
        let mut v = vec![3.0f32, 4.0];
        normalize_l2(&mut v);
        assert!((v[0] - 0.6).abs() < 1e-6);
        assert!((v[1] - 0.8).abs() < 1e-6);
    }

    #[test]
    fn projector_forward_options_resample_to_2048() {
        let input = vec![0.5; 3072];
        let out = apply_extract_token_options(&input, ExtractTokenOptions::for_projector_forward());
        assert_eq!(out.len(), crate::types::EMBEDDING_DIM);
    }

    /// Existing finite ranking fixture: strictly decreasing scores keep
    /// their previous selection `[0, 1]` for `top_k = 2`.
    #[test]
    fn route_top_k_ranks_raw_scores_before_softmax() {
        let scores = [0.0_f32, 1.0, f32::INFINITY];
        let (weights, selected) = route_top_k(&scores, 1).unwrap();
        assert_eq!(selected, vec![2]);
        // Finite-value policy: one +Inf → one-hot at that expert.
        assert_eq!(weights, vec![0.0, 0.0, 1.0]);
    }

    #[test]
    fn route_top_k_preserves_raw_order_when_softmax_underflows() {
        // After max-subtraction, exp(-150) and exp(-140) both underflow to 0, so
        // ranking softmax weights would tie experts 1 and 2 and pick ID 1.
        let scores = [100.0_f32, -50.0, -40.0];
        let weights = softmax(&scores);
        assert_eq!(weights[1], 0.0);
        assert_eq!(weights[2], 0.0);
        let (_weights, selected) = route_top_k(&scores, 2).unwrap();
        assert_eq!(selected, vec![0, 2]);
    }

    #[test]
    fn top_k_zero_still_rejects_nan() {
        assert!(matches!(
            top_k_indices(&[f32::NAN], 0).unwrap_err(),
            HybridError::NanRoutingScore { expert_id: 0 }
        ));
    }

    #[test]
    fn finite_distinct_scores_keep_expected_selection() {
        let scores = [0.9_f32, 0.5, 0.3, 0.1];
        assert_eq!(top_k_indices(&scores, 2).unwrap(), vec![0, 1]);
        assert_eq!(top_k_indices(&scores, 1).unwrap(), vec![0]);
        assert_eq!(top_k_indices(&scores, 4).unwrap(), vec![0, 1, 2, 3]);
    }

    #[test]
    fn all_equal_finite_scores_select_lowest_ids() {
        let scores = [0.25_f32, 0.25, 0.25, 0.25];
        assert_eq!(top_k_indices(&scores, 2).unwrap(), vec![0, 1]);
        assert_eq!(top_k_indices(&scores, 4).unwrap(), vec![0, 1, 2, 3]);
    }

    #[test]
    fn partial_ties_prefer_lowest_expert_id() {
        let scores = [0.4_f32, 0.9, 0.4, 0.1];
        // 0.9 at expert 1, then the two 0.4s at 0 then 2.
        assert_eq!(top_k_indices(&scores, 3).unwrap(), vec![1, 0, 2]);
    }

    #[test]
    fn tied_high_scores_are_stable_across_id_permutations() {
        // Same three-way tie on the high value, assigned to different IDs.
        let permutations: [&[f32]; 3] = [
            &[1.0, 1.0, 0.0, 1.0],
            &[0.0, 1.0, 1.0, 1.0],
            &[1.0, 0.0, 1.0, 1.0],
        ];
        let expected: [&[usize]; 3] = [&[0, 1, 3], &[1, 2, 3], &[0, 2, 3]];
        for (scores, want) in permutations.iter().zip(expected) {
            assert_eq!(top_k_indices(scores, 3).unwrap(), want);
        }
    }

    #[test]
    fn repeated_runs_match_for_ties_and_infinities() {
        let scores = [1.0_f32, f32::INFINITY, 1.0, f32::NEG_INFINITY, 1.0];
        let first = top_k_indices(&scores, 4).unwrap();
        for _ in 0..16 {
            assert_eq!(top_k_indices(&scores, 4).unwrap(), first);
        }
        assert_eq!(first, vec![1, 0, 2, 4]);
    }

    #[test]
    fn nan_is_rejected_without_partial_cmp_fallback() {
        let scores = [0.2_f32, f32::NAN, 0.9];
        let err = top_k_indices(&scores, 2).unwrap_err();
        assert!(matches!(err, HybridError::NanRoutingScore { expert_id: 1 }));
        assert_eq!(err.to_string(), "NaN routing score at expert 1");
    }

    #[test]
    fn first_nan_is_reported_when_several_are_present() {
        let scores = [f32::NAN, 1.0, f32::NAN];
        assert!(matches!(
            top_k_indices(&scores, 1).unwrap_err(),
            HybridError::NanRoutingScore { expert_id: 0 }
        ));
    }

    #[test]
    fn pos_inf_ranks_above_finite_and_neg_inf_below() {
        let scores = [1.0_f32, f32::NEG_INFINITY, f32::INFINITY, 2.0];
        assert_eq!(top_k_indices(&scores, 4).unwrap(), vec![2, 3, 0, 1]);
    }

    #[test]
    fn equal_infinities_break_ties_by_expert_id() {
        let pos = [f32::INFINITY, 0.0, f32::INFINITY];
        assert_eq!(top_k_indices(&pos, 2).unwrap(), vec![0, 2]);
        let neg = [f32::NEG_INFINITY, 1.0, f32::NEG_INFINITY];
        assert_eq!(top_k_indices(&neg, 3).unwrap(), vec![1, 0, 2]);
    }

    #[test]
    fn signed_zeros_are_equal_and_break_ties_by_id() {
        let scores = [-0.0_f32, 0.0, -0.0, 1.0];
        assert_eq!(top_k_indices(&scores, 3).unwrap(), vec![3, 0, 1]);
        assert_eq!(top_k_indices(&scores, 4).unwrap(), vec![3, 0, 1, 2]);
    }

    #[test]
    fn empty_scores_yield_empty_selection() {
        assert_eq!(top_k_indices(&[], 0).unwrap(), Vec::<usize>::new());
        assert_eq!(top_k_indices(&[], 3).unwrap(), Vec::<usize>::new());
    }

    #[test]
    fn top_k_zero_one_n_and_n_plus_one() {
        let scores = [0.1_f32, 0.4, 0.3];
        let n = scores.len();
        assert_eq!(top_k_indices(&scores, 0).unwrap(), Vec::<usize>::new());
        assert_eq!(top_k_indices(&scores, 1).unwrap(), vec![1]);
        assert_eq!(top_k_indices(&scores, n).unwrap(), vec![1, 2, 0]);
        assert_eq!(top_k_indices(&scores, n + 1).unwrap(), vec![1, 2, 0]);
    }

    fn assert_unique_in_range_and_monotonic(scores: &[f32], selected: &[usize]) {
        let mut seen = HashSet::with_capacity(selected.len());
        for &expert_id in selected {
            assert!(
                expert_id < scores.len(),
                "expert {expert_id} out of range for {} scores",
                scores.len()
            );
            assert!(seen.insert(expert_id), "duplicate expert {expert_id}");
        }
        for window in selected.windows(2) {
            let (left, right) = (window[0], window[1]);
            let (left_score, right_score) = (scores[left], scores[right]);
            assert!(
                left_score >= right_score,
                "selected scores must be non-increasing: {left_score} then {right_score}"
            );
            if left_score == right_score {
                assert!(
                    left < right,
                    "equal scores must break ties by ascending expert id, got {left} then {right}"
                );
            }
        }
    }

    #[test]
    fn property_unique_in_range_and_monotonic_selected_scores() {
        let fixtures: &[&[f32]] = &[
            &[0.1, 0.2, 0.3, 0.4],
            &[1.0, 1.0, 1.0],
            &[5.0, 1.0, 5.0, 1.0, 0.0],
            &[f32::INFINITY, 0.0, f32::NEG_INFINITY, f32::INFINITY],
            &[-0.0, 0.0, 0.0, -0.0],
            &[],
        ];
        for scores in fixtures {
            for top_k in [0, 1, scores.len(), scores.len().saturating_add(1)] {
                let selected = top_k_indices(scores, top_k).unwrap();
                assert_eq!(selected.len(), top_k.min(scores.len()));
                assert_unique_in_range_and_monotonic(scores, &selected);
            }
        }

        let mut rng = SplitMix64(0xC0FFEE_u64);
        for trial in 0..256 {
            let n = 1 + (rng.next_u64() as usize % 16);
            let mut scores = Vec::with_capacity(n);
            for _ in 0..n {
                scores.push(rng.next_routing_score());
            }
            if scores.iter().any(|score| score.is_nan()) {
                assert!(matches!(
                    top_k_indices(&scores, n.min(3)).unwrap_err(),
                    HybridError::NanRoutingScore { .. }
                ));
                continue;
            }
            let top_k = rng.next_u64() as usize % (n + 2);
            let selected = top_k_indices(&scores, top_k).unwrap();
            assert_eq!(selected.len(), top_k.min(n));
            assert_unique_in_range_and_monotonic(&scores, &selected);
            let again = top_k_indices(&scores, top_k).unwrap();
            assert_eq!(selected, again, "trial {trial} was not deterministic");
        }
    }

    /// SplitMix64 so property trials are reproducible without extra crates.
    struct SplitMix64(u64);

    impl SplitMix64 {
        fn next_u64(&mut self) -> u64 {
            self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
            let mut z = self.0;
            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
            z ^ (z >> 31)
        }

        fn next_routing_score(&mut self) -> f32 {
            match self.next_u64() % 32 {
                0 => f32::NAN,
                1 => f32::INFINITY,
                2 => f32::NEG_INFINITY,
                3 => 0.0,
                4 => -0.0,
                _ => {
                    let unit = (self.next_u64() >> 40) as f32 / (1u32 << 24) as f32;
                    unit * 20.0 - 10.0
                }
            }
        }
    }
}