diff --git a/ignition/components/logprobs.py b/ignition/components/logprobs.py index 7efbcb03e..3aca7de4f 100644 --- a/ignition/components/logprobs.py +++ b/ignition/components/logprobs.py @@ -18,8 +18,11 @@ _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 _REDUCTION_WARPS = 4 -_MERGE_WARPS = 8 +_MERGE_WARPS = 4 @triton.jit @@ -52,82 +55,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 +160,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 +179,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..f2c8be56b --- /dev/null +++ b/tests/components/test_logprobs.py @@ -0,0 +1,282 @@ +# 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, + next(args for kernel, args, *_ in op._preparation if kernel is _finish), + 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)