interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

GitHub aien-dev/aien-sovereign-core-mv#646 (code only)

closed derived 24493268cba85025 #646

Imported from GitHub aien-dev/aien-sovereign-core-mv#646 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base 1e6ae85c977b628fa26a8c84c8b16194e78e67e2 · Head 6800feec2fcbb496624636ac0b85b718ee3a348a

Fetch it

A git bundle of the pull request's head, 4710 bytes.

curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/24493268cba85025.bundle -o 24493268cba85025.bundle
git fetch 24493268cba85025.bundle refs/pull/646/head

Raw bundle · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aien-sovereign-core-mv
646
6800feec2fcbb496624636ac0b85b718ee3a348a
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":646,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/646","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:45Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/.crumb b/.crumb
index 294084cd..468495b2 100644
--- a/.crumb
+++ b/.crumb
@@ -83,7 +83,7 @@
         },
         {
           "digest": "1a65d8ae9be7c2e6ccc39d7ed20762dfde808132a3216c8b82d0ce0232233343",
-          "last_commit": "5ae9d6a3",
+          "last_commit": "f8eea420",
           "name": "crates/aien-cli",
           "purpose": ""
         },
@@ -101,7 +101,7 @@
         },
         {
           "digest": "6b6ef510d49930df5acdbcd6e25fd349c620b9d01039af8b379e37510f52adc6",
-          "last_commit": "1eab4ec8",
+          "last_commit": "fe3677c3",
           "name": "scripts",
           "purpose": ""
         },
@@ -113,20 +113,20 @@
         },
         {
           "digest": "489b92d3d4363d2b403d6fee34a384284a40c25176df4dcc77eef07478ff8825",
-          "last_commit": "96d89167",
+          "last_commit": "fe3677c3",
           "name": "tools/aien-local-ci",
           "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health "
         }
       ],
       "children_root": "sha256:77e12a731b5dc9bca1bfe16166523fea1ad27cb510dd9a9703f53d01b8bef4a8",
-      "compiled_at": "2026-10-20T10:44:05Z",
+      "compiled_at": "2026-10-22T12:19:15Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:a35c9c2c0ae2f3e8bc64c1484c96630edab9594af8f04cfeb5717661a09ae321",
+      "digest": "sha256:de877fb56086ea206a3d966ca377135d4c857d886d18e66dfb8d36d40bc6d9cc",
       "evidence_files": 1578,
       "evidence_root": "sha256:135e27a1a0704c4a8371cd2c1eb555f2b5beec61c212949b029a5457418a7160",
       "files": 5894,
-      "generated_at_commit": "ec4459ac2c604e6ac63c1265d42e0270f0a5429c",
-      "source_tree": "sha256:07bff5f313f90893a6289222eb83f60c342feac5c39a060a7bbd1fc58fbef7ce"
+      "generated_at_commit": "e75e240da2c26f7fa8868ab970497d1914760615",
+      "source_tree": "sha256:b0899a24fa11041302298dae9548a1e08a9b771e09b35a8ea188844cfba4c64a"
     }
   },
   "history": [],
diff --git a/crates/aien-serve-http/src/sampling.rs b/crates/aien-serve-http/src/sampling.rs
index e2a00329..23d451ff 100644
--- a/crates/aien-serve-http/src/sampling.rs
+++ b/crates/aien-serve-http/src/sampling.rs
@@ -303,16 +303,47 @@ pub fn sample_next(logits: &[f32], params: &GenerateParams, step: usize) -> u32
     SamplingObserver::new(params).sample(logits, step)
 }
 
+/// Rank order: higher value first, lower token id first on exact ties.
+fn rank_cmp(logits: &[f32], a: usize, b: usize) -> std::cmp::Ordering {
+    logits[b]
+        .partial_cmp(&logits[a])
+        .unwrap_or(std::cmp::Ordering::Equal)
+        .then(a.cmp(&b))
+}
+
 /// Copies `logits` with everything outside the `k` largest values set to -inf.
 /// Ties at the boundary keep the lower token id, matching the nucleus tie rule.
