Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion aspec/models/dflash.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
*,
Expand All @@ -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:
Expand Down
6 changes: 6 additions & 0 deletions aspec/models/domino.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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,
*,
Expand Down
289 changes: 289 additions & 0 deletions aspec/models/ops/fused_ce.py
Original file line number Diff line number Diff line change
@@ -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)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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)
28 changes: 28 additions & 0 deletions docs/user-guide/domino.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading