Repository navigation
perf(domino): fuse full-vocabulary cross-entropy #76
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hereisaway
wants to merge
2
commits into
inclusionAI:main
Choose a base branch
from
hereisaway:feat/domino-fused-ce
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+823
−1
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| 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) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.