From 133721382b427c5907ebf4c39f1e39788a325dc7 Mon Sep 17 00:00:00 2001 From: kbenkhaled Date: Wed, 2 Dec 2026 02:10:57 +0000 Subject: [PATCH 1/2] Bound PreparedLogprobs merge block and share kernels across speculative widths Why: `PreparedLogprobs` specialized all four Triton kernels (`_statistics`, `_normalization`, `_candidates`, and `_finish`) on `WIDTH: tl.constexpr`, and `_finish` sorted all `TILES * 32` per-tile `uint64` candidates in a single `tl.sort()` block. For a 262,144-token vocabulary (`TILES = 256`), `_finish` unrolled an 8,192-element `uint64` bitonic sort network once per speculative width (`1..6`). On an 8 GiB Jetson Orin Nano (CUDA 13.2 `ptxas`), compiling those six specializations took ~19.5 minutes during graph catalog construction; on a 128 GiB Jetson Thor (CUDA 13.2), cold preparation across widths `1..6` took 65.40 s and `_finish` ran in 84.2 us at width 6. What: - Before: `WIDTH` was a `tl.constexpr` parameter in `_statistics`, `_normalization`, `_candidates`, and `_finish`, causing separate Triton compilations per speculative width, and `_finish` set `BLOCK = next_power_of_2(tiles * 32)` (up to 8,192 at 8 warps). - After (`ignition/components/logprobs.py`): - Replaced `WIDTH: tl.constexpr` with runtime `width` decorated with `@triton.jit(do_not_specialize=["width"])` across all four kernels and promoted `pos = row.to(tl.int64) * width + col` for 64-bit addressing. - Bounded `_finish`'s `BLOCK` at `_MERGE_BLOCK = 512` (`_MERGE_WARPS = 4`), iteratively merging `BLOCK - CANDIDATES` (480) incoming keys into slots `CANDIDATES..BLOCK-1` when `TILES * CANDIDATES > BLOCK`. Because each step retains the top 32 unsigned `uint64` packed keys and `MAX_TOP_LOGPROBS` is 20, the global top 20 (including exact tie ordering, signed-zero canonicalization, `-inf`, and `vocab < 20` sentinel padding) is bit-exact. - Tests (`tests/components/test_logprobs.py`): added CPU merge-block bound checks and CUDA tests covering single-specialization sharing and execution across widths `(1, 2, 6, 16)` with multiple active rows, exact top-20 tie ordering across chunk boundaries and vocabularies `[1, 5, 19, 64, 1025, 16384, 16385, 31744, 248320, 262144]` (BF16 and FP32), canonical `+0.0` bits with `-inf` tails, requested-flag-only gating, requested token IDs (including negative and out-of-range IDs), stale-epoch / `row >= live` gating, and stream-ordered functional CUDA graph capture and replay. Result: - Observed on Jetson Thor (`SM110`, `V = 262,144`, widths `1..6`): cold `PreparedLogprobs.prepare()` dropped from `65.40 s` to `4.46 s` (`14.7x` faster), `_finish` GPU latency at width 6 dropped from `84.2 us` to `38.2 us` (`2.2x` faster), and all tested widths share one compiled cubin per kernel. - Observed on Jetson Orin Nano 8 GiB (`SM87`, `V = 262,144`, widths `1..6`): cold `PreparedLogprobs.prepare()` across all six widths completed in `11.83 s` (`_finish` compiles once in `4.25 s` vs ~3m 15s x 6 = ~19.5 min previously, `241.3 us` GPU latency at width 6). - Output buffers matched `main` (`1fbcc3c9`) bit-for-bit (`torch.equal` on raw `int32` words) across `vocab in (19, 1025, 16385, 31744, 262144)` at width 6 on Jetson Thor and matched eager execution bit-for-bit through `compile_forward()` at widths 1 and 4 (`V = 16,385`), with no core format or ABI change. Evidence and limitations: - Live CUDA + CPU pytest (`FLARE_RUN_CUDA_TESTS=1 pytest -q tests/components/test_logprobs.py tests/components/test_completion_outputs.py tests/components/test_completion_capacity.py`): `87 passed, 0 failed` on both Jetson Thor (`SM110`, 3.73 s warm / 66.99 s cold) and Jetson Orin Nano 8 GiB (`SM87`, 200.8 s cold). - Raw `int32` output word equality against `1fbcc3c9` verified on Jetson Thor for `vocab in (19, 1025, 16385, 31744, 262144)` with >32 cutoff-straddling ties and dominant `+0.0`/`-inf` rows. - Verified Flare's `compile_forward()` (`wrap_triton` -> `flare::storage_call`) lowering produces bit-exact outputs at `width=1` and `width=4` (`V = 16,385`) on Jetson Thor. - Limitations: SM103/SM120/SM121 hardware, full end-to-end `ignition export` / `flare run` serving benchmarks, and SM87 baseline `BLOCK=8192` runtime latency were not re-measured in this pass. Equivalent `tl.sort` / `WIDTH` kernels in external recipe repositories (`vocabulary_logprobs.py`, `prompt_logprobs.py`) are outside this repository and left for follow-up. Design-Signed-Off-By: Gemini 4 Neon; design-review=2e5b Signed-off-by: kbenkhaled --- ignition/components/logprobs.py | 61 ++++--- tests/components/test_logprobs.py | 278 ++++++++++++++++++++++++++++++ 2 files changed, 317 insertions(+), 22 deletions(-) create mode 100644 tests/components/test_logprobs.py diff --git a/ignition/components/logprobs.py b/ignition/components/logprobs.py index 7efbcb03e..03a1990e5 100644 --- a/ignition/components/logprobs.py +++ b/ignition/components/logprobs.py @@ -18,8 +18,12 @@ _VOCAB_TILE = 1024 # A global top-20 token is in its tile's top 20; round up to 32 for the merge sort. _TILE_CANDIDATES = triton.next_power_of_2(MAX_TOP_LOGPROBS) +# Merge per-tile candidates in bounded chunks so large vocabularies (e.g. 256k -> 8192 keys) +# do not unroll an 8192-element bitonic network in Triton/PTX while keeping bit-exact ordering. +_MERGE_BLOCK = 512 +assert _MERGE_BLOCK > _TILE_CANDIDATES and (_MERGE_BLOCK & (_MERGE_BLOCK - 1)) == 0 _REDUCTION_WARPS = 4 -_MERGE_WARPS = 8 +_MERGE_WARPS = 4 @triton.jit @@ -52,82 +56,95 @@ def _position(Records, Frame, Requested, Slots, Epochs, Live, row, col, return slot, token, valid & (token >= 0) -@triton.jit +@triton.jit(do_not_specialize=["width"]) def _statistics(Logits, Records, Frame, Requested, Slots, Epochs, Live, Stats, - V: tl.constexpr, WIDTH: tl.constexpr, TILES: tl.constexpr, + V: tl.constexpr, width, TILES: tl.constexpr, SLOTS: tl.constexpr, FIELDS: tl.constexpr, BLOCK: tl.constexpr): row, col, tile = tl.program_id(0), tl.program_id(1), tl.program_id(2) _, _, valid = _position(Records, Frame, Requested, Slots, Epochs, Live, row, col, SLOTS, FIELDS) if valid: + pos = row.to(tl.int64) * width + col ids = tile * BLOCK + tl.arange(0, BLOCK) - x = tl.load(Logits + (row * WIDTH + col) * V + ids, ids < V, other=-float("inf")).to(tl.float32) + x = tl.load(Logits + pos * V + ids, ids < V, other=-float("inf")).to(tl.float32) maximum = tl.max(x, 0) mass = tl.sum(tl.exp(x - tl.where(maximum == -float("inf"), 0., maximum)), 0) - index = (row * WIDTH + col) * TILES + tile + index = pos * TILES + tile tl.store(Stats + index * 2, maximum) tl.store(Stats + index * 2 + 1, mass) -@triton.jit +@triton.jit(do_not_specialize=["width"]) def _normalization(Records, Frame, Requested, Slots, Epochs, Live, Stats, Lse, - WIDTH: tl.constexpr, TILES: tl.constexpr, SLOTS: tl.constexpr, + width, TILES: tl.constexpr, SLOTS: tl.constexpr, FIELDS: tl.constexpr, BLOCK: tl.constexpr): row, col = tl.program_id(0), tl.program_id(1) _, _, valid = _position(Records, Frame, Requested, Slots, Epochs, Live, row, col, SLOTS, FIELDS) if valid: - base = (row * WIDTH + col) * TILES + pos = row.to(tl.int64) * width + col + base = pos * TILES tiles = tl.arange(0, BLOCK) maxima = tl.load(Stats + (base + tiles) * 2, tiles < TILES, other=-float("inf")) masses = tl.load(Stats + (base + tiles) * 2 + 1, tiles < TILES, other=0.) maximum = tl.max(maxima, 0) lse = maximum + tl.log(tl.sum(masses * tl.exp(maxima - maximum), 0)) - tl.store(Lse + row * WIDTH + col, lse) + tl.store(Lse + pos, lse) -@triton.jit +@triton.jit(do_not_specialize=["width"]) def _candidates(Logits, Records, Frame, Requested, Slots, Epochs, Live, Lse, Keys, - V: tl.constexpr, WIDTH: tl.constexpr, TILES: tl.constexpr, + V: tl.constexpr, width, TILES: tl.constexpr, SLOTS: tl.constexpr, FIELDS: tl.constexpr, BLOCK: tl.constexpr, CANDIDATES: tl.constexpr): row, col, tile = tl.program_id(0), tl.program_id(1), tl.program_id(2) _, _, valid = _position(Records, Frame, Requested, Slots, Epochs, Live, row, col, SLOTS, FIELDS) if valid: + pos = row.to(tl.int64) * width + col ids = tile * BLOCK + tl.arange(0, BLOCK) - x = tl.load(Logits + (row * WIDTH + col) * V + ids, ids < V, other=-float("inf")).to(tl.float32) - x -= tl.load(Lse + row * WIDTH + col) + x = tl.load(Logits + pos * V + ids, ids < V, other=-float("inf")).to(tl.float32) + x -= tl.load(Lse + pos) # Rank the reported FP32 values, including ties introduced by subtraction. keys = tl.sort(tl.where(ids < V, _sort_key(x, ids), 0), descending=True) - index = (row * WIDTH + col) * TILES + tile + index = pos * TILES + tile k = tl.arange(0, BLOCK) tl.store(Keys + index * CANDIDATES + k, keys, k < CANDIDATES) -@triton.jit +@triton.jit(do_not_specialize=["width"]) def _finish(Logits, Records, Frame, Requested, Slots, Epochs, Live, Lse, Keys, Output, TokenIds, Counts, - V: tl.constexpr, WIDTH: tl.constexpr, TILES: tl.constexpr, + V: tl.constexpr, width, TILES: tl.constexpr, SLOTS: tl.constexpr, FIELDS: tl.constexpr, BLOCK: tl.constexpr, CANDIDATES: tl.constexpr, TOP: tl.constexpr, IDS: tl.constexpr, OUTPUT_TOKENS: tl.constexpr, OUTPUT_FIELDS: tl.constexpr, PAIR_FIELDS: tl.constexpr): row, col = tl.program_id(0), tl.program_id(1) slot, token, valid = _position(Records, Frame, Requested, Slots, Epochs, Live, row, col, SLOTS, FIELDS) if valid: + pos = row.to(tl.int64) * width + col out = Output + ((tl.load(Frame) * SLOTS + slot) * OUTPUT_TOKENS + col) * OUTPUT_FIELDS - chosen = tl.load(Logits + (row * WIDTH + col) * V + token).to(tl.float32) - tl.load(Lse + row * WIDTH + col) + chosen = tl.load(Logits + pos * V + token).to(tl.float32) - tl.load(Lse + pos) tl.store(out, token.to(tl.int32)) tl.store(out + 1, chosen.to(tl.int32, bitcast=True)) count = tl.load(Counts + slot) if count > 0: selected = tl.arange(0, IDS) requested_ids = tl.load(TokenIds + slot * IDS + selected, selected < count, other=-1) - requested_values = tl.load(Logits + (row * WIDTH + col) * V + requested_ids, + requested_values = tl.load(Logits + pos * V + requested_ids, (selected < count) & (requested_ids >= 0) & (requested_ids < V), other=float("nan")).to(tl.float32) - requested_values -= tl.load(Lse + row * WIDTH + col) + requested_values -= tl.load(Lse + pos) tl.store(out + (1 + selected) * PAIR_FIELDS, requested_ids, selected < count) tl.store(out + (1 + selected) * PAIR_FIELDS + 1, requested_values.to(tl.int32, bitcast=True), selected < count) else: k = tl.arange(0, BLOCK) - keys = tl.load(Keys + (row * WIDTH + col) * TILES * CANDIDATES + k, k < TILES * CANDIDATES, other=0) + total: tl.constexpr = TILES * CANDIDATES + base = pos * total + keys = tl.load(Keys + base + k, k < total, other=0) keys = tl.sort(keys, descending=True) + if total > BLOCK: + step: tl.constexpr = BLOCK - CANDIDATES + for offset in range(BLOCK, total, step): + idx = offset + (k - CANDIDATES) + incoming = tl.load(Keys + base + idx, (k >= CANDIDATES) & (idx < total), other=0) + keys = tl.where(k < CANDIDATES, keys, incoming) + keys = tl.sort(keys, descending=True) ids, values = _sort_pair(keys) tl.store(out + (1 + k) * PAIR_FIELDS, ids, k < TOP) tl.store(out + (1 + k) * PAIR_FIELDS + 1, values.to(tl.int32, bitcast=True), k < TOP) @@ -144,6 +161,7 @@ def __init__(self, logits, completion, slots, epochs, live, frame): if not 1 <= width <= completion.token_capacity: raise ValueError("raw logprob width exceeds completion token capacity") tiles = triton.cdiv(vocab, _VOCAB_TILE) + merge_block = min(triton.next_power_of_2(tiles * _TILE_CANDIDATES), _MERGE_BLOCK) self.logits = logits self.row_inputs = (slots, epochs, live) self.layout = { @@ -162,8 +180,7 @@ def __init__(self, logits, completion, slots, epochs, live, frame): (_candidates, (*common, self.lse, self.keys, *dimensions, _VOCAB_TILE, _TILE_CANDIDATES), (batch, width, tiles), _REDUCTION_WARPS), (_finish, (*common, self.lse, self.keys, completion.logprobs, completion.token_ids, - completion.token_id_counts, *dimensions, - triton.next_power_of_2(tiles * _TILE_CANDIDATES), _TILE_CANDIDATES, + completion.token_id_counts, *dimensions, merge_block, _TILE_CANDIDATES, MAX_TOP_LOGPROBS, MAX_LOGPROB_TOKEN_IDS, completion.token_capacity, LOGPROB_FIELDS, LOGPROB_PAIR_FIELDS), (batch, width, 1), _MERGE_WARPS), ) diff --git a/tests/components/test_logprobs.py b/tests/components/test_logprobs.py new file mode 100644 index 000000000..dc6ff572e --- /dev/null +++ b/tests/components/test_logprobs.py @@ -0,0 +1,278 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""PreparedLogprobs preserves exact top-k tie ordering while sharing width-independent kernels.""" + +import os + +import pytest +import torch + +from ignition.components.completion import ( + CompletionOutputs, + EMITTED_COUNT_FIELD, + LOGPROB_PAIR_FIELDS, + MAX_TOP_LOGPROBS, + VECTOR_TOKENS_FIELD, +) +from ignition.components.logprobs import PreparedLogprobs, _MERGE_BLOCK, _finish + + +def _reference_logprobs(logits: torch.Tensor): + """Reference FP32 log-softmax and exact tie-broken top-20 (higher value, then smaller ID).""" + f = logits.float() + lse = torch.logsumexp(f, dim=-1, keepdim=True) + logp = f - lse + canonical = torch.where(logp == 0.0, torch.zeros_like(logp), logp) + vocab = canonical.shape[-1] + k = min(MAX_TOP_LOGPROBS, vocab) + # Stable descending sort preserves ascending token ID order on exact ties and handles +0.0/-inf. + order = torch.argsort(canonical, dim=-1, descending=True, stable=True)[..., :k] + top_ids = order.to(torch.int32) + top_vals = torch.gather(canonical, -1, order) + return logp, top_ids, top_vals + + +def _setup_completion(device, *, slots=4, token_capacity=6, frame_idx=1): + completion = CompletionOutputs.allocate((2, slots, VECTOR_TOKENS_FIELD + token_capacity), device=device) + completion.logprobs.fill_(-99) + frame = torch.tensor([frame_idx], dtype=torch.int32, device=device) + return completion, frame + + +def _unpack_top(out_row: torch.Tensor): + ids = out_row[2 : 2 + MAX_TOP_LOGPROBS * LOGPROB_PAIR_FIELDS : LOGPROB_PAIR_FIELDS] + vals = out_row[3 : 2 + MAX_TOP_LOGPROBS * LOGPROB_PAIR_FIELDS : LOGPROB_PAIR_FIELDS].view(torch.float32) + return ids, vals + + +@pytest.mark.parametrize("vocab,expected_block", [ + (1, 32), + (64, 32), + (1024, 32), + (1025, 64), + (16384, 512), + (16385, _MERGE_BLOCK), + (31744, _MERGE_BLOCK), + (262144, _MERGE_BLOCK), +]) +def test_finish_merge_block_is_bounded_for_large_vocabularies(vocab, expected_block): + completion, frame = _setup_completion("meta") + logits = torch.empty((2, 6, vocab), dtype=torch.bfloat16, device="meta") + slots = torch.empty((2,), dtype=torch.int32, device="meta") + epochs = torch.empty((2,), dtype=torch.int64, device="meta") + live = torch.empty((1,), dtype=torch.int32, device="meta") + op = PreparedLogprobs(logits, completion, slots, epochs, live, frame) + finish_args = dict(zip(_finish.arg_names, op._preparation[3][1], strict=True)) + assert finish_args["BLOCK"] == expected_block + + +@pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", reason="CUDA opt-in") +def test_logprobs_kernels_share_one_specialization_and_execute_across_widths(): + device = "cuda" + vocab = 262144 + max_width = 16 + completion, frame = _setup_completion(device, slots=4, token_capacity=max_width, frame_idx=0) + row_slots = torch.tensor([1, 3], dtype=torch.int32, device=device) + row_epochs = torch.tensor([4, 9], dtype=torch.int64, device=device) + live = torch.tensor([2], dtype=torch.int32, device=device) + completion.requested[1] = 1 + completion.requested[3] = 1 + completion.records[0, 1, 0] = 4 + completion.records[0, 3, 0] = 9 + + # Cover width=1 (equal_to_1), arbitrary widths, and width=16 (divisible_by_16) with batch=2 active rows. + hashes = [] + for width in (1, 2, 6, 16): + completion.logprobs.fill_(-99) + completion.records[0, 1, EMITTED_COUNT_FIELD] = width + completion.records[0, 3, EMITTED_COUNT_FIELD] = width + completion.records[0, 1, VECTOR_TOKENS_FIELD : VECTOR_TOKENS_FIELD + width] = torch.arange(width, device=device) + completion.records[0, 3, VECTOR_TOKENS_FIELD : VECTOR_TOKENS_FIELD + width] = torch.arange( + vocab - width, vocab, device=device + ) + torch.manual_seed(100 + width) + logits = torch.randn((2, width, vocab), dtype=torch.bfloat16, device=device) + # Distinct dominant peaks on row 0 vs row 1 to catch any width-stride bug at row > 0. + for col in range(width): + logits[0, col, col] = 12.0 + logits[1, col, vocab - 1 - col] = 12.0 + + op = PreparedLogprobs(logits, completion, row_slots, row_epochs, live, frame) + op.prepare() + hashes.append(( + op.statistics.compiled.hash, + op.normalization.compiled.hash, + op.candidates.compiled.hash, + op.finish.compiled.hash, + )) + op() + torch.cuda.synchronize() + + _, ref_ids, ref_vals = _reference_logprobs(logits) + for row, slot in ((0, 1), (1, 3)): + for col in range(width): + got_ids, got_vals = _unpack_top(completion.logprobs[0, slot, col]) + assert torch.equal(got_ids, ref_ids[row, col]) + assert torch.allclose(got_vals, ref_vals[row, col], atol=1e-5, rtol=0) + assert len(set(hashes)) == 1 + + +@pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", reason="CUDA opt-in") +@pytest.mark.parametrize("vocab", [1, 5, 19, 64, 1025, 16384, 16385, 31744, 248320, 262144]) +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float32]) +def test_chunked_finish_matches_exact_top20_tie_ordering_and_preserves_inactive_slots(vocab, dtype): + device = "cuda" + batch, width, slots_n = 3, 6, 4 + completion, frame = _setup_completion(device, slots=slots_n, token_capacity=width, frame_idx=1) + torch.manual_seed(vocab) + logits = torch.randn((batch, width, vocab), dtype=dtype, device=device) + + # Row 0 -> slot 2 (active, requested, 4 emitted tokens): plant > 32 exact ties spanning chunk 0, + # merge chunk boundaries (tiles 15/16 and 30/31), and the final tile so ties straddle rank 20. + tie_indices = set() + for base in (0, 1024, 15 * 1024, 16 * 1024, 30 * 1024, 31 * 1024, max(0, vocab - 40)): + for off in range(8): + idx = base + off + if idx < vocab: + tie_indices.add(idx) + tie_list = sorted(tie_indices) + for col in range(width): + for idx in tie_list: + logits[0, col, idx] = 9.0 + logits[0, col, vocab - 1] = 10.0 # single highest token in the very last tile + + # Row 2 -> slot 0 (active, requested, 3 emitted tokens): + # - col 0: top-20 tokens live exclusively in the final tile/chunk, displacing all earlier chunks. + # - col 1: dominant single finite logit with -inf elsewhere -> exact +0.0 logprob. + # - col 2: ordinary random distribution with row > 0 indexing. + tail_count = min(MAX_TOP_LOGPROBS, vocab) + for i in range(tail_count): + logits[2, 0, vocab - 1 - i] = 15.0 - 0.1 * i + logits[2, 1].fill_(float("-inf")) + logits[2, 1, vocab - 1] = 3.0 + + # Row 0 -> slot 2 (active), Row 1 -> slot 1 (unrequested, otherwise valid), Row 2 -> slot 0 (active). + row_slots = torch.tensor([2, 1, 0], dtype=torch.int32, device=device) + row_epochs = torch.tensor([7, 9, 11], dtype=torch.int64, device=device) + live = torch.tensor([3], dtype=torch.int32, device=device) + completion.requested[2] = 1 + completion.requested[0] = 1 + completion.records[1, 1, 0] = 9 + completion.records[1, 1, EMITTED_COUNT_FIELD] = 4 + completion.records[1, 1, VECTOR_TOKENS_FIELD : VECTOR_TOKENS_FIELD + 4] = 0 + completion.records[1, 2, 0] = 7 + completion.records[1, 2, EMITTED_COUNT_FIELD] = 4 + chosen_row0 = [0, min(17, vocab - 1), vocab // 2, vocab - 1] + for col, tok in enumerate(chosen_row0): + completion.records[1, 2, VECTOR_TOKENS_FIELD + col] = tok + + completion.records[1, 0, 0] = 11 + completion.records[1, 0, EMITTED_COUNT_FIELD] = 3 + chosen_row2 = [vocab - 1, vocab - 1, 0] + for col, tok in enumerate(chosen_row2): + completion.records[1, 0, VECTOR_TOKENS_FIELD + col] = tok + + op = PreparedLogprobs(logits, completion, row_slots, row_epochs, live, frame) + op.prepare() + op() + torch.cuda.synchronize() + + ref_logp, ref_ids, ref_vals = _reference_logprobs(logits) + k_valid = min(MAX_TOP_LOGPROBS, vocab) + for row, slot, chosen_list in ((0, 2, chosen_row0), (2, 0, chosen_row2)): + out = completion.logprobs[1, slot] + for col, tok in enumerate(chosen_list): + assert int(out[col, 0].item()) == tok + actual_chosen = out[col, 1:2].view(torch.float32).item() + expected_chosen = ref_logp[row, col, tok].item() + assert abs(actual_chosen - expected_chosen) <= 1e-5 + got_ids, got_vals = _unpack_top(out[col]) + assert torch.equal(got_ids[:k_valid], ref_ids[row, col]) + finite = torch.isfinite(ref_vals[row, col]) + assert torch.allclose(got_vals[:k_valid][finite], ref_vals[row, col][finite], atol=1e-5, rtol=0) + assert torch.equal(torch.isneginf(got_vals[:k_valid]), torch.isneginf(ref_vals[row, col])) + if k_valid < MAX_TOP_LOGPROBS: + assert torch.all(got_ids[k_valid:] == -1) + assert torch.all(torch.isnan(got_vals[k_valid:])) + # Unemitted trailing columns stay untouched. + assert torch.all(out[len(chosen_list) :] == -99) + + # Dominant single-finite logit (row 2 -> slot 0, col 1) packs canonical +0.0 bits (0x00000000). + assert int(completion.logprobs[1, 0, 1, 3].item()) == 0 + # Unrequested slot, unused slot, and inactive frame stay untouched. + assert torch.all(completion.logprobs[1, 1] == -99) + assert torch.all(completion.logprobs[1, 3] == -99) + assert torch.all(completion.logprobs[0] == -99) + + +@pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", reason="CUDA opt-in") +def test_logprobs_requested_token_ids_gating_and_functional_graph_capture(): + device = "cuda" + batch, width, vocab = 4, 4, 248320 + completion, frame = _setup_completion(device, slots=4, token_capacity=width, frame_idx=0) + torch.manual_seed(42) + logits = torch.randn((batch, width, vocab), dtype=torch.bfloat16, device=device) + + # Row 0 -> slot 0 (top-k); Row 1 -> slot 3 (requested IDs); Row 2 -> slot 2 (stale epoch); + # Row 3 -> slot 1 (row >= live). + row_slots = torch.tensor([0, 3, 2, 1], dtype=torch.int32, device=device) + row_epochs = torch.tensor([3, 5, 99, 1], dtype=torch.int64, device=device) + live = torch.tensor([3], dtype=torch.int32, device=device) + for slot in range(4): + completion.requested[slot] = 1 + completion.records[0, 0, 0] = 3 + completion.records[0, 0, EMITTED_COUNT_FIELD] = 2 + completion.records[0, 0, VECTOR_TOKENS_FIELD : VECTOR_TOKENS_FIELD + 2] = torch.tensor([5, vocab - 1], device=device) + completion.records[0, 3, 0] = 5 + completion.records[0, 3, EMITTED_COUNT_FIELD] = 3 + completion.records[0, 3, VECTOR_TOKENS_FIELD : VECTOR_TOKENS_FIELD + 3] = torch.tensor([1, 2, 3], device=device) + completion.records[0, 2, 0] = 77 # mismatch with row_epochs[2] == 99 + completion.records[0, 2, EMITTED_COUNT_FIELD] = 2 + completion.records[0, 1, 0] = 1 + completion.records[0, 1, EMITTED_COUNT_FIELD] = 2 + + req_ids = [0, vocab // 2, vocab - 1, -5, vocab + 7] + completion.token_id_counts[3] = len(req_ids) + completion.token_ids[3, : len(req_ids)] = torch.tensor(req_ids, dtype=torch.int32, device=device) + + op = PreparedLogprobs(logits, completion, row_slots, row_epochs, live, frame) + op.prepare() + op.functional(dynamic_inputs=True) + + # Synchronize setup stream before warmup and graph capture on a side stream. + stream = torch.cuda.Stream(device=device) + stream.wait_stream(torch.cuda.current_stream(device=device)) + with torch.cuda.stream(stream): + op.run(logits, slots=row_slots, generations=row_epochs, live_rows=live) + stream.synchronize() + + completion.logprobs.fill_(-99) + stream.wait_stream(torch.cuda.current_stream(device=device)) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + op.run(logits, slots=row_slots, generations=row_epochs, live_rows=live) + graph.replay() + stream.synchronize() + + ref_logp, ref_ids, ref_vals = _reference_logprobs(logits) + out0 = completion.logprobs[0, 0] + for col in range(2): + got_ids, got_vals = _unpack_top(out0[col]) + assert torch.equal(got_ids, ref_ids[0, col]) + assert torch.allclose(got_vals, ref_vals[0, col], atol=1e-5, rtol=0) + + out3 = completion.logprobs[0, 3] + for col in range(3): + for i, tid in enumerate(req_ids): + assert int(out3[col, (1 + i) * LOGPROB_PAIR_FIELDS].item()) == tid + val = out3[col, (1 + i) * LOGPROB_PAIR_FIELDS + 1 : (1 + i) * LOGPROB_PAIR_FIELDS + 2].view(torch.float32).item() + if 0 <= tid < vocab: + assert abs(val - ref_logp[1, col, tid].item()) <= 1e-5 + else: + assert val != val # NaN for negative or out-of-range requested token ID + + # Stale epoch (slot 2) and row >= live (slot 1) must not mutate output. + assert torch.all(completion.logprobs[0, 2] == -99) + assert torch.all(completion.logprobs[0, 1] == -99) From 3ac58fea7a5fdaeeac477235209b6d6515dba921 Mon Sep 17 00:00:00 2001 From: kbenkhaled Date: Thu, 3 Dec 2026 17:10:26 +0000 Subject: [PATCH 2/2] Drop tautological module assert and match _finish by kernel in test ignition/components/logprobs.py checked two adjacent module-level integer literals (_MERGE_BLOCK = 512 and _TILE_CANDIDATES = 32) with a top-level assert, and tests/components/test_logprobs.py indexed _finish out of op._preparation by hardcoded position [3]. Changes: - ignition/components/logprobs.py: remove the module-level assert on _MERGE_BLOCK and _TILE_CANDIDATES. - tests/components/test_logprobs.py: select _finish arguments by matching `kernel is _finish` instead of hardcoded tuple index `[3]`. Result: removes dead module-import assertion and decouples the unit test from preparation tuple ordering, with zero runtime behavior change. Validation (Jetson Thor SM110, hf-thor-v2b container): - FLARE_RUN_CUDA_TESTS=1 pytest -q tests/components/test_logprobs.py tests/components/test_completion_outputs.py tests/components/test_completion_capacity.py: 87 passed, 0 failed. - Before (1fbcc3c9) vs after CUDA-graph overhead (median on-minus-base across 3 alternating trials, BF16, width in {1, 6}, rows in {1, 8, 16}): - V=16,384 (8 -> 4 warps, same BLOCK=512): 1.00x-1.01x across all 6 shapes (e.g. w=1,r=1: 15.2 -> 15.0 us; w=6,r=16: 303.4 -> 303.8 us). - V=32,768: 22.4 -> 24.3 us (w=1,r=1); 50.7 -> 53.1 us (w=6,r=1); 600.7 -> 606.7 us (w=6,r=16, 0.99x). - V=131,072: 1.02x-1.25x faster across all 6 shapes (w=1,r=1: 71.8 -> 57.3 us; w=6,r=1: 190.9 -> 176.3 us; w=6,r=16: 2429 -> 2370 us). - V=248,320: 1.07x-1.49x faster across all 6 shapes (w=1,r=1: 148.9 -> 100.0 us; w=6,r=1: 374.7 -> 322.4 us; w=6,r=16: 5056 -> 4519 us). - V=262,144: 1.06x-1.47x faster across all 6 shapes (w=1,r=1: 149.1 -> 101.2 us; w=6,r=1: 388.4 -> 339.1 us; w=6,r=16: 5278 -> 4766 us). Limitations: SM103/SM120/SM121 GPUs and end-to-end served throughput were not measured on this commit. Design-Signed-Off-By: Gemini 4 Neon; design-review=2e5b Signed-off-by: kbenkhaled --- ignition/components/logprobs.py | 1 - tests/components/test_logprobs.py | 6 +++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/ignition/components/logprobs.py b/ignition/components/logprobs.py index 03a1990e5..3aca7de4f 100644 --- a/ignition/components/logprobs.py +++ b/ignition/components/logprobs.py @@ -21,7 +21,6 @@ # Merge per-tile candidates in bounded chunks so large vocabularies (e.g. 256k -> 8192 keys) # do not unroll an 8192-element bitonic network in Triton/PTX while keeping bit-exact ordering. _MERGE_BLOCK = 512 -assert _MERGE_BLOCK > _TILE_CANDIDATES and (_MERGE_BLOCK & (_MERGE_BLOCK - 1)) == 0 _REDUCTION_WARPS = 4 _MERGE_WARPS = 4 diff --git a/tests/components/test_logprobs.py b/tests/components/test_logprobs.py index dc6ff572e..f2c8be56b 100644 --- a/tests/components/test_logprobs.py +++ b/tests/components/test_logprobs.py @@ -64,7 +64,11 @@ def test_finish_merge_block_is_bounded_for_large_vocabularies(vocab, expected_bl epochs = torch.empty((2,), dtype=torch.int64, device="meta") live = torch.empty((1,), dtype=torch.int32, device="meta") op = PreparedLogprobs(logits, completion, slots, epochs, live, frame) - finish_args = dict(zip(_finish.arg_names, op._preparation[3][1], strict=True)) + finish_args = dict(zip( + _finish.arg_names, + next(args for kernel, args, *_ in op._preparation if kernel is _finish), + strict=True, + )) assert finish_args["BLOCK"] == expected_block