mirror of
https://github.com/lightseekorg/tokenspeed.git
synced 2026-12-04 10:26:50 +08:00
feat(sampling): vendor sonic-sampler's kernels as the sonic backend (#3200)
## Summary Brings back the `sonic` sampling backend from #1506, with sonic-sampler's Triton kernels vendored in `tokenspeed-kernel` instead of imported as a package. - **Kernels only.** `tokenspeed_kernel/thirdparty/sonic_sampler` holds the kernels of sonic-sampler 1.0.0 plus the two commits on [LorrinWWW/sonic-sampler@tokenspeed](https://github.com/LorrinWWW/sonic-sampler/tree/tokenspeed) (runtime batch size, in-kernel Philox noise), compiled by `tokenspeed-triton`, and the `Indicator` bit layout. sonic's msgspec host layer, class-based interfaces, packaged dispatch tables and per-slot noise planes are not vendored; `tokenspeed_kernel.ops.sampling.sonic` launches the kernels over plain slot tensors (`SlotState`, `sample`, `verify`). The vendored README lists every local change. `tokenspeed-kernel` gains no dependency. The kernels keep row offsets into the logits in int32, so launches and backends past 2³¹ elements are refused on the host. - **No startup tuning.** sonic's speed depends on its vocab tile, top-k strategy and warps. Its config comes from a table keyed by vocabulary size class and logits rows (`pick`), measured on GB200 over 13 vocabularies (32k to 262k), 1 to 512 rows, plain decode and three-draft verify, 60 configs each: the picks run within 8% of the best config at every point (0.3% on average) and 3.6x to 11x faster than the `flashinfer` backend's per-step call. Every config draws the same tokens, so the table changes speed only. - **Exact fp32 logits.** Soft-capped heads (Beam) emit fp32 logits. bf16 keys only pick each row's top-128 candidates; the selection and verify kernels re-read their fp32 values and apply fp32 temperature, top-p, min-p and penalties before the draw, and greedy is the first exact fp32 maximum. bf16 logits draw bit-identically to the bf16-only kernels. - **Fixes over #1506.** `verify(N=1)` refills its accept lengths every call (the runtime's stop conditions cut them in place, and a stale zero ended later requests with no token). Warm-up also compiles the offset slot pointers of mixed rounds and the int64 sampling offsets, so no sonic kernel compiles while serving. Behaviour differences from `flashinfer`: `top_k=-1` is bounded top-128 truncation; bf16 logits rank at bf16 resolution (greedy within one bf16 ulp of the maximum); logit bias is stored in bf16; repetition penalties count generated tokens only. NVIDIA only: the kernels call NVIDIA's libdevice `fast_logf`, which the HIP libdevice lacks, so the registry imports sonic and its tests run only on NVIDIA. Not supported yet: vocab-sharded sampling (TP gathers full rows, as with `flashinfer`), `--enable-speculative-sampling`, draft trees, DP sampling, top-k output logprobs. ## Benchmarks All on GB200. Per step, sonic's sampling call is 4x to 10x faster than `flashinfer`'s; end to end that is about 2% TPOT at 64 concurrent requests and 1% to 5% at 16 on Qwen3-8B and Beam, where sampling is a small share of the step. ### Standalone: one sampling step Each backend's real per-step call, captured in CUDA graphs, at temperature 0.7 and top-p 0.95: `verify` with one token per request (plain decode) or four (three drafts); sonic runs its table's pick. Time per step in µs, sonic / `flashinfer` (speedup). Plain decode, bf16 logits: | Vocabulary | 1 request | 16 | 64 | 256 | 512 | |---|---|---|---|---|---| | 32,000 (Llama 2) | 11 / 54 (4.8x) | 12 / 66 (5.6x) | 17 / 83 (4.9x) | 34 / 193 (5.6x) | 61 / 313 (5.1x) | | 128,256 (Llama 3) | 14 / 97 (7.1x) | 18 / 131 (7.3x) | 36 / 204 (5.6x) | 108 / 550 (5.1x) | 205 / 974 (4.7x) | | 151,936 (Qwen3, Beam) | 15 / 104 (7.0x) | 22 / 148 (6.7x) | 43 / 236 (5.5x) | 137 / 641 (4.7x) | 263 / 1146 (4.3x) | | 201,088 (gpt-oss) | 15 / 132 (9.0x) | 26 / 186 (7.0x) | 55 / 303 (5.5x) | 172 / 829 (4.8x) | 334 / 1498 (4.5x) | | 262,144 | 16 / 167 (10.6x) | 29 / 227 (7.8x) | 68 / 381 (5.6x) | 222 / 1053 (4.7x) | 431 / 1913 (4.4x) | Three-draft verify, bf16 logits: | Vocabulary | 1 request | 16 | 64 | 128 | |---|---|---|---|---| | 32,000 (Llama 2) | 16 / 59 (3.6x) | 23 / 84 (3.7x) | 40 / 183 (4.5x) | 68 / 279 (4.1x) | | 128,256 (Llama 3) | 19 / 107 (5.6x) | 43 / 201 (4.6x) | 116 / 504 (4.4x) | 215 / 854 (4.0x) | | 151,936 (Qwen3, Beam) | 20 / 111 (5.5x) | 50 / 232 (4.6x) | 146 / 583 (4.0x) | 275 / 1000 (3.6x) | | 201,088 (gpt-oss) | 22 / 143 (6.6x) | 62 / 301 (4.8x) | 184 / 746 (4.1x) | 349 / 1298 (3.7x) | | 262,144 | 21 / 179 (8.4x) | 72 / 383 (5.3x) | 225 / 943 (4.2x) | 432 / 1659 (3.8x) | Exact fp32 logits cost 0% to 10% over bf16 (151,936 vocabulary, µs): | Requests | sonic bf16 | sonic fp32 | `flashinfer` fp32 | |---|---|---|---| | 1 | 15.0 | 16.2 | 105 | | 16 | 21.8 | 23.4 | 145 | | 64 | 43.0 | 47.0 | 239 | | 512 | 263 | 262 | 1164 | | 64, three drafts | 146 | 154 | 588 | The config table's picks land within 7.3% of the best of 60 configs at every point measured (13 vocabularies from 32k to 262k, 1 to 512 rows, plain and three-draft), 0.3% on average. On all-greedy batches the `greedy` backend's single argmax stays fastest at large batches (sonic is 1.2x to 2.2x slower there, e.g. 64 vs 45 µs at 512 Qwen3 requests) and ties it at small ones; both are 10x to 20x faster than `flashinfer`. ### End to end 1024 input and 1024 output tokens per request, random prompts. Qwen3-8B, TP1, bf16 logits; two rounds with the GPUs swapped: | | `flashinfer` | sonic | |---|---|---| | TPOT at 64 concurrent (ms) | 6.51, 6.16, 6.49, 6.17 | 6.38, 6.06, 6.39, 6.05 | | Output tok/s at 64 concurrent | 9241, 8957, 9269, 9145 | 9411, 9278, 9389, 9254 | | TPOT at 16 concurrent (ms) | 3.89, 3.92 | 3.87, 3.84 | | GSM8K (1319, temperature 0.6, top-p 0.95) | 92.8 | 93.0 | | Greedy outputs (4 prompts) | | identical | Beam (501B-A23B NVFP4), TP4, fp32 soft-capped logits; two rounds and a rerun after the fixes: | | `flashinfer` | sonic | |---|---|---| | TPOT at 64 concurrent (ms) | 10.27, 10.25, 10.48, 10.32 | 10.15, 10.03, 10.09, 9.98, 10.04 | | Output tok/s at 64 concurrent | 5962, 6035, 5893, 5992 | 6132, 6142, 6149, 6176, 6142 | | TPOT at 16 concurrent (ms) | 6.27, 6.22 | 5.96, 6.09, 6.05 | | GSM8K (1319, Beam's eval sampling) | 97.0 | 97.1 | | Greedy outputs (4 prompts) | | identical | Sonic's first Beam run is left out: it hit a one-time 4 s Triton compile (the offset slot pointer of mixed rounds), which warm-up now covers. ## Test Plan All on GB200. - [x] pre-commit on the changed files; `test_sonic_vendor.py` (15), `test_sonic_backend.py` (46, including fp32 greedy near-ties, fp32 sampled and verified distributions against the exact softmax, penalties, config independence for both dtypes, no Triton compile after warm-up), `test_slot_state.py` (46, now including sonic), `test_cli_config_compat.py` (58). - [x] bf16 and fp32 draws bit-identical across the launcher rewrite (24/24 launches each, mixed greedy, top-p, top-k/min-p and penalised requests, with and without drafts). - [x] Config sweep vs `flashinfer` (above). - [x] Qwen3-8B TP1 vs `flashinfer`, two rounds with GPUs swapped: c64 TPOT 6.38/6.06 and 6.39/6.05 ms vs 6.51/6.16 and 6.49/6.17; c16 3.87/3.84 vs 3.89/3.92; GSM8K 93.0 vs 92.8; greedy outputs 4/4 identical. - [x] Beam TP4 (fp32 logits) vs `flashinfer`, two rounds: c64 TPOT 10.15 (round 1's first run hit the since-fixed serve-time compile), 10.03/10.09 ms vs 10.27/10.25, 10.48/10.32; c16 5.96/6.09 vs 6.27/6.22; GSM8K 97.1 vs 97.0; greedy outputs 4/4 identical in both rounds; no sonic kernel compiled while serving. - [x] After rebasing on main: pre-commit, the tests above and `test_sampling_backend_registry.py` pass; Qwen3-8B (c64 TPOT 6.38/6.03 ms) and Beam (10.19/10.00 ms) greedy outputs 4/4 identical to `flashinfer`, no sonic kernel compiled while serving. - [x] After the review fixes: bf16 and fp32 draws bit-identical to the previous head (24/24 launches each); Qwen3-8B (c64 TPOT 6.38/6.05 ms) and Beam (10.24/9.91 ms) greedy outputs 4/4 identical to `flashinfer`, no sonic kernel compiled while serving. - [x] sonic imported and tested on NVIDIA only: the sonic backend (46), registry, slot-state and CLI (108) tests pass. --------- Signed-off-by: Nicolas <nperrin.ai@gmail.com>
This commit is contained in:
@@ -547,7 +547,7 @@ for the online variant.
|
||||
| `--draft-moe-backend` | MoE backend for the speculative decoding draft model. |
|
||||
| `--all2all-backend` | MoE all-to-all backend. |
|
||||
| `--deepep-mode` | DeepEP mode: `auto`, `normal`, or `low_latency`. `auto` uses `low_latency` for decode batches and `normal` for prefill batches. `normal` reads its per-expert receive counts on the host, so it forces eager execution and disables CUDA graphs. |
|
||||
| `--sampling-backend` | Sampling backend: `greedy`, `flashinfer`, `flashinfer_full`, `triton`, or `triton_full`. |
|
||||
| `--sampling-backend` | Sampling backend: `greedy`, `flashinfer`, `flashinfer_full`, `triton`, `triton_full`, or `sonic` (vendored [sonic-sampler](https://github.com/tachyontrails/sonic-sampler) kernels: one fused Triton pipeline per step; `top_k=-1` is realized as bounded top-128 truncation; bf16 logits ranked at bf16 resolution, fp32 logits sampled exactly among the top-128 candidates; kernel configs from a table measured on Blackwell, no startup tuning; see the `--sampling-backend` help for its memory cost). |
|
||||
| `--disable-deepseek-v41-token-blacklist` | Allow DeepSeek V4.1 to generate BOS, PAD, and image control/placeholder token IDs `0, 2, 129262..129264`; these are masked by default. |
|
||||
|
||||
Set backend choices explicitly in production. `auto` is useful for bring-up, but
|
||||
|
||||
@@ -1041,7 +1041,10 @@ Greedy requests normalize to `top_k=1` in `SamplingParams.__post_init__`; the
|
||||
pool-indexed sampling route serves them, which is exactly what the captured
|
||||
graph records. `SamplingBatchInfo.is_all_greedy` and the eager-only argmax
|
||||
branches were deleted. Equivalence (top_k=1 == argmax, ties excepted) is
|
||||
pinned by `test/runtime/sampling/test_greedy_route_equivalence.py`.
|
||||
pinned by `test/runtime/sampling/test_greedy_route_equivalence.py` (for
|
||||
`sonic`, whose kernels rank candidates at bf16 resolution -- a penalized
|
||||
greedy pick lies within one bf16 ulp of the maximum -- and realize `top_k=-1`
|
||||
as bounded top-128 truncation, by `test_sonic_backend.py`).
|
||||
|
||||
Admission uses the selected sampling backend's finite top-k bound. GPU
|
||||
backends retain the exclusive 128 bound. `ascend_full` accepts positive
|
||||
@@ -1082,8 +1085,11 @@ window that accepts nothing and resolves to exactly one sampled token
|
||||
through the same pool kernels, `accept_length == 1`
|
||||
(`test_decode_verify_n1_equivalence.py`; Triton and FlashInfer's
|
||||
`per-request` stream use the same draw in `sample()` and `verify(N=1)`;
|
||||
FlashInfer's legacy `batch` stream retains the coin route). `future_input_map` is `[pool, output_length]` for
|
||||
the same reason: single-token decode is a width-1 candidate window.
|
||||
FlashInfer's legacy `batch` stream retains the coin route; `sonic` resolves
|
||||
the width-1 window through its single-step kernel, bitwise equal to
|
||||
`sample()`, pinned by `test_sonic_backend.py`). `future_input_map` is
|
||||
`[pool, output_length]` for the same reason: single-token decode is a width-1
|
||||
candidate window.
|
||||
|
||||
Backends express verify geometry as a **floor**, not a mode: seq_lens clamp
|
||||
to `clamp_min(q_len)` unconditionally (drafts and plain decode have floor 1,
|
||||
@@ -1187,8 +1193,11 @@ the contract: ordering, masking, supported configurations and cost.
|
||||
persistent output buffers, on eager and replay alike. The FlashInfer backend
|
||||
packs tokens and accept lengths into one region (`_output_pack_buf`), so its
|
||||
`get_packed_output_d2h` collapses the two device-to-host copies into one; the
|
||||
Triton backends return separate token and length buffers and take the
|
||||
executor's two-copy path (`get_packed_output_d2h` returns None).
|
||||
Triton backends and `sonic` return separate token and length buffers and
|
||||
take the executor's two-copy path (`get_packed_output_d2h` returns None).
|
||||
The stop conditions cut the returned accept lengths in place (0 for a stopped
|
||||
request), so a backend whose decode rows return a buffer of ones refills it on
|
||||
every call, as `sonic` and FlashInfer do.
|
||||
|
||||
### Logits capture state follows the tensor's device
|
||||
|
||||
|
||||
@@ -0,0 +1,686 @@
|
||||
# Copyright (c) 2026 LightSeek Foundation
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
|
||||
"""Sonic Sampler backend — fused single-step sampling + chain verification.
|
||||
|
||||
One fused Triton pipeline (`sample`, two kernels; `verify`, three, for
|
||||
spec-decode) handles a mixed batch (greedy + temperature/top_k/top_p/min_p
|
||||
+ penalties + grammar) selected per row by an `Indicator` bitfield — no separate
|
||||
greedy path or per-mode graph.
|
||||
|
||||
Buffers are either **slot-indexed** per-request state (indicator bits, scalars,
|
||||
grammar, counts, bias) in one ``SlotState`` sized to ``max_req_pool_size + 1``
|
||||
and gathered at ``slot_mapping[row]`` (= ``req_pool_indices``), written on the
|
||||
device once in ``_reset_slot``; or **batch-indexed**
|
||||
I/O sized to max batch (scratchpad keys, verify's candidate values/indices).
|
||||
Noise is drawn inside sonic's kernels from Philox keyed by the slot's seed
|
||||
and the absolute position of the token drawn (``_prepare_sampling_offsets``),
|
||||
at the candidates the kernels actually read: no noise plane, no per-step
|
||||
refresh, draws that depend only on the request, and every TP rank drawing the
|
||||
same. The slot rows are part of the retraction image (``slot_state_rows``).
|
||||
|
||||
The runtime's unified sampling rule routes every decode row through
|
||||
``verify()`` — non-speculative serving is its ``N == 1`` case (a one-column
|
||||
candidate window with nothing to accept). ``verify`` needs a lookahead
|
||||
of at least one, so that case resolves through ``sample``: the same
|
||||
kernel ``sample()`` uses, reading the same slot state and noise, so the two
|
||||
paths are bitwise identical (pinned by ``test_sonic_backend.py``).
|
||||
|
||||
Not yet supported: DP-sampling, draft trees, top-k output logprobs, EAGLE3
|
||||
``d2t`` cross-vocab.
|
||||
|
||||
The kernels and indicator bits are sonic-sampler's, vendored in
|
||||
``tokenspeed_kernel.thirdparty.sonic_sampler``; ``tokenspeed_kernel.ops.sampling.sonic``
|
||||
launches them and picks their config per launch from a table (``pick``);
|
||||
nothing tunes at startup.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
from tokenspeed_kernel.ops.sampling import sonic
|
||||
from tokenspeed_kernel.ops.sampling.sonic import (
|
||||
MAX_K,
|
||||
MAX_OFFSET,
|
||||
Indicator,
|
||||
SlotState,
|
||||
SonicConfig,
|
||||
pick,
|
||||
scratchpad_columns,
|
||||
)
|
||||
from tokenspeed_kernel.platform import pdl_enabled
|
||||
from typing_extensions import override
|
||||
|
||||
from tokenspeed.runtime.sampling.backends.base import (
|
||||
SamplingBackend,
|
||||
SamplingBackendConfig,
|
||||
)
|
||||
from tokenspeed.runtime.sampling.registry import register_backend
|
||||
from tokenspeed.runtime.sampling.sampling_params import _SAMPLING_EPS, SamplingParams
|
||||
from tokenspeed.runtime.sampling.utils import gather_token_logprobs_torch
|
||||
from tokenspeed.runtime.utils.nvtx import nvtx_range
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
from tokenspeed.runtime.layers.logits_processor import LogitsProcessorOutput
|
||||
from tokenspeed.runtime.sampling.sampling_batch_info import SamplingBatchInfo
|
||||
from tokenspeed.runtime.sampling.tree_verify import TreeVerifyBatch
|
||||
|
||||
|
||||
# Logits sonic ranks: bf16, or fp32 (soft-capped heads) sampled exactly at the candidates bf16 keys pick.
|
||||
_LOGITS_DTYPES = (torch.bfloat16, torch.float32)
|
||||
|
||||
# Never-admitted slots' fp32 temperature, top-p, min-p, repetition, frequency and presence.
|
||||
_EXACT_DEFAULTS = (1.0, 1.0, 0.0, 1.0, 0.0, 0.0)
|
||||
|
||||
|
||||
def _sanitize(sp: SamplingParams) -> tuple[float, int, float, float]:
|
||||
"""Sanitize a request's ``(temperature, top_k, top_p, min_p)`` for sonic.
|
||||
|
||||
``_reset_slot`` derives the ``Indicator`` bits from the same values it writes
|
||||
into the slot state (``Indicator.from_params`` tests them exactly), so
|
||||
sanitizing here keeps every bit agreeing with what the kernel reads:
|
||||
epsilon-neutral temperature stays ``1.0`` (bit off — skips a wasted
|
||||
``logits / t`` vocab pass), and ``top_k`` is capped at MAX_K so the ``-1``
|
||||
"disabled" sentinel lands on the bounded top-MAX_K path (bit off). The
|
||||
greedy early return also pins temperature to 1.0, so the slot's indicator
|
||||
is exactly ``GREEDY`` and the kernel skips the temperature pass. ``min_p =
|
||||
1.0`` is remapped to 0.999 because ``from_params`` tests the open interval
|
||||
(1.0 would drop the MIN_P bit); the bf16 buffer rounds it back to 1.0
|
||||
and ``_reset_slot`` stores 1.0 in the fp32 row, whose pivot = max keeps
|
||||
only max-probability tokens, as requested."""
|
||||
|
||||
if sp.top_k == 1: # TokenSpeed's greedy encoding
|
||||
|
||||
return 1.0, 1, 1.0, 0.0
|
||||
|
||||
temperature = 1.0
|
||||
|
||||
if abs(sp.temperature - 1.0) > _SAMPLING_EPS:
|
||||
|
||||
temperature = float(sp.temperature)
|
||||
|
||||
min_p = float(sp.min_p)
|
||||
|
||||
if min_p >= 1.0:
|
||||
|
||||
min_p = 0.999
|
||||
|
||||
return temperature, min(int(sp.top_k), MAX_K), float(sp.top_p), min_p
|
||||
|
||||
|
||||
class SonicSamplingBackend(SamplingBackend):
|
||||
"""Fused sampling + chain verification via sonic-sampler. Mixed greedy /
|
||||
temperature / top_k / top_p / min_p in one pipeline; ``top_k`` bounded by
|
||||
``MAX_K = 128``. Per-request state is slot-indexed by ``req_pool_indices``,
|
||||
written once at admission.
|
||||
|
||||
top_k semantics: finite ``top_k >= 128`` never reaches the backend —
|
||||
``SamplingParams.verify()`` rejects it at request time (same limit as the
|
||||
flashinfer fused kernel). ``top_k = -1`` (full vocab) arrives as the
|
||||
``_TOP_K_DISABLED`` sentinel and is realized as **bounded top-128
|
||||
truncation**: the kernel's bit-packed reduction keeps only the top-128
|
||||
candidates per row, so mass beyond them is dropped (negligible for the
|
||||
peaked distributions a model emits at temperature <= 1, but significant on
|
||||
flat ones or at high temperature). flashinfer's ``-1``
|
||||
samples the full vocab; this is the one distribution difference the
|
||||
backend chooses. Inherited from sonic's 16-bit packed ranking: bf16 logits'
|
||||
candidates are compared at bf16 resolution (temperature, penalties and
|
||||
logit bias are applied in bf16, and the scaled logits are re-rounded), so
|
||||
where the fp32 backends separate near-tied tokens sonic's greedy pick is
|
||||
only guaranteed to lie within one bf16 ulp of the maximum (pinned by
|
||||
``test_sonic_backend.py``); temperature/top_p/min_p are stored in bf16 too.
|
||||
fp32 logits (soft-capped heads) are sampled exactly: their bf16 keys only
|
||||
pick the top-128 candidates, whose fp32 values are re-read and given fp32
|
||||
temperature, top_p, min_p and penalties (logit bias stays bf16), and
|
||||
greedy is the first exact fp32 maximum. Under TP, decode counts for
|
||||
penalties accumulate in-kernel from each rank's own draw, before the
|
||||
rank-0 broadcast that decides the emitted token.
|
||||
|
||||
Requires bf16 or fp32 logits and ``vocab_size >= 512`` (its top-k
|
||||
reduction's minimum)."""
|
||||
|
||||
_HAS_POOL_STATE = True
|
||||
_SUPPORTS_DP_VERIFY = False
|
||||
|
||||
# Prompt token counts the runtime never fills: every slot reads zeros.
|
||||
constant_slot_state = ("state.context_counts", "_exact_state.context_counts")
|
||||
|
||||
@override
|
||||
def __init__(self, config: SamplingBackendConfig) -> None:
|
||||
|
||||
super().__init__(config)
|
||||
|
||||
if config.vocab_size < 512:
|
||||
|
||||
raise ValueError(
|
||||
f"SonicSamplingBackend requires config.vocab_size >= 512, got "
|
||||
f"{config.vocab_size} (sonic's top-k reduction minimum)"
|
||||
)
|
||||
|
||||
if config.device is None:
|
||||
|
||||
raise ValueError("SonicSamplingBackend requires config.device")
|
||||
|
||||
self.vocab_size = int(config.vocab_size)
|
||||
self.max_bs = int(config.max_bs)
|
||||
self.device = config.device
|
||||
|
||||
# n_max = γ+1 under spec-decode, else 1; drives the verify timestep dim.
|
||||
self.n_max = max(1, int(config.max_draft_tokens_per_req))
|
||||
self.gamma = self.n_max - 1
|
||||
self.spec = self.n_max > 1
|
||||
|
||||
# Slot-indexed state, +1 for the padding sentinel; timesteps=n_max serves sample and verify.
|
||||
self.pool_rows = config.max_req_pool_size + 1
|
||||
|
||||
# The kernels' row offsets are int32; the largest launch must fit (``sonic.sample`` checks each).
|
||||
if self.max_bs * self.n_max * self.vocab_size > MAX_OFFSET:
|
||||
|
||||
raise ValueError(
|
||||
f"SonicSamplingBackend needs max_bs * draft tokens * vocab_size <= "
|
||||
f"{MAX_OFFSET}, got {self.max_bs} * {self.n_max} * {self.vocab_size}"
|
||||
)
|
||||
|
||||
rows = self.max_bs * self.n_max
|
||||
|
||||
with torch.device(self.device):
|
||||
|
||||
# Batch-indexed working space, persistent (captured kernel never allocs).
|
||||
self.scratchpad = torch.empty(
|
||||
(rows, scratchpad_columns(self.vocab_size)), dtype=torch.uint32
|
||||
)
|
||||
self.out_tok = torch.empty((self.max_bs, 1), dtype=torch.int32)
|
||||
self.lengths_buf = torch.ones((self.max_bs,), dtype=torch.int32)
|
||||
|
||||
if self.spec:
|
||||
|
||||
# verify() drafted-tokens I/O and candidate scratch; see ``_fused_multistep``.
|
||||
self.v_drafted = torch.empty(self.max_bs, self.n_max, dtype=torch.int32)
|
||||
self.v_accepted = torch.empty((self.max_bs, 1), dtype=torch.int32)
|
||||
self.accept_buf = torch.empty((self.max_bs,), dtype=torch.int32)
|
||||
self.values = torch.empty((rows, MAX_K), dtype=torch.float32)
|
||||
self.indices = torch.empty((rows, MAX_K), dtype=torch.int32)
|
||||
|
||||
# fp32 temperature, top-p, min-p and penalties, read with fp32 logits so none rounds to bf16.
|
||||
self.exact_scalars = (
|
||||
torch.tensor(_EXACT_DEFAULTS, dtype=torch.float32)[:, None]
|
||||
.repeat(1, self.pool_rows)
|
||||
.contiguous()
|
||||
)
|
||||
|
||||
# The slot-indexed state every launch gathers at ``slot_mapping[row]``; never-admitted slots keep the backend's seed.
|
||||
self.state = SlotState.allocate(
|
||||
self.pool_rows, self.n_max, self.vocab_size, config.random_seed, self.device
|
||||
)
|
||||
self._exact_state = self.state.with_scalars(self.exact_scalars)
|
||||
|
||||
# xgrammar's int32 bitmask layout, scattered per step by ``_scatter_grammar``.
|
||||
self.grammar = self.state.grammar
|
||||
|
||||
# fp32 logits compile their own kernels: warmed the first time they arrive.
|
||||
self._fp32_warm = False
|
||||
|
||||
# The kernels run on CUDA only; a state built elsewhere (tests) has nothing to compile.
|
||||
if torch.device(self.device).type == "cuda":
|
||||
|
||||
self._warmup(torch.bfloat16)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# JIT warm-up
|
||||
# ------------------------------------------------------------------ #
|
||||
def _warmup(self, dtype: torch.dtype) -> None:
|
||||
"""Launch every batch size once on dummy logits gathering slot 0.
|
||||
|
||||
Graph capture only compiles the decode row counts it captures; the
|
||||
eager paths (prefill rows of a mixed round, uncaptured batch sizes)
|
||||
would otherwise hit new kernel variants at runtime, and each Triton
|
||||
compile stalls the whole server for seconds. Each launch takes the
|
||||
config serving picks for its rows, and Triton caches by config and
|
||||
integer specialization of ``batch_size``, so most launches here are
|
||||
cache hits."""
|
||||
|
||||
with torch.device(self.device):
|
||||
|
||||
logits = torch.zeros(
|
||||
(self.max_bs * self.n_max, self.vocab_size), dtype=dtype
|
||||
)
|
||||
slot = torch.zeros((self.max_bs,), dtype=torch.int64)
|
||||
# Mixed rounds pass the decode rows' slots at an offset, a pointer Triton specializes apart from 16-byte aligned ones.
|
||||
shifted = torch.zeros((self.max_bs + 1,), dtype=torch.int64)[1:]
|
||||
# The dtype of the base class's offsets pool, which serving passes.
|
||||
offsets = torch.zeros((self.pool_rows,), dtype=torch.int64)
|
||||
cand = torch.zeros((self.max_bs, self.n_max), dtype=torch.int32)
|
||||
|
||||
for slots in (slot, shifted):
|
||||
|
||||
for bs in range(1, self.max_bs + 1):
|
||||
|
||||
self._fused_singular(logits[:bs], slots[:bs], offsets)
|
||||
|
||||
if self.spec:
|
||||
|
||||
self._fused_multistep(
|
||||
logits[: bs * self.n_max], slots[:bs], offsets, cand[:bs]
|
||||
)
|
||||
|
||||
# The warm-up gathered slot 0 with counting on; leave it clean.
|
||||
self.reset_capture_state()
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Per-slot admission state (flip detection, via the base class)
|
||||
# ------------------------------------------------------------------ #
|
||||
@override
|
||||
def _reset_slot(self, pool_idx: int, sp: SamplingParams) -> None:
|
||||
"""Write a newly-assigned slot's per-request state once (called by the
|
||||
base ``prepare_step`` on a slot's owning-rid flip), straight into
|
||||
sonic's device buffers like the sibling backends. sonic's own host-side
|
||||
slot management (unfenced copies through pinned relays, a per-slot
|
||||
noise plane) is not vendored.
|
||||
|
||||
``Indicator.from_params`` derives the bits from the same sanitized
|
||||
values written here, so every bit agrees with what the kernel reads;
|
||||
the GRAMMAR bit comes from ``sp.has_grammar`` (the masks arrive per
|
||||
step through ``_scatter_grammar``). ``greedy_draft``: drafts are point
|
||||
draws (chain EAGLE, topk=1), so stochastic rows verify under sonic's
|
||||
masked-rejection regime."""
|
||||
|
||||
temperature, top_k, top_p, min_p = _sanitize(sp)
|
||||
|
||||
bias: dict[int, float] | None = None
|
||||
|
||||
if sp.logit_bias:
|
||||
|
||||
bias = {int(t): float(v) for t, v in sp.logit_bias.items()}
|
||||
|
||||
bits = Indicator.from_params(
|
||||
grammar=sp.has_grammar,
|
||||
multiplicative=float(sp.repetition_penalty),
|
||||
frequency=float(sp.frequency_penalty),
|
||||
presence=float(sp.presence_penalty),
|
||||
logit_bias=bias is not None,
|
||||
temperature=temperature,
|
||||
top_k=top_k,
|
||||
top_p=top_p,
|
||||
min_p=min_p,
|
||||
greedy_draft=True,
|
||||
)
|
||||
|
||||
state = self.state
|
||||
# The fp32 row keeps a requested min_p of 1.0 exact; 0.999 only sets the MIN_P bit.
|
||||
exact_min_p = 1.0 if min_p and float(sp.min_p) >= 1.0 else min_p
|
||||
|
||||
state.indicators[pool_idx].fill_(int(bits))
|
||||
state.top_k[pool_idx].fill_(top_k)
|
||||
state.decode_counts[pool_idx].zero_()
|
||||
|
||||
for rows, row_min_p in ((state, min_p), (self._exact_state, exact_min_p)):
|
||||
|
||||
values = (
|
||||
temperature,
|
||||
top_p,
|
||||
row_min_p,
|
||||
float(sp.repetition_penalty),
|
||||
float(sp.frequency_penalty),
|
||||
float(sp.presence_penalty),
|
||||
)
|
||||
for row, value in zip(
|
||||
(
|
||||
rows.temperature,
|
||||
rows.top_p,
|
||||
rows.min_p,
|
||||
rows.repetition,
|
||||
rows.frequency,
|
||||
rows.presence,
|
||||
),
|
||||
values,
|
||||
strict=True,
|
||||
):
|
||||
|
||||
row[pool_idx].fill_(value)
|
||||
|
||||
row = state.logit_bias[pool_idx]
|
||||
row.zero_()
|
||||
|
||||
if bias:
|
||||
|
||||
row[list(bias)] = torch.tensor(
|
||||
list(bias.values()), dtype=torch.bfloat16, device=self.device
|
||||
)
|
||||
|
||||
self.grammar[pool_idx].fill_(-1)
|
||||
state.seeds[pool_idx].fill_(int(sp.seed))
|
||||
|
||||
@override
|
||||
def slot_state_rows(self, slot: int) -> list[torch.Tensor]:
|
||||
"""The slot's rows ``_reset_slot`` writes, which a retraction images and restores."""
|
||||
|
||||
state = self.state
|
||||
rows = slice(slot, slot + 1)
|
||||
|
||||
return [
|
||||
state.indicators[rows],
|
||||
state.temperature[rows],
|
||||
state.top_k[rows],
|
||||
state.top_p[rows],
|
||||
state.min_p[rows],
|
||||
state.repetition[rows],
|
||||
state.frequency[rows],
|
||||
state.presence[rows],
|
||||
state.decode_counts[rows],
|
||||
state.logit_bias[rows],
|
||||
self.grammar[rows],
|
||||
state.seeds[rows],
|
||||
*(row[rows] for row in self.exact_scalars),
|
||||
]
|
||||
|
||||
@override
|
||||
def reset_capture_state(self) -> None:
|
||||
"""Warm-up routes all rows to slot 0 and accumulates its decode counts;
|
||||
zero them so the captured graph reads a clean baseline."""
|
||||
|
||||
self.state.decode_counts[0].zero_()
|
||||
|
||||
def _scatter_grammar(
|
||||
self,
|
||||
vocab_mask: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
bs: int,
|
||||
n: int,
|
||||
) -> None:
|
||||
"""Scatter xgrammar's row-indexed ``[bs*n, W]`` bitmask (row ``i*n+j`` =
|
||||
request ``i``, position ``j``) into the slot-indexed ``grammar`` buffer
|
||||
``[pool_rows, n_max, W]``, both int32 with the same bit semantics (SET =
|
||||
allowed; token ``t`` -> word ``t//32``, bit ``t%32``), so it's a plain
|
||||
copy. Captured/graph-safe (same pattern as the draft-probs scatter).
|
||||
|
||||
Mixed prefill+decode spec rounds slice the row-indexed mask per request,
|
||||
so both halves arrive misaligned (the runtime's mask slicing is the fix).
|
||||
Only the verify half is detectable from shapes (the prefill half has
|
||||
``bs`` rows either way), and it raises in the same step, before the
|
||||
mis-scattered rows are read. That check also fires on mixed rounds with
|
||||
no grammar request when a grammar backend is configured (all-ones
|
||||
mask). The plane is slot-resident: a GRAMMAR-bit slot must receive a
|
||||
mask every step, which ``bind_grammar_mask_buf`` guarantees whenever a
|
||||
grammar backend is on; admission resets the slot's rows to all-ones."""
|
||||
|
||||
w = self.grammar.shape[-1]
|
||||
|
||||
if vocab_mask.shape[-1] != w:
|
||||
|
||||
raise RuntimeError(
|
||||
f"grammar bitmask width {vocab_mask.shape[-1]} != sonic grammar "
|
||||
f"buffer width {w} (vocab mismatch: backend vocab vs config "
|
||||
f"vocab_size={self.vocab_size})"
|
||||
)
|
||||
|
||||
# Row-count guard for the mixed-round misalignment described above.
|
||||
if vocab_mask.shape[0] != bs * n:
|
||||
|
||||
raise RuntimeError(
|
||||
f"grammar bitmask rows {vocab_mask.shape[0]} != bs*n = {bs * n}: "
|
||||
"vocab_mask is misaligned with this sub-batch (mixed "
|
||||
"prefill+decode spec batches slice the row-indexed mask by "
|
||||
"request). Grammar + spec decode requires an aligned mask per "
|
||||
"sub-batch."
|
||||
)
|
||||
|
||||
self.grammar[slot_mapping, :n] = vocab_mask.view(bs, n, w)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Tuned dispatch
|
||||
# ------------------------------------------------------------------ #
|
||||
def _check_logits(self, logits: torch.Tensor) -> SlotState:
|
||||
"""The slot state these logits launch with: fp32 logits read the fp32 scalars."""
|
||||
|
||||
if logits.dtype not in _LOGITS_DTYPES or logits.shape[-1] != self.vocab_size:
|
||||
|
||||
raise ValueError(
|
||||
f"SonicSamplingBackend requires bf16 or fp32 logits of width "
|
||||
f"{self.vocab_size}, got {logits.dtype} x {logits.shape[-1]}"
|
||||
)
|
||||
|
||||
if logits.dtype == torch.bfloat16:
|
||||
|
||||
return self.state
|
||||
|
||||
if not self._fp32_warm and not torch.cuda.is_current_stream_capturing():
|
||||
|
||||
self._fp32_warm = True
|
||||
self._warmup(torch.float32)
|
||||
|
||||
return self._exact_state
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Sampling (inside the captured graph)
|
||||
# ------------------------------------------------------------------ #
|
||||
def _fused_singular(
|
||||
self,
|
||||
logits: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
offsets: torch.Tensor,
|
||||
config: SonicConfig | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""One draw per row into ``out_tok``, counted for penalties; returns the ``[bs, 1]`` tokens."""
|
||||
|
||||
state = self._check_logits(logits)
|
||||
|
||||
bs = logits.shape[0]
|
||||
|
||||
return sonic.sample(
|
||||
logits,
|
||||
state,
|
||||
slot_mapping,
|
||||
offsets,
|
||||
self.out_tok[:bs],
|
||||
self.scratchpad[:bs],
|
||||
config or pick(self.vocab_size, bs),
|
||||
enable_pdl=pdl_enabled(),
|
||||
)
|
||||
|
||||
def _sample_rows(
|
||||
self,
|
||||
logits_output: LogitsProcessorOutput,
|
||||
sampling_info: SamplingBatchInfo,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""One fused single-step draw per row: the body shared by ``sample()``
|
||||
and the ``N == 1`` (non-speculative decode) case of ``verify()``."""
|
||||
|
||||
logits = logits_output.next_token_logits
|
||||
|
||||
bs = logits.shape[0]
|
||||
|
||||
# Padded rows carry slot 0 and write it (grammar, counts); the runtime never allocates it.
|
||||
slot_mapping = sampling_info.req_pool_indices[:bs]
|
||||
|
||||
# Native grammar: scatter the bitmask; the kernel masks in-fused.
|
||||
if sampling_info.vocab_mask is not None:
|
||||
|
||||
self._scatter_grammar(sampling_info.vocab_mask, slot_mapping, bs, 1)
|
||||
|
||||
sampled = self._fused_singular(
|
||||
logits, slot_mapping, self._prepare_sampling_offsets(sampling_info)
|
||||
).view(-1)
|
||||
|
||||
# TP-rank sync (rank 0 wins): gathered logits are not bit-identical across ranks.
|
||||
self.maybe_broadcast(sampled)
|
||||
|
||||
self._write_logprob_outputs(logits_output, logits, sampling_info, sampled)
|
||||
|
||||
# The runtime's stop conditions cut the returned lengths in place, so every call refills them.
|
||||
lengths = self.lengths_buf[:bs]
|
||||
lengths.fill_(1)
|
||||
|
||||
return sampled, lengths
|
||||
|
||||
def _write_logprob_outputs(
|
||||
self,
|
||||
logits_output: LogitsProcessorOutput,
|
||||
logits: torch.Tensor,
|
||||
sampling_info: SamplingBatchInfo,
|
||||
tokens: torch.Tensor,
|
||||
) -> None:
|
||||
"""Selected-token logprobs over the raw (grammar-masked) distribution,
|
||||
like flashinfer. Native grammar doesn't touch ``logits``, so the mask is
|
||||
applied to a copy here; only paid when logprobs are enabled (off by
|
||||
default)."""
|
||||
|
||||
if not self.config.enable_output_logprobs:
|
||||
|
||||
return
|
||||
|
||||
if sampling_info.vocab_mask is not None:
|
||||
|
||||
logits = logits.clone()
|
||||
sampling_info.apply_vocab_mask(
|
||||
logits=logits, vocab_mask=sampling_info.vocab_mask
|
||||
)
|
||||
|
||||
logits_output.next_token_logprobs = gather_token_logprobs_torch(logits, tokens)
|
||||
|
||||
@override
|
||||
@nvtx_range("sampling:sample", color="yellow")
|
||||
def sample(
|
||||
self,
|
||||
logits_output: LogitsProcessorOutput,
|
||||
sampling_info: SamplingBatchInfo,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
|
||||
return self._sample_rows(logits_output, sampling_info)
|
||||
|
||||
def _fused_multistep(
|
||||
self,
|
||||
logits: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
offsets: torch.Tensor,
|
||||
candidates: torch.Tensor,
|
||||
config: SonicConfig | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""One ``verify`` launch over ``[bs * n, V]`` logits; returns ``(drafted, accepted)``.
|
||||
|
||||
``drafted[:, :γ]`` holds the γ proposals and is the output too: the
|
||||
kernel stores only the corrected token at the
|
||||
rejection offset (the rest of the row must already be the drafts), so
|
||||
this keeps sonic's in-place semantics with a stable captured pointer
|
||||
(the default would clone-allocate). The trailing bonus column is
|
||||
output-only: the kernel masks it out of the draft load and
|
||||
short-circuits the residual correction there. No draft probabilities:
|
||||
sonic's masked-rejection regime natively verifies point-draw drafts
|
||||
(accept iff u <= p(draft), residual = p with the drafted token zeroed)."""
|
||||
|
||||
state = self._check_logits(logits)
|
||||
|
||||
bs, n = candidates.shape
|
||||
gamma = n - 1
|
||||
|
||||
drafted = self.v_drafted[:bs]
|
||||
drafted[:, :gamma].copy_(candidates[:, 1:])
|
||||
drafted[:, gamma:].zero_()
|
||||
accepted = self.v_accepted[:bs]
|
||||
|
||||
sonic.verify(
|
||||
logits,
|
||||
state,
|
||||
slot_mapping,
|
||||
offsets,
|
||||
drafted,
|
||||
accepted,
|
||||
self.scratchpad[: bs * n],
|
||||
self.values[: bs * n],
|
||||
self.indices[: bs * n],
|
||||
config or pick(self.vocab_size, bs * n),
|
||||
enable_pdl=pdl_enabled(),
|
||||
)
|
||||
|
||||
return drafted, accepted
|
||||
|
||||
@override
|
||||
@nvtx_range("sampling:verify", color="yellow")
|
||||
def verify(
|
||||
self,
|
||||
logits_output: LogitsProcessorOutput,
|
||||
sampling_info: SamplingBatchInfo,
|
||||
candidates: torch.Tensor,
|
||||
*,
|
||||
tree: TreeVerifyBatch | None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Chain speculative verification via sonic's ``verify``.
|
||||
|
||||
``candidates`` is ``[bs, n]`` (n = γ+1): column 0 is the last verified
|
||||
token, 1..γ the drafts. sonic compares its per-position selection against
|
||||
``drafted[s]`` at the same index, so we pass ``drafted = candidates[:, 1:]``
|
||||
and read back ``drafted`` (the accepted prefix + next token) with
|
||||
``accept_length = accepted + 1``. Greedy and stochastic rows resolve in
|
||||
one pipeline via per-row indicators; the drafts are point draws, handled
|
||||
natively by sonic's masked-rejection regime (``draft_probabilities=None``:
|
||||
accept iff u <= p(draft), residual = p with the drafted token zeroed).
|
||||
|
||||
``n == 1`` is non-speculative decode (the runtime's unified sampling
|
||||
rule): nothing to accept, one token to draw, ``accept_length == 1`` —
|
||||
exactly ``sample()``, so it takes the ``sample`` path. Widths
|
||||
other than 1 and ``n_max`` are refused (``v_drafted`` is ``[max_bs,
|
||||
n_max]``)."""
|
||||
|
||||
if tree is not None:
|
||||
|
||||
raise RuntimeError("SonicSamplingBackend verifies draft chains only")
|
||||
|
||||
bs, n = candidates.shape
|
||||
|
||||
if n == 1:
|
||||
|
||||
return self._sample_rows(logits_output, sampling_info)
|
||||
|
||||
if n != self.n_max:
|
||||
|
||||
raise RuntimeError(
|
||||
f"verify candidates width {n} != configured n_max {self.n_max}"
|
||||
)
|
||||
|
||||
logits = logits_output.next_token_logits # flat [bs * n, V]
|
||||
|
||||
slot_mapping = sampling_info.req_pool_indices[:bs]
|
||||
|
||||
# Native per-draft-position grammar: scatter then mask in-fused.
|
||||
if sampling_info.vocab_mask is not None:
|
||||
|
||||
self._scatter_grammar(sampling_info.vocab_mask, slot_mapping, bs, n)
|
||||
|
||||
predict, accepted = self._fused_multistep(
|
||||
logits,
|
||||
slot_mapping,
|
||||
self._prepare_sampling_offsets(sampling_info),
|
||||
candidates,
|
||||
)
|
||||
|
||||
predict = predict.view(-1)
|
||||
accept_lengths = torch.add(accepted.view(-1), 1, out=self.accept_buf[:bs])
|
||||
|
||||
# TP-rank sync — see sample().
|
||||
self.maybe_broadcast(predict, accept_lengths)
|
||||
|
||||
self._write_logprob_outputs(logits_output, logits, sampling_info, predict)
|
||||
|
||||
return predict, accept_lengths
|
||||
|
||||
|
||||
register_backend("sonic", SonicSamplingBackend)
|
||||
@@ -77,6 +77,8 @@ def _is_sampling_backend_available(backend_name: str) -> bool:
|
||||
return True
|
||||
if backend_name == "triton_full":
|
||||
return True
|
||||
if backend_name == "sonic":
|
||||
return platform.is_nvidia
|
||||
if backend_name == "ascend_full":
|
||||
if not platform.is_npu:
|
||||
return False
|
||||
@@ -108,6 +110,10 @@ def get_sampling_backend_class(server_args: ServerArgs) -> type[SamplingBackend]
|
||||
from tokenspeed.runtime.sampling.backends import triton as _t # noqa: F401
|
||||
from tokenspeed.runtime.sampling.backends import triton_full as _tf # noqa: F401
|
||||
|
||||
# sonic's kernels use NVIDIA's libdevice; other platforms never import them.
|
||||
if current_platform().is_nvidia:
|
||||
from tokenspeed.runtime.sampling.backends import sonic as _so # noqa: F401
|
||||
|
||||
name = _resolve_backend_name(server_args)
|
||||
if current_platform().is_npu and name == "ascend_full":
|
||||
from tokenspeed.runtime.sampling.backends import ( # noqa: F401
|
||||
|
||||
@@ -197,6 +197,16 @@ class SamplingParams(msgspec.Struct, kw_only=True, array_like=True):
|
||||
if sum(x is not None for x in grammars) > 1:
|
||||
raise ValueError("Only one of regex, json_schema, or ebnf can be set.")
|
||||
|
||||
@property
|
||||
def has_grammar(self) -> bool:
|
||||
"""Whether the request carries a structured-output constraint."""
|
||||
return (
|
||||
self.json_schema is not None
|
||||
or self.regex is not None
|
||||
or self.ebnf is not None
|
||||
or self.structural_tag is not None
|
||||
)
|
||||
|
||||
def requested_features(self) -> "set[str]":
|
||||
"""Return the set of backend-facing feature names this request needs.
|
||||
|
||||
|
||||
@@ -3739,6 +3739,7 @@ class ServerArgs:
|
||||
"triton",
|
||||
"triton_full",
|
||||
"ascend_full",
|
||||
"sonic",
|
||||
],
|
||||
default=ServerArgs.sampling_backend,
|
||||
help="Sampling backend. "
|
||||
@@ -3754,7 +3755,17 @@ class ServerArgs:
|
||||
"'ascend_full': graph-safe Ascend top-k/top-p/min-p sampling and chain verify. "
|
||||
"Allocates a counts[max_req_pool_size, vocab_size] int32 buffer (substantial memory). "
|
||||
"ascend_full caps finite top_k at 4096; larger values use 4096. "
|
||||
"Other backends require finite top_k < 128. -1 disables top-k.",
|
||||
"Other backends require finite top_k < 128. -1 disables top-k. "
|
||||
"'sonic': one fused Triton pipeline per step (vendored sonic-sampler; two kernels "
|
||||
"for sampling, three for chain verification) covering greedy, "
|
||||
"temperature/top_k/top_p/min_p, penalties, logit_bias and grammar for both "
|
||||
"single-step sampling and chain verification; top_k=-1 is realized as bounded "
|
||||
"top-128 truncation. bf16 logits are ranked at bf16 resolution; fp32 logits "
|
||||
"(soft-capped heads) are sampled exactly in fp32 among the top-128 candidates. "
|
||||
"Its kernel config per batch size comes from a table measured on "
|
||||
"Blackwell, so nothing is tuned at startup. Allocates slot-indexed "
|
||||
"[max_req_pool_size, vocab_size] token counts and logit bias: about 10 bytes "
|
||||
"per element on device (substantial memory).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--sampling-stream",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -92,6 +92,9 @@ from tokenspeed.runtime.sampling.backends.flashinfer_full import ( # noqa: E402
|
||||
from tokenspeed.runtime.sampling.backends.greedy import ( # noqa: E402
|
||||
GreedySamplingBackend,
|
||||
)
|
||||
from tokenspeed.runtime.sampling.backends.sonic import ( # noqa: E402
|
||||
SonicSamplingBackend,
|
||||
)
|
||||
from tokenspeed.runtime.sampling.backends.triton import ( # noqa: E402
|
||||
TritonSamplingBackend,
|
||||
)
|
||||
@@ -107,8 +110,12 @@ SAMPLING_BACKENDS = (
|
||||
FlashInferFullSamplingBackend,
|
||||
TritonSamplingBackend,
|
||||
TritonFullSamplingBackend,
|
||||
SonicSamplingBackend,
|
||||
)
|
||||
|
||||
# The per-slot buffers each sampling backend's rid-flip reset must write.
|
||||
SCATTERED_SLOT_STATE = {SonicSamplingBackend: ("state.temperature", "state.seeds")}
|
||||
|
||||
# One request-pool geometry for every owner: max_bs decode rows, one sink row
|
||||
# (max_req_pool_size = max_bs + 1) and the graph-padding row past it.
|
||||
MAX_BS = 9
|
||||
@@ -232,15 +239,19 @@ def _dsa(pool, *, is_draft: bool) -> DSABackend:
|
||||
|
||||
def _sampling_backend(cls) -> SamplingBackend:
|
||||
"""A sampling backend over the test pool geometry, on the CPU."""
|
||||
sonic = cls is SonicSamplingBackend
|
||||
# sonic verifies point-draw drafts and has no draft-prob verify.
|
||||
draft_probs = cls not in (GreedySamplingBackend, SonicSamplingBackend)
|
||||
config = SamplingBackendConfig(
|
||||
synthetic_acceptance_length=None,
|
||||
enable_speculative_sampling=cls is not GreedySamplingBackend,
|
||||
enable_speculative_sampling=draft_probs,
|
||||
sampling_stream="batch",
|
||||
logprob_order="torch",
|
||||
max_bs=MAX_BS,
|
||||
max_draft_tokens_per_req=SPEC_TOKENS,
|
||||
max_req_pool_size=MAX_REQ_POOL_SIZE,
|
||||
vocab_size=VOCAB,
|
||||
# sonic's top-k reduction needs at least 512 columns.
|
||||
vocab_size=512 if sonic else VOCAB,
|
||||
device="cpu",
|
||||
)
|
||||
# The Triton backends size a scratch buffer by the SM count.
|
||||
@@ -508,8 +519,14 @@ def test_sampling_backend_images_an_unprepared_slot_as_nobodys(cls, previous_occ
|
||||
reset.assert_called_once()
|
||||
assert reset.call_args.args[:2] == (dst_slot, params)
|
||||
assert backend._last_rid_per_slot[dst_slot] == victim
|
||||
assert float(backend._temperature_pool[dst_slot]) == pytest.approx(0.3)
|
||||
assert int(backend._seed_pool[dst_slot]) == int(params.seed)
|
||||
per_slot = _per_slot_tensors(backend, {POOL_ROWS})
|
||||
temperature, seed = (
|
||||
per_slot[name]
|
||||
for name in SCATTERED_SLOT_STATE.get(cls, ("_temperature_pool", "_seed_pool"))
|
||||
)
|
||||
# sonic keeps its temperature in bf16.
|
||||
assert float(temperature[dst_slot]) == pytest.approx(0.3, abs=2**-8)
|
||||
assert int(seed[dst_slot]) == int(params.seed)
|
||||
if isinstance(backend, FlashInferSamplingBackend):
|
||||
# The coin stream starts from the request's own seed: the step above
|
||||
# drew its coins from a generator seeded by the reset.
|
||||
@@ -605,7 +622,7 @@ def _is_runtime_component(value) -> bool:
|
||||
return (
|
||||
not isinstance(value, (torch.Tensor, torch.nn.Module, SlotStateExporter))
|
||||
and hasattr(value, "__dict__")
|
||||
and type(value).__module__.startswith("tokenspeed.")
|
||||
and type(value).__module__.startswith(("tokenspeed.", "tokenspeed_kernel."))
|
||||
)
|
||||
|
||||
|
||||
@@ -704,7 +721,7 @@ def test_sampling_backend_slot_state_is_complete(cls):
|
||||
_assert_slot_state_complete(backend, exporter=backend, slot_domains={POOL_ROWS})
|
||||
# The declared constant pools exist, are per-slot, and really are constant.
|
||||
per_slot = _per_slot_tensors(backend, {POOL_ROWS})
|
||||
for name in SamplingBackend.constant_slot_state:
|
||||
for name in cls.constant_slot_state:
|
||||
assert name in per_slot
|
||||
assert per_slot[name].abs().sum() == 0
|
||||
# Every per-slot thing the rid-flip reset writes is in the image.
|
||||
@@ -712,9 +729,9 @@ def test_sampling_backend_slot_state_is_complete(cls):
|
||||
exported = _storage_ids(backend.slot_state_rows(0))
|
||||
written = []
|
||||
for name, tensor in per_slot.items():
|
||||
if name in SamplingBackend.constant_slot_state:
|
||||
if name in cls.constant_slot_state:
|
||||
continue
|
||||
if name in SamplingBackend.token_derived_slot_state:
|
||||
if name in cls.token_derived_slot_state:
|
||||
# Derived scratch is neither restored nor changed by admission.
|
||||
tensor[2].fill_(197)
|
||||
before = tensor.clone()
|
||||
@@ -726,7 +743,8 @@ def test_sampling_backend_slot_state_is_complete(cls):
|
||||
if tensor[2].abs().sum() != 0:
|
||||
written.append(name)
|
||||
assert tensor.untyped_storage().data_ptr() in exported, name
|
||||
assert "_temperature_pool" in written and "_seed_pool" in written
|
||||
expected = SCATTERED_SLOT_STATE.get(cls, ("_temperature_pool", "_seed_pool"))
|
||||
assert set(expected) <= set(written), written
|
||||
|
||||
|
||||
def test_completeness_check_catches_an_unexported_buffer():
|
||||
|
||||
@@ -99,6 +99,15 @@ Copyright (c) 2023-2026, Songlin Yang, Yu Zhang, Zhiyuan Li
|
||||
|
||||
Licensed under the MIT License, whose full license text is available in the repository LICENSE file.
|
||||
|
||||
Notice for tachyontrails/sonic-sampler
|
||||
-------------------------------
|
||||
Apache License, Version 2.0
|
||||
|
||||
Copyright (c) 2026 SonicSampler Team.
|
||||
|
||||
Licensed under the Apache License, Version 2.0, whose full license text is available
|
||||
in tokenspeed_kernel/thirdparty/sonic_sampler/LICENSE.
|
||||
|
||||
Notice for SGLang
|
||||
-------------------------------
|
||||
Apache License, Version 2.0
|
||||
|
||||
@@ -1132,6 +1132,11 @@ setup(
|
||||
"csrc/include/**/*.h",
|
||||
"csrc/include/**/*.cuh",
|
||||
],
|
||||
# Vendored sonic-sampler: its license and provenance.
|
||||
"tokenspeed_kernel.thirdparty.sonic_sampler": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
],
|
||||
# Optional JIT adapter for fused AllGather quantization.
|
||||
"tokenspeed_kernel.thirdparty.flashinfer": [
|
||||
"allgather_quant.cu",
|
||||
|
||||
@@ -0,0 +1,588 @@
|
||||
# Copyright (c) 2026 LightSeek Foundation
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
|
||||
"""sonic-sampler's kernels, launched for the runtime's ``sonic`` sampling backend.
|
||||
|
||||
The kernels are vendored in ``tokenspeed_kernel.thirdparty.sonic_sampler.ops`` (see the
|
||||
package README for the upstream commit and the local changes); this module
|
||||
launches them over the backend's slot-indexed state and picks their config
|
||||
from a table keyed by vocabulary size class and logits rows, so no server
|
||||
tunes at startup. On GB200 (13 vocabularies from 32k to 262k, 1 to 512 rows,
|
||||
plain decode and three-draft verify, 60 configs swept) its picks run within 8%
|
||||
of the best config at every point and 0.3% on average, and 3.6x to 11x faster
|
||||
than the FlashInfer backend. The other Blackwell GPUs share it; any other GPU
|
||||
uses it unmeasured.
|
||||
|
||||
Every config draws the same tokens (the selection is exact; only its tiling
|
||||
and warps differ), so the table changes speed only. bf16 logits rank at bf16
|
||||
resolution; fp32 logits (soft-capped heads) are sampled exactly in fp32 among
|
||||
the top-128 candidates their bf16 keys pick.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import functools
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
from tokenspeed_kernel._triton import tl, triton
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.core.flags import Indicator
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.base import MAX_K, next_power_of_2
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.multistep import (
|
||||
cumulative_unpack_kernel,
|
||||
)
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.prologue import (
|
||||
bitpacked_reduction_kernel,
|
||||
)
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.singular import (
|
||||
cumulative_selection_kernel,
|
||||
)
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.verify import (
|
||||
chain_speculative_verification_kernel,
|
||||
)
|
||||
from torch import Tensor
|
||||
|
||||
# The kernels' block for top-k logprob targets, which the runtime never requests.
|
||||
_LOGPROB_BLOCK = 8
|
||||
|
||||
# Adaptive top-k's scale factor, unread with adaptive top-k off.
|
||||
_TOP_K_SCALE = 4
|
||||
|
||||
# The kernels keep row * stride offsets into the logits and the scratchpad in int32.
|
||||
MAX_OFFSET = 2**31
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SonicConfig:
|
||||
"""One way to run sonic's pipeline: the vocab tile, the top-k strategy and the warps of its first two stages."""
|
||||
|
||||
block_n: int
|
||||
radix: bool
|
||||
first_warps: int
|
||||
second_warps: int
|
||||
|
||||
|
||||
_BITONIC_2K = SonicConfig(2048, False, 8, 8)
|
||||
_BITONIC_4K = SonicConfig(4096, False, 8, 8)
|
||||
_RADIX_2K = SonicConfig(2048, True, 4, 8)
|
||||
_RADIX_4K = SonicConfig(4096, True, 8, 8)
|
||||
_RADIX_8K = SonicConfig(8192, True, 16, 8)
|
||||
_RADIX_16K = SonicConfig(16384, True, 16, 8)
|
||||
|
||||
# Per vocabulary class (largest size, None for the rest): (most logits rows, config), the last bound None.
|
||||
# Few rows want fewer, wider tiles until the first stage's tiles about fill the SMs; many rows want 2k-4k radix tiles.
|
||||
TABLE: tuple[tuple[int | None, tuple[tuple[int | None, SonicConfig], ...]], ...] = (
|
||||
(80_000, ((4, _BITONIC_2K), (64, _RADIX_4K), (None, _RADIX_2K))),
|
||||
(
|
||||
140_000,
|
||||
(
|
||||
(1, _BITONIC_2K),
|
||||
(4, _BITONIC_4K),
|
||||
(8, _RADIX_8K),
|
||||
(16, _RADIX_16K),
|
||||
(64, _RADIX_4K),
|
||||
(None, _RADIX_2K),
|
||||
),
|
||||
),
|
||||
(160_000, ((4, _BITONIC_4K), (16, _RADIX_8K), (None, _RADIX_4K))),
|
||||
(None, ((2, _BITONIC_4K), (4, _RADIX_8K), (8, _RADIX_16K), (None, _RADIX_4K))),
|
||||
)
|
||||
|
||||
|
||||
def _fit(config: SonicConfig, vocab_size: int) -> SonicConfig:
|
||||
"""``config`` with its tile halved until the vocabulary spans two tiles, as sonic's reduction needs."""
|
||||
block_n = config.block_n
|
||||
while 2 * block_n > vocab_size and block_n > 1024:
|
||||
block_n //= 2
|
||||
if 2 * block_n <= vocab_size:
|
||||
return SonicConfig(
|
||||
block_n, config.radix, config.first_warps, config.second_warps
|
||||
)
|
||||
# Below 2048 columns: two or three bitonic tiles.
|
||||
return SonicConfig(1 << (vocab_size.bit_length() - 2), False, 4, 4)
|
||||
|
||||
|
||||
@functools.cache
|
||||
def pick(vocab_size: int, rows: int) -> SonicConfig:
|
||||
"""The config for one launch over ``[rows, vocab_size]`` logits.
|
||||
|
||||
Args:
|
||||
vocab_size: the logits width (at least 512, sonic's reduction minimum).
|
||||
rows: the launch's logits rows (requests, times drafts plus one for verify).
|
||||
|
||||
Returns:
|
||||
The table's config for the vocabulary's class and the rows, with its
|
||||
tile narrowed when the vocabulary does not span two tiles.
|
||||
"""
|
||||
rows_table = next(t for size, t in TABLE if size is None or vocab_size <= size)
|
||||
config = next(c for bound, c in rows_table if bound is None or rows <= bound)
|
||||
return _fit(config, vocab_size)
|
||||
|
||||
|
||||
def configs(vocab_size: int) -> tuple[SonicConfig, ...]:
|
||||
"""Every config ``pick`` returns for ``vocab_size``, for warm-up and the scratchpad."""
|
||||
rows_table = next(t for size, t in TABLE if size is None or vocab_size <= size)
|
||||
return tuple(dict.fromkeys(_fit(c, vocab_size) for _, c in rows_table))
|
||||
|
||||
|
||||
def scratchpad_columns(vocab_size: int) -> int:
|
||||
"""Scratchpad columns one logits row needs: the narrowest picked tile's blocks, ``MAX_K`` keys each."""
|
||||
return triton.cdiv(vocab_size, min(c.block_n for c in configs(vocab_size))) * MAX_K
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SlotState:
|
||||
"""The per-slot tensors sonic's kernels gather at each row's slot.
|
||||
|
||||
Scalars are bf16, or fp32 for fp32 logits (``with_scalars``); every
|
||||
tensor's first dimension is the slot.
|
||||
"""
|
||||
|
||||
indicators: Tensor # [P] int16 ``Indicator`` bits (at most 0x800).
|
||||
temperature: Tensor # [P].
|
||||
top_k: Tensor # [P] int32, at most ``MAX_K``.
|
||||
top_p: Tensor # [P].
|
||||
min_p: Tensor # [P].
|
||||
repetition: Tensor # [P] multiplicative repetition penalty.
|
||||
frequency: Tensor # [P].
|
||||
presence: Tensor # [P].
|
||||
grammar: Tensor # [P, timesteps, ceil(V / 32)] int32 bitmask (xgrammar's), set bits allowed.
|
||||
context_counts: Tensor # [P, V] int32 prompt counts.
|
||||
decode_counts: Tensor # [P, V] int32 counts of drawn tokens.
|
||||
logit_bias: Tensor # [P, V] bf16.
|
||||
seeds: Tensor # [P] int64 Philox seeds.
|
||||
|
||||
@classmethod
|
||||
def allocate(
|
||||
cls,
|
||||
slots: int,
|
||||
timesteps: int,
|
||||
vocab_size: int,
|
||||
seed: int,
|
||||
device: torch.device | str,
|
||||
) -> SlotState:
|
||||
"""Every slot in its never-admitted state: no manipulators, bounded top-k, all tokens allowed.
|
||||
|
||||
Args:
|
||||
slots: Slots, the padding sentinel included.
|
||||
timesteps: Logits rows per request (drafts plus one).
|
||||
vocab_size: The logits width.
|
||||
seed: Philox seed of never-admitted slots.
|
||||
device: Where the tensors live.
|
||||
|
||||
Returns:
|
||||
The state, bf16 scalars.
|
||||
"""
|
||||
bf16 = torch.bfloat16
|
||||
with torch.device(device):
|
||||
context_counts, decode_counts = torch.zeros(
|
||||
(2, slots, vocab_size), dtype=torch.int32
|
||||
)
|
||||
return cls(
|
||||
indicators=torch.zeros(slots, dtype=torch.int16),
|
||||
temperature=torch.ones(slots, dtype=bf16),
|
||||
top_k=torch.full((slots,), MAX_K, dtype=torch.int32),
|
||||
top_p=torch.ones(slots, dtype=bf16),
|
||||
min_p=torch.zeros(slots, dtype=bf16),
|
||||
repetition=torch.ones(slots, dtype=bf16),
|
||||
frequency=torch.zeros(slots, dtype=bf16),
|
||||
presence=torch.zeros(slots, dtype=bf16),
|
||||
grammar=torch.full(
|
||||
(slots, timesteps, triton.cdiv(vocab_size, 32)),
|
||||
-1,
|
||||
dtype=torch.int32,
|
||||
),
|
||||
context_counts=context_counts,
|
||||
decode_counts=decode_counts,
|
||||
logit_bias=torch.zeros((slots, vocab_size), dtype=bf16),
|
||||
seeds=torch.full((slots,), seed, dtype=torch.int64),
|
||||
)
|
||||
|
||||
def with_scalars(self, scalars: Tensor) -> SlotState:
|
||||
"""This state reading ``scalars``' rows (temperature, top-p, min-p, repetition, frequency, presence) instead."""
|
||||
temperature, top_p, min_p, repetition, frequency, presence = scalars
|
||||
return dataclasses.replace(
|
||||
self,
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
min_p=min_p,
|
||||
repetition=repetition,
|
||||
frequency=frequency,
|
||||
presence=presence,
|
||||
)
|
||||
|
||||
|
||||
def _check_offsets(logits: Tensor, scratchpad: Tensor) -> None:
|
||||
"""Refuse a launch whose logits or scratchpad rows reach past the kernels' int32 row offsets."""
|
||||
for name, tensor in (("logits", logits), ("scratchpad", scratchpad)):
|
||||
if tensor.shape[0] * tensor.stride(0) > MAX_OFFSET:
|
||||
raise ValueError(
|
||||
f"sonic's {name} span {tensor.shape[0]} rows of stride "
|
||||
f"{tensor.stride(0)}, past its int32 offsets ({MAX_OFFSET} elements)"
|
||||
)
|
||||
|
||||
|
||||
def _exact(logits: Tensor) -> bool:
|
||||
"""Whether the logits are fp32, which the kernels sample exactly; bf16 is the other supported dtype."""
|
||||
if logits.dtype not in (torch.bfloat16, torch.float32):
|
||||
raise ValueError(f"sonic samples bf16 or fp32 logits, got {logits.dtype}")
|
||||
return logits.dtype == torch.float32
|
||||
|
||||
|
||||
def sample(
|
||||
logits: Tensor,
|
||||
state: SlotState,
|
||||
slots: Tensor,
|
||||
offsets: Tensor,
|
||||
tokens: Tensor,
|
||||
scratchpad: Tensor,
|
||||
config: SonicConfig,
|
||||
enable_pdl: bool,
|
||||
) -> Tensor:
|
||||
"""Draw one token per logits row from its slot's distribution, counting it in the slot's decode counts.
|
||||
|
||||
Args:
|
||||
logits: ``[B, V]`` bf16 or fp32 logits.
|
||||
state: The slot state; fp32 scalars with fp32 logits.
|
||||
slots: ``[B]`` int64 slot of each row.
|
||||
offsets: ``[P]`` int64 Philox offset of each slot (the drawn token's position).
|
||||
tokens: ``[B, 1]`` int32 output.
|
||||
scratchpad: ``[B, >= scratchpad_columns(V)]`` uint32 keys.
|
||||
config: The launch config (``pick``).
|
||||
enable_pdl: Launch with programmatic dependent launch.
|
||||
|
||||
Returns:
|
||||
``tokens``.
|
||||
|
||||
Raises:
|
||||
ValueError: The logits are neither bf16 nor fp32, or a row offset
|
||||
would pass ``MAX_OFFSET``.
|
||||
"""
|
||||
_check_offsets(logits, scratchpad)
|
||||
exact = _exact(logits)
|
||||
rows, vocab_size = logits.shape
|
||||
blocks = triton.cdiv(vocab_size, config.block_n)
|
||||
block_v = next_power_of_2(blocks)
|
||||
stride_x, stride_y = logits.stride(0), scratchpad.stride(0)
|
||||
stride_g, stride_c = state.grammar.stride(0), state.decode_counts.stride(0)
|
||||
|
||||
bitpacked_reduction_kernel[(rows, blocks)](
|
||||
logits,
|
||||
state.indicators,
|
||||
slots,
|
||||
None,
|
||||
None,
|
||||
state.grammar,
|
||||
state.context_counts,
|
||||
state.decode_counts,
|
||||
None,
|
||||
state.repetition,
|
||||
state.frequency,
|
||||
state.presence,
|
||||
state.logit_bias,
|
||||
state.temperature,
|
||||
scratchpad,
|
||||
vocab_size,
|
||||
0,
|
||||
0,
|
||||
MAX_K,
|
||||
_TOP_K_SCALE,
|
||||
rows,
|
||||
False,
|
||||
False,
|
||||
True,
|
||||
True,
|
||||
False,
|
||||
False,
|
||||
config.radix,
|
||||
enable_pdl,
|
||||
stride_x,
|
||||
stride_g,
|
||||
stride_c,
|
||||
None,
|
||||
stride_y,
|
||||
config.block_n,
|
||||
None,
|
||||
None,
|
||||
exact,
|
||||
tl.float32 if exact else tl.bfloat16,
|
||||
num_warps=config.first_warps,
|
||||
)
|
||||
cumulative_selection_kernel[(rows,)](
|
||||
scratchpad,
|
||||
state.indicators,
|
||||
slots,
|
||||
None,
|
||||
state.decode_counts,
|
||||
None,
|
||||
state.seeds,
|
||||
offsets,
|
||||
state.top_k,
|
||||
state.top_p,
|
||||
state.min_p,
|
||||
None,
|
||||
tokens,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
blocks,
|
||||
1,
|
||||
vocab_size,
|
||||
MAX_K,
|
||||
None,
|
||||
block_v,
|
||||
block_v * MAX_K,
|
||||
False,
|
||||
True,
|
||||
False,
|
||||
False,
|
||||
True,
|
||||
False,
|
||||
not config.radix,
|
||||
enable_pdl,
|
||||
False,
|
||||
False,
|
||||
stride_y,
|
||||
None,
|
||||
None,
|
||||
tokens.stride(0),
|
||||
None,
|
||||
None,
|
||||
stride_c,
|
||||
None,
|
||||
None,
|
||||
config.block_n,
|
||||
block_v,
|
||||
_LOGPROB_BLOCK,
|
||||
logits if exact else None,
|
||||
state.grammar if exact else None,
|
||||
state.context_counts if exact else None,
|
||||
None,
|
||||
state.repetition if exact else None,
|
||||
state.frequency if exact else None,
|
||||
state.presence if exact else None,
|
||||
state.logit_bias if exact else None,
|
||||
state.temperature if exact else None,
|
||||
vocab_size,
|
||||
0,
|
||||
0,
|
||||
False,
|
||||
stride_x,
|
||||
stride_g,
|
||||
None,
|
||||
None,
|
||||
exact,
|
||||
num_warps=config.second_warps,
|
||||
)
|
||||
return tokens
|
||||
|
||||
|
||||
def verify(
|
||||
logits: Tensor,
|
||||
state: SlotState,
|
||||
slots: Tensor,
|
||||
offsets: Tensor,
|
||||
drafted: Tensor,
|
||||
accepted: Tensor,
|
||||
scratchpad: Tensor,
|
||||
values: Tensor,
|
||||
indices: Tensor,
|
||||
config: SonicConfig,
|
||||
enable_pdl: bool,
|
||||
) -> None:
|
||||
"""Verify each request's point-draw drafts against its slot's distribution by masked rejection.
|
||||
|
||||
Accepts draft ``j`` with probability ``p(draft)``, draws the rejected
|
||||
position from ``p`` without the draft, counting emitted tokens in the
|
||||
slot's decode counts.
|
||||
|
||||
Args:
|
||||
logits: ``[B * (g + 1), V]`` bf16 or fp32 logits, request-major.
|
||||
state: The slot state; fp32 scalars with fp32 logits.
|
||||
slots: ``[B]`` int64 slot of each request.
|
||||
offsets: ``[P]`` int64 Philox offset of each slot (its first row's position).
|
||||
drafted: ``[B, g + 1]`` int32 drafts in the first ``g`` columns; on
|
||||
return the accepted prefix and the next token.
|
||||
accepted: ``[B, 1]`` int32 output: accepted drafts per request.
|
||||
scratchpad: ``[B * (g + 1), >= scratchpad_columns(V)]`` uint32 keys.
|
||||
values: ``[B * (g + 1), MAX_K]`` fp32 candidate probabilities (scratch).
|
||||
indices: ``[B * (g + 1), MAX_K]`` int32 candidate tokens (scratch).
|
||||
config: The launch config (``pick``).
|
||||
enable_pdl: Launch with programmatic dependent launch.
|
||||
|
||||
Raises:
|
||||
ValueError: The logits are neither bf16 nor fp32, or a row offset
|
||||
would pass ``MAX_OFFSET``.
|
||||
"""
|
||||
_check_offsets(logits, scratchpad)
|
||||
exact = _exact(logits)
|
||||
rows, vocab_size = logits.shape
|
||||
batch_size, timesteps = drafted.shape
|
||||
gamma = timesteps - 1
|
||||
blocks = triton.cdiv(vocab_size, config.block_n)
|
||||
block_v, block_g = next_power_of_2(blocks), next_power_of_2(timesteps)
|
||||
stride_x, stride_y = logits.stride(0), scratchpad.stride(0)
|
||||
stride_g = state.grammar.flatten(0, -2).stride(0)
|
||||
stride_c = state.decode_counts.stride(0)
|
||||
|
||||
bitpacked_reduction_kernel[(rows, blocks)](
|
||||
logits,
|
||||
state.indicators,
|
||||
slots,
|
||||
None,
|
||||
None,
|
||||
state.grammar,
|
||||
state.context_counts,
|
||||
state.decode_counts,
|
||||
drafted,
|
||||
state.repetition,
|
||||
state.frequency,
|
||||
state.presence,
|
||||
state.logit_bias,
|
||||
state.temperature,
|
||||
scratchpad,
|
||||
vocab_size,
|
||||
0,
|
||||
gamma,
|
||||
MAX_K,
|
||||
_TOP_K_SCALE,
|
||||
batch_size,
|
||||
False,
|
||||
True,
|
||||
True,
|
||||
False,
|
||||
False,
|
||||
False,
|
||||
config.radix,
|
||||
enable_pdl,
|
||||
stride_x,
|
||||
stride_g,
|
||||
stride_c,
|
||||
None,
|
||||
stride_y,
|
||||
config.block_n,
|
||||
None,
|
||||
block_g,
|
||||
exact,
|
||||
tl.float32 if exact else tl.bfloat16,
|
||||
num_warps=config.first_warps,
|
||||
)
|
||||
cumulative_unpack_kernel[(rows,)](
|
||||
scratchpad,
|
||||
state.indicators,
|
||||
slots,
|
||||
None,
|
||||
state.top_k,
|
||||
state.top_p,
|
||||
state.min_p,
|
||||
values,
|
||||
indices,
|
||||
blocks,
|
||||
1,
|
||||
vocab_size,
|
||||
gamma,
|
||||
MAX_K,
|
||||
None,
|
||||
batch_size,
|
||||
block_v,
|
||||
block_v * MAX_K,
|
||||
False,
|
||||
True,
|
||||
False,
|
||||
False,
|
||||
not config.radix,
|
||||
enable_pdl,
|
||||
stride_y,
|
||||
None,
|
||||
None,
|
||||
config.block_n,
|
||||
block_v,
|
||||
None,
|
||||
logits if exact else None,
|
||||
state.grammar if exact else None,
|
||||
state.context_counts if exact else None,
|
||||
state.decode_counts if exact else None,
|
||||
drafted if exact else None,
|
||||
state.repetition if exact else None,
|
||||
state.frequency if exact else None,
|
||||
state.presence if exact else None,
|
||||
state.logit_bias if exact else None,
|
||||
state.temperature if exact else None,
|
||||
vocab_size,
|
||||
0,
|
||||
stride_x,
|
||||
stride_g,
|
||||
stride_c,
|
||||
block_g,
|
||||
exact,
|
||||
num_warps=config.second_warps,
|
||||
)
|
||||
chain_speculative_verification_kernel[(batch_size,)](
|
||||
values,
|
||||
indices,
|
||||
state.indicators,
|
||||
slots,
|
||||
None,
|
||||
drafted,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
state.seeds,
|
||||
offsets,
|
||||
state.decode_counts,
|
||||
None,
|
||||
drafted,
|
||||
accepted,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
gamma,
|
||||
MAX_K,
|
||||
True,
|
||||
False,
|
||||
enable_pdl,
|
||||
True,
|
||||
False,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
stride_c,
|
||||
None,
|
||||
block_g,
|
||||
_LOGPROB_BLOCK,
|
||||
num_warps=next_power_of_2(timesteps),
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MAX_K",
|
||||
"MAX_OFFSET",
|
||||
"TABLE",
|
||||
"Indicator",
|
||||
"SlotState",
|
||||
"SonicConfig",
|
||||
"configs",
|
||||
"pick",
|
||||
"sample",
|
||||
"scratchpad_columns",
|
||||
"verify",
|
||||
]
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
# sonic-sampler
|
||||
|
||||
This directory vendors the kernels and wrappers of
|
||||
[sonic-sampler](https://github.com/tachyontrails/sonic-sampler) 1.0.0
|
||||
(Apache-2.0, `LICENSE`), at commit
|
||||
`c1acbca39b7faa9269b24e73dee2b57fe6215c7e` of the `tokenspeed` branch of
|
||||
[LorrinWWW/sonic-sampler](https://github.com/LorrinWWW/sonic-sampler/tree/tokenspeed).
|
||||
That branch adds two commits to the 1.0.0 release
|
||||
(`b3f8b7dfa052e0fde3020223346039a251b3e0ab`):
|
||||
|
||||
- `0371ed8aa59941f99b0ef675c01094f7b7e6c19b`: the batch size is a runtime
|
||||
argument, so one kernel serves every batch size instead of compiling one per
|
||||
size.
|
||||
- `c1acbca39b7faa9269b24e73dee2b57fe6215c7e`: with `noise_seeds` and
|
||||
`noise_offsets`, the Gumbel and acceptance noise is drawn in-kernel from
|
||||
Philox keyed by the slot's seed and `offset * 256 + timestep`, so no noise
|
||||
plane is allocated or refreshed per step.
|
||||
|
||||
Only the kernels (`ops/`) and their indicator bit layout (`core/flags.py`'s
|
||||
`Indicator`) are vendored. `tokenspeed_kernel.ops.sampling.sonic` launches
|
||||
them over the backend's slot state and picks their config; `--sampling-backend
|
||||
sonic` selects them.
|
||||
|
||||
## Local changes
|
||||
|
||||
The vendored sources differ from `src/sonic_sampler` at that commit only by:
|
||||
|
||||
- the package path: `sonic_sampler.` imports name
|
||||
`tokenspeed_kernel.thirdparty.sonic_sampler`;
|
||||
- Triton imports: `from triton import ...`, `triton.language.extra.libdevice`
|
||||
and `triton.language.core.builtin` go through `tokenspeed_kernel._triton`,
|
||||
so the kernels compile with `tokenspeed-triton`;
|
||||
- exact fp32 logits (soft-capped heads): `ops/prologue.py` gathers the logit
|
||||
manipulators into `transform`, which keeps the logits' dtype
|
||||
(`value_dtype`; bf16 logits compile as before), and adds `exact_maximum`,
|
||||
`exact_greedy` and `exact_candidates`. Under the `exact` flag of
|
||||
`bitpacked_reduction_kernel`, `cumulative_selection_kernel` and
|
||||
`cumulative_unpack_kernel`, greedy rows keep each block's fp32 maximum and
|
||||
its first column, and sampled rows rank by bf16 keys only to pick their
|
||||
top-128 candidates, whose fp32 values are re-read (from the new trailing
|
||||
arguments), transformed and re-sorted before masking and the draw;
|
||||
- the msgspec host layer is not vendored: `base/`, `core/buffer.py`,
|
||||
`interface/` (the `fused_singular`/`fused_multistep` wrappers, the tiling
|
||||
and warp-config structs, the class-based interfaces), the packaged dispatch
|
||||
tables (`resources/`), and `ops/copy.py`; `core/flags.py` keeps only
|
||||
`Indicator` (with `stochastic` and `from_params`), and `core/naive.py` (the
|
||||
reference sampler, the only user of `cytoolz`) is left out. With them go
|
||||
the kernels only the class-based interfaces launch,
|
||||
`ops/topk/bitpack.py:bitpacked_reduction_kernel` and
|
||||
`ops/topk/unpack.py:merge_unpack_kernel`, and `__version__`;
|
||||
- repository formatting (black, isort).
|
||||
|
||||
The upstream docs, assets and packaging are not vendored. To update, copy
|
||||
`src/sonic_sampler/ops` and `core/flags.py` from the new commit, apply the
|
||||
changes above, and check the launch arguments in
|
||||
`tokenspeed_kernel.ops.sampling.sonic` against the new wrappers.
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.core.flags import Indicator
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import IntFlag, auto, unique
|
||||
from operator import lshift
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.base import MAX_K
|
||||
|
||||
# The most top-k log-probabilities a request may ask for.
|
||||
MAX_TOP_LP: int = 5
|
||||
|
||||
|
||||
@unique
|
||||
class Indicator(IntFlag):
|
||||
|
||||
# Grammar Enablement -> 0x1.
|
||||
GRAMMAR = auto()
|
||||
|
||||
# Repetition (Multiplicative) -> 0x2.
|
||||
MULTIPLICATIVE = auto()
|
||||
|
||||
# Repetition (Frequency) -> 0x4.
|
||||
FREQUENCY = auto()
|
||||
|
||||
# Repetition (Presence) -> 0x8.
|
||||
PRESENCE = auto()
|
||||
|
||||
# Logit Bias -> 0x10.
|
||||
BIAS = auto()
|
||||
|
||||
# Temperature -> 0x20.
|
||||
TEMPERATURE = auto()
|
||||
|
||||
# Top-1 -> 0x40.
|
||||
GREEDY = auto()
|
||||
|
||||
# Top-K -> 0x80.
|
||||
TOP_K = auto()
|
||||
|
||||
# Top-P -> 0x100.
|
||||
TOP_P = auto()
|
||||
|
||||
# Min-P -> 0x200.
|
||||
MIN_P = auto()
|
||||
|
||||
# Output Top-K Log-Probs -> 0x400.
|
||||
TOP_K_LOGPROBS = auto()
|
||||
|
||||
# Stochastic Verify over Greedy Drafting -> 0x800.
|
||||
STOCHASTIC_VERIFY_GREEDY_DRAFT = auto()
|
||||
|
||||
@classmethod
|
||||
def stochastic(cls) -> Indicator:
|
||||
|
||||
return (
|
||||
Indicator.TEMPERATURE | Indicator.TOP_K | Indicator.TOP_P | Indicator.MIN_P
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_params(
|
||||
cls,
|
||||
grammar: bool = False,
|
||||
multiplicative: float = 1.0,
|
||||
frequency: float = 0.0,
|
||||
presence: float = 0.0,
|
||||
logit_bias: bool = False,
|
||||
temperature: float = 1.0,
|
||||
top_k: int = MAX_K,
|
||||
top_p: float = 1.0,
|
||||
min_p: float = 0.0,
|
||||
top_k_logprobs: int = 0,
|
||||
greedy_draft: bool = False,
|
||||
) -> Indicator:
|
||||
|
||||
flags = [
|
||||
grammar,
|
||||
multiplicative != 1.0,
|
||||
frequency != 0.0,
|
||||
presence != 0.0,
|
||||
logit_bias,
|
||||
temperature != 1.0,
|
||||
(greedy := (top_k == 1)),
|
||||
1 < top_k < MAX_K,
|
||||
not greedy and (0.0 < top_p < 1.0),
|
||||
not greedy and (0.0 < min_p < 1.0),
|
||||
not greedy and (0 < top_k_logprobs <= MAX_TOP_LP),
|
||||
not greedy and greedy_draft,
|
||||
]
|
||||
|
||||
positions = range(len(flags))
|
||||
bits = map(int, flags)
|
||||
|
||||
return cls(sum(map(lshift, bits, positions)))
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.base import MAX_K
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
cdiv, jit = triton.cdiv, triton.jit
|
||||
from tokenspeed_kernel._triton import tl # noqa.
|
||||
|
||||
builtin = tl.core.builtin
|
||||
from tokenspeed_kernel._triton import libdevice # noqa.
|
||||
|
||||
fast_expf, fast_logf = libdevice.fast_expf, libdevice.fast_logf
|
||||
|
||||
|
||||
MAX_K: int = 128
|
||||
|
||||
NOISE_FLOOR: tl.constexpr = tl.constexpr(1.0e-7)
|
||||
NOISE_STRIDE: tl.constexpr = tl.constexpr(256)
|
||||
|
||||
|
||||
def next_power_of_2(value: int) -> int:
|
||||
|
||||
active_bits = int.bit_count(value)
|
||||
|
||||
return (1 << int.bit_length(value)) if active_bits > 1 else value
|
||||
|
||||
|
||||
@jit
|
||||
def gdc_wait():
|
||||
|
||||
tl.inline_asm_elementwise(
|
||||
asm="griddepcontrol.wait;",
|
||||
constraints="=r",
|
||||
args=[],
|
||||
dtype=tl.int32,
|
||||
is_pure=False,
|
||||
pack=1,
|
||||
)
|
||||
|
||||
|
||||
@jit
|
||||
def gdc_launch_dependents():
|
||||
|
||||
tl.inline_asm_elementwise(
|
||||
asm="griddepcontrol.launch_dependents;",
|
||||
constraints="=r",
|
||||
args=[],
|
||||
dtype=tl.int32,
|
||||
is_pure=False,
|
||||
pack=1,
|
||||
)
|
||||
|
||||
|
||||
@jit
|
||||
def philox_key(h_ptr, l_ptr, batch_id, step):
|
||||
|
||||
# Key the stream by the slot's seed and offset, so draws advance with the request only.
|
||||
|
||||
seed = tl.load(h_ptr + batch_id).to(tl.int64)
|
||||
offset = tl.load(l_ptr + batch_id).to(tl.int64)
|
||||
|
||||
lo, hi, _, _ = tl.randint4x(seed, offset * NOISE_STRIDE + step)
|
||||
|
||||
return (hi.to(tl.int64) << 32) | lo.to(tl.int64)
|
||||
|
||||
|
||||
@jit
|
||||
def philox_gumbel(key, indices):
|
||||
|
||||
# Draw one Philox round per group of four consecutive token indices.
|
||||
|
||||
u0, u1, u2, u3 = tl.rand4x(key, indices // 4)
|
||||
|
||||
lane = indices % 4
|
||||
uniform = tl.where(
|
||||
lane == 0, u0, tl.where(lane == 1, u1, tl.where(lane == 2, u2, u3))
|
||||
)
|
||||
|
||||
return tl.log(-tl.log(tl.maximum(uniform, NOISE_FLOOR)))
|
||||
|
||||
|
||||
@jit
|
||||
def philox_uniform(
|
||||
h_ptr,
|
||||
l_ptr,
|
||||
batch_id,
|
||||
span,
|
||||
mask,
|
||||
counter,
|
||||
block_g: tl.constexpr,
|
||||
):
|
||||
|
||||
tl.static_assert(block_g <= NOISE_STRIDE)
|
||||
|
||||
uniform = tl.zeros((block_g,), dtype=tl.float32)
|
||||
|
||||
for step in tl.static_range(block_g):
|
||||
|
||||
# Draw each step's coin in (0, 1] past the counters its gumbel noise consumes.
|
||||
|
||||
key = philox_key(h_ptr, l_ptr, batch_id, step)
|
||||
coin = tl.rand(key, counter + tl.zeros((1,), dtype=tl.int32))
|
||||
coin = tl.maximum(1.0 - coin, NOISE_FLOOR)
|
||||
|
||||
uniform = tl.where(span == step, coin.broadcast_to((block_g,)), uniform)
|
||||
|
||||
return tl.where(mask, uniform, 0.0)
|
||||
|
||||
|
||||
@jit
|
||||
def ones_like(other):
|
||||
|
||||
return tl.full(other.shape, 1, dtype=other.dtype)
|
||||
|
||||
|
||||
@jit
|
||||
def log_softmax(logits, maximum):
|
||||
|
||||
scores = logits.to(tl.float32) - maximum
|
||||
exp_sum = tl.sum(fast_expf(scores), axis=0)
|
||||
|
||||
return scores - fast_logf(exp_sum)
|
||||
|
||||
|
||||
@jit
|
||||
def nucleus_masking(p_ptr, batch_id, logits, maximum, max_k: tl.constexpr):
|
||||
|
||||
scores = fast_expf(logits.to(tl.float32) - maximum)
|
||||
ladder = tl.cumsum(scores, axis=0)
|
||||
|
||||
scale = tl.gather(
|
||||
ladder, tl.full((1,), max_k - 1, dtype=tl.int32), axis=0
|
||||
) * tl.load(p_ptr + batch_id).to(tl.float32)
|
||||
|
||||
return ladder <= scale
|
||||
|
||||
|
||||
@builtin
|
||||
def to_scalar(value, _semantic=None, _generator=None):
|
||||
|
||||
return _semantic.unsplat(value)
|
||||
|
||||
|
||||
@jit
|
||||
def cumulative_masking(
|
||||
k_ptr,
|
||||
p_ptr,
|
||||
n_ptr,
|
||||
batch_id,
|
||||
indicator,
|
||||
values,
|
||||
maximum,
|
||||
offsets,
|
||||
max_k: tl.constexpr,
|
||||
):
|
||||
|
||||
minima: tl.constexpr = -float("inf")
|
||||
|
||||
if (indicator & 0x80) > 0:
|
||||
|
||||
subset_mask = offsets < tl.load(k_ptr + batch_id)
|
||||
values = tl.where(subset_mask, values, minima)
|
||||
|
||||
if (indicator & 0x100) > 0:
|
||||
|
||||
nucleus_mask = nucleus_masking(p_ptr, batch_id, values, maximum, max_k) | (
|
||||
offsets == 0
|
||||
)
|
||||
|
||||
values = tl.where(nucleus_mask, values, minima)
|
||||
|
||||
if (indicator & 0x200) > 0:
|
||||
|
||||
pivot = fast_logf(tl.load(n_ptr + batch_id).to(tl.float32)) + maximum
|
||||
values = tl.where(values >= pivot, values, minima)
|
||||
|
||||
return values
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
cdiv, jit = triton.cdiv, triton.jit
|
||||
|
||||
|
||||
@jit
|
||||
def mask_pair(shape):
|
||||
|
||||
sign = tl.full(shape, 0x8000, dtype=tl.uint16)
|
||||
full = tl.full(shape, 0xFFFF, dtype=tl.uint16)
|
||||
|
||||
return sign, full
|
||||
|
||||
|
||||
@jit
|
||||
def encode_block(values):
|
||||
"""
|
||||
Project the representable real numbers into the finite set of natural numbers, ℕ_0, such that:
|
||||
|
||||
• Positive numbers are merely offset by 2^15 given their ascending ordering, while
|
||||
|
||||
• Negative numbers, given the inverse ordering of their absolute values, are inverted
|
||||
via (2^16 - x - 1).
|
||||
|
||||
Note that `values` here is inherently bit-casted to an unsigned 16-bit integer first and the above
|
||||
is achieved by encoding the value under the following scheme:
|
||||
|
||||
• Positive --( Mask: 0x8000 )-> [ Sign Bit: 1, Lower 15 Bits As-Is ].
|
||||
|
||||
• Negative --( Mask: 0xFFFF )-> [ Inverted 16 Bits ].
|
||||
|
||||
With mask(s) applied by the XOR operation and the resulting block being upcasted to 32-bit
|
||||
unsigned integer(s).
|
||||
|
||||
"""
|
||||
shape: tl.constexpr = values.shape
|
||||
|
||||
sign, full = mask_pair(shape)
|
||||
|
||||
encoded = values.to(tl.uint16, bitcast=True)
|
||||
|
||||
mask = tl.where((encoded & sign) != 0, full, sign)
|
||||
|
||||
return (encoded ^ mask).to(tl.uint32)
|
||||
|
||||
|
||||
@jit
|
||||
def shift_pack(values, indices, block_n):
|
||||
"""
|
||||
Shifts the lower 16 bits of `values` to the upper half and inverts the `indices` with
|
||||
respect to `block_n` to the lower half.
|
||||
|
||||
"""
|
||||
return (values << 16) | ((block_n - 1) ^ indices)
|
||||
|
||||
|
||||
@jit
|
||||
def bitpack_block(values, indices, block_n):
|
||||
"""
|
||||
Packs each ℕ_0-projected unsigned 16-bit integer `value` into the upper half of an unsigned
|
||||
32-bit integer with its corresponding inverted `index` into the lower half.
|
||||
|
||||
Note(s):
|
||||
|
||||
• Here, the indices are inverted via (BLOCK_N - k - 1) to ensure stable sorting /
|
||||
selection i.e. earlier positioned tied-values are ordered first.
|
||||
|
||||
Caveat(s):
|
||||
|
||||
• All indices must no value greater than (2^16 - 1) i.e. 65,535.
|
||||
|
||||
"""
|
||||
encoded = encode_block(values)
|
||||
|
||||
return shift_pack(encoded, indices, block_n)
|
||||
|
||||
|
||||
@jit
|
||||
def bitpack_scalar(value, index, block_n):
|
||||
|
||||
raw = value.to(tl.uint16, bitcast=True)
|
||||
|
||||
if (raw & 0x8000) != 0:
|
||||
|
||||
raw ^= 0xFFFF
|
||||
|
||||
else:
|
||||
|
||||
raw ^= 0x8000
|
||||
|
||||
encoded = raw.to(tl.uint32)
|
||||
|
||||
return (encoded << 16) | ((block_n - 1) ^ index)
|
||||
|
||||
|
||||
@jit
|
||||
def decode_block(values):
|
||||
|
||||
shape: tl.constexpr = values.shape
|
||||
|
||||
sign, full = mask_pair(shape)
|
||||
|
||||
decoded = values.to(tl.uint16)
|
||||
|
||||
mask = tl.where((decoded & sign) == 0, full, sign)
|
||||
|
||||
return (decoded ^ mask).to(tl.bfloat16, bitcast=True)
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
jit = triton.jit
|
||||
from tokenspeed_kernel._triton import libdevice # noqa.
|
||||
|
||||
fast_expf = libdevice.fast_expf
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.base import (
|
||||
cumulative_masking,
|
||||
gdc_launch_dependents,
|
||||
gdc_wait,
|
||||
log_softmax,
|
||||
)
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.prologue import (
|
||||
exact_candidates,
|
||||
exact_greedy,
|
||||
)
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.singular import greedy_maximum
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.topk.unpack import unpack_top_k
|
||||
|
||||
|
||||
@jit
|
||||
def resolve_indices(
|
||||
q_ptr,
|
||||
f_ptr,
|
||||
row_id,
|
||||
lookahead: tl.constexpr,
|
||||
batch_size: tl.int32,
|
||||
slotted: tl.constexpr,
|
||||
varlen: tl.constexpr,
|
||||
block_q: tl.constexpr,
|
||||
):
|
||||
"""
|
||||
Compute the batch id, step id, and margin given the row id of the current tile.
|
||||
|
||||
"""
|
||||
if varlen:
|
||||
|
||||
row_ids = tl.arange(0, block_q)
|
||||
row_mask = row_ids < (batch_size + 1)
|
||||
|
||||
lengths = tl.load(q_ptr + row_ids, mask=row_mask, other=0, cache_modifier=".cv")
|
||||
marked = ((lengths <= row_id) & row_mask).to(tl.uint32)
|
||||
|
||||
batch_id = tl.sum(marked, axis=0) - 1
|
||||
margin = tl.load(q_ptr + batch_id)
|
||||
|
||||
step_id = row_id - margin
|
||||
|
||||
else:
|
||||
|
||||
timesteps = lookahead + 1
|
||||
|
||||
batch_id = row_id // timesteps
|
||||
step_id = row_id % timesteps
|
||||
|
||||
margin = batch_id * timesteps
|
||||
|
||||
if slotted:
|
||||
|
||||
batch_id = tl.load(f_ptr + batch_id)
|
||||
|
||||
return batch_id, margin, step_id
|
||||
|
||||
|
||||
@jit
|
||||
def cumulative_unpack_kernel(
|
||||
# Input Data Pointer(s).
|
||||
s_ptr, # Scratch-Pad -> [ L, Z_v • M ].
|
||||
z_ptr, # Indicators -> [ B ].
|
||||
f_ptr, # Slot Mapping -> [ B ].
|
||||
q_ptr, # Cumulative Lengths -> [ B + 1 ].
|
||||
k_ptr, # Top-K -> [ B ].
|
||||
p_ptr, # Top-P -> [ B ].
|
||||
n_ptr, # Min-P -> [ B ].
|
||||
# Output Data Pointer(s).
|
||||
v_ptr, # Selected Values -> [ B • (γ + 1), M ].
|
||||
j_ptr, # Selected Indices -> [ B • (γ + 1), M ].
|
||||
# Model Specific(s).
|
||||
vocab_blocks: tl.constexpr, # Local Vocab Blocks -> Z_v // W.
|
||||
world_size: tl.constexpr, # World Size -> W.
|
||||
shard_size: tl.constexpr, # Shard Size -> V_d // W.
|
||||
lookahead: tl.constexpr, # Lookahead -> γ.
|
||||
max_k: tl.constexpr, # Maximum Top-K Value -> M.
|
||||
scale: tl.constexpr, # Reciprocal of Power-of-2 Integer Scale Factor.
|
||||
batch_size: tl.int32, # Total Sequences -> B.
|
||||
total_rows: tl.constexpr, # Total (Sharded) Logical Vocab Blocks -> W • Z_v'.
|
||||
total_cols: tl.constexpr, # Total Logical Bit-Packed Columns -> W • Z_v' • M.
|
||||
# Conditional Flag(s).
|
||||
sharded: tl.constexpr, # Sharded Scratch-Pad Flag.
|
||||
slotted: tl.constexpr, # Slot Indirection Flag.
|
||||
varlen: tl.constexpr, # Variable-Length Lookahead Flag.
|
||||
is_adaptive: tl.constexpr, # Adaptive Scaling Applied Flag.
|
||||
is_alternating: tl.constexpr, # Alternating Ascending-Descending Tile(s) Flag.
|
||||
enable_pdl: tl.constexpr, # PDL Enablement Flag.
|
||||
# Stride(s).
|
||||
stride_s: tl.constexpr, # Batch Stride of Scratch-Pad.
|
||||
stride_r: tl.constexpr, # Batch Stride of Sharded Scratch-Pad -> Z_v • M.
|
||||
stride_b: tl.constexpr, # Logical Batch Stride of Sharded Scratch-Pad -> Z_v' • M.
|
||||
# Kernel Specific(s).
|
||||
block_n: tl.constexpr, # Block Size of Vocab Block(s).
|
||||
block_v: tl.constexpr, # Next Power-of-2 Vocab Block(s) -> Z_v'.
|
||||
block_q: tl.constexpr, # Block Size of Cumulative Length(s).
|
||||
# Exact fp32 Re-Read of the Candidates (exact only).
|
||||
x_ptr, # Logits -> [ L, V_d' / W ].
|
||||
gr_ptr, # Grammar Bit-Mask -> [ B • (γ' + 1), V_t / 32 ].
|
||||
cr_ptr, # Context Counts -> [ B, V_t ].
|
||||
dr_ptr, # Decode Counts -> [ B, V_t ].
|
||||
tr_ptr, # Drafted Tokens -> [ L ].
|
||||
rr_ptr, # Repetition Penalties -> [ B ].
|
||||
fr_ptr, # Frequency Penalties -> [ B ].
|
||||
pr_ptr, # Presence Penalties -> [ B ].
|
||||
br_ptr, # Logit Bias -> [ B, V_t ].
|
||||
er_ptr, # Temperature -> [ B ].
|
||||
vocab_size: tl.constexpr, # Local Vocab Size.
|
||||
shard_offset: tl.constexpr, # Local Shard Offset.
|
||||
stride_x: tl.constexpr, # Batch Stride of Logits.
|
||||
stride_gr: tl.constexpr, # Batch Stride of Grammar Bit-Mask.
|
||||
stride_cr: tl.constexpr, # Batch Stride of Counts and Bias.
|
||||
block_t: tl.constexpr, # Block Size of Drafted Tokens.
|
||||
exact: tl.constexpr, # Exact fp32 Logits Flag.
|
||||
) -> None:
|
||||
|
||||
# Extract the batch id from program id and load the indicator.
|
||||
|
||||
row_id = tl.program_id(axis=0)
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_wait()
|
||||
|
||||
batch_id, margin, step_id = resolve_indices(
|
||||
q_ptr,
|
||||
f_ptr,
|
||||
row_id,
|
||||
lookahead,
|
||||
batch_size,
|
||||
slotted,
|
||||
varlen,
|
||||
block_q,
|
||||
)
|
||||
|
||||
indicator = tl.load(z_ptr + batch_id)
|
||||
|
||||
if (indicator & 0x40) > 0:
|
||||
|
||||
# Load, reduce, and unpack greedy i.e. top-1 maximum.
|
||||
|
||||
if exact:
|
||||
|
||||
selection = exact_greedy(
|
||||
s_ptr, row_id, vocab_blocks, enable_pdl, stride_s, block_v
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
target, shift = greedy_maximum(
|
||||
s_ptr,
|
||||
row_id,
|
||||
max_k,
|
||||
vocab_blocks,
|
||||
world_size,
|
||||
shard_size,
|
||||
sharded,
|
||||
enable_pdl,
|
||||
stride_s,
|
||||
block_n,
|
||||
block_v,
|
||||
)
|
||||
|
||||
# Unpack the selected token id from the target index.
|
||||
|
||||
selection = shift + ((block_n - 1) ^ (target & 0xFFFF))
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
# Store at margin boundary for later contiguous read-out.
|
||||
|
||||
tl.store(j_ptr + (margin * max_k) + step_id, selection)
|
||||
|
||||
else:
|
||||
|
||||
# Load, reduce, and unpack top-k stochastic subset.
|
||||
|
||||
values, indices = unpack_top_k(
|
||||
s_ptr,
|
||||
row_id,
|
||||
vocab_blocks,
|
||||
world_size,
|
||||
shard_size,
|
||||
max_k,
|
||||
scale,
|
||||
total_rows,
|
||||
total_cols,
|
||||
sharded,
|
||||
is_adaptive,
|
||||
is_alternating,
|
||||
enable_pdl,
|
||||
stride_r,
|
||||
stride_b,
|
||||
stride_s,
|
||||
block_n,
|
||||
block_v,
|
||||
)
|
||||
|
||||
if exact:
|
||||
|
||||
# Re-read the candidates' exact values: bf16 keys only chose them.
|
||||
|
||||
values, indices = exact_candidates(
|
||||
x_ptr,
|
||||
row_id,
|
||||
indices,
|
||||
indicator,
|
||||
None,
|
||||
gr_ptr,
|
||||
cr_ptr,
|
||||
dr_ptr,
|
||||
tr_ptr,
|
||||
rr_ptr,
|
||||
fr_ptr,
|
||||
pr_ptr,
|
||||
br_ptr,
|
||||
er_ptr,
|
||||
batch_id,
|
||||
step_id,
|
||||
margin,
|
||||
lookahead + 1,
|
||||
vocab_size,
|
||||
shard_offset,
|
||||
lookahead,
|
||||
False,
|
||||
True,
|
||||
False,
|
||||
stride_x,
|
||||
stride_gr,
|
||||
stride_cr,
|
||||
None,
|
||||
block_t,
|
||||
max_k,
|
||||
)
|
||||
|
||||
# Prepare for later softmax computation and write-out offset(s).
|
||||
|
||||
maximum = tl.gather(values, tl.full((1,), 0, dtype=tl.int32), axis=0)
|
||||
offsets = tl.arange(0, max_k)
|
||||
|
||||
if (indicator & 0x380) > 0:
|
||||
|
||||
# Apply top-k, top-p, and / or min-p subset masking.
|
||||
|
||||
values = cumulative_masking(
|
||||
k_ptr,
|
||||
p_ptr,
|
||||
n_ptr,
|
||||
batch_id,
|
||||
indicator,
|
||||
values,
|
||||
maximum,
|
||||
offsets,
|
||||
max_k,
|
||||
)
|
||||
|
||||
# Compute softmax from values with potentially masked subset.
|
||||
|
||||
values = fast_expf(log_softmax(values, maximum))
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
# Write-out the target values and top-k indices.
|
||||
|
||||
positions = (row_id * max_k) + offsets
|
||||
|
||||
tl.store(v_ptr + positions, values)
|
||||
tl.store(j_ptr + positions, indices)
|
||||
+720
@@ -0,0 +1,720 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
cdiv, jit = triton.cdiv, triton.jit
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.base import (
|
||||
gdc_launch_dependents,
|
||||
gdc_wait,
|
||||
ones_like,
|
||||
)
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.encoding import bitpack_scalar
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.topk.bitpack import top_k_reduction
|
||||
|
||||
__all__ = ["bitpacked_reduction_kernel"]
|
||||
|
||||
|
||||
@jit
|
||||
def grammar(
|
||||
g_ptr,
|
||||
logits,
|
||||
indicator,
|
||||
batch_id,
|
||||
step_id,
|
||||
timesteps,
|
||||
cols,
|
||||
mask,
|
||||
minima,
|
||||
stride_g: tl.constexpr,
|
||||
):
|
||||
|
||||
if g_ptr is not None and (indicator & 0x1):
|
||||
|
||||
target_id = (batch_id * timesteps) + step_id
|
||||
|
||||
bitmask = tl.load(
|
||||
g_ptr + (target_id * stride_g) + (cols // 32), mask=mask, other=-1
|
||||
) >> (cols % 32)
|
||||
|
||||
logits = tl.where((bitmask & 0x1) > 0, logits, minima)
|
||||
|
||||
return logits
|
||||
|
||||
|
||||
@jit
|
||||
def repetition(
|
||||
c_ptr,
|
||||
r_ptr,
|
||||
f_ptr,
|
||||
p_ptr,
|
||||
batch_id,
|
||||
indicator,
|
||||
logits,
|
||||
decode,
|
||||
minima,
|
||||
cols,
|
||||
mask,
|
||||
stride_c: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
value_dtype: tl.constexpr,
|
||||
):
|
||||
|
||||
values = logits
|
||||
|
||||
if c_ptr is not None and (indicator & 0x2) > 0:
|
||||
|
||||
# Apply multiplicative penalties.
|
||||
|
||||
total = decode + tl.load(
|
||||
c_ptr + (batch_id * stride_c) + cols, mask=mask, other=0
|
||||
)
|
||||
|
||||
scales = tl.load(r_ptr + batch_id).broadcast_to(block_n)
|
||||
scales = tl.where(total > 0, scales, ones_like(scales))
|
||||
|
||||
values = tl.where(values < 0, values * scales, values / scales).to(value_dtype)
|
||||
|
||||
if (indicator & 0x4) > 0:
|
||||
|
||||
# Apply frequency penalties.
|
||||
|
||||
values -= decode.to(value_dtype) * tl.load(f_ptr + batch_id)
|
||||
|
||||
if (indicator & 0x8) > 0:
|
||||
|
||||
# Apply presence penalties.
|
||||
|
||||
values -= (decode > 0).to(value_dtype) * tl.load(p_ptr + batch_id)
|
||||
|
||||
return tl.where(mask, values, minima)
|
||||
|
||||
|
||||
@jit
|
||||
def logit_bias(b_ptr, indicator, logits, batch_id, cols, mask, stride_b: tl.constexpr):
|
||||
|
||||
values = logits
|
||||
|
||||
if b_ptr is not None and (indicator & 0x10) > 0:
|
||||
|
||||
values += tl.load(b_ptr + (batch_id * stride_b) + cols, mask=mask, other=0.0)
|
||||
|
||||
return values
|
||||
|
||||
|
||||
@jit
|
||||
def greedy_reduction(
|
||||
y_ptr,
|
||||
batch_id,
|
||||
block_id,
|
||||
logits,
|
||||
enable_pdl: tl.constexpr,
|
||||
stride_y: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
|
||||
value, index = tl.max(logits, axis=0, return_indices=True)
|
||||
|
||||
maximum = bitpack_scalar(value.to(tl.bfloat16), index, block_n)
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
target = (batch_id * stride_y) + block_id
|
||||
|
||||
tl.store(y_ptr + target, maximum)
|
||||
|
||||
|
||||
@jit
|
||||
def decode_counts(
|
||||
d_ptr,
|
||||
t_ptr,
|
||||
batch_id,
|
||||
step_id,
|
||||
margin,
|
||||
cols,
|
||||
mask,
|
||||
lookahead: tl.constexpr,
|
||||
tokens: tl.constexpr,
|
||||
singular: tl.constexpr,
|
||||
stride_d: tl.constexpr,
|
||||
stride_t: tl.constexpr,
|
||||
block_t: tl.constexpr,
|
||||
):
|
||||
"""
|
||||
Load decode counts block and conditionally update based on drafted tokens availability.
|
||||
|
||||
Note(s):
|
||||
|
||||
• The drafted tokens i.e. `t_ptr` here should index column-wise from the first draft
|
||||
timestep i.e. the first drafted token:
|
||||
|
||||
[ t_1, t_2, ..., t_γ ]
|
||||
|
||||
• In the non-singular case, it is assumed that the drafted tokens has an additional
|
||||
slot for the additional rejection-sampled token by the target model:
|
||||
|
||||
[ t_1, t_2, ..., t_γ, t_{γ+1} ]
|
||||
|
||||
"""
|
||||
decode = tl.load(d_ptr + (batch_id * stride_d) + cols, mask=mask, other=0)
|
||||
|
||||
if tokens:
|
||||
|
||||
if singular:
|
||||
|
||||
timesteps = tl.arange(0, block_t)
|
||||
step_mask = timesteps < lookahead
|
||||
|
||||
drafted = tl.load(
|
||||
t_ptr + (batch_id * stride_t) + timesteps, mask=step_mask, other=-1
|
||||
)
|
||||
|
||||
decode += tl.sum((drafted[:, None] == cols[None, :]).to(tl.int32), axis=0)
|
||||
|
||||
elif step_id > 0:
|
||||
|
||||
time_steps = tl.arange(0, block_t)
|
||||
|
||||
block_mask = time_steps < step_id
|
||||
draft_tokens = tl.load(
|
||||
t_ptr + margin + time_steps, mask=block_mask, other=-1
|
||||
)
|
||||
|
||||
decode += tl.sum(
|
||||
(draft_tokens[:, None] == cols[None, :]).to(tl.int32), axis=0
|
||||
)
|
||||
|
||||
return decode
|
||||
|
||||
|
||||
@jit
|
||||
def transform(
|
||||
logits,
|
||||
indicator,
|
||||
cols,
|
||||
mask,
|
||||
m_ptr,
|
||||
g_ptr,
|
||||
c_ptr,
|
||||
d_ptr,
|
||||
t_ptr,
|
||||
r_ptr,
|
||||
f_ptr,
|
||||
p_ptr,
|
||||
b_ptr,
|
||||
e_ptr,
|
||||
batch_id,
|
||||
step_id,
|
||||
margin,
|
||||
timesteps,
|
||||
shard_offset: tl.constexpr,
|
||||
lookahead: tl.constexpr,
|
||||
indirection: tl.constexpr,
|
||||
tokens: tl.constexpr,
|
||||
singular: tl.constexpr,
|
||||
stride_g: tl.constexpr,
|
||||
stride_c: tl.constexpr,
|
||||
stride_t: tl.constexpr,
|
||||
block_t: tl.constexpr,
|
||||
width: tl.constexpr,
|
||||
value_dtype: tl.constexpr,
|
||||
):
|
||||
"""A request's grammar mask, repetition penalties, logit bias and temperature applied to ``logits`` at ``cols``, kept in ``value_dtype``."""
|
||||
|
||||
minima: tl.constexpr = -float("inf")
|
||||
|
||||
if (indicator & 0x1F) > 0:
|
||||
|
||||
# Has at least one of grammar, repetition, and / or logit bias.
|
||||
|
||||
cols += shard_offset
|
||||
|
||||
if indirection:
|
||||
|
||||
cols = tl.load(m_ptr + cols, mask=mask, other=0)
|
||||
|
||||
# Apply grammar bit-mask.
|
||||
|
||||
logits = grammar(
|
||||
g_ptr,
|
||||
logits,
|
||||
indicator,
|
||||
batch_id,
|
||||
step_id,
|
||||
timesteps,
|
||||
cols,
|
||||
mask,
|
||||
minima,
|
||||
stride_g,
|
||||
)
|
||||
|
||||
# Apply repetition penalties (multiplicative, frequency, and / or presence).
|
||||
|
||||
if d_ptr is not None and (indicator & 0xE) > 0:
|
||||
|
||||
decode = decode_counts(
|
||||
d_ptr,
|
||||
t_ptr,
|
||||
batch_id,
|
||||
step_id,
|
||||
margin,
|
||||
cols,
|
||||
mask,
|
||||
lookahead,
|
||||
tokens,
|
||||
singular,
|
||||
stride_c,
|
||||
stride_t,
|
||||
block_t,
|
||||
)
|
||||
|
||||
logits = repetition(
|
||||
c_ptr,
|
||||
r_ptr,
|
||||
f_ptr,
|
||||
p_ptr,
|
||||
batch_id,
|
||||
indicator,
|
||||
logits,
|
||||
decode,
|
||||
minima,
|
||||
cols,
|
||||
mask,
|
||||
stride_c,
|
||||
width,
|
||||
value_dtype,
|
||||
)
|
||||
|
||||
# Apply logit bias.
|
||||
|
||||
logits = logit_bias(b_ptr, indicator, logits, batch_id, cols, mask, stride_c)
|
||||
|
||||
if (indicator & 0x20) > 0:
|
||||
|
||||
# Apply temperature.
|
||||
|
||||
logits = (logits / tl.load(e_ptr + batch_id)).to(value_dtype)
|
||||
|
||||
return logits
|
||||
|
||||
|
||||
@jit
|
||||
def exact_maximum(
|
||||
y_ptr,
|
||||
row_id,
|
||||
block_id,
|
||||
blocks,
|
||||
shift,
|
||||
logits,
|
||||
enable_pdl: tl.constexpr,
|
||||
stride_y: tl.constexpr,
|
||||
):
|
||||
"""Store a block's exact fp32 maximum and its first column: the value bits in the row's first ``blocks`` slots, the column after them."""
|
||||
|
||||
value, index = tl.max(logits, axis=0, return_indices=True)
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
target = (row_id * stride_y) + block_id
|
||||
|
||||
tl.store(y_ptr + target, value.to(tl.uint32, bitcast=True))
|
||||
tl.store(y_ptr + target + blocks, (shift + index).to(tl.uint32))
|
||||
|
||||
|
||||
@jit
|
||||
def exact_greedy(
|
||||
s_ptr,
|
||||
row_id,
|
||||
vocab_blocks: tl.constexpr,
|
||||
enable_pdl: tl.constexpr,
|
||||
stride_s: tl.constexpr,
|
||||
block_v: tl.constexpr,
|
||||
):
|
||||
"""The first column holding the row's exact fp32 maximum, from the blocks' ``exact_maximum`` slots."""
|
||||
|
||||
span = tl.arange(0, block_v)
|
||||
span_mask = span < vocab_blocks
|
||||
offsets = (row_id * stride_s) + span
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_wait()
|
||||
|
||||
maxima = tl.load(s_ptr + offsets, mask=span_mask, other=0xFF800000)
|
||||
columns = tl.load(s_ptr + offsets + vocab_blocks, mask=span_mask, other=0)
|
||||
|
||||
# Blocks run in vocabulary order, so the first maximal block holds the first maximal column.
|
||||
|
||||
_, block = tl.max(maxima.to(tl.float32, bitcast=True), axis=0, return_indices=True)
|
||||
|
||||
return tl.sum(tl.where(span == block, columns, 0), axis=0).to(tl.int32)
|
||||
|
||||
|
||||
@jit
|
||||
def exact_candidates(
|
||||
x_ptr,
|
||||
row_id,
|
||||
indices,
|
||||
indicator,
|
||||
m_ptr,
|
||||
g_ptr,
|
||||
c_ptr,
|
||||
d_ptr,
|
||||
t_ptr,
|
||||
r_ptr,
|
||||
f_ptr,
|
||||
p_ptr,
|
||||
b_ptr,
|
||||
e_ptr,
|
||||
batch_id,
|
||||
step_id,
|
||||
margin,
|
||||
timesteps,
|
||||
vocab_size: tl.constexpr,
|
||||
shard_offset: tl.constexpr,
|
||||
lookahead: tl.constexpr,
|
||||
indirection: tl.constexpr,
|
||||
tokens: tl.constexpr,
|
||||
singular: tl.constexpr,
|
||||
stride_x: tl.constexpr,
|
||||
stride_g: tl.constexpr,
|
||||
stride_c: tl.constexpr,
|
||||
stride_t: tl.constexpr,
|
||||
block_t: tl.constexpr,
|
||||
max_k: tl.constexpr,
|
||||
):
|
||||
"""The candidates' exact fp32 values, recomputed from the logits, sorted descending with the lower column first on ties."""
|
||||
|
||||
index_dtype: tl.constexpr = indices.dtype
|
||||
|
||||
mask = indices < vocab_size
|
||||
columns = tl.where(mask, indices, 0).to(tl.int32)
|
||||
|
||||
logits = tl.load(
|
||||
x_ptr + (row_id * stride_x) + columns, mask=mask, other=-float("inf")
|
||||
)
|
||||
|
||||
logits = transform(
|
||||
logits,
|
||||
indicator,
|
||||
columns,
|
||||
mask,
|
||||
m_ptr,
|
||||
g_ptr,
|
||||
c_ptr,
|
||||
d_ptr,
|
||||
t_ptr,
|
||||
r_ptr,
|
||||
f_ptr,
|
||||
p_ptr,
|
||||
b_ptr,
|
||||
e_ptr,
|
||||
batch_id,
|
||||
step_id,
|
||||
margin,
|
||||
timesteps,
|
||||
shard_offset,
|
||||
lookahead,
|
||||
indirection,
|
||||
tokens,
|
||||
singular,
|
||||
stride_g,
|
||||
stride_c,
|
||||
stride_t,
|
||||
block_t,
|
||||
max_k,
|
||||
tl.float32,
|
||||
)
|
||||
|
||||
# Order-preserving fp32 bits above the inverted column: one descending sort orders both.
|
||||
|
||||
bits = logits.to(tl.uint32, bitcast=True)
|
||||
ordered = tl.where((bits & 0x80000000) != 0, ~bits, bits | 0x80000000)
|
||||
|
||||
keys = (ordered.to(tl.uint64) << 32) | (~columns.to(tl.uint32)).to(tl.uint64)
|
||||
keys = tl.sort(keys, descending=True)
|
||||
|
||||
ordered = (keys >> 32).to(tl.uint32)
|
||||
bits = tl.where((ordered & 0x80000000) != 0, ordered & 0x7FFFFFFF, ~ordered)
|
||||
|
||||
values = bits.to(tl.float32, bitcast=True)
|
||||
indices = (~(keys & 0xFFFFFFFF).to(tl.uint32)).to(index_dtype)
|
||||
|
||||
return values, indices
|
||||
|
||||
|
||||
@jit
|
||||
def resolve_indices(
|
||||
q_ptr,
|
||||
s_ptr,
|
||||
row_id,
|
||||
lookahead: tl.constexpr,
|
||||
batch_size: tl.int32,
|
||||
slotted: tl.constexpr,
|
||||
singular: tl.constexpr,
|
||||
varlen: tl.constexpr,
|
||||
block_q: tl.constexpr,
|
||||
):
|
||||
"""
|
||||
Resolves the batch id, step id, and margin given the row id of the current tile
|
||||
and supporting metadata under `singular`, `varlen`, and `multistep` settings.
|
||||
|
||||
Note(s):
|
||||
|
||||
• The `batch_id` resolves to the sequence index of the current tile, possibly
|
||||
re-mapped via slot indirection.
|
||||
|
||||
• The `step_id`, applicable only in `multistep` setting, resolves to the time
|
||||
index of the current tile.
|
||||
|
||||
• The `margin` resolves to the offset of the current tile within the in-flight batch.
|
||||
|
||||
• The `timesteps` refers to the maximum number of tokens per query in the batch,
|
||||
which defaults to 1 for singular and `γ + 1` for multistep.
|
||||
|
||||
"""
|
||||
if singular:
|
||||
|
||||
batch_id = row_id
|
||||
margin = row_id
|
||||
|
||||
step_id = 0
|
||||
timesteps = 1
|
||||
|
||||
elif varlen:
|
||||
|
||||
row_ids = tl.arange(0, block_q)
|
||||
row_mask = row_ids < (batch_size + 1)
|
||||
|
||||
# Note: Ensuring cached here allows for leveraging L2 in loading the `margin`.
|
||||
|
||||
lengths = tl.load(q_ptr + row_ids, mask=row_mask, other=0, cache_modifier=".cv")
|
||||
marked = ((lengths <= row_id) & row_mask).to(tl.uint32)
|
||||
|
||||
batch_id = tl.sum(marked, axis=0) - 1
|
||||
margin = tl.load(q_ptr + batch_id)
|
||||
|
||||
# Padded batch handling requires skipping tail end of row(s).
|
||||
|
||||
# skipped = (batch_id >= batch_size)
|
||||
|
||||
step_id = row_id - margin
|
||||
timesteps = lookahead + 1
|
||||
|
||||
else:
|
||||
|
||||
timesteps = lookahead + 1
|
||||
|
||||
batch_id = row_id // timesteps
|
||||
step_id = row_id % timesteps
|
||||
|
||||
margin = batch_id * timesteps
|
||||
|
||||
if slotted:
|
||||
|
||||
batch_id = tl.load(s_ptr + batch_id)
|
||||
|
||||
return batch_id, step_id, margin, timesteps
|
||||
|
||||
|
||||
@jit
|
||||
def bitpacked_reduction_kernel(
|
||||
# Input Data Pointer(s).
|
||||
x_ptr, # Logits -> [ L, V_d' / W ].
|
||||
z_ptr, # Indicators -> [ B ].
|
||||
s_ptr, # Slot Mapping -> [ B ].
|
||||
q_ptr, # Cumulative Lengths -> [ B + 1 ].
|
||||
m_ptr, # D2T Mapping -> [ V_d ].
|
||||
g_ptr, # Grammar Bit-Mask -> [ B • (γ' + 1), V_t / 32 ].
|
||||
c_ptr, # Context Counts -> [ B, V_t ].
|
||||
d_ptr, # Decode Counts -> [ B, V_t ].
|
||||
t_ptr, # Tokens -> [ T ].
|
||||
r_ptr, # Repetition Penalties -> [ B ].
|
||||
f_ptr, # Frequency Penalties -> [ B ].
|
||||
p_ptr, # Presence Penalties -> [ B ].
|
||||
b_ptr, # Logit Bias -> [ B, V_t ].
|
||||
e_ptr, # Temperature -> [ B ].
|
||||
# Output Data Pointer(s).
|
||||
y_ptr, # Scratch-Pad -> [ L, Z_v • M ].
|
||||
# Model Specific(s).
|
||||
vocab_size: tl.constexpr, # Local Vocab Size.
|
||||
shard_offset: tl.constexpr, # Local Shard Offset.
|
||||
lookahead: tl.constexpr, # Maximum Lookahead -> γ.
|
||||
max_k: tl.constexpr, # Maximum Top-K Value -> M.
|
||||
scale: tl.constexpr, # Power-of-2 Integer Scale Factor.
|
||||
batch_size: tl.int32, # Total Sequences -> B.
|
||||
# Conditional Flag(s).
|
||||
indirection: tl.constexpr, # Vocab Indirection Flag.
|
||||
tokens: tl.constexpr, # Drafted / Decoded Tokens Flag.
|
||||
slotted: tl.constexpr, # Slot Indirection Flag.
|
||||
singular: tl.constexpr, # Singular Timestep Flag.
|
||||
varlen: tl.constexpr, # Variable-Length Lookahead Flag.
|
||||
enable_adaptive: tl.constexpr, # Apply Adaptive Filtering & Reduction.
|
||||
enable_radix: tl.constexpr, # Apply Radix Filtering & Reduction.
|
||||
enable_pdl: tl.constexpr, # PDL Enablement Flag.
|
||||
# Stride(s).
|
||||
stride_x: tl.constexpr, # Batch Stride of Logits.
|
||||
stride_g: tl.constexpr, # Batch Stride of Grammar Bit-Mask.
|
||||
stride_c: tl.constexpr, # Batch Stride of Counts (Target Vocab Size) -> V_t.
|
||||
stride_t: tl.constexpr, # Batch Stride of Tokens.
|
||||
stride_y: tl.constexpr, # Batch Stride of Scratch-Pad.
|
||||
# Kernel Specific(s).
|
||||
block_n: tl.constexpr, # Block Size of Vocab Block(s).
|
||||
block_q: tl.constexpr, # Block Size of Cumulative Length(s).
|
||||
block_t: tl.constexpr, # Block Size of Token(s).
|
||||
exact: tl.constexpr, # Exact fp32 Logits Flag (bf16 keys only pick candidates).
|
||||
value_dtype: tl.constexpr, # Dtype the logit manipulators keep.
|
||||
) -> None:
|
||||
"""
|
||||
Note that the value of L and T in the above shapes differ as follows:
|
||||
|
||||
•----------•-------------------•---------------------------•
|
||||
| Singular | Fixed-γ Multistep | Variable-Length Multistep |
|
||||
•-----•----------•-------------------•---------------------------•
|
||||
| L | B | B • (γ + 1) | Σ_i^B (γ_i + 1) |
|
||||
•-----•----------•-------------------•---------------------------•
|
||||
| T | B • γ | B • (γ + 1) | Σ_i^B (γ_i + 1) |
|
||||
•-----•----------•-------------------•---------------------------•
|
||||
|
||||
In the case of the grammar bit-mask, the value of γ' is given as follows:
|
||||
|
||||
• Singular / Fixed-γ Multistep -> γ
|
||||
|
||||
• Variable-Length Multistep -> max_i { γ_i | 0 ≤ i < B }
|
||||
|
||||
"""
|
||||
# Define compile-time program-level constant(s).
|
||||
|
||||
minima: tl.constexpr = -float("inf")
|
||||
|
||||
# Load and extract batch and block id(s) from program id(s).
|
||||
|
||||
row_id = tl.program_id(axis=0)
|
||||
col_id = tl.program_id(axis=1)
|
||||
|
||||
# Compute the column indices and corresponding mask.
|
||||
|
||||
shift = col_id * block_n
|
||||
steps = tl.arange(0, block_n)
|
||||
|
||||
cols = shift + steps
|
||||
mask = cols < vocab_size
|
||||
|
||||
# Compute the block offsets and slot id (if has slot indirection).
|
||||
|
||||
offsets = (row_id * stride_x) + cols
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_wait()
|
||||
|
||||
batch_id, step_id, margin, timesteps = resolve_indices(
|
||||
q_ptr,
|
||||
s_ptr,
|
||||
row_id,
|
||||
lookahead,
|
||||
batch_size,
|
||||
slotted,
|
||||
singular,
|
||||
varlen,
|
||||
block_q,
|
||||
)
|
||||
|
||||
# Load the logits and the bit-indicator(s).
|
||||
|
||||
logits = tl.load(x_ptr + offsets, mask=mask, other=-float("inf"))
|
||||
indicator = tl.load(z_ptr + batch_id)
|
||||
|
||||
logits = transform(
|
||||
logits,
|
||||
indicator,
|
||||
cols,
|
||||
mask,
|
||||
m_ptr,
|
||||
g_ptr,
|
||||
c_ptr,
|
||||
d_ptr,
|
||||
t_ptr,
|
||||
r_ptr,
|
||||
f_ptr,
|
||||
p_ptr,
|
||||
b_ptr,
|
||||
e_ptr,
|
||||
batch_id,
|
||||
step_id,
|
||||
margin,
|
||||
timesteps,
|
||||
shard_offset,
|
||||
lookahead,
|
||||
indirection,
|
||||
tokens,
|
||||
singular,
|
||||
stride_g,
|
||||
stride_c,
|
||||
stride_t,
|
||||
block_t,
|
||||
block_n,
|
||||
value_dtype,
|
||||
)
|
||||
|
||||
if (indicator & 0x40) > 0:
|
||||
|
||||
# Greedy (Top-1) selection.
|
||||
|
||||
if exact:
|
||||
|
||||
exact_maximum(
|
||||
y_ptr,
|
||||
row_id,
|
||||
col_id,
|
||||
tl.num_programs(axis=1),
|
||||
shift,
|
||||
logits,
|
||||
enable_pdl,
|
||||
stride_y,
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
greedy_reduction(
|
||||
y_ptr, row_id, col_id, logits, enable_pdl, stride_y, block_n
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
# Top-K selection by bf16 keys; exact logits are re-read at the candidates.
|
||||
|
||||
top_k_reduction(
|
||||
y_ptr,
|
||||
row_id,
|
||||
col_id,
|
||||
logits.to(tl.bfloat16),
|
||||
steps,
|
||||
max_k,
|
||||
scale,
|
||||
enable_adaptive,
|
||||
enable_radix,
|
||||
enable_pdl,
|
||||
stride_y,
|
||||
block_n,
|
||||
)
|
||||
+439
@@ -0,0 +1,439 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
cdiv, jit = triton.cdiv, triton.jit
|
||||
from tokenspeed_kernel._triton import libdevice # noqa.
|
||||
|
||||
fast_expf = libdevice.fast_expf
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.base import (
|
||||
cumulative_masking,
|
||||
gdc_launch_dependents,
|
||||
gdc_wait,
|
||||
log_softmax,
|
||||
philox_gumbel,
|
||||
philox_key,
|
||||
to_scalar,
|
||||
)
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.prologue import (
|
||||
exact_candidates,
|
||||
exact_greedy,
|
||||
)
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.topk.unpack import unpack_top_k
|
||||
|
||||
|
||||
@jit
|
||||
def sharded_maximum(
|
||||
s_ptr,
|
||||
row_id,
|
||||
max_k: tl.constexpr,
|
||||
vocab_blocks: tl.constexpr,
|
||||
world_size: tl.constexpr,
|
||||
shard_size: tl.constexpr,
|
||||
enable_pdl: tl.constexpr,
|
||||
stride_s: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
block_v: tl.constexpr,
|
||||
):
|
||||
|
||||
rows = tl.arange(0, block_v)[None, :]
|
||||
cols = tl.arange(0, world_size)[:, None] * (vocab_blocks * max_k)
|
||||
|
||||
block_offsets = (row_id * stride_s) + (rows + cols)
|
||||
row_mask = rows < vocab_blocks
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_wait()
|
||||
|
||||
maximums = tl.load(s_ptr + block_offsets, mask=row_mask, other=0).reshape(
|
||||
(block_v * world_size,)
|
||||
)
|
||||
|
||||
target, index = tl.max(maximums, axis=0, return_indices=True)
|
||||
|
||||
shift = ((index // world_size) * shard_size) + ((index % world_size) * block_n)
|
||||
|
||||
return target, shift
|
||||
|
||||
|
||||
@jit
|
||||
def unsharded_maximum(
|
||||
s_ptr,
|
||||
row_id,
|
||||
vocab_blocks: tl.constexpr,
|
||||
enable_pdl: tl.constexpr,
|
||||
stride_s: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
block_v: tl.constexpr,
|
||||
):
|
||||
|
||||
block_span = tl.arange(0, block_v)
|
||||
|
||||
row_mask = block_span < vocab_blocks
|
||||
row_offsets = (row_id * stride_s) + block_span
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_wait()
|
||||
|
||||
targets = tl.load(s_ptr + row_offsets, mask=row_mask, other=0)
|
||||
target, index = tl.max(targets, axis=0, return_indices=True)
|
||||
|
||||
return target, (index * block_n)
|
||||
|
||||
|
||||
@jit
|
||||
def greedy_maximum(
|
||||
s_ptr,
|
||||
row_id,
|
||||
max_k: tl.constexpr,
|
||||
vocab_blocks: tl.constexpr,
|
||||
world_size: tl.constexpr,
|
||||
shard_size: tl.constexpr,
|
||||
sharded: tl.constexpr,
|
||||
enable_pdl: tl.constexpr,
|
||||
stride_s: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
block_v: tl.constexpr,
|
||||
):
|
||||
|
||||
if sharded:
|
||||
|
||||
return sharded_maximum(
|
||||
s_ptr,
|
||||
row_id,
|
||||
max_k,
|
||||
vocab_blocks,
|
||||
world_size,
|
||||
shard_size,
|
||||
enable_pdl,
|
||||
stride_s,
|
||||
block_n,
|
||||
block_v,
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
return unsharded_maximum(
|
||||
s_ptr, row_id, vocab_blocks, enable_pdl, stride_s, block_n, block_v
|
||||
)
|
||||
|
||||
|
||||
@jit
|
||||
def decode_update(
|
||||
d_ptr,
|
||||
batch_id,
|
||||
token_id,
|
||||
prefill: tl.constexpr,
|
||||
stride_d: tl.constexpr,
|
||||
):
|
||||
|
||||
if prefill:
|
||||
|
||||
tl.store(d_ptr + (batch_id * stride_d) + token_id, 1)
|
||||
|
||||
else:
|
||||
|
||||
value = tl.load(d_ptr + (batch_id * stride_d) + token_id) + 1
|
||||
|
||||
tl.store(d_ptr + (batch_id * stride_d) + token_id, value)
|
||||
|
||||
|
||||
@jit
|
||||
def cumulative_selection_kernel(
|
||||
# Input Data Pointer(s).
|
||||
s_ptr, # Scratch-Pad -> [ L, Z_v • M ].
|
||||
z_ptr, # Indicators -> [ B ].
|
||||
f_ptr, # Slot Mapping -> [ B ].
|
||||
m_ptr, # D2T Mapping -> [ V_d ].
|
||||
d_ptr, # Decode Counts -> [ B, V_t ].
|
||||
g_ptr, # Gumbel Noise -> [ B, V_t ].
|
||||
h_ptr, # Noise Seeds -> [ B ].
|
||||
l_ptr, # Noise Offsets -> [ B ].
|
||||
k_ptr, # Top-K -> [ B ].
|
||||
p_ptr, # Top-P -> [ B ].
|
||||
n_ptr, # Min-P -> [ B ].
|
||||
r_ptr, # Top-K Log-Probabilities -> [ B ].
|
||||
# Output Data Pointer(s).
|
||||
t_ptr, # Selected Tokens -> [ B ].
|
||||
w_ptr, # Log-Probabilities -> [ B ].
|
||||
y_ptr, # Draft Probabilities -> [ B, V_t ].
|
||||
q_ptr, # Top-K Log-Probabilities (Values) -> [ B, T ].
|
||||
j_ptr, # Top-K Log-Probabilities (Indices) -> [ B, T ].
|
||||
# Model Specific(s).
|
||||
vocab_blocks: tl.constexpr, # Local Vocab Blocks -> Z_v // W.
|
||||
world_size: tl.constexpr, # World Size -> W.
|
||||
shard_size: tl.constexpr, # Shard Size -> V_d // W.
|
||||
max_k: tl.constexpr, # Maximum Top-K Value -> M.
|
||||
scale: tl.constexpr, # Reciprocal of Power-of-2 Integer Scale Factor.
|
||||
total_rows: tl.constexpr, # Total (Sharded) Logical Vocab Blocks -> W • Z_v'.
|
||||
total_cols: tl.constexpr, # Total Logical Bit-Packed Columns -> W • Z_v' • M.
|
||||
# Conditional Flag(s).
|
||||
indirection: tl.constexpr, # Vocab Indirection Flag.
|
||||
slotted: tl.constexpr, # Slot Indirection Flag.
|
||||
sharded: tl.constexpr, # Sharded Scratch-Pad Flag.
|
||||
prefill: tl.constexpr, # Prefill (First Update) Flag.
|
||||
update_counts: tl.constexpr, # Update Decode Counts Flag.
|
||||
is_adaptive: tl.constexpr, # Adaptive Scaling Applied Flag.
|
||||
is_alternating: tl.constexpr, # Alternating Ascending-Descending Tile(s) Flag.
|
||||
enable_pdl: tl.constexpr, # PDL Enablement Flag.
|
||||
logprobs: tl.constexpr, # Log-Probabilities Flag.
|
||||
probabilities: tl.constexpr, # Draft Probabilities Flag.
|
||||
# Stride(s).
|
||||
stride_s: tl.constexpr, # Batch Stride of Scratch-Pad.
|
||||
stride_r: tl.constexpr, # Batch Stride of Sharded Scratch-Pad -> Z_v • M.
|
||||
stride_b: tl.constexpr, # Logical Batch Stride of Sharded Scratch-Pad -> Z_v' • M.
|
||||
stride_t: tl.constexpr, # Batch Stride of Selected Tokens.
|
||||
stride_w: tl.constexpr, # Batch Stride of Log-Probabilities.
|
||||
stride_y: tl.constexpr, # Batch Stride of Draft Probabilities.
|
||||
stride_d: tl.constexpr, # Batch Stride of Decode Counts (Target Vocab Size) -> V_t.
|
||||
stride_g: tl.constexpr, # Batch Stride of Gumbel Noise.
|
||||
stride_q: tl.constexpr, # Batch Stride of Top-K Log-Probabilities (Values).
|
||||
# Kernel Specific(s).
|
||||
block_n: tl.constexpr, # Block Size of Vocab Block(s).
|
||||
block_v: tl.constexpr, # Next Power-of-2 Vocab Block(s) -> Z_v'.
|
||||
block_q: tl.constexpr, # Next Power-of-2 Top-K Log-Probabilities Targets -> T'.
|
||||
# Exact fp32 Re-Read of the Candidates (exact only).
|
||||
x_ptr, # Logits -> [ B, V_d' / W ].
|
||||
gr_ptr, # Grammar Bit-Mask -> [ B, V_t / 32 ].
|
||||
cr_ptr, # Context Counts -> [ B, V_t ].
|
||||
tr_ptr, # Drafted Tokens -> [ B, γ ].
|
||||
rr_ptr, # Repetition Penalties -> [ B ].
|
||||
fr_ptr, # Frequency Penalties -> [ B ].
|
||||
pr_ptr, # Presence Penalties -> [ B ].
|
||||
br_ptr, # Logit Bias -> [ B, V_t ].
|
||||
er_ptr, # Temperature -> [ B ].
|
||||
vocab_size: tl.constexpr, # Local Vocab Size.
|
||||
shard_offset: tl.constexpr, # Local Shard Offset.
|
||||
lookahead: tl.constexpr, # Drafted Tokens per Row.
|
||||
tokens: tl.constexpr, # Drafted Tokens Flag.
|
||||
stride_x: tl.constexpr, # Batch Stride of Logits.
|
||||
stride_gr: tl.constexpr, # Batch Stride of Grammar Bit-Mask.
|
||||
stride_tr: tl.constexpr, # Batch Stride of Drafted Tokens.
|
||||
block_t: tl.constexpr, # Block Size of Drafted Tokens.
|
||||
exact: tl.constexpr, # Exact fp32 Logits Flag.
|
||||
) -> None:
|
||||
|
||||
# Extract the batch id from program id and load the indicator.
|
||||
|
||||
row_id = tl.program_id(axis=0)
|
||||
batch_id = row_id
|
||||
|
||||
if slotted:
|
||||
|
||||
batch_id = tl.load(f_ptr + batch_id)
|
||||
|
||||
indicator = tl.load(z_ptr + batch_id)
|
||||
|
||||
if (indicator & 0x40) > 0:
|
||||
|
||||
# Load, reduce, and select greedy i.e. top-1 maximum.
|
||||
|
||||
if exact:
|
||||
|
||||
selection = exact_greedy(
|
||||
s_ptr, row_id, vocab_blocks, enable_pdl, stride_s, block_v
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
target, shift = greedy_maximum(
|
||||
s_ptr,
|
||||
row_id,
|
||||
max_k,
|
||||
vocab_blocks,
|
||||
world_size,
|
||||
shard_size,
|
||||
sharded,
|
||||
enable_pdl,
|
||||
stride_s,
|
||||
block_n,
|
||||
block_v,
|
||||
)
|
||||
|
||||
# Unpack the selected token id from the target index.
|
||||
|
||||
selection = shift + ((block_n - 1) ^ (target & 0xFFFF))
|
||||
|
||||
if indirection:
|
||||
|
||||
# Re-map the selected token id to the target vocabulary.
|
||||
|
||||
selection = tl.load(m_ptr + selection)
|
||||
|
||||
if update_counts:
|
||||
|
||||
# Increment the decode count for the selected token.
|
||||
|
||||
decode_update(d_ptr, batch_id, selection, prefill, stride_d)
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
tl.store(t_ptr + (row_id * stride_t), selection)
|
||||
|
||||
else:
|
||||
|
||||
# Load, reduce, and unpack top-k stochastic subset.
|
||||
|
||||
values, indices = unpack_top_k(
|
||||
s_ptr,
|
||||
row_id,
|
||||
vocab_blocks,
|
||||
world_size,
|
||||
shard_size,
|
||||
max_k,
|
||||
scale,
|
||||
total_rows,
|
||||
total_cols,
|
||||
sharded,
|
||||
is_adaptive,
|
||||
is_alternating,
|
||||
enable_pdl,
|
||||
stride_r,
|
||||
stride_b,
|
||||
stride_s,
|
||||
block_n,
|
||||
block_v,
|
||||
)
|
||||
|
||||
if exact:
|
||||
|
||||
# Re-read the candidates' exact values: bf16 keys only chose them.
|
||||
|
||||
values, indices = exact_candidates(
|
||||
x_ptr,
|
||||
row_id,
|
||||
indices,
|
||||
indicator,
|
||||
m_ptr,
|
||||
gr_ptr,
|
||||
cr_ptr,
|
||||
d_ptr,
|
||||
tr_ptr,
|
||||
rr_ptr,
|
||||
fr_ptr,
|
||||
pr_ptr,
|
||||
br_ptr,
|
||||
er_ptr,
|
||||
batch_id,
|
||||
0,
|
||||
row_id,
|
||||
1,
|
||||
vocab_size,
|
||||
shard_offset,
|
||||
lookahead,
|
||||
indirection,
|
||||
tokens,
|
||||
True,
|
||||
stride_x,
|
||||
stride_gr,
|
||||
stride_d,
|
||||
stride_tr,
|
||||
block_t,
|
||||
max_k,
|
||||
)
|
||||
|
||||
if (indicator & 0x380) > 0:
|
||||
|
||||
# Prepare for and apply top-k, top-p, and / or min-p subset masking.
|
||||
|
||||
maximum = tl.gather(values, tl.full((1,), 0, dtype=tl.int32), axis=0)
|
||||
offsets = tl.arange(0, max_k)
|
||||
|
||||
values = cumulative_masking(
|
||||
k_ptr,
|
||||
p_ptr,
|
||||
n_ptr,
|
||||
batch_id,
|
||||
indicator,
|
||||
values,
|
||||
maximum,
|
||||
offsets,
|
||||
max_k,
|
||||
)
|
||||
|
||||
if indirection:
|
||||
|
||||
# Re-map the selected token indices to the target vocabulary.
|
||||
|
||||
indices = tl.load(m_ptr + indices)
|
||||
|
||||
if g_ptr is not None:
|
||||
|
||||
noise = tl.load(g_ptr + (batch_id * stride_g) + indices)
|
||||
|
||||
else:
|
||||
|
||||
# Draw the gumbel noise in-kernel at the unpacked subset.
|
||||
|
||||
key = philox_key(h_ptr, l_ptr, batch_id, 0)
|
||||
noise = philox_gumbel(key, indices)
|
||||
|
||||
selected = tl.argmax(values - noise, axis=0, keep_dims=True)
|
||||
token_id = to_scalar(tl.gather(indices, selected, axis=0))
|
||||
|
||||
if update_counts:
|
||||
|
||||
# Increment the decode count for the selected token.
|
||||
|
||||
decode_update(d_ptr, batch_id, token_id, prefill, stride_d)
|
||||
|
||||
if logprobs or probabilities:
|
||||
|
||||
maximum = tl.gather(values, tl.full((1,), 0, dtype=tl.int32), axis=0)
|
||||
log_scores = log_softmax(values, maximum)
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
if logprobs:
|
||||
|
||||
log_score = to_scalar(tl.gather(log_scores, selected, axis=0))
|
||||
|
||||
tl.store(w_ptr + (row_id * stride_w), log_score)
|
||||
|
||||
if (indicator & 0x400) > 0:
|
||||
|
||||
logprobs_ids = tl.arange(0, block_q)
|
||||
logprobs_mask = logprobs_ids < tl.load(r_ptr + batch_id)
|
||||
|
||||
top_logprobs = tl.gather(log_scores, logprobs_ids, axis=0)
|
||||
top_tokens = tl.gather(indices, logprobs_ids, axis=0)
|
||||
|
||||
logprobs_offsets = (row_id * stride_q) + logprobs_ids
|
||||
|
||||
tl.store(q_ptr + logprobs_offsets, top_logprobs, mask=logprobs_mask)
|
||||
tl.store(j_ptr + logprobs_offsets, top_tokens, mask=logprobs_mask)
|
||||
|
||||
if probabilities:
|
||||
|
||||
probs_offsets = (batch_id * stride_y) + indices
|
||||
|
||||
tl.store(y_ptr + probs_offsets, fast_expf(log_scores))
|
||||
|
||||
elif enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
tl.store(t_ptr + (row_id * stride_t), token_id)
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
jit = triton.jit
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.encoding import (
|
||||
encode_block,
|
||||
shift_pack,
|
||||
)
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.topk.radix import radix_partition
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.topk.selection import (
|
||||
bitonic_selection,
|
||||
radix_selection,
|
||||
)
|
||||
|
||||
|
||||
@jit
|
||||
def sparse_threshold(encoded, marked, threshold, max_k: tl.constexpr):
|
||||
|
||||
# Construct mid-span mask and bins for partitioning.
|
||||
|
||||
bits: tl.constexpr = 5
|
||||
bins: tl.constexpr = 1 << bits
|
||||
|
||||
mask: tl.constexpr = bins - 1
|
||||
|
||||
# Apply radix partitioning and update threshold.
|
||||
|
||||
values = ((encoded >> bits) & mask) ^ mask
|
||||
head, margin = radix_partition(values, marked, max_k, bins)
|
||||
|
||||
threshold = ((threshold << bits) | (head ^ mask)) << bits
|
||||
|
||||
# Construct lower-span mask and bins for conditional partitioning.
|
||||
|
||||
if margin > 0:
|
||||
|
||||
marked &= values == head
|
||||
|
||||
values = (encoded & mask) ^ mask
|
||||
tail, margin = radix_partition(values, marked, margin, bins)
|
||||
|
||||
if head == 0 and tail == 0:
|
||||
|
||||
threshold |= mask - 1
|
||||
margin &= 0
|
||||
|
||||
else:
|
||||
|
||||
threshold |= tail ^ mask
|
||||
|
||||
else:
|
||||
|
||||
threshold |= mask
|
||||
|
||||
return threshold, margin
|
||||
|
||||
|
||||
@jit
|
||||
def screen_combine(max_a, count_a, max_b, count_b):
|
||||
"""
|
||||
Fused maximum threshold and count in a single optimized IADD and IMNMX reduction tree
|
||||
that avoids a separate counting pass and halves inter-warp synchronization relative
|
||||
to a two-pass approach.
|
||||
|
||||
"""
|
||||
is_greater = max_a > max_b
|
||||
is_equal = max_a == max_b
|
||||
|
||||
new_max = tl.maximum(max_a, max_b)
|
||||
|
||||
peak_count = tl.where(is_equal, count_a + count_b, count_b)
|
||||
new_count = tl.where(is_greater, count_a, peak_count)
|
||||
|
||||
return new_max, new_count
|
||||
|
||||
|
||||
@jit
|
||||
def radix_bitonic(
|
||||
y_ptr,
|
||||
batch_id,
|
||||
block_id,
|
||||
logits,
|
||||
indices,
|
||||
max_k: tl.constexpr, # Maximum Top-K Value -> M.
|
||||
scale: tl.constexpr, # Power-of-2 Integer Scale Factor.
|
||||
enable_pdl: tl.constexpr,
|
||||
stride_y: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
|
||||
# Encode scaled logits into numerical lexicographic ordering i.e. uint32.
|
||||
|
||||
encoded = encode_block(logits * scale)
|
||||
|
||||
# Verify low-entropy of most-significant bit(s).
|
||||
|
||||
upper = encoded >> 10
|
||||
ones = tl.full(upper.shape, 1, dtype=tl.int32)
|
||||
|
||||
threshold, count = tl.reduce((upper, ones), axis=0, combine_fn=screen_combine)
|
||||
|
||||
marked = upper == threshold
|
||||
sparse = count >= max_k
|
||||
|
||||
if sparse:
|
||||
|
||||
# Execute two-pass radix filtering based on lower bits.
|
||||
|
||||
threshold, margin = sparse_threshold(encoded, marked, threshold, max_k)
|
||||
|
||||
# Apply radix filtering for masked-scattering.
|
||||
|
||||
radix_selection(
|
||||
y_ptr,
|
||||
batch_id,
|
||||
block_id,
|
||||
encoded,
|
||||
threshold,
|
||||
margin,
|
||||
indices,
|
||||
max_k,
|
||||
enable_pdl,
|
||||
stride_y,
|
||||
block_n,
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
# Fallback to optimized bitonic top-k.
|
||||
|
||||
packed = shift_pack(encoded, indices, block_n)
|
||||
|
||||
bitonic_selection(
|
||||
y_ptr,
|
||||
batch_id,
|
||||
block_id,
|
||||
packed,
|
||||
max_k,
|
||||
enable_pdl,
|
||||
stride_y,
|
||||
block_n,
|
||||
)
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
cdiv, jit = triton.cdiv, triton.jit
|
||||
|
||||
|
||||
"""
|
||||
The following suite of kernels were adapted from the official Triton repository:
|
||||
|
||||
https://github.com/triton-lang/triton/blob/main/python/triton/language/standard.py
|
||||
|
||||
with specific modifications and optimizations to allow for:
|
||||
|
||||
• Revised bitonic folding that minimizes inter-warp barrier(s).
|
||||
|
||||
• Selective reductions and reshape(s) for layouts to maximize occupancy.
|
||||
|
||||
• Leveraging optimized IMNMX.U32.U32 instructions during CAS.
|
||||
|
||||
• Support alternating write-outs across vocab block(s) / tile(s).
|
||||
|
||||
"""
|
||||
|
||||
|
||||
@jit
|
||||
def indicator(pair, outer: tl.constexpr, inner: tl.constexpr):
|
||||
"""
|
||||
Expands the bit-`pair` into a tensor with shape [1, ..., 1, 2, 1, ..., 1]
|
||||
where the 2 is at the `inner`-th position from the end.
|
||||
|
||||
"""
|
||||
return tl.reshape(pair, ([1] * outer) + [2] + ([1] * inner))
|
||||
|
||||
|
||||
@jit
|
||||
def compare_and_swap(values, pair, flip, dim: tl.constexpr, total: tl.constexpr):
|
||||
|
||||
outer: tl.constexpr = total - dim - 1
|
||||
|
||||
# Flip along the middle dimension.
|
||||
|
||||
result = values ^ tl.xor_sum(values, axis=outer, keep_dims=True)
|
||||
|
||||
# Determine right / left position along the axis, expand, and flip.
|
||||
|
||||
ordering = flip ^ indicator(pair, outer, dim)
|
||||
|
||||
# Ensure CAS compiles down to optimized IMNMX.U32.U32 instruction(s).
|
||||
|
||||
minima = tl.minimum(values, result)
|
||||
maxima = tl.maximum(values, result)
|
||||
|
||||
# Conditional swap while preserving bitonic invariant(s) and ordering stability.
|
||||
|
||||
return tl.where(ordering != 0, maxima, minima)
|
||||
|
||||
|
||||
@jit
|
||||
def hypercube_merge(values, pair, flip, stage: tl.constexpr, total: tl.constexpr):
|
||||
|
||||
hypercube = values
|
||||
|
||||
for i in tl.static_range(0, stage):
|
||||
|
||||
hypercube = compare_and_swap(hypercube, pair, flip, stage - i - 1, total)
|
||||
|
||||
return hypercube
|
||||
|
||||
|
||||
@jit
|
||||
def bitonic_fold(
|
||||
values,
|
||||
pair,
|
||||
rows: tl.constexpr,
|
||||
max_k: tl.constexpr,
|
||||
folds: tl.constexpr,
|
||||
descending: tl.constexpr,
|
||||
factor_n: tl.constexpr,
|
||||
factor_k: tl.constexpr,
|
||||
):
|
||||
|
||||
# Iteratively reduce across folds via bitonic reduction.
|
||||
|
||||
block = values
|
||||
|
||||
for i in tl.static_range(1, folds + 1):
|
||||
|
||||
block = block.reshape((rows >> i, 2, max_k))
|
||||
|
||||
left_block, right_block = tl.split(block.trans(0, 2, 1))
|
||||
block = tl.maximum(left_block, right_block)
|
||||
|
||||
hypercube = tl.reshape(block, [2] * (factor_n - i - 1))
|
||||
|
||||
if i < folds:
|
||||
|
||||
flip = indicator(pair, folds - i - 1, factor_k)
|
||||
block = hypercube_merge(hypercube, pair, flip, factor_k, factor_n - i - 1)
|
||||
|
||||
else:
|
||||
|
||||
block = hypercube_merge(
|
||||
hypercube, pair, descending, factor_k, factor_n - i - 1
|
||||
)
|
||||
|
||||
return block.reshape((max_k,))
|
||||
|
||||
|
||||
@jit
|
||||
def bitonic_reduction(
|
||||
values, rows: tl.constexpr, max_k: tl.constexpr, total_cols: tl.constexpr
|
||||
):
|
||||
|
||||
factor_n: tl.constexpr = tl.standard._log2(total_cols) + 1 # noqa.
|
||||
factor_k: tl.constexpr = tl.standard._log2(max_k) # noqa.
|
||||
|
||||
folds: tl.constexpr = tl.standard._log2(rows) # noqa.
|
||||
|
||||
pair = tl.arange(0, 2).to(tl.int1)
|
||||
|
||||
return bitonic_fold(values, pair, rows, max_k, folds, 1, factor_n, factor_k)
|
||||
|
||||
|
||||
@jit
|
||||
def top_k(values, descending: tl.constexpr, max_k: tl.constexpr, block_n: tl.constexpr):
|
||||
"""
|
||||
Ordered bitonic top-k via alternating reduction across hypercube folds with focused
|
||||
optimizations around CAS instructions, minimized inter-warp barrier(s), and maximized
|
||||
occupancy.
|
||||
|
||||
Note(s):
|
||||
|
||||
• `values` -> [`block_n`]
|
||||
|
||||
• `factor_k` -> log_2(`max_k`)
|
||||
|
||||
• `factor_n` -> log_2(`block_n`)
|
||||
|
||||
"""
|
||||
factor_n: tl.constexpr = tl.standard._log2(block_n) # noqa.
|
||||
factor_k: tl.constexpr = tl.standard._log2(max_k) # noqa.
|
||||
|
||||
folds: tl.constexpr = factor_n - factor_k - 1
|
||||
rows: tl.constexpr = 1 << folds
|
||||
|
||||
hypercube = tl.reshape(values, [2] * factor_n)
|
||||
pair = tl.arange(0, 2).to(tl.int1)
|
||||
|
||||
for stage in tl.static_range(1, factor_k + 1):
|
||||
|
||||
flip = indicator(pair, factor_n - stage - 1, stage)
|
||||
hypercube = hypercube_merge(hypercube, pair, flip, stage, factor_n)
|
||||
|
||||
hypercube = tl.max(hypercube, axis=folds)
|
||||
|
||||
if folds > 0:
|
||||
|
||||
# Continue with alternating rows with non-zero fold(s) remaining.
|
||||
|
||||
flip = indicator(pair, folds - 1, factor_k)
|
||||
hypercube = hypercube_merge(hypercube, pair, flip, factor_k, factor_n - 1)
|
||||
|
||||
grouped = tl.reshape(hypercube, (rows, max_k))
|
||||
|
||||
return bitonic_fold(
|
||||
grouped, pair, rows, max_k, folds, descending, factor_n, factor_k
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
# Short circuit folding with final ascending / descending merge.
|
||||
|
||||
hypercube = hypercube_merge(hypercube, pair, descending, factor_k, factor_n - 1)
|
||||
|
||||
return tl.reshape(hypercube, (max_k,))
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
cdiv, jit = triton.cdiv, triton.jit
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.encoding import bitpack_block
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.topk.adaptive import radix_bitonic
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.topk.radix import radix_threshold
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.topk.selection import (
|
||||
bitonic_selection,
|
||||
radix_selection,
|
||||
)
|
||||
|
||||
|
||||
@jit
|
||||
def top_k_reduction(
|
||||
y_ptr,
|
||||
row_id,
|
||||
col_id,
|
||||
logits,
|
||||
indices,
|
||||
max_k: tl.constexpr,
|
||||
scale: tl.constexpr,
|
||||
enable_adaptive: tl.constexpr,
|
||||
enable_radix: tl.constexpr,
|
||||
enable_pdl: tl.constexpr,
|
||||
stride_y: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
|
||||
if enable_adaptive:
|
||||
|
||||
radix_bitonic(
|
||||
y_ptr,
|
||||
row_id,
|
||||
col_id,
|
||||
logits,
|
||||
indices,
|
||||
max_k,
|
||||
scale,
|
||||
enable_pdl,
|
||||
stride_y,
|
||||
block_n,
|
||||
)
|
||||
|
||||
elif enable_radix:
|
||||
|
||||
# Compute the threshold and marginal via radix filtering.
|
||||
|
||||
encoded, threshold, margin = radix_threshold(logits, max_k)
|
||||
|
||||
# Packed radix top-k reduction.
|
||||
|
||||
radix_selection(
|
||||
y_ptr,
|
||||
row_id,
|
||||
col_id,
|
||||
encoded,
|
||||
threshold,
|
||||
margin,
|
||||
indices,
|
||||
max_k,
|
||||
enable_pdl,
|
||||
stride_y,
|
||||
block_n,
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
# Packed bitonic top-k reduction.
|
||||
|
||||
packed = bitpack_block(logits, indices, block_n)
|
||||
|
||||
bitonic_selection(
|
||||
y_ptr,
|
||||
row_id,
|
||||
col_id,
|
||||
packed,
|
||||
max_k,
|
||||
enable_pdl,
|
||||
stride_y,
|
||||
block_n,
|
||||
)
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
jit = triton.jit
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.encoding import encode_block
|
||||
|
||||
|
||||
@jit
|
||||
def radix_partition(values, mask, upper: tl.constexpr, bins: tl.constexpr):
|
||||
"""
|
||||
Optimized radix pivot and margin computation via a packed masked-max reduction strategy
|
||||
with a single IMNMX reduction tree with IMAD.SHL.U32 pre-op.
|
||||
|
||||
"""
|
||||
ladder = tl.cumsum(tl.histogram(values, bins, mask=mask), axis=0)
|
||||
|
||||
offsets = tl.arange(0, bins) + 1
|
||||
packed = tl.max(tl.where(ladder <= upper, (ladder << 8) | offsets, 0), axis=0)
|
||||
|
||||
pivot = packed & 0xFF
|
||||
target = packed >> 8
|
||||
|
||||
return pivot, upper - target
|
||||
|
||||
|
||||
@jit
|
||||
def radix_threshold(logits, max_k: tl.constexpr):
|
||||
|
||||
# Encode logits into numerical lexicographic ordering i.e. uint32.
|
||||
|
||||
encoded = encode_block(logits)
|
||||
|
||||
# Filter candidates based on upper 8-bits in the first phase.
|
||||
|
||||
values = (encoded >> 8) ^ 0xFF
|
||||
head, margin = radix_partition(values, None, max_k, 256)
|
||||
|
||||
threshold = (head ^ 0xFF) << 8
|
||||
|
||||
if margin > 0:
|
||||
|
||||
# Filter candidates based on lower 8-bits in the second phase.
|
||||
|
||||
mask = values == head
|
||||
values = (encoded & 0xFF) ^ 0xFF
|
||||
|
||||
tail, margin = radix_partition(values, mask, margin, 256)
|
||||
|
||||
if head == 0 and tail == 0:
|
||||
|
||||
threshold |= 0xFE
|
||||
margin &= 0
|
||||
|
||||
else:
|
||||
|
||||
threshold |= tail ^ 0xFF
|
||||
|
||||
else:
|
||||
|
||||
threshold |= 0xFF
|
||||
|
||||
return encoded, threshold, margin
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
cdiv, jit = triton.cdiv, triton.jit
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.base import gdc_launch_dependents
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.encoding import shift_pack
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.topk.bitonic import (
|
||||
top_k as bitonic_top_k,
|
||||
)
|
||||
|
||||
|
||||
@jit
|
||||
def bitonic_selection(
|
||||
y_ptr,
|
||||
batch_id,
|
||||
block_id,
|
||||
packed,
|
||||
max_k: tl.constexpr,
|
||||
enable_pdl: tl.constexpr,
|
||||
stride_y: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
|
||||
# Apply bitonic top-k to reduce tile to top-k selections in block-alternating order.
|
||||
|
||||
selections = bitonic_top_k(packed, block_id & 1, max_k, block_n)
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
targets = (batch_id * stride_y) + (block_id * max_k) + tl.arange(0, max_k)
|
||||
|
||||
tl.store(y_ptr + targets, selections)
|
||||
|
||||
|
||||
@jit
|
||||
def radix_selection(
|
||||
y_ptr,
|
||||
batch_id,
|
||||
block_id,
|
||||
encoded,
|
||||
threshold,
|
||||
margin,
|
||||
indices,
|
||||
max_k: tl.constexpr,
|
||||
enable_pdl: tl.constexpr,
|
||||
stride_y: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
|
||||
# Pack indices for stable ordering.
|
||||
|
||||
packed = shift_pack(encoded, indices, block_n)
|
||||
|
||||
# Accumulate mask for position(s).
|
||||
|
||||
equal = encoded == threshold
|
||||
equal &= tl.cumsum(equal, axis=0) <= margin
|
||||
|
||||
marked = (encoded > threshold) | equal
|
||||
|
||||
# Ensure ordered (coalescer-friendly) bounded positions for storing top-k entries.
|
||||
|
||||
positions = tl.cumsum(marked, axis=0) - marked
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
shifts = (batch_id * stride_y) + (block_id * max_k) + positions
|
||||
|
||||
tl.store(y_ptr + shifts, packed, mask=marked)
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
cdiv, jit = triton.cdiv, triton.jit
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.base import gdc_wait
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.encoding import decode_block
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.topk.bitonic import (
|
||||
bitonic_reduction,
|
||||
)
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.topk.bitonic import (
|
||||
top_k as bitonic_top_k,
|
||||
)
|
||||
|
||||
|
||||
@jit
|
||||
def unsharded_top_k(
|
||||
s_ptr,
|
||||
row_id,
|
||||
vocab_blocks: tl.constexpr,
|
||||
max_k: tl.constexpr,
|
||||
scale: tl.constexpr,
|
||||
total_cols: tl.constexpr,
|
||||
is_adaptive: tl.constexpr,
|
||||
is_alternating: tl.constexpr,
|
||||
enable_pdl: tl.constexpr,
|
||||
stride_s: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
block_v: tl.constexpr,
|
||||
):
|
||||
"""
|
||||
Note(s):
|
||||
|
||||
• `total_cols` -> `block_v` • `max_k`
|
||||
|
||||
"""
|
||||
# Define the XOR-based index inverting mask(s).
|
||||
|
||||
upper_mask = tl.constexpr(block_n - 1)
|
||||
total_mask = tl.constexpr(total_cols - 1)
|
||||
|
||||
slice_mask = tl.constexpr(max_k - 1)
|
||||
|
||||
# Prepare the layout block offset(s), absolute offset(s), and relative indices.
|
||||
|
||||
block_ids = tl.arange(0, block_v)[:, None]
|
||||
block_mask = block_ids < vocab_blocks
|
||||
|
||||
local_indices = (block_ids * max_k) + tl.arange(0, max_k)[None, :]
|
||||
block_offsets = (row_id * stride_s) + local_indices
|
||||
|
||||
local_mask = total_mask
|
||||
|
||||
if is_alternating:
|
||||
|
||||
local_mask = total_mask ^ (((block_ids & 1) ^ 1) * slice_mask)
|
||||
|
||||
local_indices ^= local_mask
|
||||
local_offsets = block_ids * block_n
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_wait()
|
||||
|
||||
# Load the uint32 packed [ Z_v', M ] block values from the scratch-pad.
|
||||
|
||||
unsharded_packed = tl.load(s_ptr + block_offsets, mask=block_mask, other=0)
|
||||
|
||||
# Prepare the absolute indices across the vocab block(s).
|
||||
|
||||
unsharded_absolutes = (
|
||||
((unsharded_packed & 0xFFFF) ^ upper_mask) + local_offsets
|
||||
).reshape((total_cols,))
|
||||
|
||||
# Replace packed indices with relative indices.
|
||||
|
||||
unsharded_packed = (unsharded_packed & 0xFFFF_0000) | local_indices
|
||||
|
||||
# Apply bitonic reduction across vocab block(s) to select top-k entries.
|
||||
|
||||
if is_alternating:
|
||||
|
||||
unsharded_reduced = bitonic_reduction(
|
||||
unsharded_packed, block_v, max_k, total_cols
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
unsharded_reduced = bitonic_top_k(unsharded_packed, 1, max_k, total_cols)
|
||||
|
||||
# Extract values and indices from packed entries.
|
||||
|
||||
unsharded_values = decode_block((unsharded_reduced >> 16).to(tl.uint16)).to(
|
||||
tl.bfloat16, bitcast=True
|
||||
)
|
||||
|
||||
if is_adaptive:
|
||||
|
||||
unsharded_values *= scale
|
||||
|
||||
unsharded_indices = (unsharded_reduced & 0xFFFF) ^ total_mask
|
||||
|
||||
if is_alternating:
|
||||
|
||||
factor_k: tl.constexpr = tl.standard._log2(max_k) # noqa.
|
||||
|
||||
entry_block = unsharded_indices >> factor_k
|
||||
entry_index = (unsharded_indices & slice_mask) ^ (
|
||||
((entry_block & 1) ^ 1) * slice_mask
|
||||
)
|
||||
|
||||
unsharded_indices = (entry_block << factor_k) | entry_index
|
||||
|
||||
unsharded_indices = tl.gather(unsharded_absolutes, unsharded_indices, axis=0)
|
||||
|
||||
return unsharded_values, unsharded_indices
|
||||
|
||||
|
||||
@jit
|
||||
def sharded_top_k(
|
||||
s_ptr,
|
||||
row_id,
|
||||
vocab_blocks: tl.constexpr,
|
||||
world_size: tl.constexpr,
|
||||
shard_size: tl.constexpr,
|
||||
max_k: tl.constexpr,
|
||||
scale: tl.constexpr,
|
||||
total_rows: tl.constexpr,
|
||||
total_cols: tl.constexpr,
|
||||
is_adaptive: tl.constexpr,
|
||||
is_alternating: tl.constexpr,
|
||||
enable_pdl: tl.constexpr,
|
||||
shard_stride: tl.constexpr,
|
||||
block_stride: tl.constexpr,
|
||||
stride_s: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
block_v: tl.constexpr,
|
||||
):
|
||||
"""
|
||||
In the sharded case, each row of the scratch-pad can be logically viewed in the form of
|
||||
[ W, Z_v, M ] where the layout and logical offset(s) across the shards, { s_i | 0 ≤ i < W },
|
||||
are given by `vocab_blocks` • `max_k` and `shard_size` respectively.
|
||||
|
||||
Note(s):
|
||||
|
||||
• Z_v' i.e. `block_v` here is the next power-of-2 of `vocab_blocks`.
|
||||
|
||||
• `shard_stride` -> `vocab_blocks` • `max_k`
|
||||
|
||||
• `block_stride` -> `block_v` • `max_k`
|
||||
|
||||
• `total_cols` -> `world_size` • `block_v` • `max_k`
|
||||
|
||||
• `total_rows` -> `world_size` • `block_v`
|
||||
|
||||
"""
|
||||
# Define the logical constant(s) of the program.
|
||||
|
||||
total_mask = tl.constexpr(total_cols - 1)
|
||||
upper_mask = tl.constexpr(block_n - 1)
|
||||
|
||||
slice_mask = tl.constexpr(max_k - 1)
|
||||
|
||||
# Prepare the layout block offset(s), absolute offset(s), and relative indices.
|
||||
|
||||
shard_ids = tl.arange(0, world_size)[:, None, None]
|
||||
block_steps = tl.arange(0, block_v)[None, :, None]
|
||||
|
||||
block_shifts = (block_steps * max_k) + tl.arange(0, max_k)[None, None, :]
|
||||
|
||||
layout_offsets = (row_id * stride_s) + (shard_ids * shard_stride) + block_shifts
|
||||
step_mask = block_steps < vocab_blocks
|
||||
|
||||
absolute_offsets = (shard_ids * shard_size) + (block_steps * block_n)
|
||||
relative_indices = (shard_ids * block_stride) + block_shifts
|
||||
|
||||
local_mask = total_mask
|
||||
|
||||
if is_alternating:
|
||||
|
||||
local_mask = total_mask ^ (((block_steps & 1) ^ 1) * slice_mask)
|
||||
|
||||
relative_indices ^= local_mask
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_wait()
|
||||
|
||||
# Load the uint32 packed [ W, Z_v', M ] block values from the scratch-pad.
|
||||
|
||||
sharded_packed = tl.load(s_ptr + layout_offsets, mask=step_mask, other=0)
|
||||
|
||||
# Prepare the absolute indices across the vocab block(s).
|
||||
|
||||
sharded_absolutes = (
|
||||
((sharded_packed & 0xFFFF) ^ upper_mask) + absolute_offsets
|
||||
).reshape((total_cols,))
|
||||
|
||||
# Replace packed indices with relative indices.
|
||||
|
||||
sharded_packed = (sharded_packed & 0xFFFF_0000) | relative_indices
|
||||
|
||||
# Apply bitonic reduction across vocab block(s) to select top-k entries.
|
||||
|
||||
if is_alternating:
|
||||
|
||||
sharded_packed = sharded_packed.reshape((total_rows, max_k))
|
||||
sharded_reduced = bitonic_reduction(
|
||||
sharded_packed, total_rows, max_k, total_cols
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
sharded_reduced = bitonic_top_k(sharded_packed, 1, max_k, total_cols)
|
||||
|
||||
# Extract values and indices from packed entries.
|
||||
|
||||
sharded_values = decode_block((sharded_reduced >> 16).to(tl.uint16)).to(
|
||||
tl.bfloat16, bitcast=True
|
||||
)
|
||||
|
||||
if is_adaptive:
|
||||
|
||||
sharded_values *= scale
|
||||
|
||||
sharded_indices = (sharded_reduced & 0xFFFF) ^ total_mask
|
||||
|
||||
if is_alternating:
|
||||
|
||||
factor_k: tl.constexpr = tl.standard._log2(max_k) # noqa.
|
||||
|
||||
entry_block = sharded_indices >> factor_k
|
||||
entry_index = (sharded_indices & slice_mask) ^ (
|
||||
((entry_block & 1) ^ 1) * slice_mask
|
||||
)
|
||||
|
||||
sharded_indices = (entry_block << factor_k) | entry_index
|
||||
|
||||
sharded_indices = tl.gather(sharded_absolutes, sharded_indices, axis=0)
|
||||
|
||||
return sharded_values, sharded_indices
|
||||
|
||||
|
||||
@jit
|
||||
def unpack_top_k(
|
||||
s_ptr,
|
||||
row_id,
|
||||
vocab_blocks: tl.constexpr,
|
||||
world_size: tl.constexpr,
|
||||
shard_size: tl.constexpr,
|
||||
max_k: tl.constexpr,
|
||||
scale: tl.constexpr,
|
||||
total_rows: tl.constexpr,
|
||||
total_cols: tl.constexpr,
|
||||
sharded: tl.constexpr,
|
||||
is_adaptive: tl.constexpr,
|
||||
is_alternating: tl.constexpr,
|
||||
enable_pdl: tl.constexpr,
|
||||
shard_stride: tl.constexpr,
|
||||
block_stride: tl.constexpr,
|
||||
stride_s: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
block_v: tl.constexpr,
|
||||
):
|
||||
|
||||
if sharded:
|
||||
|
||||
return sharded_top_k(
|
||||
s_ptr,
|
||||
row_id,
|
||||
vocab_blocks,
|
||||
world_size,
|
||||
shard_size,
|
||||
max_k,
|
||||
scale,
|
||||
total_rows,
|
||||
total_cols,
|
||||
is_adaptive,
|
||||
is_alternating,
|
||||
enable_pdl,
|
||||
shard_stride,
|
||||
block_stride,
|
||||
stride_s,
|
||||
block_n,
|
||||
block_v,
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
return unsharded_top_k(
|
||||
s_ptr,
|
||||
row_id,
|
||||
vocab_blocks,
|
||||
max_k,
|
||||
scale,
|
||||
total_cols,
|
||||
is_adaptive,
|
||||
is_alternating,
|
||||
enable_pdl,
|
||||
stride_s,
|
||||
block_n,
|
||||
block_v,
|
||||
)
|
||||
+469
@@ -0,0 +1,469 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Copyright (c) 2026 SonicSampler Team.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tokenspeed_kernel._triton import tl, triton # noqa.
|
||||
|
||||
jit = triton.jit
|
||||
from tokenspeed_kernel._triton import libdevice # noqa.
|
||||
|
||||
fast_logf = libdevice.fast_logf
|
||||
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops.base import (
|
||||
gdc_launch_dependents,
|
||||
gdc_wait,
|
||||
ones_like,
|
||||
philox_gumbel,
|
||||
philox_key,
|
||||
philox_uniform,
|
||||
)
|
||||
|
||||
|
||||
@jit
|
||||
def resolve_shift_margin(
|
||||
q_ptr,
|
||||
f_ptr,
|
||||
block_id: tl.constexpr,
|
||||
lookahead: tl.constexpr,
|
||||
slotted: tl.constexpr,
|
||||
varlen: tl.constexpr,
|
||||
):
|
||||
|
||||
batch_id = block_id
|
||||
|
||||
if varlen:
|
||||
|
||||
margin, upper = tl.split(tl.load(q_ptr + block_id + tl.arange(0, 2)))
|
||||
timesteps = upper - margin
|
||||
|
||||
else:
|
||||
|
||||
timesteps = lookahead + 1
|
||||
margin = block_id * timesteps
|
||||
|
||||
if slotted:
|
||||
|
||||
batch_id = tl.load(f_ptr + batch_id)
|
||||
|
||||
return batch_id, margin, timesteps
|
||||
|
||||
|
||||
@jit
|
||||
def verify_greedy(
|
||||
j_ptr,
|
||||
margin,
|
||||
span,
|
||||
drafted,
|
||||
steps_mask,
|
||||
draft_mask,
|
||||
max_k: tl.constexpr,
|
||||
):
|
||||
|
||||
selections = tl.load(j_ptr + (margin * max_k) + span, mask=steps_mask, other=-1)
|
||||
|
||||
matched = (selections == drafted) & draft_mask
|
||||
accepted = tl.argmin(matched, axis=0)
|
||||
|
||||
token = tl.gather(selections, accepted[None], axis=0)
|
||||
|
||||
return token, accepted, selections
|
||||
|
||||
|
||||
@jit
|
||||
def decode_update(
|
||||
c_ptr,
|
||||
batch_id,
|
||||
span,
|
||||
indices,
|
||||
accepted,
|
||||
stride_c: tl.constexpr,
|
||||
):
|
||||
|
||||
tl.atomic_add(
|
||||
c_ptr + (batch_id * stride_c) + indices,
|
||||
ones_like(indices),
|
||||
mask=(span <= accepted),
|
||||
sem="acq_rel",
|
||||
scope="cta",
|
||||
)
|
||||
|
||||
|
||||
@jit
|
||||
def load_targets(
|
||||
v_ptr,
|
||||
j_ptr,
|
||||
margin,
|
||||
span,
|
||||
cols,
|
||||
mask,
|
||||
max_k: tl.constexpr,
|
||||
):
|
||||
|
||||
offsets = ((margin + span) * max_k)[:, None] + cols[None, :]
|
||||
|
||||
indices = tl.load(j_ptr + offsets, mask=mask[:, None], other=-1)
|
||||
values = tl.load(v_ptr + offsets, mask=mask[:, None], other=0)
|
||||
|
||||
return values, indices
|
||||
|
||||
|
||||
@jit
|
||||
def verify_drafted(
|
||||
d_ptr,
|
||||
u_ptr,
|
||||
h_ptr,
|
||||
l_ptr,
|
||||
batch_id,
|
||||
indicator,
|
||||
span,
|
||||
drafted,
|
||||
probabilities,
|
||||
indices,
|
||||
mask,
|
||||
block_g: tl.constexpr,
|
||||
stride_c: tl.constexpr,
|
||||
stride_d: tl.constexpr,
|
||||
stride_u: tl.constexpr,
|
||||
):
|
||||
|
||||
# Extract the selected target probabilities via masked-sum HFMA reduction tree.
|
||||
|
||||
matches = indices == drafted[:, None]
|
||||
targets = tl.sum(probabilities * matches, axis=1)
|
||||
|
||||
# Load or draw the uniform random values.
|
||||
|
||||
if u_ptr is not None:
|
||||
|
||||
uniform = tl.load(u_ptr + (batch_id * stride_u) + span, mask=mask, other=0)
|
||||
|
||||
else:
|
||||
|
||||
uniform = philox_uniform(
|
||||
h_ptr,
|
||||
l_ptr,
|
||||
batch_id,
|
||||
span,
|
||||
mask,
|
||||
stride_c,
|
||||
block_g,
|
||||
)
|
||||
|
||||
if d_ptr is not None and (indicator & 0x800) == 0:
|
||||
|
||||
# Load the drafted token source probabilities.
|
||||
|
||||
positions = (batch_id * stride_d) + (span * stride_c) + drafted
|
||||
sources = tl.load(d_ptr + positions, mask=mask, other=0)
|
||||
|
||||
# Update the LHS of the verification inequality.
|
||||
|
||||
uniform *= sources
|
||||
|
||||
# Compute the rejection offset(s) i.e. total accepted.
|
||||
|
||||
marked = (uniform <= targets) & mask
|
||||
accepted = tl.argmin(marked, axis=0)
|
||||
|
||||
return accepted, targets, matches
|
||||
|
||||
|
||||
@jit
|
||||
def rejection_sample(
|
||||
d_ptr,
|
||||
e_ptr,
|
||||
h_ptr,
|
||||
l_ptr,
|
||||
batch_id,
|
||||
timesteps,
|
||||
indicator,
|
||||
span,
|
||||
drafted,
|
||||
accepted,
|
||||
targets,
|
||||
matches,
|
||||
probabilities,
|
||||
indices,
|
||||
block_g,
|
||||
max_k: tl.constexpr,
|
||||
update_token: tl.constexpr,
|
||||
update_scores: tl.constexpr,
|
||||
stride_c: tl.constexpr,
|
||||
stride_d: tl.constexpr,
|
||||
stride_e: tl.constexpr,
|
||||
):
|
||||
|
||||
# Gather the rejected row from the target probabilities and indices.
|
||||
|
||||
rejected = accepted.broadcast_to(1, max_k)
|
||||
|
||||
scores = tl.gather(probabilities, rejected, axis=0).reshape((max_k,))
|
||||
|
||||
positions = tl.gather(indices, rejected, axis=0).reshape((max_k,))
|
||||
|
||||
# Load or draw the gumbel noise for the corresponding position(s).
|
||||
|
||||
shifts = (accepted * stride_c) + positions
|
||||
|
||||
if e_ptr is not None:
|
||||
|
||||
gumbel = tl.load(e_ptr + (batch_id * stride_e) + shifts)
|
||||
|
||||
else:
|
||||
|
||||
key = philox_key(h_ptr, l_ptr, batch_id, accepted)
|
||||
gumbel = philox_gumbel(key, positions)
|
||||
|
||||
if accepted == (timesteps - 1):
|
||||
|
||||
# Skip residual correction when all drafted tokens are accepted.
|
||||
|
||||
residuals = scores
|
||||
|
||||
elif d_ptr is None or (indicator & 0x800) > 0:
|
||||
|
||||
# Masked rejection sampling under the stochastic-verify-greedy-draft regime.
|
||||
|
||||
predicate = tl.gather(matches, rejected, axis=0).reshape((max_k,))
|
||||
|
||||
residuals = tl.where(predicate, 0.0, scores)
|
||||
|
||||
else:
|
||||
|
||||
# Load the draft probabilities for the corresponding position(s).
|
||||
|
||||
marginals = tl.load(d_ptr + (batch_id * stride_d) + shifts)
|
||||
residuals = tl.clamp(scores - marginals, 0.0, 1.0)
|
||||
|
||||
# Apply rejection sampling to surface the next token.
|
||||
|
||||
selection = tl.argmax(fast_logf(residuals) - gumbel, axis=0, keep_dims=True)
|
||||
token = tl.gather(positions, selection, axis=0)
|
||||
|
||||
if update_token:
|
||||
|
||||
drafted = tl.where(span == accepted, token.broadcast_to((block_g,)), drafted)
|
||||
|
||||
if update_scores:
|
||||
|
||||
score = tl.gather(scores, selection, axis=0).broadcast_to((block_g,))
|
||||
|
||||
targets = tl.where(span == accepted, score, targets)
|
||||
|
||||
return token, targets, drafted
|
||||
|
||||
|
||||
@jit
|
||||
def chain_speculative_verification_kernel(
|
||||
# Input Data Pointer(s).
|
||||
v_ptr, # Selected Values -> [ B • (γ + 1), M ].
|
||||
j_ptr, # Selected Indices -> [ B • (γ + 1), M ].
|
||||
z_ptr, # Indicators -> [ B ].
|
||||
f_ptr, # Slot Mapping -> [ B ].
|
||||
q_ptr, # Cumulative Lengths -> [ B + 1 ].
|
||||
t_ptr, # Drafted Tokens -> [ B • (γ + 1) ].
|
||||
d_ptr, # Draft Probabilities -> [ B, γ, V ].
|
||||
u_ptr, # Uniform -> [ B, γ ].
|
||||
e_ptr, # Gumbel Noise -> [ B • (γ + 1), V ].
|
||||
h_ptr, # Noise Seeds -> [ B ].
|
||||
l_ptr, # Noise Offsets -> [ B ].
|
||||
c_ptr, # Decode Counts -> [ B, V ].
|
||||
r_ptr, # Top-K Log-Probabilities -> [ B ].
|
||||
# Output Data Pointer(s).
|
||||
o_ptr, # Output Tokens -> [ B • (γ + 1) ].
|
||||
a_ptr, # Total Accepted Token(s) -> [ B ].
|
||||
w_ptr, # Log-Probabilities -> [ B • (γ + 1) ].
|
||||
y_ptr, # Top-K Log-Probabilities (Values) -> [ B • (γ + 1), Z ].
|
||||
k_ptr, # Top-K Log-Probabilities (Indices) -> [ B • (γ + 1), Z ].
|
||||
# Model Specific(s).
|
||||
lookahead: tl.constexpr, # Lookahead -> γ.
|
||||
max_k: tl.constexpr, # Maximum Top-K Value -> M.
|
||||
# Conditional Flag(s).
|
||||
slotted: tl.constexpr, # Slot Indirection Flag.
|
||||
varlen: tl.constexpr, # Variable-Length Lookahead Flag.
|
||||
enable_pdl: tl.constexpr, # PDL Enablement Flag.
|
||||
update_counts: tl.constexpr, # Update Decode Counts Flag.
|
||||
logprobs: tl.constexpr, # Log-Probabilities Flag.
|
||||
# Stride(s).
|
||||
stride_d: tl.constexpr, # Batch Stride of Draft Probabilities.
|
||||
stride_e: tl.constexpr, # Batch Stride of Gumbel Noise.
|
||||
stride_u: tl.constexpr, # Batch Stride of Uniform.
|
||||
stride_c: tl.constexpr, # Batch Stride of Decode Counts (Target Vocab Size) -> V.
|
||||
stride_z: tl.constexpr, # Batch Stride of Top-K Log-Probabilities (Values).
|
||||
# Kernel Specific(s).
|
||||
block_g: tl.constexpr, # Next Power-of-2 Timesteps (γ + 1) -> T.
|
||||
block_z: tl.constexpr, # Next Power-of-2 Top-K Log-Probabilities Targets -> Z'.
|
||||
) -> None:
|
||||
|
||||
block_id = tl.program_id(axis=0)
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_wait()
|
||||
|
||||
# Extract the batch id from program id and load the indicator.
|
||||
|
||||
batch_id, margin, timesteps = resolve_shift_margin(
|
||||
q_ptr,
|
||||
f_ptr,
|
||||
block_id,
|
||||
lookahead,
|
||||
slotted,
|
||||
varlen,
|
||||
)
|
||||
|
||||
indicator = tl.load(z_ptr + batch_id)
|
||||
|
||||
# Set-up the token and column-wise span(s).
|
||||
|
||||
span = tl.arange(0, block_g)
|
||||
cols = tl.arange(0, max_k)
|
||||
|
||||
# Define the (γ + 1) steps mask and the γ draft mask.
|
||||
|
||||
steps_mask = span < timesteps
|
||||
draft_mask = span < (timesteps - 1)
|
||||
|
||||
# Load the drafted tokens block.
|
||||
|
||||
drafted = tl.load(t_ptr + margin + span, mask=draft_mask, other=0)
|
||||
|
||||
if (indicator & 0x40) > 0:
|
||||
|
||||
# Apply greedy verification.
|
||||
|
||||
token, accepted, selections = verify_greedy(
|
||||
j_ptr,
|
||||
margin,
|
||||
span,
|
||||
drafted,
|
||||
steps_mask,
|
||||
draft_mask,
|
||||
max_k,
|
||||
)
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
else:
|
||||
|
||||
# Load target token indices and probabilities -> [ T, M ].
|
||||
|
||||
probabilities, indices = load_targets(
|
||||
v_ptr, j_ptr, margin, span, cols, steps_mask, max_k
|
||||
)
|
||||
|
||||
# Verify the drafted tokens against the target probabilities.
|
||||
|
||||
accepted, targets, matches = verify_drafted(
|
||||
d_ptr,
|
||||
u_ptr,
|
||||
h_ptr,
|
||||
l_ptr,
|
||||
batch_id,
|
||||
indicator,
|
||||
span,
|
||||
drafted,
|
||||
probabilities,
|
||||
indices,
|
||||
draft_mask,
|
||||
block_g,
|
||||
stride_c,
|
||||
stride_d,
|
||||
stride_u,
|
||||
)
|
||||
|
||||
# Rejection-sample the next token and conditionally update selected token(s) and score(s).
|
||||
|
||||
token, targets, selections = rejection_sample(
|
||||
d_ptr,
|
||||
e_ptr,
|
||||
h_ptr,
|
||||
l_ptr,
|
||||
batch_id,
|
||||
timesteps,
|
||||
indicator,
|
||||
span,
|
||||
drafted,
|
||||
accepted,
|
||||
targets,
|
||||
matches,
|
||||
probabilities,
|
||||
indices,
|
||||
block_g,
|
||||
max_k,
|
||||
update_counts,
|
||||
logprobs,
|
||||
stride_c,
|
||||
stride_d,
|
||||
stride_e,
|
||||
)
|
||||
|
||||
if logprobs:
|
||||
|
||||
# Compute selected token log-probabilities.
|
||||
|
||||
log_scores = fast_logf(targets)
|
||||
span_mask = span <= accepted
|
||||
|
||||
if (indicator & 0x400) > 0:
|
||||
|
||||
# Extract top-k token indices and compute their corresponding log-probabilities.
|
||||
|
||||
logprobs_ids = tl.arange(0, block_z)[None, :].broadcast_to(
|
||||
(block_g, block_z)
|
||||
)
|
||||
|
||||
logprobs_mask = (logprobs_ids < tl.load(r_ptr + batch_id)) & span_mask[
|
||||
:, None
|
||||
]
|
||||
offsets = ((margin + span)[:, None] * stride_z) + logprobs_ids
|
||||
|
||||
top_logprobs = tl.gather(probabilities, logprobs_ids, axis=1).to(
|
||||
tl.float32
|
||||
)
|
||||
|
||||
top_tokens = tl.gather(indices, logprobs_ids, axis=1)
|
||||
|
||||
if enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
tl.store(y_ptr + offsets, fast_logf(top_logprobs), mask=logprobs_mask)
|
||||
tl.store(k_ptr + offsets, top_tokens, mask=logprobs_mask)
|
||||
|
||||
elif enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
tl.store(w_ptr + margin + span, log_scores, mask=span_mask)
|
||||
|
||||
elif enable_pdl:
|
||||
|
||||
gdc_launch_dependents()
|
||||
|
||||
if update_counts:
|
||||
|
||||
# Increment the decode count(s) for the accepted and selected token(s).
|
||||
|
||||
decode_update(c_ptr, batch_id, span, selections, accepted, stride_c)
|
||||
|
||||
# Store the rejection-sampled / next seed token and the total accepted.
|
||||
|
||||
tl.store(o_ptr + margin + accepted[None], token)
|
||||
tl.store(a_ptr + block_id, accepted)
|
||||
@@ -0,0 +1,107 @@
|
||||
# Copyright (c) 2026 LightSeek Foundation
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
|
||||
"""The vendored sonic-sampler kernels: compiled by tokenspeed-triton, no upstream package or msgspec host layer, and the config table that drives them."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from tokenspeed_kernel._triton import triton
|
||||
from tokenspeed_kernel.ops.sampling import sonic
|
||||
from tokenspeed_kernel.ops.sampling.sonic import (
|
||||
MAX_OFFSET,
|
||||
TABLE,
|
||||
configs,
|
||||
pick,
|
||||
scratchpad_columns,
|
||||
)
|
||||
from tokenspeed_kernel.thirdparty.sonic_sampler.ops import (
|
||||
multistep,
|
||||
prologue,
|
||||
singular,
|
||||
verify,
|
||||
)
|
||||
|
||||
|
||||
def test_kernels_are_tokenspeed_triton_jit_functions():
|
||||
kernels = (
|
||||
prologue.bitpacked_reduction_kernel,
|
||||
singular.cumulative_selection_kernel,
|
||||
multistep.cumulative_unpack_kernel,
|
||||
verify.chain_speculative_verification_kernel,
|
||||
)
|
||||
for kernel in kernels:
|
||||
assert isinstance(kernel, triton.JITFunction)
|
||||
assert not any(name.split(".")[0] == "sonic_sampler" for name in sys.modules)
|
||||
|
||||
|
||||
def test_the_vendored_kernels_need_no_msgspec():
|
||||
root = pathlib.Path(prologue.__file__).parents[1]
|
||||
assert not any("msgspec" in path.read_text() for path in root.rglob("*.py"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"vocab_size", [512, 1000, 1024, 3000, 32000, 65536, 128256, 151936, 201088, 262144]
|
||||
)
|
||||
def test_every_pick_tiles_the_vocabulary_in_two_blocks_or_more(vocab_size):
|
||||
for rows in [*range(1, 70), 127, 128, 129, 512, 4096]:
|
||||
config = pick(vocab_size, rows)
|
||||
assert 2 * config.block_n <= vocab_size
|
||||
assert config in configs(vocab_size)
|
||||
|
||||
|
||||
def test_the_table_closes_every_class_and_row_range():
|
||||
assert TABLE[-1][0] is None
|
||||
sizes = [size for size, _ in TABLE[:-1]]
|
||||
assert sizes == sorted(sizes)
|
||||
for _, rows_table in TABLE:
|
||||
assert rows_table[-1][0] is None
|
||||
bounds = [bound for bound, _ in rows_table[:-1]]
|
||||
assert bounds == sorted(bounds)
|
||||
|
||||
|
||||
def test_the_scratchpad_holds_the_narrowest_picked_tiles_blocks():
|
||||
narrowest = min(c.block_n for c in configs(151936))
|
||||
assert scratchpad_columns(151936) == -(-151936 // narrowest) * 128
|
||||
|
||||
|
||||
def test_launches_past_the_int32_row_offsets_are_refused():
|
||||
"""The kernels keep row offsets in int32, so a launch whose logits reach past 2**31 elements is refused before it runs."""
|
||||
vocab = 1 << 18
|
||||
rows = MAX_OFFSET // vocab + 1
|
||||
logits = torch.empty((rows, vocab), dtype=torch.bfloat16, device="meta")
|
||||
scratchpad = torch.empty((rows, 1), dtype=torch.uint32, device="meta")
|
||||
config = pick(vocab, rows)
|
||||
with pytest.raises(ValueError, match="int32 offsets"):
|
||||
sonic.sample(
|
||||
logits, None, None, None, None, scratchpad, config, enable_pdl=False
|
||||
)
|
||||
with pytest.raises(ValueError, match="int32 offsets"):
|
||||
sonic.verify(
|
||||
logits, None, None, None, None, None, scratchpad, None, None, config, False
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(pytest.main([__file__, "-v"]))
|
||||
Reference in New Issue
Block a user