diff --git a/aspec/models/dflash.py b/aspec/models/dflash.py index 8de5085..51719dc 100644 --- a/aspec/models/dflash.py +++ b/aspec/models/dflash.py @@ -516,6 +516,14 @@ def _extra_position_metrics( """Algorithm-specific additional per-position metrics for evaluation.""" return {} + def _ce_per_token( + self, + flat_logits: torch.Tensor, + flat_targets: torch.Tensor, + ) -> torch.Tensor: + """Per-token CE hook for algorithm-specific fused epilogues.""" + return F.cross_entropy(flat_logits, flat_targets, reduction="none") + def _training_loss( self, *, @@ -540,7 +548,7 @@ def _training_loss( vocab_size = logits.size(-1) flat_logits = logits.view(-1, vocab_size) flat_targets = target_ids.view(-1) - ce_per_token = F.cross_entropy(flat_logits, flat_targets, reduction="none") + ce_per_token = self._ce_per_token(flat_logits, flat_targets) loss_per_token = self.ce_loss_alpha * ce_per_token if self.uses_target_distribution: diff --git a/aspec/models/domino.py b/aspec/models/domino.py index 7a984b4..35e42b4 100644 --- a/aspec/models/domino.py +++ b/aspec/models/domino.py @@ -14,6 +14,7 @@ import torch from aspec.models.dflash import DFlashModel +from aspec.models.ops.fused_ce import ce_from_logits, use_fused_ce class DominoModel(DFlashModel): @@ -92,6 +93,11 @@ def set_lambda_base(self, lambda_base) -> None: raise ValueError("Domino lambda_base must be a finite number in [0, 1]") self.lambda_base = lambda_base + def _ce_per_token(self, flat_logits, flat_targets): + if use_fused_ce(flat_logits, flat_targets): + return ce_from_logits(flat_logits, flat_targets)[0] + return super()._ce_per_token(flat_logits, flat_targets) + def _training_loss( self, *, diff --git a/aspec/models/ops/fused_ce.py b/aspec/models/ops/fused_ce.py new file mode 100644 index 0000000..c620064 --- /dev/null +++ b/aspec/models/ops/fused_ce.py @@ -0,0 +1,289 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""Tiled full-vocabulary cross-entropy from already-materialized logits. + +The caller owns the vocabulary projection. This module only replaces the +``log_softmax``/``nll_loss`` epilogue and its backward, so algorithms whose +logits are not a plain ``F.linear`` (for example Domino's corrected logits) +can use the same tiled path. The kernels follow the Medusa fused CE epilogue +in ``medusa_ce.py``; the PyTorch objective remains the numerical reference and +the fallback for CPU, non-BF16, unavailable Triton, compiling, or oversized +backward buffers. +""" + +from __future__ import annotations + +import torch +from torch.autograd.function import once_differentiable + +try: # Triton is optional for CPU planning/tests. + import triton + import triton.language as tl + + _TRITON_IMPORT_ERROR: BaseException | None = None +except Exception as exc: # pragma: no cover - exercised by CPU fallback tests + triton = None + tl = None + _TRITON_IMPORT_ERROR = exc + +_BLOCK_N = 2048 +_STATS = 5 +_MIN_ROWS = 64 +_MAX_EXACT_ARGMAX_VOCAB = 2**24 +_DLOGITS_BUDGET_BYTES = 2 * 1024**3 +_NUM_WARPS_N = 8 +_NUM_WARPS_MERGE = 4 + + +def _triton_unavailable() -> bool: + return _TRITON_IMPORT_ERROR is not None or triton is None + + +def _is_compiling() -> bool: + compiler = getattr(torch, "compiler", None) + is_compiling = getattr(compiler, "is_compiling", None) + return bool(is_compiling()) if is_compiling is not None else False + + +def _device_supported(device: torch.device) -> bool: + try: + return torch.cuda.get_device_capability(device) >= (8, 0) + except Exception: # pragma: no cover - defensive for unusual device stubs + return False + + +def use_fused_ce(logits: torch.Tensor, targets: torch.Tensor) -> bool: + """Whether the tiled CE epilogue can serve this full-vocabulary loss. + + ``logits`` must be a contiguous CUDA BF16 ``[rows, vocab]`` tensor and + ``targets`` one int64 target per row. The backward buffer is bounded so a + long selection falls back instead of allocating an unbounded ``dlogits``. + """ + return ( + not _triton_unavailable() + and not _is_compiling() + and logits.is_cuda + and targets.is_cuda + and logits.device == targets.device + and logits.dtype is torch.bfloat16 + and logits.ndim == 2 + and logits.shape[0] >= _MIN_ROWS + and 0 < logits.shape[1] <= _MAX_EXACT_ARGMAX_VOCAB + and targets.dtype is torch.int64 + and targets.ndim == 1 + and targets.numel() == logits.shape[0] + and logits.is_contiguous() + and logits.shape[0] * logits.shape[1] * 2 <= _DLOGITS_BUDGET_BYTES + and _device_supported(logits.device) + ) + + +if not _triton_unavailable(): + + @triton.jit(do_not_specialize=["V"]) + def _ce_partials( + Z, + Targets, + Partials, + V, + TILES: tl.constexpr, + STATS: tl.constexpr, + BLOCK_N: tl.constexpr, + ): + row = tl.program_id(0).to(tl.int64) + tile = tl.program_id(1).to(tl.int64) + cols = tile * BLOCK_N + tl.arange(0, BLOCK_N).to(tl.int64) + mask = cols < V + z = tl.load(Z + row * V + cols, mask=mask, other=-float("inf")).to(tl.float32) + tmax = tl.max(z, 0) + tsum = tl.sum(tl.exp(z - tmax), 0) + tsum = tl.where(tmax == -float("inf"), 0.0, tsum) + local = tl.arange(0, BLOCK_N) + arg_col = tile * BLOCK_N + tl.min( + tl.where(z == tmax, local, BLOCK_N).to(tl.int32), 0 + ).to(tl.int64) + # PyTorch argmax treats NaN as larger than every finite value and + # returns the first NaN. Keep that column separately so a NaN row's + # hit indicator matches the reference even though tl.max ignores NaN. + nan_col = tl.min(tl.where(z != z, cols, V), 0) + target = tl.load(Targets + row).to(tl.int64) + target_val = tl.max(tl.where(cols == target, z, -float("inf")), 0) + base = (row * TILES + tile) * STATS + tl.store(Partials + base, tmax) + tl.store(Partials + base + 1, tsum) + tl.store(Partials + base + 2, arg_col.to(tl.float32)) + tl.store(Partials + base + 3, target_val) + tl.store(Partials + base + 4, nan_col.to(tl.float32)) + + @triton.jit + def _merge_stats( + Partials, + RowMax, + LogTotal, + Nll, + Hits, + Targets, + TILES: tl.constexpr, + STATS: tl.constexpr, + BLOCK_TILES: tl.constexpr, + V: tl.constexpr, + ): + row = tl.program_id(0).to(tl.int64) + tile = tl.arange(0, BLOCK_TILES) + valid = tile < TILES + base = (row * TILES + tile) * STATS + tmax = tl.load(Partials + base, mask=valid, other=-float("inf")) + tsum = tl.load(Partials + base + 1, mask=valid, other=0.0) + arg_col = tl.load(Partials + base + 2, mask=valid, other=float(V)) + target_val = tl.load(Partials + base + 3, mask=valid, other=-float("inf")) + nan_col = tl.load(Partials + base + 4, mask=valid, other=float(V)) + + row_max = tl.max(tmax, 0) + total = tl.sum( + tl.where(tmax == -float("inf"), 0.0, tsum * tl.exp(tmax - row_max)), 0 + ) + log_total = tl.log(total) + + best_val = tl.max(tmax, 0) + best_col = tl.min(tl.where(tmax == best_val, arg_col, float(V)), 0) + first_nan = tl.min(nan_col, 0) + best_col = tl.where(first_nan < V, first_nan, best_col) + target = tl.load(Targets + row).to(tl.int64) + tl.device_assert( + (target >= 0) & (target < V), + "fused CE target index out of vocabulary", + ) + target_logit = tl.max(target_val, 0) + # Keep the shifted normalization separate from row_max so large logits + # do not lose log(total) to FP32 rounding. + nll = (row_max - target_logit) + log_total + hit = (best_col.to(tl.int64) == target).to(tl.float32) + tl.store(RowMax + row, row_max) + tl.store(LogTotal + row, log_total) + tl.store(Nll + row, nll) + tl.store(Hits + row, hit) + + @triton.jit(do_not_specialize=["V"]) + def _dlogits( + Z, + RowMax, + LogTotal, + Targets, + Scale, + DZ, + V, + TILES: tl.constexpr, + BLOCK_N: tl.constexpr, + ): + row = tl.program_id(0).to(tl.int64) + tile = tl.program_id(1).to(tl.int64) + cols = tile * BLOCK_N + tl.arange(0, BLOCK_N).to(tl.int64) + mask = cols < V + z = tl.load(Z + row * V + cols, mask=mask, other=-float("inf")).to(tl.float32) + row_max = tl.load(RowMax + row) + log_total = tl.load(LogTotal + row) + scale = tl.load(Scale + row) + target = tl.load(Targets + row).to(tl.int64) + probs = tl.exp((z - row_max) - log_total) + probs = tl.where(cols == target, probs - 1.0, probs) + tl.store( + DZ + row * V + cols, + (probs * scale).to(tl.bfloat16), + mask=mask, + ) + +else: # pragma: no cover - CPU import path + _ce_partials = _merge_stats = _dlogits = None + + +class _CEFromLogits(torch.autograd.Function): + @staticmethod + def forward(ctx, logits: torch.Tensor, targets: torch.Tensor): + rows, vocab = logits.shape + tiles = triton.cdiv(vocab, _BLOCK_N) + block_tiles = triton.next_power_of_2(tiles) + merge_warps = _NUM_WARPS_MERGE if block_tiles >= 32 else 1 + partials = torch.empty((rows, tiles, _STATS), device=logits.device, + dtype=torch.float32) + row_max = torch.empty((rows,), device=logits.device, dtype=torch.float32) + log_total = torch.empty((rows,), device=logits.device, dtype=torch.float32) + nll = torch.empty((rows,), device=logits.device, dtype=torch.float32) + hits = torch.empty((rows,), device=logits.device, dtype=torch.float32) + + with torch.cuda.device(logits.device): + _ce_partials[(rows, tiles)]( + logits, + targets, + partials, + vocab, + tiles, + _STATS, + _BLOCK_N, + num_warps=_NUM_WARPS_N, + enable_fp_fusion=False, + ) + _merge_stats[(rows,)]( + partials, + row_max, + log_total, + nll, + hits, + targets, + tiles, + _STATS, + block_tiles, + vocab, + num_warps=merge_warps, + debug=True, + enable_fp_fusion=False, + ) + + ctx.save_for_backward(logits, targets, row_max, log_total) + ctx.mark_non_differentiable(hits) + return nll, hits + + @staticmethod + @once_differentiable + def backward(ctx, grad_nll, grad_hits): + del grad_hits + logits, targets, row_max, log_total = ctx.saved_tensors + if grad_nll is None: + return None, None + grad_nll = grad_nll.contiguous() + rows, vocab = logits.shape + tiles = triton.cdiv(vocab, _BLOCK_N) + dlogits = torch.empty_like(logits) + with torch.cuda.device(logits.device): + _dlogits[(rows, tiles)]( + logits, + row_max, + log_total, + targets, + grad_nll, + dlogits, + vocab, + tiles, + _BLOCK_N, + num_warps=_NUM_WARPS_N, + enable_fp_fusion=False, + ) + return dlogits, None + + +def ce_from_logits(logits: torch.Tensor, targets: torch.Tensor): + """Per-row tiled CE from BF16 logits. + + Returns ``(nll, hits)`` where ``nll`` is FP32 and differentiable and + ``hits`` is FP32 ``{0, 1}`` and detached. The caller owns any mean/sum + normalization and must use :func:`use_fused_ce` before calling this. + """ + if _triton_unavailable(): + raise RuntimeError( + "fused CE from logits requires Triton; use the PyTorch reference" + ) from _TRITON_IMPORT_ERROR + if not use_fused_ce(logits, targets): + raise ValueError("logits/targets do not satisfy the fused CE contract") + if not targets.is_contiguous(): + targets = targets.contiguous() + return _CEFromLogits.apply(logits, targets) diff --git a/docs/user-guide/domino.md b/docs/user-guide/domino.md index 116565f..f42317b 100644 --- a/docs/user-guide/domino.md +++ b/docs/user-guide/domino.md @@ -265,6 +265,34 @@ sampled anchors produce both branches: second evaluation pass, and the mixed objective and trained correction head are unchanged by this reporting mode. +### Loss epilogue + +On CUDA BF16 logits, `DominoModel._ce_per_token` dispatches both branches to the +tiled `aspec.models.ops.fused_ce.ce_from_logits` epilogue. It saves BF16 logits +and row statistics instead of FP32 `log_softmax`, and writes the BF16 gradient in +backward. CPU, non-BF16, non-contiguous, unavailable Triton, whole-model compile +and oversized backward buffers keep the PyTorch `F.cross_entropy` reference. The +objective, checkpoint topology and exact-recovery state are unchanged. + +Loss-only benchmark on one H100 PCIe (rows 2048, vocab 151936, `lambda_base=0.3`, +five warmup and twenty measured iterations) via +`python tools/performance/bench_domino_loss.py --out domino_loss_bench.json`. +The run used Python 3.11.18, CUDA 13.0, torch 2.13.0+cu130 and Triton 3.7.1; the +script records the full hardware/software/config identity and statistics in the +JSON report. + +| Cell | Median | Peak extra | +| --- | ---: | ---: | +| PyTorch BF16 fallback (`F.cross_entropy`) | 6.77 ms | 2.49 GB | +| PyTorch FP32 numerical oracle | 16.43 ms | 4.98 GB | +| Tiled `ce_from_logits` | 3.50 ms | 1.25 GB | + +The fused path is 1.93x the BF16 fallback and matches the FP32 oracle's loss and +gradient norm exactly in that run; the BF16 fallback itself differs from the FP32 +oracle by about `8e-5` relative loss. This isolates the two CE epilogues; it +excludes the Draft backbone, Target inference, transport, optimizer, convergence, +acceptance and serving throughput. + ## Minimal numerical use Inside the [isolated Linux environment](installation.md): diff --git a/tests/cpu/test_fused_ce.py b/tests/cpu/test_fused_ce.py new file mode 100644 index 0000000..91d3118 --- /dev/null +++ b/tests/cpu/test_fused_ce.py @@ -0,0 +1,34 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""CPU contract checks for the from-logits fused CE dispatch.""" + +import pytest +import torch + +from aspec.models.ops.fused_ce import ce_from_logits, use_fused_ce + + +def _logits(rows=64, vocab=4097): + return torch.randn(rows, vocab, dtype=torch.bfloat16) + + +def test_cpu_logits_fall_back_to_reference(): + logits = _logits() + targets = torch.zeros(logits.shape[0], dtype=torch.int64) + assert not use_fused_ce(logits, targets) + with pytest.raises((RuntimeError, ValueError)): + ce_from_logits(logits, targets) + + +def test_contract_rejects_wrong_dtype_and_rows(): + targets = torch.zeros(64, dtype=torch.int64) + assert not use_fused_ce(torch.randn(64, 4097), targets) + assert not use_fused_ce(_logits(rows=63), torch.zeros(63, dtype=torch.int64)) + + +def test_contract_rejects_wrong_targets_and_layout(): + logits = _logits() + assert not use_fused_ce(logits, torch.zeros(64, dtype=torch.int32)) + assert not use_fused_ce(logits, torch.zeros(65, dtype=torch.int64)) + assert not use_fused_ce(logits[:, ::2], torch.zeros(64, dtype=torch.int64)) diff --git a/tests/test_domino_fused_ce_gpu.py b/tests/test_domino_fused_ce_gpu.py new file mode 100644 index 0000000..6977a1b --- /dev/null +++ b/tests/test_domino_fused_ce_gpu.py @@ -0,0 +1,222 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""GPU parity and edge cases for the from-logits fused CE used by Domino. + +Run with ``ASPEC_RUN_GPU_INTEGRATION=1`` on a CUDA device. The reference is +Torch's BF16 cross-entropy over the same logits. +""" + +import os + +import pytest +import torch +import torch.nn.functional as F + +if os.environ.get("ASPEC_RUN_GPU_INTEGRATION") != "1": + pytest.skip("set ASPEC_RUN_GPU_INTEGRATION=1 for GPU integration", allow_module_level=True) +if not torch.cuda.is_available(): + pytest.skip("CUDA is required", allow_module_level=True) +pytest.importorskip("triton") + +import aspec.models.domino as domino_module # noqa: E402 +from aspec.models.domino import DominoModel # noqa: E402 +from aspec.models.draft.domino import DominoConfig, DominoDraftModel # noqa: E402 +from aspec.models.ops.fused_ce import ce_from_logits, use_fused_ce # noqa: E402 + + +def _tensors(rows, vocab, seed=0, scale=1.0): + generator = torch.Generator(device="cuda").manual_seed(seed) + logits = torch.randn(rows, vocab, device="cuda", dtype=torch.bfloat16, + generator=generator) * scale + targets = torch.randint(0, vocab, (rows,), device="cuda", generator=generator) + return logits, targets + + +def _reference(logits, targets): + logits_f32 = logits.float() + return (F.cross_entropy(logits_f32, targets, reduction="none"), + (logits_f32.argmax(-1) == targets).float()) + + +def _assert_gradient_close(actual, expected, name): + assert torch.isfinite(actual).all(), f"{name} has non-finite values" + error = ((actual.float() - expected.float()).norm() + / expected.float().norm().clamp_min(1e-6)) + assert error < 2e-2, f"{name} relative norm error {error.item():.4f}" + scale = expected.float().abs().max().clamp_min(1e-8) + max_abs = (actual.float() - expected.float()).abs().max() + assert max_abs <= 2e-2 * scale, ( + f"{name} max abs error {max_abs.item():.6f} exceeds 2% of scale " + f"{scale.item():.6f}" + ) + + +@pytest.mark.parametrize("vocab,rows", [(4097, 64), (16385, 65), (151936, 64)]) +def test_ce_matches_torch(vocab, rows): + logits, targets = _tensors(rows, vocab, seed=vocab + rows) + assert use_fused_ce(logits, targets) + nll, hits = ce_from_logits(logits, targets) + ref_nll, ref_hits = _reference(logits, targets) + torch.testing.assert_close(nll, ref_nll, rtol=1e-4, atol=1e-5) + assert torch.equal(hits, ref_hits) + + +@pytest.mark.parametrize("vocab", [3, 127, 4097, 16385]) +def test_vocab_not_divisible_by_block(vocab): + logits, targets = _tensors(65, vocab, seed=vocab) + if logits.shape[0] < 64: + pytest.skip("fused CE requires at least 64 rows") + nll, hits = ce_from_logits(logits, targets) + ref_nll, ref_hits = _reference(logits, targets) + torch.testing.assert_close(nll, ref_nll, rtol=1e-4, atol=1e-5) + assert torch.equal(hits, ref_hits) + + +def test_gradient_matches_torch(): + logits, targets = _tensors(64, 4097, seed=11) + logits_ref = logits.detach().clone().requires_grad_(True) + logits_fused = logits.detach().clone().requires_grad_(True) + weights = torch.rand(64, device="cuda", dtype=torch.float32) + 0.5 + + ref_nll, _ = _reference(logits_ref, targets) + (ref_nll * weights).sum().backward() + fused_nll, _ = ce_from_logits(logits_fused, targets) + (fused_nll * weights).sum().backward() + + torch.testing.assert_close(fused_nll, ref_nll, rtol=1e-4, atol=1e-5) + _assert_gradient_close(logits_fused.grad, logits_ref.grad, "logits") + + +def test_large_logits_are_finite(): + logits, targets = _tensors(64, 4097, seed=13, scale=100.0) + nll, _ = ce_from_logits(logits, targets) + ref_nll, _ = _reference(logits, targets) + assert torch.isfinite(nll).all() + torch.testing.assert_close(nll, ref_nll, rtol=5e-3, atol=5e-2) + + +def test_nan_row_propagates(): + logits, targets = _tensors(2, 4097, seed=17) + logits[0, 31] = float("nan") + # The op requires 64 rows; pad the batch and keep the NaN row observable. + pad_logits = torch.zeros(64, 4097, device="cuda", dtype=torch.bfloat16) + pad_targets = torch.zeros(64, device="cuda", dtype=torch.int64) + pad_logits[:2] = logits + pad_targets[:2] = targets + pad_targets[0] = 31 + nll, hits = ce_from_logits(pad_logits, pad_targets) + ref_nll, ref_hits = _reference(pad_logits, pad_targets) + assert torch.isnan(nll[0]) + assert hits[0].item() == 1 + assert torch.equal(hits, ref_hits) + torch.testing.assert_close(nll[1:], ref_nll[1:], rtol=1e-4, atol=1e-5) + + +def test_all_negative_inf_row_propagates_nan(): + logits = torch.full((64, 4097), float("-inf"), device="cuda", + dtype=torch.bfloat16) + targets = torch.zeros(64, device="cuda", dtype=torch.int64) + nll, _ = ce_from_logits(logits, targets) + assert torch.isnan(nll).all() + + +def test_non_contiguous_logits_fall_back(): + logits = torch.randn(64, 8194, device="cuda", dtype=torch.bfloat16)[:, ::2] + targets = torch.zeros(64, device="cuda", dtype=torch.int64) + assert not use_fused_ce(logits, targets) + with pytest.raises(ValueError): + ce_from_logits(logits, targets) + + +def _make_domino_model(): + config = DominoConfig( + hidden_size=32, + intermediate_size=64, + num_hidden_layers=1, + num_attention_heads=2, + num_key_value_heads=1, + head_dim=16, + vocab_size=4097, + num_target_layers=1, + target_hidden_size=32, + target_num_hidden_layers=4, + target_layer_ids=[1], + mask_token_id=4096, + max_position_embeddings=128, + block_size=8, + rms_norm_eps=1e-6, + emb_dim=6, + gru_hidden_dim=8, + shift_label=True, + pure_draft_prefix_len=1, + ) + with torch.random.fork_rng(devices=[]): + torch.random.default_generator.manual_seed(17) + draft = DominoDraftModel(config) + draft.embed_tokens.requires_grad_(False) + return DominoModel( + draft, + block_size=config.block_size, + num_anchors=8, + attention_backend="sdpa", + loss_decay_gamma=0.0, + lambda_base=0.3, + ) + + +def _make_domino_inputs(): + generator = torch.Generator(device="cuda").manual_seed(31) + input_ids = torch.arange(1, 33, device="cuda").reshape(1, 32) + return { + "input_ids": input_ids, + "hidden_states_list": torch.randn( + 1, 32, 32, device="cuda", dtype=torch.bfloat16, generator=generator), + "loss_mask": torch.ones_like(input_ids), + "lm_head_weight": torch.randn( + 4097, 32, device="cuda", dtype=torch.bfloat16, generator=generator), + "last_hidden_states": torch.randn( + 1, 32, 32, device="cuda", dtype=torch.bfloat16, generator=generator), + "injected_anchors": torch.tensor( + [[2, 5, 8, 11, 14, 17, 20, 23]], device="cuda"), + "injected_keep_mask": torch.ones( + 1, 8, dtype=torch.bool, device="cuda"), + } + + +def test_domino_dispatch_matches_reference(monkeypatch): + model = _make_domino_model().to(device="cuda") + inputs = _make_domino_inputs() + model.train() + + with torch.autocast("cuda", dtype=torch.bfloat16): + monkeypatch.setattr(domino_module, "use_fused_ce", lambda *_: False) + loss_ref, *_ = model(**inputs) + loss_ref.backward() + grads_ref = { + name: param.grad.detach().clone() + for name, param in model.named_parameters() + if param.grad is not None + } + model.zero_grad(set_to_none=True) + + calls = [] + real_ce = domino_module.ce_from_logits + + def counted_ce(logits, targets): + calls.append(1) + return real_ce(logits, targets) + + monkeypatch.setattr(domino_module, "use_fused_ce", lambda *_: True) + monkeypatch.setattr(domino_module, "ce_from_logits", counted_ce) + loss_fused, *_ = model(**inputs) + loss_fused.backward() + + assert calls + torch.testing.assert_close(loss_fused, loss_ref, rtol=2e-2, atol=2e-3) + for name, param in model.named_parameters(): + if param.grad is None: + assert name not in grads_ref + continue + assert name in grads_ref, name + _assert_gradient_close(param.grad, grads_ref[name], name) diff --git a/tools/performance/bench_domino_loss.py b/tools/performance/bench_domino_loss.py new file mode 100644 index 0000000..aa0492b --- /dev/null +++ b/tools/performance/bench_domino_loss.py @@ -0,0 +1,235 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""Domino CE epilogue benchmark on synthetic Qwen3-8B-shaped logits. + +This isolates the two full-vocabulary cross-entropy branches of one Domino +training step. It does not run the Draft backbone, Target inference, transport, +an optimizer, convergence, acceptance or serving throughput. The reference is +Torch's BF16 ``F.cross_entropy`` over the same logits; the fused cell is the +tiled ``ce_from_logits`` epilogue. + +The run fails when the fused loss or gradient fingerprint moves away from the +reference, so the timings always describe the same objective. +""" + +from __future__ import annotations + +import argparse +import json +import math +import statistics +import sys + +import torch +import torch.nn.functional as F + +from aspec.models.ops.fused_ce import ce_from_logits, use_fused_ce + +_PARITY_TOL = 1e-3 + + +def _summary(values): + return { + "median_ms": statistics.median(values), + "mean_ms": statistics.fmean(values), + "min_ms": min(values), + "max_ms": max(values), + "samples": len(values), + } + + +def _arguments(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--rows", type=int, default=2048) + parser.add_argument("--vocab", type=int, default=151936) + parser.add_argument("--lambda-base", type=float, default=0.3) + parser.add_argument("--warmup", type=int, default=5) + parser.add_argument("--iters", type=int, default=20) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--out", default="domino_loss_bench.json") + args = parser.parse_args() + for name in ("rows", "vocab", "warmup", "iters"): + if getattr(args, name) <= 0: + parser.error(f"{name} must be positive") + if not 0.0 <= args.lambda_base <= 1.0: + parser.error("lambda-base must be in [0, 1]") + return args + + +def _make_inputs(args): + generator = torch.Generator(device="cuda").manual_seed(args.seed) + base = torch.randn(args.rows, args.vocab, device="cuda", + dtype=torch.bfloat16, generator=generator) + corrected = torch.randn(args.rows, args.vocab, device="cuda", + dtype=torch.bfloat16, generator=generator) + targets = torch.randint(0, args.vocab, (args.rows,), device="cuda", + generator=generator) + weights = torch.rand(args.rows, device="cuda", dtype=torch.float32, + generator=generator) + 0.5 + return base, corrected, targets, weights + + +def _reference_loss(base, corrected, targets, weights, lambda_base): + # This is the actual PyTorch fallback used by DFlashModel._ce_per_token: + # BF16 logits go straight into F.cross_entropy, with no explicit upcast. + corrected_ce = F.cross_entropy(corrected, targets, reduction="none") + base_ce = F.cross_entropy(base, targets, reduction="none") + mixed = (1.0 - lambda_base) * corrected_ce + lambda_base * base_ce + return (mixed * weights).sum() + + +def _oracle_loss(base, corrected, targets, weights, lambda_base): + # Numerical oracle only: FP32 log-softmax, matching the fused kernel's + # internal accumulation rather than the BF16 fallback's output precision. + corrected_ce = F.cross_entropy(corrected.float(), targets, reduction="none") + base_ce = F.cross_entropy(base.float(), targets, reduction="none") + mixed = (1.0 - lambda_base) * corrected_ce + lambda_base * base_ce + return (mixed * weights).sum() + + +def _fused_loss(base, corrected, targets, weights, lambda_base): + corrected_ce, _ = ce_from_logits(corrected, targets) + base_ce, _ = ce_from_logits(base, targets) + mixed = (1.0 - lambda_base) * corrected_ce + lambda_base * base_ce + return (mixed * weights).sum() + + +def _run_cell(name, args, inputs, loss_fn): + base, corrected, targets, weights = inputs + base = base.detach().clone().requires_grad_(True) + corrected = corrected.detach().clone().requires_grad_(True) + + def step(): + base.grad = None + corrected.grad = None + loss = loss_fn(base, corrected, targets, weights, args.lambda_base) + loss.backward() + return loss.detach() + + for _ in range(args.warmup): + step() + torch.cuda.synchronize() + # Warmup leaves gradients that the measured steps release and recreate; + # exclude them from the baseline. + base.grad = None + corrected.grad = None + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + baseline = torch.cuda.memory_allocated() + + times = [] + last_loss = None + for _ in range(args.iters): + start = torch.cuda.Event(enable_timing=True) + end = torch.cuda.Event(enable_timing=True) + start.record() + last_loss = step() + end.record() + end.synchronize() + times.append(start.elapsed_time(end)) + + # Capture the peak before the FP32 gradient-norm diagnostics allocate + # conversion and square temporaries. + torch.cuda.synchronize() + peak_extra = torch.cuda.max_memory_allocated() - baseline + grad_norm = math.sqrt( + float(base.grad.float().pow(2).sum()) + + float(corrected.grad.float().pow(2).sum()) + ) + return { + "cell": name, + "timing": _summary(times), + "peak_extra_bytes": int(peak_extra), + "fingerprint": { + "loss": float(last_loss), + "grad_norm": grad_norm, + }, + } + + +def main(): + args = _arguments() + if not torch.cuda.is_available(): + raise SystemExit("CUDA is required") + inputs = _make_inputs(args) + if not use_fused_ce(inputs[0], inputs[2]): + raise SystemExit("fused CE is not supported on this device/input") + + results = [] + for name, loss_fn in ( + ("reference", _reference_loss), + ("oracle", _oracle_loss), + ("fused", _fused_loss), + ): + torch.cuda.empty_cache() + results.append(_run_cell(name, args, inputs, loss_fn)) + torch.cuda.synchronize() + + by_cell = {result["cell"]: result for result in results} + reference = by_cell["reference"] + oracle = by_cell["oracle"] + fused = by_cell["fused"] + + def _rel(actual, expected): + return abs(actual - expected) / max(abs(expected), 1e-12) + + fused_loss_rel = _rel( + fused["fingerprint"]["loss"], oracle["fingerprint"]["loss"]) + fused_grad_rel = _rel( + fused["fingerprint"]["grad_norm"], oracle["fingerprint"]["grad_norm"]) + reference_loss_rel = _rel( + reference["fingerprint"]["loss"], oracle["fingerprint"]["loss"]) + reference_grad_rel = _rel( + reference["fingerprint"]["grad_norm"], oracle["fingerprint"]["grad_norm"]) + saving_ms = reference["timing"]["median_ms"] - fused["timing"]["median_ms"] + report = { + "script": "tools/performance/bench_domino_loss.py", + "scope": "Domino two-branch CE epilogue forward+backward on synthetic " + "Qwen3-8B-shaped logits (BF16 fallback, FP32 oracle, fused " + "tiled path); no Draft/Target forward, transport, optimizer, " + "convergence, acceptance or serving claims", + "config": { + "rows": args.rows, + "vocab": args.vocab, + "lambda_base": args.lambda_base, + "warmup": args.warmup, + "iters": args.iters, + "seed": args.seed, + }, + "hardware": { + "device": torch.cuda.get_device_name(0), + "capability": list(torch.cuda.get_device_capability(0)), + "total_memory_bytes": torch.cuda.get_device_properties(0).total_memory, + }, + "software": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "triton": getattr(sys.modules.get("triton"), "__version__", None), + "python": sys.version.split()[0], + }, + "results": results, + "derived": { + "saving_ms": saving_ms, + "speedup": reference["timing"]["median_ms"] / fused["timing"]["median_ms"], + "fused_vs_oracle_loss_rel_delta": fused_loss_rel, + "fused_vs_oracle_grad_norm_rel_delta": fused_grad_rel, + "reference_vs_oracle_loss_rel_delta": reference_loss_rel, + "reference_vs_oracle_grad_norm_rel_delta": reference_grad_rel, + }, + "parity_tolerance": _PARITY_TOL, + } + text = json.dumps(report, indent=2, sort_keys=True) + print(text) + with open(args.out, "w", encoding="utf-8") as handle: + handle.write(text + "\n") + if not (fused_loss_rel <= _PARITY_TOL and fused_grad_rel <= _PARITY_TOL): + raise SystemExit( + f"fused loss/gradient fingerprint diverged from the FP32 oracle " + f"beyond {_PARITY_TOL:g}; the timings in {args.out} do not describe " + f"the same objective" + ) + + +if __name__ == "__main__": + main()