"""models/topk.py against a stable sort: the selection mask, its tie rule and the threshold bracket. Shapes: rows x 1..300 positions, keep 1..80; fp32 scores of several kinds. Exact (no tolerance): selections are compared as sets.""" import pytest import torch from trnrt.models import topk def _kinds(g: torch.Generator, rows: int, n: int) -> dict[str, torch.Tensor]: r = torch.randn(rows, n, generator=g) return { "normal": r, "tied_small_integers": torch.randint(-3, 4, (rows, n), generator=g).float(), "relu_zeros": torch.relu(r) * (torch.rand(rows, n, generator=g) > 0.3), "all_equal": torch.full((rows, n), 0.5), "masked_to_minus_1e30": torch.where(torch.rand(rows, n, generator=g) > 0.5, r, torch.tensor(-1e30)), "wide_range": r * torch.exp(torch.randn(rows, n, generator=g) * 30), "signed_zeros": torch.where(r > 0, torch.tensor(0.0), torch.tensor(-0.0)), "tiny": r * 1e-38, } @pytest.mark.parametrize(("n", "keep"), [(1, 1), (7, 3), (64, 8), (100, 99), (300, 80), (257, 1), (33, 33), (20, 40)]) def test_topk_mask_matches_stable_sort(n, keep): g = torch.Generator().manual_seed(n * 1000 + keep) for name, s in _kinds(g, 5, n).items(): got = topk.topk_mask(s, keep) want = topk.reference_mask(s, keep) assert torch.equal(got, want), name assert int(got.sum(-1).max()) == min(keep, n) == int(got.sum(-1).min()), name def test_topk_mask_leading_dims_and_infinities(): g = torch.Generator().manual_seed(3) s = torch.randn(2, 3, 40, generator=g) s[0, 0, :5] = float("-inf") s[1, 2, 7] = float("inf") assert torch.equal(topk.topk_mask(s, 9), topk.reference_mask(s, 9)) def test_kth_value_brackets_the_threshold(): g = torch.Generator().manual_seed(11) for name, s in _kinds(g, 6, 90).items(): for keep in (1, 5, 45, 90): lo, hi = topk.kth_value(s, keep) t = torch.sort(s, dim=-1, descending=True).values[:, keep - 1 : keep] assert torch.equal(lo, t), (name, keep) assert bool((hi >= lo).all()) assert bool(((s >= lo).sum(-1, keepdim=True) >= keep).all()) above = (s >= hi).sum(-1, keepdim=True) assert bool(((hi == lo) | (above < keep)).all()), (name, keep) def test_mask_indices_lists_the_selected_positions_in_order(): g = torch.Generator().manual_seed(5) s = torch.randn(4, 3, 50, generator=g) sel = topk.topk_mask(s, 12) idx = topk.mask_indices(sel, 12) assert idx.shape == (4, 3, 12) assert torch.equal(torch.zeros_like(sel).scatter(-1, idx, True), sel) assert bool((idx[..., 1:] > idx[..., :-1]).all())