Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

dsv41_ref: top-k ties go to the lowest index, and the indexer never keeps -inf

RayanR0001ffeb0b40f94
diff --git a/c/tests/test_dsv41_ref_topk.py b/c/tests/test_dsv41_ref_topk.py
new file mode 100644
index 00000000..2c354cfd
--- /dev/null
+++ b/c/tests/test_dsv41_ref_topk.py
@@ -0,0 +1,57 @@
+"""dsv41_ref's top-k selections are the engine's: ties to the lowest index, and the
+indexer never keeps a -inf position.
+
+`torch.topk` promises neither. On macOS arm64 it returns [1, 2, 4] for the top 3 of
+[0, 0, 0, 0, 1], so the reference generated there picked different indexer blocks
+than the one generated on Linux, and `dsv41_tiny` failed 6/8 against an engine that
+was right. deepseek_v41.c indexer_run / candidate_blocks take the lowest index with
+a strict `>` and leave an empty slot -1; these cases pin the reference to that.
+"""
+import os
+import sys
+import unittest
+
+try:
+ import torch
+except ImportError as e:
+ raise unittest.SkipTest(f"torch not installed: {e}")
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "tools"))
+import dsv41_ref as R # noqa: E402
+
+INF = float("inf")
+
+
+class TopkTies(unittest.TestCase):
+ def test_ties_go_to_the_lowest_index(self):
+ scores = torch.tensor([[0.0, 0.0, 0.0, 0.0, 1.0],
+ [2.0, 0.5, 2.0, 0.5, 0.5]])
+ self.assertEqual(R.topk_lowest(scores, 3).tolist(), [[4, 0, 1], [0, 2, 1]])
+
+ def test_indexer_ties_at_relu_zero(self):
+ # one block wins, four tie at exactly 0.0 for the remaining two slots
+ score = torch.tensor([[0.0, 0.0, 0.0, 0.0, 0.7]])
+ self.assertEqual(R.indexer_pick(score, 3, torch.tensor(5), 10).tolist(), [[10, 11, 14]])
+
+ def test_indexer_leaves_masked_positions_empty(self):
+ # a candidate mask left two finite scores for topk=4: the other two slots
+ # are empty, not two arbitrary masked blocks
+ score = torch.tensor([[-INF, 0.3, -INF, -INF, 0.1, -INF]])
+ self.assertEqual(R.indexer_pick(score, 4, torch.tensor(6), 0).tolist(), [[1, 4, -1, -1]])
+
+ def test_indexer_prefill_rows_respect_lens(self):
+ # prefill: row t reaches `lens[t]` positions, the rest are -inf
+ score = torch.tensor([[0.2, -INF, -INF],
+ [0.2, 0.0, -INF]])
+ lens = torch.tensor([[1], [2]])
+ self.assertEqual(R.indexer_pick(score, 2, lens, 5).tolist(), [[5, -1], [5, 6]])
+
+ def test_candidate_blocks_tie_to_the_lowest_block(self):
+ # four blocks of two; blocks 0, 1 and 2 tie, the last block is pinned in
+ logits = torch.tensor([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]])
+ keep = R.select_candidate_blocks(logits, torch.tensor(8), 2, 2)
+ self.assertEqual(keep.int().tolist(), [[1, 1, 0, 0, 0, 0, 1, 1]])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tools/dsv41_ref.py b/c/tools/dsv41_ref.py
index d1a99ccc..5e7dbd17 100644
--- a/c/tools/dsv41_ref.py
+++ b/c/tools/dsv41_ref.py
@@ -16,6 +16,12 @@ vendor's line is quoted. Deviations that are deliberate:
(`fp8_dequant` / `fp4_dequant` below). The oracle therefore validates the engine's
arithmetic, not its ability to guess a rounding mode.
- no distributed anything: world_size == 1, so the parallel/sharded classes collapse.
+- top-k selections break ties by the lowest index (`topk_lowest`), and the indexer
+ never keeps a -inf position. `torch.topk` leaves both unspecified: the relu makes
+ exact 0.0 ties, and a candidate mask can leave fewer finite scores than `index_topk`.
+ Which tied index torch returns differs between its x86 and arm64 kernels, so the
+ reference generated on macOS arm64 disagreed with the one generated on Linux. The
+ engine takes the lowest index and marks an empty slot -1, and so does this file.
"""
from __future__ import annotations
@@ -196,6 +202,24 @@ def hc_split_sinkhorn(mixes, hc_scale, hc_base, hc_mult, iters, eps):
return pre, post, comb
+def topk_lowest(scores: torch.Tensor, k: int) -> torch.Tensor:
+ """Indices of the k largest scores along the last dim, ties to the lowest index.
+ A stable descending sort keeps equal scores in index order; `torch.topk` does
+ not promise any order among ties."""
+ return scores.sort(dim=-1, descending=True, stable=True).indices[..., :k]
+
+
+def indexer_pick(score: torch.Tensor, topk: int, lens, offset: int) -> torch.Tensor:
+ """Indexer.forward's last step: the best `topk` positions of each row, in position
+ order, shifted by `offset`, -1 for an empty slot. A -inf position (masked by `lens`
+ or by the candidate blocks) is an empty slot, not a pick: it is parked past the end
+ so it sorts last and becomes -1."""
+ idxs = topk_lowest(score, topk)
+ idxs = torch.where(score.gather(-1, idxs) > -float("inf"), idxs, score.shape[-1])
+ idxs = idxs.sort(dim=-1).values
+ return torch.where(idxs < lens, idxs + offset, torch.tensor(-1)).int()
+
+
def sparse_attn(q, kv, attn_sink, topk_idxs, softmax_scale):
"""kernel.py sparse_attn, in torch.
@@ -394,9 +418,7 @@ class RefModel:
score, lens, c["candidate_topk_blocks"], c["candidate_block_size"])
elif 0 <= c["candidate_source_layer"] < layer:
score = score.masked_fill(~shared["candidates"], -float("inf"))
- topk = min(c["index_topk"], end_pos // ratio)
- idxs = score.topk(topk, dim=-1, sorted=False).indices.sort(dim=-1).values
- return torch.where(idxs < lens, idxs + offset, torch.tensor(-1)).int()
+ return indexer_pick(score, min(c["index_topk"], end_pos // ratio), lens, offset)
def attention(self, layer: int, x: torch.Tensor, start_pos: int, shared: dict) -> torch.Tensor:
c = self.c
@@ -699,8 +721,8 @@ def select_candidate_blocks(logits, compress_lens, topk_blocks, block_size):
num_blocks = scores.shape[-1]
last = (compress_lens - 1) // block_size
scores = scores.masked_fill(torch.arange(num_blocks) == last, float("inf"))
- top = scores.topk(min(topk_blocks, num_blocks), dim=-1)
- keep = torch.zeros_like(scores, dtype=torch.bool).scatter_(-1, top.indices, top.values > -float("inf"))
+ top = topk_lowest(scores, min(topk_blocks, num_blocks))
+ keep = torch.zeros_like(scores, dtype=torch.bool).scatter_(-1, top, scores.gather(-1, top) > -float("inf"))
return keep.repeat_interleave(block_size, dim=-1)[..., :width]