+///
+/// Uses an O(V) partial selection. The comparator is a strict total order only
+/// when no logit is NaN (NaN compares Equal to everything, which is not
+/// transitive), so any NaN input takes the original full-sort path to keep its
+/// exact historical output.
 fn top_k_mask(logits: &[f32], k: usize) -> Vec<f32> {
+    if logits.iter().any(|v| v.is_nan()) {
+        return top_k_mask_full_sort(logits, k);
+    }
+    let mut out = vec![f32::NEG_INFINITY; logits.len()];
+    if k == 0 {
+        return out;
+    }
+    let mut order: Vec<usize> = (0..logits.len()).collect();
+    let winners = if k < order.len() {
+        order.select_nth_unstable_by(k - 1, |&a, &b| rank_cmp(logits, a, b));
+        &order[..k]
+    } else {
+        &order[..]
+    };
+    for &i in winners {
+        out[i] = logits[i];
+    }
+    out
+}
+
+/// The original O(V log V) implementation: reference for tests and the path for
+/// vectors containing NaN.
+fn top_k_mask_full_sort(logits: &[f32], k: usize) -> Vec<f32> {
     let mut order: Vec<usize> = (0..logits.len()).collect();
-    order.sort_by(|&a, &b| {
-        logits[b]
-            .partial_cmp(&logits[a])
-            .unwrap_or(std::cmp::Ordering::Equal)
-            .then(a.cmp(&b))
-    });
+    order.sort_by(|&a, &b| rank_cmp(logits, a, b));
     let mut out = vec![f32::NEG_INFINITY; logits.len()];
     for &i in &order[..k] {
         out[i] = logits[i];
@@ -443,6 +474,144 @@ mod tests {
         assert!(r.log_fields().ends_with("MUTANT=ignore-seed"));
     }
 
+    /// Deterministic xorshift for reproducible vectors.
+    fn rng(state: &mut u64) -> u64 {
+        *state ^= *state << 13;
+        *state ^= *state >> 7;
+        *state ^= *state << 17;
+        *state
+    }
+
+    fn same_bits(a: &[f32], b: &[f32]) -> bool {
+        a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
+    }
+
+    fn check_all_k(logits: &[f32], ks: &[usize]) {
+        for &k in ks.iter().filter(|&&k| k <= logits.len()) {
+            assert!(
+                same_bits(&top_k_mask(logits, k), &top_k_mask_full_sort(logits, k)),
+                "k={k} len={}",
+                logits.len()
+            );
+        }
+    }
+
+    #[test]
+    fn top_k_selection_matches_full_sort_random_and_tied() {
+        let mut st = 0x9E37_79B9_7F4A_7C15u64;
+        for len in [1usize, 2, 5, 64, 1000, 4097] {
+            let ks = [0, 1, 20, 100, len.saturating_sub(1), len];
+            // Random finite, with negatives.
+            let v: Vec<f32> = (0..len)
+                .map(|_| (rng(&mut st) % 20001) as f32 / 1000.0 - 10.0)
+                .collect();
+            check_all_k(&v, &ks);
+            // Tie-heavy: only 4 distinct values, includes -0.0 and 0.0.
+            let t: Vec<f32> = (0..len)
+                .map(|_| [-1.0f32, 0.0, -0.0, 2.5][(rng(&mut st) % 4) as usize])
+                .collect();
+            check_all_k(&t, &ks);
+            // All equal.
+            check_all_k(&vec![1.5; len], &ks);
+            // Infinities mixed in.
+            let i: Vec<f32> = (0..len)
+                .map(|_| match rng(&mut st) % 6 {
+                    0 => f32::INFINITY,
+                    1 => f32::NEG_INFINITY,
+                    _ => (rng(&mut st) % 7) as f32,
+                })
+                .collect();
+            check_all_k(&i, &ks);
+            // NaN mixed in: falls back to the original path, bit-identical.
+            let n: Vec<f32> = (0..len)
+                .map(|_| match rng(&mut st) % 5 {
+                    0 => f32::NAN,
+                    1 => f32::INFINITY,
+                    _ => (rng(&mut st) % 5) as f32,
+                })
+                .collect();
+            // The original comparator is not a total order with NaN, so the
+            // full sort may itself panic; the new path must match either way.
+            for k in [0, 1, 20.min(len), len] {
+                let a = std::panic::catch_unwind(|| top_k_mask(&n, k));
+                let b = std::panic::catch_unwind(|| top_k_mask_full_sort(&n, k));
+                match (a, b) {
+                    (Ok(a), Ok(b)) => assert!(same_bits(&a, &b)),
+                    (Err(_), Err(_)) => {}
+                    _ => panic!("NaN behavior diverged at k={k}"),
+                }
+            }
+        }
+    }
+
+    #[test]
+    fn top_k_ties_at_cutoff_keep_lower_token_id() {
+        let m = top_k_mask(&[1.0, 3.0, 1.0, 1.0, 3.0], 3);
+        assert_eq!(m, vec![1.0, 3.0, f32::NEG_INFINITY, f32::NEG_INFINITY, 3.0]);
+    }
+
+    #[test]
+    fn sampled_tokens_and_record_match_with_reference_mask() {
+        let mut st = 7u64;
+        let logits: Vec<f32> = (0..5000)
+            .map(|_| (rng(&mut st) % 400) as f32 / 40.0 - 5.0)
+            .collect();
+        for k in [1usize, 20, 100] {
+            let masked = top_k_mask(&logits, k);
+            let reference = top_k_mask_full_sort(&logits, k);
+            assert!(same_bits(&masked, &reference));
+            let params = GenerateParams {
+                top_p: 0.9,
+                ..p(0.8, k)
+            };
+            let mut o = SamplingObserver::with_mutant(&params, None);
+            let mut r = SamplingObserver::with_mutant(
+                &GenerateParams {
+                    top_k: 0,
+                    ..params.clone()
+                },
+                None,
+            );
+            for step in 0..50 {
+                assert_eq!(o.sample(&logits, step), r.sample(&reference, step));
+            }
+            assert_eq!(o.record().kept, r.record().kept);
+        }
+    }
+
+    /// Microbenchmark: `cargo test --release -p aien-serve-http --lib
+    /// sampling::tests::bench_top_k -- --ignored --nocapture`.
+    #[test]
+    #[ignore]
+    fn bench_top_k() {
+        let mut st = 1u64;
+        let logits: Vec<f32> = (0..152_064)
+            .map(|_| (rng(&mut st) % 100_000) as f32 / 5000.0 - 10.0)
+            .collect();
+        for k in [1usize, 20, 100] {
+            for (name, f) in [
+                (
+                    "full_sort",
+                    top_k_mask_full_sort as fn(&[f32], usize) -> Vec<f32>,
+                ),
+                ("select", top_k_mask),
+            ] {
+                let mut t: Vec<f64> = (0..21)
+                    .map(|_| {
+                        let s = std::time::Instant::now();
+                        std::hint::black_box(f(std::hint::black_box(&logits), k));
+                        s.elapsed().as_secs_f64() * 1e3
+                    })
+                    .collect();
+                t.sort_by(|a, b| a.partial_cmp(b).unwrap());
+                println!(
+                    "k={k:<3} {name:<9} median {:.3} ms min {:.3} max {:.3}",
+                    t[10], t[0], t[20]
+                );
+            }
+        }
+    }
+
     #[test]
     fn mutant_variable_is_refused_without_debug_assertions() {
         assert_eq!(parse_mutant(None, false), Ok(None));