From 85ff599c5ba7635799932491877dcab503f18859 Mon Sep 17 00:00:00 2001 From: bohaotu Date: Wed, 25 Nov 2026 12:03:53 +0800 Subject: [PATCH 1/4] perf(medusa): fuse full-vocabulary CE and bound its memory Add a Medusa-specific Triton CE/argmax/dlogits epilogue while keeping the PyTorch objective as the numerical reference and fallback path. - Replace per-128-token dW accumulation with one whole-head dW GEMM in the fast path; retain BF16 logits only within an 8 GiB all-head budget. - Bound backward dlogits to a 2 GiB full-buffer budget and accumulate dW per token chunk for longer selections. - Fail closed for vocabularies above 2^24 where the FP32 tile argmax column would not be exact, and enable the target device assert. - Add CPU fallback/2-layer wiring tests and GPU parity/edge tests, including the chunked backward path and its BF16-accumulation-noise calibration. - Add tools/performance/bench_medusa_loss.py and document the L20 loss-only measurement (3.22x vs reference, 1.20x vs whole-head restructure), memory bounds and explicit non-claims. Review fixes: bounded dlogits, V > 2^24 fallback, active device assert, shared retained-logits budget constant, and calibrated chunked-gradient test. Refs #17 --- aspec/models/medusa.py | 101 ++++-- aspec/models/ops/medusa_ce.py | 436 ++++++++++++++++++++++++ docs/user-guide/algorithms.md | 4 + docs/user-guide/medusa.md | 77 +++++ tests/cpu/test_medusa_fused_fallback.py | 216 ++++++++++++ tests/test_medusa_loss_kernel_gpu.py | 260 ++++++++++++++ tools/performance/bench_medusa_loss.py | 337 ++++++++++++++++++ 7 files changed, 1410 insertions(+), 21 deletions(-) create mode 100644 aspec/models/ops/medusa_ce.py create mode 100644 tests/cpu/test_medusa_fused_fallback.py create mode 100644 tests/test_medusa_loss_kernel_gpu.py create mode 100644 tools/performance/bench_medusa_loss.py diff --git a/aspec/models/medusa.py b/aspec/models/medusa.py index cbe8d47..62a041d 100644 --- a/aspec/models/medusa.py +++ b/aspec/models/medusa.py @@ -15,18 +15,63 @@ from torch.nn import functional as F from torch.utils.checkpoint import checkpoint +from aspec.models.ops.medusa_ce import medusa_head_ce, use_fused_medusa_ce + +# Retaining BF16 logits removes one projection pass in backward. Bound the +# all-head retained bytes so gradient checkpointing still protects long +# sequences; 4K/Qwen3-8B/K=5 (about 6.2 GiB) uses the faster saved mode. +SAVE_LOGITS_BUDGET_BYTES = 8 * 1024**3 + class MedusaModel(nn.Module): def __init__(self, draft_model, gradient_checkpointing=False): super().__init__() - # Chunked CE retains each chunk's f32 logits until backward - # (~chunk x vocab x 4 bytes per head); long-sequence training should - # enable gradient_checkpointing, as the maintained recipes do. + # The reference path retains each chunk's FP32 logits until backward. + # The fused path instead uses the budget below: small selections retain + # BF16 logits and skip one projection pass; long selections recompute. self.draft_model = draft_model self.num_heads = draft_model.medusa_num_heads self.gradient_checkpointing = gradient_checkpointing self.vocab_pruning = False + def _save_fused_logits(self, tokens, vocab): + if not self.gradient_checkpointing: + return True + retained = tokens * vocab * 2 * self.num_heads + return retained <= SAVE_LOGITS_BUDGET_BYTES + + def _reference_head_loss( + self, + head, + features, + input_ids_row, + feature_positions, + label_positions, + selected, + ): + """Reference per-head CE at the t+2+i offset, one head.""" + total = features.new_zeros((), dtype=torch.float32) + hits = features.new_zeros((), dtype=torch.float32) + for indices in selected.split(128): + targets = input_ids_row.index_select( + 0, label_positions.index_select(0, indices)) + chunk_features = features.index_select( + 0, feature_positions.index_select(0, indices)) + + def loss_chunk(chunk_features, targets, head=head): + logits = head(chunk_features) + return (F.cross_entropy(logits.float(), targets, reduction="sum"), + (logits.argmax(-1) == targets).float().sum()) + + if self.gradient_checkpointing and self.training and torch.is_grad_enabled(): + loss, chunk_hits = checkpoint(loss_chunk, chunk_features, targets, + use_reentrant=False) + else: + loss, chunk_hits = loss_chunk(chunk_features, targets) + total = total + loss + hits = hits + chunk_hits.detach() + return total, hits + def forward(self, input_ids, hidden_states, loss_mask, attention_mask, thd_layout=None): if thd_layout is not None: raise NotImplementedError("Medusa currently supports padded CP1 execution only") @@ -54,24 +99,38 @@ def forward(self, input_ids, hidden_states, loss_mask, attention_mask, thd_layou feature_positions = label_positions - offset keep = loss_mask[row].index_select(0, label_positions).bool() selected = keep.nonzero().flatten() - for indices in selected.split(128): - targets = input_ids[row].index_select( - 0, label_positions.index_select(0, indices)) - chunk_features = features.index_select( - 0, feature_positions.index_select(0, indices)) - - def loss_chunk(chunk_features, targets, head=head): - logits = self.draft_model.medusa_head[head](chunk_features) - return (F.cross_entropy(logits.float(), targets, reduction="sum"), - (logits.argmax(-1) == targets).float().sum()) - - if self.gradient_checkpointing and self.training and torch.is_grad_enabled(): - loss, hits = checkpoint(loss_chunk, chunk_features, targets, - use_reentrant=False) - else: - loss, hits = loss_chunk(chunk_features, targets) - sums[head] = sums[head] + loss - correct[head] = correct[head] + hits.detach() + head_module = self.draft_model.medusa_head[head] + if selected.numel() and use_fused_medusa_ce( + features, + head_module[-1].weight, + num_rows=selected.numel(), + ): + selected_features = features.index_select( + 0, feature_positions.index_select(0, selected)) + selected_labels = label_positions.index_select(0, selected) + targets = input_ids[row].index_select(0, selected_labels) + projected = head_module[:-1](selected_features) + nll, hits = medusa_head_ce( + projected, + head_module[-1].weight, + targets, + save_logits=self._save_fused_logits( + selected.numel(), head_module[-1].weight.shape[0] + ), + ) + sums[head] = sums[head] + nll.sum() + correct[head] = correct[head] + hits.sum() + elif selected.numel(): + loss_sum, hits_sum = self._reference_head_loss( + head_module, + features, + input_ids[row], + feature_positions, + label_positions, + selected, + ) + sums[head] = sums[head] + loss_sum + correct[head] = correct[head] + hits_sum counts[head] = counts[head] + selected.numel() losses = [value / count.clamp_min(1) for value, count in zip(sums, counts, strict=True)] return (losses, [value.detach() for value in losses], diff --git a/aspec/models/ops/medusa_ce.py b/aspec/models/ops/medusa_ce.py new file mode 100644 index 0000000..176ded0 --- /dev/null +++ b/aspec/models/ops/medusa_ce.py @@ -0,0 +1,436 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""Fused full-vocabulary cross-entropy for Medusa heads-only training. + +The reference Medusa objective computes, per head, the mean CE over the +selected assistant tokens. A naive implementation materialises FP32 logits, +runs a separate argmax pass, and lets autograd accumulate one ``[V, H]`` +weight gradient per row chunk. This module keeps the PyTorch objective as +the numerical reference while providing a fused Triton epilogue: + +- ``_ce_partials`` streams each vocabulary tile once, capturing tile max, + sum-exp, argmax and the target logit. +- ``_merge_stats`` merges tile statistics into a per-row log-sum-exp, NLL and + exact argmax (lowest vocabulary index on ties). +- ``_dlogits`` writes ``(softmax - onehot) * upstream`` in BF16. +- ``_MedusaCE`` recomputes logits chunk-wise in backward when requested. It + issues one ``dX``/``dW`` GEMM per head when the full BF16 ``dlogits`` buffer + fits the backward budget, and otherwise accumulates ``dW`` per token chunk + so long selections stay bounded. + +The vocabulary projection itself stays on cuBLAS: on sm_89 a Triton matmul is +not expected to beat cuBLAS, and backward needs the logits again to compute +``dlogits``. This follows the same division of work as ``tiled_l1``. + +Independent implementation; Torch's CE remains the numerical reference and +the fallback for CPU, unsupported devices/dtypes, or unavailable Triton. +""" + +from __future__ import annotations + +import torch +import torch.nn.functional as F +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 +_MAX_ROW_CHUNK = 512 +_MIN_ROW_CHUNK = 64 +_SAVE_BYTES = 256 * 1024 * 1024 +_DLOGITS_BUDGET_BYTES = 2 * 1024**3 +_MAX_EXACT_ARGMAX_VOCAB = 2**24 +_MIN_TOKENS = 64 +_NUM_WARPS_N = 8 +_NUM_WARPS_MERGE = 4 + +_CAPABILITY_CACHE: dict[int, tuple[int, int]] = {} + + +def _triton_unavailable() -> bool: + return _TRITON_IMPORT_ERROR is not None or triton is None + + +def _device_capability(device: torch.device) -> tuple[int, int]: + index = device.index if device.index is not None else torch.cuda.current_device() + cached = _CAPABILITY_CACHE.get(index) + if cached is None: + cached = torch.cuda.get_device_capability(index) + _CAPABILITY_CACHE[index] = cached + return cached + + +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 _resolve_row_chunk(vocab: int, requested: int | None) -> int: + if requested is not None: + if requested <= 0: + raise ValueError("Medusa CE row_chunk must be positive") + return int(requested) + budget_rows = max(1, _SAVE_BYTES // (2 * vocab)) + chunk = min(_MAX_ROW_CHUNK, max(_MIN_ROW_CHUNK, budget_rows)) + return max(_MIN_ROW_CHUNK, (chunk // _MIN_ROW_CHUNK) * _MIN_ROW_CHUNK) + + +def use_fused_medusa_ce( + hidden: torch.Tensor, + weight: torch.Tensor, + *, + num_rows: int | None = None, +) -> bool: + """Return whether the fused epilogue can run for this head. + + ``hidden`` may be the full row feature tensor; ``num_rows`` overrides the + selected-token count when the caller has not gathered it yet. This is a + cheap predicate: no allocation, synchronization or host read of values. + """ + if _triton_unavailable() or _is_compiling(): + return False + if not hidden.is_cuda or not weight.is_cuda or hidden.device != weight.device: + return False + if hidden.dtype is not torch.bfloat16 or weight.dtype is not torch.bfloat16: + return False + if hidden.ndim != 2 or weight.ndim != 2: + return False + if hidden.shape[1] != weight.shape[1]: + return False + if weight.shape[0] == 0: + return False + if weight.shape[0] > _MAX_EXACT_ARGMAX_VOCAB: + return False + rows = hidden.shape[0] if num_rows is None else int(num_rows) + if rows < _MIN_TOKENS: + return False + if not hidden.is_contiguous() or not weight.is_contiguous(): + return False + return _device_capability(hidden.device) >= (8, 0) + + +if not _triton_unavailable(): + + @triton.jit(do_not_specialize=["V"]) + def _ce_partials( + Z, + Targets, + Partials, + 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) + 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) + target = tl.load(Targets + row).to(tl.int64) + target_val = tl.max(tl.where(cols == target, z, -float("inf")), 0) + base = (row * TILES + tile) * 4 + 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) + + @triton.jit + def _merge_stats( + Partials, + Lse, + Nll, + Hits, + Targets, + TILES: 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) * 4 + 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")) + + row_max = tl.max(tmax, 0) + total = tl.sum( + tl.where(tmax == -float("inf"), 0.0, tsum * tl.exp(tmax - row_max)), 0 + ) + lse = row_max + tl.log(total) + + best_val = tl.max(tmax, 0) + best_col = tl.min(tl.where(tmax == best_val, arg_col, float(V)), 0) + target = tl.load(Targets + row).to(tl.int64) + tl.device_assert( + (target >= 0) & (target < V), + "Medusa CE target index out of vocabulary", + ) + target_logit = tl.max(target_val, 0) + nll = lse - target_logit + hit = (best_col.to(tl.int64) == target).to(tl.float32) + tl.store(Lse + row, lse) + tl.store(Nll + row, nll) + tl.store(Hits + row, hit) + + @triton.jit(do_not_specialize=["V"]) + def _dlogits( + Z, + Lse, + 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) + lse = tl.load(Lse + row) + scale = tl.load(Scale + row) + target = tl.load(Targets + row).to(tl.int64) + probs = tl.exp(z - lse) + 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 _MedusaCE(torch.autograd.Function): + @staticmethod + def forward( + ctx, + hidden: torch.Tensor, + weight: torch.Tensor, + targets: torch.Tensor, + row_chunk: int, + save_logits: bool, + ): + rows, vocab = hidden.shape[0], weight.shape[0] + device = hidden.device + 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, 4), device=device, dtype=torch.float32) + lse = torch.empty((rows,), device=device, dtype=torch.float32) + nll = torch.empty((rows,), device=device, dtype=torch.float32) + hits = torch.empty((rows,), device=device, dtype=torch.float32) + saved_logits = ( + torch.empty((rows, vocab), device=device, dtype=torch.bfloat16) + if save_logits + else None + ) + scratch = ( + None + if save_logits + else torch.empty( + (min(row_chunk, rows), vocab), device=device, dtype=torch.bfloat16 + ) + ) + + for start in range(0, rows, row_chunk): + stop = min(start + row_chunk, rows) + count = stop - start + if saved_logits is not None: + logits_chunk = saved_logits[start:stop] + else: + logits_chunk = scratch[:count] + logits_chunk.copy_(F.linear(hidden[start:stop], weight)) + _ce_partials[(count, tiles)]( + logits_chunk, + targets[start:stop], + partials[start:stop], + vocab, + tiles, + _BLOCK_N, + num_warps=_NUM_WARPS_N, + enable_fp_fusion=False, + ) + _merge_stats[(count,)]( + partials[start:stop], + lse[start:stop], + nll[start:stop], + hits[start:stop], + targets[start:stop], + tiles, + block_tiles, + vocab, + num_warps=merge_warps, + debug=True, + enable_fp_fusion=False, + ) + + if saved_logits is not None: + ctx.save_for_backward(hidden, weight, targets, lse, saved_logits) + else: + ctx.save_for_backward( + hidden, + weight, + targets, + lse, + torch.empty(0, device=device, dtype=torch.bfloat16), + ) + ctx.row_chunk = row_chunk + ctx.save_logits = save_logits + ctx.mark_non_differentiable(hits) + return nll, hits + + @staticmethod + @once_differentiable + def backward(ctx, grad_nll, grad_hits): + del grad_hits + hidden, weight, targets, lse, saved_logits = ctx.saved_tensors + rows, vocab = hidden.shape[0], weight.shape[0] + if grad_nll is None: + return None, None, None, None, None + needs_dx = ctx.needs_input_grad[0] + needs_dw = ctx.needs_input_grad[1] + if not needs_dx and not needs_dw: + return None, None, None, None, None + grad_nll = grad_nll.contiguous() + tiles = triton.cdiv(vocab, _BLOCK_N) + with torch.no_grad(): + scratch = ( + None + if ctx.save_logits + else torch.empty( + (min(ctx.row_chunk, rows), vocab), + device=hidden.device, + dtype=torch.bfloat16, + ) + ) + if rows * vocab * 2 <= _DLOGITS_BUDGET_BYTES: + dlogits = torch.empty( + (rows, vocab), device=hidden.device, dtype=torch.bfloat16 + ) + for start in range(0, rows, ctx.row_chunk): + stop = min(start + ctx.row_chunk, rows) + count = stop - start + if ctx.save_logits: + logits_chunk = saved_logits[start:stop] + else: + logits_chunk = scratch[:count] + logits_chunk.copy_(F.linear(hidden[start:stop], weight)) + _dlogits[(count, tiles)]( + logits_chunk, + lse[start:stop], + targets[start:stop], + grad_nll[start:stop], + dlogits[start:stop], + vocab, + tiles, + _BLOCK_N, + num_warps=_NUM_WARPS_N, + enable_fp_fusion=False, + ) + dx = torch.mm(dlogits, weight) if needs_dx else None + dw = torch.mm(dlogits.t(), hidden) if needs_dw else None + else: + # Long selections never keep a full [rows, vocab] dlogits + # buffer; accumulate dW per token chunk instead. + dx = torch.empty_like(hidden) if needs_dx else None + dw = torch.zeros_like(weight) if needs_dw else None + for start in range(0, rows, ctx.row_chunk): + stop = min(start + ctx.row_chunk, rows) + count = stop - start + if ctx.save_logits: + logits_chunk = saved_logits[start:stop] + else: + logits_chunk = scratch[:count] + logits_chunk.copy_(F.linear(hidden[start:stop], weight)) + dlogits_chunk = torch.empty( + (count, vocab), device=hidden.device, dtype=torch.bfloat16 + ) + _dlogits[(count, tiles)]( + logits_chunk, + lse[start:stop], + targets[start:stop], + grad_nll[start:stop], + dlogits_chunk, + vocab, + tiles, + _BLOCK_N, + num_warps=_NUM_WARPS_N, + enable_fp_fusion=False, + ) + if needs_dx: + torch.mm(dlogits_chunk, weight, out=dx[start:stop]) + if needs_dw: + dw.addmm_(dlogits_chunk.t(), hidden[start:stop]) + return dx, dw, None, None, None + + +def medusa_head_ce( + hidden: torch.Tensor, + weight: torch.Tensor, + targets: torch.Tensor, + *, + row_chunk: int | None = None, + save_logits: bool = True, +) -> tuple[torch.Tensor, torch.Tensor]: + """Per-token Medusa CE for one head, with the fused epilogue. + + Returns ``(nll, hits)`` where ``nll`` is FP32 and differentiable and + ``hits`` is FP32 ``{0, 1}`` and detached. The caller owns the per-head + mean/count normalization; this op only sums per-token terms. + """ + if _triton_unavailable(): + raise RuntimeError( + "fused Medusa CE requires Triton; use the reference loss path" + ) from _TRITON_IMPORT_ERROR + if not hidden.is_cuda or not weight.is_cuda: + raise ValueError("fused Medusa CE requires CUDA tensors") + if hidden.device != weight.device or targets.device != hidden.device: + raise ValueError("fused Medusa CE tensors must share one CUDA device") + if hidden.dtype is not torch.bfloat16 or weight.dtype is not torch.bfloat16: + raise ValueError("fused Medusa CE requires BF16 hidden states and weights") + if hidden.ndim != 2 or weight.ndim != 2: + raise ValueError("fused Medusa CE requires 2-D hidden states and weights") + if hidden.shape[1] != weight.shape[1]: + raise ValueError("hidden and weight dimensions disagree") + if hidden.shape[0] == 0 or weight.shape[0] == 0: + raise ValueError("fused Medusa CE requires nonempty rows and vocabulary") + if weight.shape[0] > _MAX_EXACT_ARGMAX_VOCAB: + raise ValueError( + "fused Medusa CE supports vocabulary <= 2^24 for exact argmax accuracy" + ) + if targets.ndim != 1 or targets.numel() != hidden.shape[0]: + raise ValueError("fused Medusa CE requires one target per row") + if targets.dtype != torch.int64: + raise ValueError("fused Medusa CE requires int64 targets") + if not hidden.is_contiguous() or not weight.is_contiguous(): + raise ValueError("fused Medusa CE requires contiguous tensors") + if not targets.is_contiguous(): + targets = targets.contiguous() + return _MedusaCE.apply( + hidden, + weight, + targets, + _resolve_row_chunk(weight.shape[0], row_chunk), + bool(save_logits), + ) diff --git a/docs/user-guide/algorithms.md b/docs/user-guide/algorithms.md index 0ecd6c3..7d433e4 100644 --- a/docs/user-guide/algorithms.md +++ b/docs/user-guide/algorithms.md @@ -169,6 +169,10 @@ the sum of per-head mean cross-entropies (assistant tokens only): each head's CE within a microbatch, and microbatches are weighted equally by gradient accumulation rather than pooled by token count. The heads own trainable full-vocabulary projections. Start from `configs/recipes/medusa_qwen3_8b.yaml` (SDPA, CP1, MBS1, non-packing, REPLICATE, Store/TCP). +The loss automatically selects a fused Triton CE/argmax/dlogits epilogue with one `dW` GEMM per +head (or bounded per-chunk accumulation for long selections) when CUDA BF16 and Triton are +available, and falls back to the reference path otherwise; `gradient_checkpointing` still bounds +the dominant vocabulary-logit memory through an internal retained-logits budget. Native export, strict reload and per-head held-out reporting are implemented, as is greedy and typical/nucleus sampling candidate-tree acceptance through a standalone Hugging Face evaluator; SGLang integration and production serving remain future work; see [details](medusa.md). diff --git a/docs/user-guide/medusa.md b/docs/user-guide/medusa.md index 614b6a5..a4b0817 100644 --- a/docs/user-guide/medusa.md +++ b/docs/user-guide/medusa.md @@ -49,6 +49,83 @@ The current path fails closed outside the following: - `fsdp_strategy: REPLICATE`, one node. Anchored training, MTP conditioning and whole-model compile are rejected. +## Loss kernel and measured execution + +The objective uses a Medusa-specific fused epilogue when the selected rows are +CUDA BF16 and Triton is available; otherwise it keeps the reference path. The +fused path gathers one head's selected rows once, applies the residual block +once, runs one wide vocabulary GEMM per row chunk, and replaces per-chunk FP32 +logits, `argmax` and CE with a tiled Triton CE/argmax/dlogits epilogue. It +issues one `dW` GEMM per head when the full BF16 dlogits buffer fits the +backward budget; longer selections accumulate `dW` per token chunk instead of +per 128-token chunk. CPU, unsupported dtypes/devices/shapes, +unavailable Triton, whole-model compile and very short selections use the +reference path; `tests/cpu/test_medusa.py` pins that path unchanged. + +`gradient_checkpointing` still bounds the dominant vocabulary-logit memory +through an internal 8 GiB budget; the residual block is applied once and its +smaller `[T, H]` activations are retained. When the all-head BF16 logits fit +the budget (Qwen3-8B `K=5`, 4094 selected tokens and `V=151936` is about +6.2 GiB), the fused path retains them and skips one projection pass in +backward; longer selections recompute. The backward pass keeps one full BF16 +`dlogits` buffer only when it fits a 2 GiB budget; otherwise it accumulates +`dX`/`dW` per token chunk. The fused path requires `V <= 2^24` because the +tile argmax column is carried in FP32; larger vocabularies use the reference +path. No configuration field is added. + +Measured on one NVIDIA L20 48GB (sm_89, driver 580.126.20, CUDA 13.0, torch +2.13.0+cu130, Triton 3.7.1), Qwen3-8B head shape `K=5`, `H=4096`, +`V=151936`, 4094 selected tokens, loss-only forward+backward, 10 warmup and +30 measured iterations in one process with shared inputs and seeds: + +| Cell | Median | p90 | / reference | Peak extra | +| --- | ---: | ---: | ---: | ---: | +| Current reference (128-token chunks) | 2456.74 ms | 2457.03 ms | 1.00× | 4.98 GB | +| Whole-head restructure (diagnostic only) | 913.61 ms | 914.79 ms | 2.69× | 11.36 GB | +| Fused epilogue + one `dW` per head | **761.95 ms** | **762.41 ms** | **3.22×** | **4.98 GB** | + +Peak extra is the delta after resident model weights and inputs; it excludes +optimizer state. Accuracy uses the lowest vocabulary index on argmax ties; +PyTorch CUDA argmax tie order is unspecified, so ties are the only metric +difference. + +The restructure is a script-only attribution cell, not a shipped path. The +reference and fused loss fingerprints are close but not bitwise equal: +`250777.75` vs `250777.95`, gradient norms `13286.11` vs `13274.47` over the +same 3,195,555,840 gradient elements, and the same accuracy count; the +difference comes from whole-head versus chunked reduction order. The +vocabulary projection remains on cuBLAS: a fully fused Triton matmul was not +adopted because sm_89 matmul quality is not expected to beat cuBLAS and the +backward pass still needs logits for `dlogits`. Forcing recompute on the +4K/`K=5` cell adds one projection pass and was rejected; the retained-logits +budget selects the faster mode when it fits. A scaled +`BF16Optimizer` smoke (`K=5`, `H=1024`, `V=32768`, 512 tokens, 20 steps) +finished with final loss `2.1982379` vs `2.1974640` and gradient norm +`1.92420` vs `1.92306`. + +`torch.profiler` attributes the reference's 2.46 s to 785 vectorized +elementwise calls (874.85 ms, the repeated gradient-buffer accumulation), +about 1.36 s of GEMMs and 114 ms of softmax. In the profiled fused cell the +three Triton kernels total about 30 ms, the GEMMs about 0.66 s, and the +785-call accumulation set disappears. Nsight Systems 2023.1 did not capture +CUDA kernel data on this sm_89 device, and Nsight Compute was denied by the +cluster (`ERR_NVGPUCTRPERM`); the profiler table is the available attribution. + +These are loss-only Draft-head measurements with real Qwen3-8B dimensions. +They are not end-to-end Target+transport training throughput, convergence, +acceptance or SGLang-serving claims. The full recipe's ~3.2B trainable heads +need about 51 GB of optimizer state and do not fit one L20; the scaled smoke is +an integration check, not a quality result. Reproduce with: + +```bash +python -m tools.performance.bench_medusa_loss --mode both \ + --heads 5 --tokens 4094 --hidden 4096 --vocab 151936 \ + --warmup 10 --iters 30 --out medusa-loss.json +``` + +`--fused-logits auto|save|recompute` exposes the retained-logits decision for +diagnosis; the trainer itself uses `auto`. + ## Export and strict reload Export a trained checkpoint as an ASpec-native asset: diff --git a/tests/cpu/test_medusa_fused_fallback.py b/tests/cpu/test_medusa_fused_fallback.py new file mode 100644 index 0000000..b8de9ef --- /dev/null +++ b/tests/cpu/test_medusa_fused_fallback.py @@ -0,0 +1,216 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""CPU-side fallback and validation for the fused Medusa CE epilogue.""" + +import copy + +import pytest +import torch +import torch.nn.functional as F +from torch import nn + +from aspec.models.draft.medusa import MedusaConfig, MedusaDraftModel +from aspec.models.medusa import MedusaModel +from aspec.models.ops import medusa_ce + + +def _tensors(rows=128, hidden=8, vocab=64, dtype=torch.bfloat16): + return ( + torch.randn(rows, hidden, dtype=dtype), + torch.randn(vocab, hidden, dtype=dtype), + ) + + +def test_predicate_rejects_cpu_tensors(): + hidden, weight = _tensors() + assert medusa_ce.use_fused_medusa_ce(hidden, weight) is False + + +def test_predicate_rejects_non_bf16_and_shape_mismatch(): + hidden, weight = _tensors(dtype=torch.float32) + assert medusa_ce.use_fused_medusa_ce(hidden, weight) is False + hidden, weight = _tensors() + assert medusa_ce.use_fused_medusa_ce(hidden[:, :4], weight) is False + assert medusa_ce.use_fused_medusa_ce(hidden.transpose(0, 1), weight) is False + + +def test_predicate_honors_num_rows(): + hidden, weight = _tensors(rows=1) + assert medusa_ce.use_fused_medusa_ce(hidden, weight, num_rows=1) is False + assert medusa_ce.use_fused_medusa_ce(hidden, weight, num_rows=1024) is False + + +def test_predicate_small_selection_threshold(monkeypatch): + class Fake: + is_cuda = True + dtype = torch.bfloat16 + ndim = 2 + shape = (64, 8) + device = "fake" + + @staticmethod + def is_contiguous(): + return True + + hidden, weight = Fake(), Fake() + monkeypatch.setattr(medusa_ce, "_TRITON_IMPORT_ERROR", None) + monkeypatch.setattr(medusa_ce, "triton", object()) + monkeypatch.setattr(medusa_ce, "_device_capability", lambda device: (8, 9)) + assert medusa_ce.use_fused_medusa_ce(hidden, weight, num_rows=63) is False + assert medusa_ce.use_fused_medusa_ce(hidden, weight, num_rows=64) is True + + +def test_predicate_rejects_vocab_beyond_exact_argmax(monkeypatch): + class Fake: + is_cuda = True + dtype = torch.bfloat16 + ndim = 2 + device = "fake" + + def __init__(self, shape): + self.shape = shape + + @staticmethod + def is_contiguous(): + return True + + hidden = Fake((64, 8)) + weight = Fake((medusa_ce._MAX_EXACT_ARGMAX_VOCAB + 1, 8)) + monkeypatch.setattr(medusa_ce, "_TRITON_IMPORT_ERROR", None) + monkeypatch.setattr(medusa_ce, "triton", object()) + monkeypatch.setattr(medusa_ce, "_device_capability", lambda device: (8, 9)) + assert medusa_ce.use_fused_medusa_ce(hidden, weight) is False + + +def test_missing_triton_falls_back(monkeypatch): + hidden, weight = _tensors() + monkeypatch.setattr(medusa_ce, "_TRITON_IMPORT_ERROR", ImportError("missing")) + assert medusa_ce.use_fused_medusa_ce(hidden, weight) is False + with pytest.raises(RuntimeError, match="requires Triton"): + medusa_ce.medusa_head_ce(hidden, weight, torch.zeros(128, dtype=torch.int64)) + + +def test_medusa_head_ce_requires_cuda(): + hidden, weight = _tensors() + targets = torch.zeros(128, dtype=torch.int64) + with pytest.raises((ValueError, RuntimeError)): + medusa_ce.medusa_head_ce(hidden, weight, targets) + + +def test_resolve_row_chunk_defaults(): + assert medusa_ce._resolve_row_chunk(151936, None) == 512 + assert medusa_ce._resolve_row_chunk(1_000_000, None) == 128 + assert medusa_ce._resolve_row_chunk(10, 7) == 7 + with pytest.raises(ValueError): + medusa_ce._resolve_row_chunk(10, 0) + + +def _tiny_model(): + config = MedusaConfig( + hidden_size=8, + vocab_size=16, + target_hidden_size=8, + target_num_hidden_layers=4, + medusa_num_heads=2, + medusa_num_layers=1, + ) + draft = MedusaDraftModel(config) + with torch.no_grad(): + for head in draft.medusa_head: + nn.init.normal_(head[0].linear.weight, std=0.05) + nn.init.normal_(head[-1].weight, std=0.05) + return MedusaModel(draft) + + +def test_save_fused_logits_budget(): + model = _tiny_model() + model.gradient_checkpointing = False + assert model._save_fused_logits(4094, 151936) is True + model.gradient_checkpointing = True + assert model._save_fused_logits(4094, 151936) is True + assert model._save_fused_logits(100_000, 151936) is False + + +def test_two_layer_wiring_matches_reference(monkeypatch): + config = MedusaConfig( + hidden_size=8, + vocab_size=16, + target_hidden_size=8, + target_num_hidden_layers=4, + medusa_num_heads=2, + medusa_num_layers=2, + ) + draft = MedusaDraftModel(config) + with torch.no_grad(): + for head in draft.medusa_head: + nn.init.normal_(head[0].linear.weight, std=0.05) + nn.init.normal_(head[1].linear.weight, std=0.05) + nn.init.normal_(head[-1].weight, std=0.05) + fused = MedusaModel(copy.deepcopy(draft)) + reference = MedusaModel(copy.deepcopy(draft)) + input_ids = torch.randint(0, 16, (1, 32)) + hidden_states = torch.randn(1, 32, 8) + loss_mask = (torch.rand(1, 32) > 0.2).long() + attention_mask = torch.ones(1, 32, dtype=torch.long) + + def fake_fused_ce(hidden, weight, targets, **kwargs): + logits = F.linear(hidden, weight).float() + return ( + F.cross_entropy(logits, targets, reduction="none"), + (logits.argmax(-1) == targets).float(), + ) + + monkeypatch.setattr("aspec.models.medusa.use_fused_medusa_ce", lambda *args, **kwargs: True) + monkeypatch.setattr("aspec.models.medusa.medusa_head_ce", fake_fused_ce) + fused_losses, _, fused_accs, fused_counts, _ = fused( + input_ids, hidden_states, loss_mask, attention_mask + ) + + monkeypatch.setattr("aspec.models.medusa.use_fused_medusa_ce", lambda *args, **kwargs: False) + ref_losses, _, ref_accs, ref_counts, _ = reference( + input_ids, hidden_states, loss_mask, attention_mask + ) + + for fused_loss, ref_loss in zip(fused_losses, ref_losses, strict=True): + torch.testing.assert_close(fused_loss, ref_loss, rtol=2e-5, atol=2e-6) + for fused_acc, ref_acc in zip(fused_accs, ref_accs, strict=True): + torch.testing.assert_close(fused_acc, ref_acc, rtol=2e-5, atol=2e-6) + assert [count.item() for count in fused_counts] == [count.item() for count in ref_counts] + + sum(fused_losses).backward() + sum(ref_losses).backward() + for (name, parameter), (ref_name, ref_parameter) in zip( + fused.named_parameters(), reference.named_parameters(), strict=True + ): + assert name == ref_name + torch.testing.assert_close(parameter.grad, ref_parameter.grad, rtol=2e-5, atol=2e-6) + + +def test_reference_path_zero_mask_keeps_zero_grads(): + model = _tiny_model() + input_ids = torch.randint(0, 16, (1, 12)) + hidden_states = torch.randn(1, 12, 8) + loss_mask = torch.zeros(1, 12, dtype=torch.long) + attention_mask = torch.ones(1, 12, dtype=torch.long) + + losses, _, _, counts, _ = model(input_ids, hidden_states, loss_mask, attention_mask) + assert all(count.item() == 0 for count in counts) + sum(losses).backward() + for parameter in model.parameters(): + assert parameter.grad is not None + assert torch.count_nonzero(parameter.grad) == 0 + + +def test_reference_path_finite_on_cpu(): + model = _tiny_model() + input_ids = torch.randint(0, 16, (1, 16)) + hidden_states = torch.randn(1, 16, 8) + loss_mask = torch.ones(1, 16, dtype=torch.long) + attention_mask = torch.ones(1, 16, dtype=torch.long) + + losses, _, accs, counts, _ = model(input_ids, hidden_states, loss_mask, attention_mask) + assert len(losses) == 2 + assert all(torch.isfinite(loss) for loss in losses) + assert all(torch.isfinite(acc) for acc in accs) + assert all(count > 0 for count in counts) diff --git a/tests/test_medusa_loss_kernel_gpu.py b/tests/test_medusa_loss_kernel_gpu.py new file mode 100644 index 0000000..f3f8d1f --- /dev/null +++ b/tests/test_medusa_loss_kernel_gpu.py @@ -0,0 +1,260 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""GPU parity and edge cases for the fused Medusa CE epilogue. + +Run with ``ASPEC_RUN_GPU_INTEGRATION=1`` on a CUDA device. The reference is +Torch's BF16 linear followed by FP32 cross-entropy, matching the production +Medusa objective. +""" + +import os + +import pytest +import torch +import torch.nn.functional as F +from torch import nn + +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") + +from aspec.models.draft.medusa import MedusaConfig, MedusaDraftModel +from aspec.models.medusa import MedusaModel +from aspec.models.ops import medusa_ce +from aspec.models.ops.medusa_ce import medusa_head_ce, use_fused_medusa_ce + + +def _tensors(tokens, hidden, vocab, seed=0): + generator = torch.Generator(device="cuda").manual_seed(seed) + x = torch.randn(tokens, hidden, device="cuda", dtype=torch.bfloat16, generator=generator) + w = torch.randn(vocab, hidden, device="cuda", dtype=torch.bfloat16, + generator=generator) * 0.05 + targets = torch.randint(0, vocab, (tokens,), device="cuda", generator=generator) + return x, w, targets + + +def _reference(x, w, targets): + logits = F.linear(x, w).float() + nll = F.cross_entropy(logits, targets, reduction="none") + hits = (logits.argmax(-1) == targets).float() + return nll, hits + + +def _manual_grads(x, w, targets): + x_ref = x.detach().clone().requires_grad_(True) + w_ref = w.detach().clone().requires_grad_(True) + loss = F.cross_entropy(F.linear(x_ref, w_ref).float(), targets, reduction="sum") + loss.backward() + return x_ref.grad, w_ref.grad + + +def _fused_grads(x, w, targets, *, save_logits): + x_fused = x.detach().clone().requires_grad_(True) + w_fused = w.detach().clone().requires_grad_(True) + nll, hits = medusa_head_ce(x_fused, w_fused, targets, save_logits=save_logits) + nll.sum().backward() + return nll.detach(), hits, x_fused.grad, w_fused.grad + + +def _assert_gradient_close(actual, expected, name): + torch.testing.assert_close(actual, expected, rtol=2e-2, atol=2e-3, msg=name) + error = (actual - expected).norm() / expected.norm().clamp_min(1e-6) + assert error < 1e-2, f"{name} relative norm error {error.item():.4f}" + + +def _assert_chunked_gradient_close(actual, expected, name): + """BF16 chunk accumulation is compared by scale, not near-zero atol.""" + 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 < 1e-2, f"{name} relative norm error {error.item():.4f}" + max_abs = (actual.float() - expected.float()).abs().max() + scale = expected.float().abs().max().clamp_min(1.0) + assert max_abs <= 1e-2 * scale, ( + f"{name} max abs error {max_abs.item():.6f} exceeds 1% of scale " + f"{scale.item():.6f}" + ) + + +@pytest.mark.parametrize( + "vocab,tokens", + [(127, 1), (4096, 7), (4096, 128), (151936, 1024)], +) +def test_nll_and_hits_match_torch(vocab, tokens): + x, w, targets = _tensors(tokens, 64, vocab) + nll, hits = medusa_head_ce(x, w, targets, save_logits=True) + ref_nll, ref_hits = _reference(x, w, 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]) +def test_vocab_not_divisible_by_block(vocab): + x, w, targets = _tensors(11, 32, vocab) + nll, hits = medusa_head_ce(x, w, targets, save_logits=True) + ref_nll, ref_hits = _reference(x, w, targets) + torch.testing.assert_close(nll, ref_nll, rtol=1e-4, atol=1e-5) + assert torch.equal(hits, ref_hits) + + +def test_target_at_tile_boundary(): + vocab = 4096 + targets = torch.tensor([0, 2047, 2048, 4095], device="cuda", dtype=torch.int64) + x = torch.randn(4, 32, device="cuda", dtype=torch.bfloat16) + w = torch.randn(vocab, 32, device="cuda", dtype=torch.bfloat16) * 0.05 + nll, hits = medusa_head_ce(x, w, targets, save_logits=True) + ref_nll, ref_hits = _reference(x, w, targets) + torch.testing.assert_close(nll, ref_nll, rtol=1e-4, atol=1e-5) + assert torch.equal(hits, ref_hits) + + +def test_dx_dw_match_reference(): + x, w, targets = _tensors(128, 64, 4096) + _, _, dx, dw = _fused_grads(x, w, targets, save_logits=True) + dx_ref, dw_ref = _manual_grads(x, w, targets) + _assert_gradient_close(dx, dx_ref, "dx") + _assert_gradient_close(dw, dw_ref, "dw") + + +def test_save_logits_modes_match(): + x, w, targets = _tensors(128, 64, 4096) + nll_true, hits_true, dx_true, dw_true = _fused_grads(x, w, targets, save_logits=True) + nll_false, hits_false, dx_false, dw_false = _fused_grads(x, w, targets, save_logits=False) + torch.testing.assert_close(nll_true, nll_false, rtol=0, atol=0) + assert torch.equal(hits_true, hits_false) + torch.testing.assert_close(dx_true, dx_false, rtol=0, atol=0) + torch.testing.assert_close(dw_true, dw_false, rtol=0, atol=0) + + +def test_chunked_backward_matches_full(monkeypatch): + x, w, targets = _tensors(1024, 64, 4096) + nll_full, hits_full, dx_full, dw_full = _fused_grads(x, w, targets, save_logits=True) + + monkeypatch.setattr(medusa_ce, "_DLOGITS_BUDGET_BYTES", 1) + nll_chunk, hits_chunk, dx_chunk, dw_chunk = _fused_grads(x, w, targets, save_logits=True) + torch.testing.assert_close(nll_full, nll_chunk, rtol=0, atol=0) + assert torch.equal(hits_full, hits_chunk) + _assert_chunked_gradient_close(dx_chunk, dx_full, "chunked saved dx") + _assert_chunked_gradient_close(dw_chunk, dw_full, "chunked saved dw") + + _, _, dx_recompute, dw_recompute = _fused_grads(x, w, targets, save_logits=False) + _assert_chunked_gradient_close(dx_recompute, dx_full, "chunked recompute dx") + _assert_chunked_gradient_close(dw_recompute, dw_full, "chunked recompute dw") + + +def test_ties_break_at_lowest_index(): + vocab = 256 + x = torch.zeros(3, 16, device="cuda", dtype=torch.bfloat16) + w = torch.zeros(vocab, 16, device="cuda", dtype=torch.bfloat16) + targets = torch.tensor([0, 5, vocab - 1], device="cuda", dtype=torch.int64) + nll, hits = medusa_head_ce(x, w, targets, save_logits=True) + expected = torch.log(torch.tensor(float(vocab), device="cuda")).expand_as(nll) + torch.testing.assert_close(nll, expected, rtol=1e-6, atol=1e-6) + assert hits.tolist() == [1.0, 0.0, 0.0] + + +def test_nonfinite_input_produces_nonfinite_nll(): + x, w, targets = _tensors(128, 64, 4096) + x = x.clone() + x[0, 0] = float("nan") + nll, _ = medusa_head_ce(x, w, targets, save_logits=True) + ref_nll, _ = _reference(x, w, targets) + assert torch.isnan(nll[0]) + assert torch.isnan(ref_nll[0]) + + +def _small_model(gradient_checkpointing): + config = MedusaConfig( + hidden_size=32, + vocab_size=128, + target_hidden_size=32, + target_num_hidden_layers=4, + medusa_num_heads=3, + medusa_num_layers=1, + ) + draft = MedusaDraftModel(config).cuda().bfloat16() + with torch.no_grad(): + for head in draft.medusa_head: + nn.init.normal_(head[0].linear.weight, std=0.05) + nn.init.normal_(head[-1].weight, std=0.05) + return MedusaModel(draft, gradient_checkpointing=gradient_checkpointing) + + +def _model_inputs(seq_len=300): + input_ids = torch.randint(0, 128, (1, seq_len), device="cuda") + hidden_states = torch.randn(1, seq_len, 32, device="cuda", dtype=torch.bfloat16) + loss_mask = (torch.rand(1, seq_len, device="cuda") > 0.2).long() + attention_mask = torch.ones(1, seq_len, dtype=torch.long, device="cuda") + return input_ids, hidden_states, loss_mask, attention_mask + + +def _require_fused_path(model, hidden_states, seq_len=128): + weight = model.draft_model.medusa_head[0][-1].weight + if not use_fused_medusa_ce( + hidden_states[0], weight, num_rows=min(seq_len, hidden_states.shape[1]) + ): + pytest.skip("fused Medusa CE is not supported on this GPU/runtime") + + +@pytest.mark.parametrize("gradient_checkpointing", [False, True]) +def test_end_to_end_parity_with_python_path(gradient_checkpointing, monkeypatch): + torch.manual_seed(1234) + fused = _small_model(gradient_checkpointing) + torch.manual_seed(1234) + reference = _small_model(gradient_checkpointing) + reference.load_state_dict( + {key: value.clone() for key, value in fused.state_dict().items()} + ) + input_ids, hidden_states, loss_mask, attention_mask = _model_inputs() + _require_fused_path(fused, hidden_states) + + fused_losses, _, fused_accs, fused_counts, _ = fused( + input_ids, hidden_states, loss_mask, attention_mask + ) + monkeypatch.setattr("aspec.models.medusa.use_fused_medusa_ce", lambda *args, **kwargs: False) + ref_losses, _, ref_accs, ref_counts, _ = reference( + input_ids, hidden_states, loss_mask, attention_mask + ) + + for fused_loss, ref_loss in zip(fused_losses, ref_losses, strict=True): + torch.testing.assert_close(fused_loss, ref_loss, rtol=1e-4, atol=1e-5) + for fused_acc, ref_acc in zip(fused_accs, ref_accs, strict=True): + torch.testing.assert_close(fused_acc, ref_acc, rtol=1e-5, atol=1e-6) + assert [count.item() for count in fused_counts] == [count.item() for count in ref_counts] + + sum(fused_losses).backward() + sum(ref_losses).backward() + for (name, parameter), (ref_name, ref_parameter) in zip( + fused.named_parameters(), reference.named_parameters(), strict=True + ): + assert name == ref_name + assert parameter.grad is not None and ref_parameter.grad is not None + _assert_gradient_close(parameter.grad, ref_parameter.grad, name) + + +def test_zero_selected_tokens_skips_kernel(monkeypatch): + model = _small_model(True) + calls = [] + monkeypatch.setattr("aspec.models.medusa.medusa_head_ce", lambda *args, **kwargs: calls.append(1)) + input_ids, hidden_states, _, attention_mask = _model_inputs() + loss_mask = torch.zeros_like(input_ids) + losses, _, _, counts, _ = model(input_ids, hidden_states, loss_mask, attention_mask) + assert calls == [] + assert all(count.item() == 0 for count in counts) + sum(losses).backward() + for parameter in model.parameters(): + assert parameter.grad is not None + assert torch.count_nonzero(parameter.grad) == 0 + + +def test_state_dict_unchanged(): + model = _small_model(True) + before = {key: (value.shape, value.dtype) for key, value in model.state_dict().items()} + input_ids, hidden_states, loss_mask, attention_mask = _model_inputs() + losses, _, _, _, _ = model(input_ids, hidden_states, loss_mask, attention_mask) + sum(losses).backward() + after = {key: (value.shape, value.dtype) for key, value in model.state_dict().items()} + assert before == after diff --git a/tools/performance/bench_medusa_loss.py b/tools/performance/bench_medusa_loss.py new file mode 100644 index 0000000..bc66142 --- /dev/null +++ b/tools/performance/bench_medusa_loss.py @@ -0,0 +1,337 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""Single-GPU Medusa heads-only loss benchmark. + +Measures one forward+backward over the vocabulary heads, excluding Target +features, transport and orchestration. Three cells are supported: + +- ``reference``: the current chunked Medusa path (128-token CE chunks, optional + gradient checkpointing). +- ``restructure``: a script-only attribution cell that gathers the whole head, + uses one wide vocabulary GEMM and one ``dW`` accumulation. +- ``fused``: the Triton CE/argmax/dlogits epilogue plus one ``dW`` per head. + +The script records loss/gradient fingerprints alongside timings so a faster +cell cannot silently change the training math. +""" + +from __future__ import annotations + +import argparse +import json +import math +import statistics +import sys + +import torch +import torch.nn.functional as F +from torch import nn +from torch.utils.checkpoint import checkpoint + +from aspec.models.draft.medusa import MedusaConfig, MedusaDraftModel +from aspec.models.medusa import SAVE_LOGITS_BUDGET_BYTES +from aspec.models.ops.medusa_ce import medusa_head_ce, use_fused_medusa_ce +from aspec.training.optimizer import BF16Optimizer + + +def _percentile(values, fraction): + ordered = sorted(values) + position = (len(ordered) - 1) * fraction + lower = int(position) + upper = min(lower + 1, len(ordered) - 1) + if lower == upper: + return ordered[lower] + return ordered[lower] * (upper - position) + ordered[upper] * (position - lower) + + +def _summary(values): + return { + "median_ms": statistics.median(values), + "mean_ms": statistics.fmean(values), + "p10_ms": _percentile(values, 0.10), + "p90_ms": _percentile(values, 0.90), + "min_ms": min(values), + "max_ms": max(values), + "samples": len(values), + } + + +def _arguments(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--mode", choices=("reference", "restructure", "fused", "both"), + default="both") + parser.add_argument("--heads", type=int, default=5) + parser.add_argument("--tokens", type=int, default=4094) + parser.add_argument("--hidden", type=int, default=4096) + parser.add_argument("--vocab", type=int, default=151936) + parser.add_argument("--warmup", type=int, default=10) + parser.add_argument("--iters", type=int, default=30) + parser.add_argument("--row-chunk", type=int, default=None) + parser.add_argument("--grad-ckpt", action=argparse.BooleanOptionalAction, default=True) + parser.add_argument("--fused-logits", choices=("auto", "save", "recompute"), + default="auto") + parser.add_argument("--optimizer-step", action="store_true") + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--out", default="medusa_loss_bench.json") + args = parser.parse_args() + if min(args.heads, args.tokens, args.hidden, args.vocab, args.warmup, args.iters) <= 0: + parser.error("heads/tokens/hidden/vocab/warmup/iters must be positive") + if args.optimizer_step and args.mode == "both": + parser.error("--optimizer-step requires a single mode so A/B weights stay identical") + if args.optimizer_step and args.heads * args.hidden * args.vocab > 200_000_000: + parser.error("--optimizer-step is limited to scaled dimensions that fit 48 GB") + return args + + +def _build_model(args): + config = MedusaConfig( + hidden_size=args.hidden, + vocab_size=args.vocab, + target_hidden_size=args.hidden, + target_num_hidden_layers=4, + medusa_num_heads=args.heads, + medusa_num_layers=1, + ) + model = MedusaDraftModel(config).cuda().bfloat16() + with torch.no_grad(): + for head in model.medusa_head: + nn.init.normal_(head[0].linear.weight, std=0.02) + return model + + +def _make_inputs(args): + generator = torch.Generator(device="cuda").manual_seed(args.seed) + hidden = torch.randn( + args.tokens, args.hidden, device="cuda", dtype=torch.bfloat16, generator=generator + ) + targets = [ + torch.randint(0, args.vocab, (args.tokens,), device="cuda", generator=generator) + for _ in range(args.heads) + ] + return hidden, targets + + +def _head_params(model): + return [parameter for parameter in model.parameters() if parameter.requires_grad] + + +def _grad_stats(params): + total = square = 0.0 + elements = 0 + for parameter in params: + if parameter.grad is None: + continue + gradient = parameter.grad.detach().float() + total += gradient.sum().item() + square += gradient.pow(2).sum().item() + elements += gradient.numel() + return { + "grad_sum": total, + "grad_norm": math.sqrt(square), + "grad_numel": elements, + } + + +def _reference_head(head, hidden, targets, grad_ckpt): + total = hidden.new_zeros((), dtype=torch.float32) + hits = hidden.new_zeros((), dtype=torch.float32) + for indices in torch.arange(hidden.shape[0], device=hidden.device).split(128): + chunk_hidden = hidden[indices] + chunk_targets = targets[indices] + + def loss_chunk(chunk_hidden, chunk_targets, head=head): + logits = head(chunk_hidden) + return ( + F.cross_entropy(logits.float(), chunk_targets, reduction="sum"), + (logits.argmax(-1) == chunk_targets).float().sum(), + ) + + if grad_ckpt: + loss, chunk_hits = checkpoint( + loss_chunk, chunk_hidden, chunk_targets, use_reentrant=False + ) + else: + loss, chunk_hits = loss_chunk(chunk_hidden, chunk_targets) + total = total + loss + hits = hits + chunk_hits.detach() + return total, hits + + +def _restructure_head(head, hidden, targets): + projected = head[:-1](hidden) + logits = F.linear(projected, head[-1].weight).float() + return ( + F.cross_entropy(logits, targets, reduction="sum"), + (logits.argmax(-1) == targets).float().sum(), + ) + + +def _fused_head(head, hidden, targets, save_logits, row_chunk): + projected = head[:-1](hidden) + nll, hits = medusa_head_ce( + projected, + head[-1].weight, + targets, + row_chunk=row_chunk, + save_logits=save_logits, + ) + return nll.sum(), hits.sum() + + +def _fused_save_logits(args): + if args.fused_logits == "save": + return True + if args.fused_logits == "recompute": + return False + if not args.grad_ckpt: + return True + return args.tokens * args.vocab * 2 * args.heads <= SAVE_LOGITS_BUDGET_BYTES + + +def _run_mode(model, hidden, targets, mode, args): + params = _head_params(model) + fused_save = _fused_save_logits(args) + optimizer = ( + BF16Optimizer( + model, + lr=1e-3, + weight_decay=0.0, + max_grad_norm=1.0, + total_steps=max(1, args.warmup + args.iters + 1), + warmup_ratio=0.0, + decay_style="cosine", + ) + if args.optimizer_step + else None + ) + + def forward_backward(step_optimizer): + for parameter in params: + parameter.grad = None + total = hidden.new_zeros((), dtype=torch.float32) + hits = hidden.new_zeros((), dtype=torch.float32) + for head, target in zip(model.medusa_head, targets, strict=True): + if mode == "reference": + loss, head_hits = _reference_head(head, hidden, target, args.grad_ckpt) + elif mode == "restructure": + loss, head_hits = _restructure_head(head, hidden, target) + else: + loss, head_hits = _fused_head( + head, hidden, target, fused_save, args.row_chunk + ) + total = total + loss + hits = hits + head_hits.detach() + total.backward() + if step_optimizer and optimizer is not None: + optimizer.step() + optimizer.zero_grad(set_to_none=True) + return total.detach(), hits + + for _ in range(args.warmup): + forward_backward(step_optimizer=False) + torch.cuda.synchronize() + torch.cuda.reset_peak_memory_stats() + peak_base = torch.cuda.memory_allocated() + + events = [] + for _ in range(args.iters): + start = torch.cuda.Event(enable_timing=True) + end = torch.cuda.Event(enable_timing=True) + start.record() + forward_backward(step_optimizer=args.optimizer_step) + end.record() + events.append((start, end)) + torch.cuda.synchronize() + times = [start.elapsed_time(end) for start, end in events] + + # Fingerprint outside the timed window, without an optimizer step, so the + # recorded gradients belong to the measured math. + for parameter in params: + parameter.grad = None + loss, hits = forward_backward(step_optimizer=False) + torch.cuda.synchronize() + fingerprint = { + "loss": float(loss.item()), + "hits": float(hits.item()), + **_grad_stats(params), + } + peak = torch.cuda.max_memory_allocated() - peak_base + return { + "mode": mode, + "timing": _summary(times), + "peak_extra_bytes": peak, + "fingerprint": fingerprint, + } + + +def main(): + args = _arguments() + if not torch.cuda.is_available(): + raise SystemExit("CUDA is required") + torch.cuda.set_device(0) + torch.manual_seed(args.seed) + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = False + + model = _build_model(args) + hidden, targets = _make_inputs(args) + + probe_hidden = hidden[: min(64, hidden.shape[0])] + probe_weight = model.medusa_head[0][-1].weight + fused_supported = use_fused_medusa_ce( + probe_hidden, probe_weight, num_rows=probe_hidden.shape[0] + ) + modes = ( + ["reference", "restructure", "fused"] + if args.mode == "both" + else [args.mode] + ) + if "fused" in modes and not fused_supported: + modes = [mode for mode in modes if mode != "fused"] + if not modes: + raise SystemExit("fused Medusa CE is not supported on this device/runtime") + + results = [] + for mode in modes: + torch.cuda.empty_cache() + results.append(_run_mode(model, hidden, targets, mode, args)) + + capability = torch.cuda.get_device_capability(0) + report = { + "script": "tools/performance/bench_medusa_loss.py", + "config": { + "heads": args.heads, + "tokens": args.tokens, + "hidden": args.hidden, + "vocab": args.vocab, + "warmup": args.warmup, + "iters": args.iters, + "row_chunk": args.row_chunk, + "grad_ckpt": args.grad_ckpt, + "fused_logits": args.fused_logits, + "optimizer_step": args.optimizer_step, + "seed": args.seed, + }, + "hardware": { + "device": torch.cuda.get_device_name(0), + "capability": list(capability), + "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], + }, + "fused_supported": fused_supported, + "results": results, + } + 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 __name__ == "__main__": + main() From 913bca5bbcadb4f3b9122ed6decf7e2032a90c50 Mon Sep 17 00:00:00 2001 From: bohaotu Date: Wed, 25 Nov 2026 12:43:13 +0800 Subject: [PATCH 2/4] fix(medusa): address CodeRabbit review findings - Retain fused logits only when a backward pass can consume them. - Clear warm-up gradients before the benchmark peak-memory baseline and refresh the measured memory figures. - Share the retained-logits budget helper with the benchmark and pin the K=5 8 GiB boundary. - Strengthen CPU guard/2-layer/benchmark-reference tests and add GPU positive-hit coverage. - Correct the 5.8 GiB unit and the random-target hit-count caveat. Refs #17 --- aspec/models/medusa.py | 16 ++- aspec/models/ops/medusa_ce.py | 16 ++- docs/user-guide/medusa.md | 22 ++-- tests/cpu/test_medusa_fused_fallback.py | 162 +++++++++++++++--------- tests/test_medusa_loss_kernel_gpu.py | 11 ++ tools/performance/bench_medusa_loss.py | 10 +- 6 files changed, 158 insertions(+), 79 deletions(-) diff --git a/aspec/models/medusa.py b/aspec/models/medusa.py index 62a041d..3e3c4f6 100644 --- a/aspec/models/medusa.py +++ b/aspec/models/medusa.py @@ -19,10 +19,17 @@ # Retaining BF16 logits removes one projection pass in backward. Bound the # all-head retained bytes so gradient checkpointing still protects long -# sequences; 4K/Qwen3-8B/K=5 (about 6.2 GiB) uses the faster saved mode. +# sequences; 4K/Qwen3-8B/K=5 (about 5.8 GiB) uses the faster saved mode. SAVE_LOGITS_BUDGET_BYTES = 8 * 1024**3 +def should_save_fused_logits(tokens, vocab, num_heads, gradient_checkpointing): + if not gradient_checkpointing: + return True + retained = tokens * vocab * 2 * num_heads + return retained <= SAVE_LOGITS_BUDGET_BYTES + + class MedusaModel(nn.Module): def __init__(self, draft_model, gradient_checkpointing=False): super().__init__() @@ -35,10 +42,9 @@ def __init__(self, draft_model, gradient_checkpointing=False): self.vocab_pruning = False def _save_fused_logits(self, tokens, vocab): - if not self.gradient_checkpointing: - return True - retained = tokens * vocab * 2 * self.num_heads - return retained <= SAVE_LOGITS_BUDGET_BYTES + return should_save_fused_logits( + tokens, vocab, self.num_heads, self.gradient_checkpointing + ) def _reference_head_loss( self, diff --git a/aspec/models/ops/medusa_ce.py b/aspec/models/ops/medusa_ce.py index 176ded0..38568f6 100644 --- a/aspec/models/ops/medusa_ce.py +++ b/aspec/models/ops/medusa_ce.py @@ -85,6 +85,19 @@ def _resolve_row_chunk(vocab: int, requested: int | None) -> int: return max(_MIN_ROW_CHUNK, (chunk // _MIN_ROW_CHUNK) * _MIN_ROW_CHUNK) +def _save_logits_for_backward( + save_logits: bool, + hidden: torch.Tensor, + weight: torch.Tensor, +) -> bool: + """Retain logits only when a backward pass can actually consume them.""" + return bool( + save_logits + and torch.is_grad_enabled() + and (hidden.requires_grad or weight.requires_grad) + ) + + def use_fused_medusa_ce( hidden: torch.Tensor, weight: torch.Tensor, @@ -427,10 +440,11 @@ def medusa_head_ce( raise ValueError("fused Medusa CE requires contiguous tensors") if not targets.is_contiguous(): targets = targets.contiguous() + save_logits = _save_logits_for_backward(save_logits, hidden, weight) return _MedusaCE.apply( hidden, weight, targets, _resolve_row_chunk(weight.shape[0], row_chunk), - bool(save_logits), + save_logits, ) diff --git a/docs/user-guide/medusa.md b/docs/user-guide/medusa.md index a4b0817..debfb24 100644 --- a/docs/user-guide/medusa.md +++ b/docs/user-guide/medusa.md @@ -66,7 +66,7 @@ reference path; `tests/cpu/test_medusa.py` pins that path unchanged. through an internal 8 GiB budget; the residual block is applied once and its smaller `[T, H]` activations are retained. When the all-head BF16 logits fit the budget (Qwen3-8B `K=5`, 4094 selected tokens and `V=151936` is about -6.2 GiB), the fused path retains them and skips one projection pass in +5.8 GiB), the fused path retains them and skips one projection pass in backward; longer selections recompute. The backward pass keeps one full BF16 `dlogits` buffer only when it fits a 2 GiB budget; otherwise it accumulates `dX`/`dW` per token chunk. The fused path requires `V <= 2^24` because the @@ -80,20 +80,22 @@ Measured on one NVIDIA L20 48GB (sm_89, driver 580.126.20, CUDA 13.0, torch | Cell | Median | p90 | / reference | Peak extra | | --- | ---: | ---: | ---: | ---: | -| Current reference (128-token chunks) | 2456.74 ms | 2457.03 ms | 1.00× | 4.98 GB | -| Whole-head restructure (diagnostic only) | 913.61 ms | 914.79 ms | 2.69× | 11.36 GB | -| Fused epilogue + one `dW` per head | **761.95 ms** | **762.41 ms** | **3.22×** | **4.98 GB** | +| Current reference (128-token chunks) | 2456.87 ms | 2457.28 ms | 1.00× | 11.38 GB | +| Whole-head restructure (diagnostic only) | 905.54 ms | 906.89 ms | 2.71× | 17.75 GB | +| Fused epilogue + one `dW` per head | **751.54 ms** | **752.79 ms** | **3.27×** | **11.37 GB** | -Peak extra is the delta after resident model weights and inputs; it excludes -optimizer state. Accuracy uses the lowest vocabulary index on argmax ties; -PyTorch CUDA argmax tie order is unspecified, so ties are the only metric -difference. +Peak extra is the delta after resident model weights/inputs and cleared +gradients; it includes gradient buffers and excludes optimizer state. Accuracy +uses the lowest vocabulary index on argmax ties; PyTorch CUDA argmax tie order +is unspecified, so ties are the only metric difference. The restructure is a script-only attribution cell, not a shipped path. The reference and fused loss fingerprints are close but not bitwise equal: `250777.75` vs `250777.95`, gradient norms `13286.11` vs `13274.47` over the -same 3,195,555,840 gradient elements, and the same accuracy count; the -difference comes from whole-head versus chunked reduction order. The +same 3,195,555,840 gradient elements. The benchmark's hit count uses random +targets and is near chance, so it is not argmax parity evidence; dedicated GPU +tests cover positive hits, tile boundaries and ties. The difference comes from +whole-head versus chunked reduction order. The vocabulary projection remains on cuBLAS: a fully fused Triton matmul was not adopted because sm_89 matmul quality is not expected to beat cuBLAS and the backward pass still needs logits for `dlogits`. Forcing recompute on the diff --git a/tests/cpu/test_medusa_fused_fallback.py b/tests/cpu/test_medusa_fused_fallback.py index b8de9ef..3a6df86 100644 --- a/tests/cpu/test_medusa_fused_fallback.py +++ b/tests/cpu/test_medusa_fused_fallback.py @@ -11,10 +11,40 @@ from torch import nn from aspec.models.draft.medusa import MedusaConfig, MedusaDraftModel -from aspec.models.medusa import MedusaModel +from aspec.models.medusa import MedusaModel, should_save_fused_logits from aspec.models.ops import medusa_ce +class _FakeTensor: + def __init__( + self, + shape=(64, 8), + *, + dtype=torch.bfloat16, + is_cuda=True, + contiguous=True, + ndim=2, + device="fake", + requires_grad=False, + ): + self.shape = shape + self.dtype = dtype + self.is_cuda = is_cuda + self._contiguous = contiguous + self.ndim = ndim + self.device = device + self.requires_grad = requires_grad + + def is_contiguous(self): + return self._contiguous + + +def _enable_fake_fused(monkeypatch): + monkeypatch.setattr(medusa_ce, "_TRITON_IMPORT_ERROR", None) + monkeypatch.setattr(medusa_ce, "triton", object()) + monkeypatch.setattr(medusa_ce, "_device_capability", lambda device: (8, 9)) + + def _tensors(rows=128, hidden=8, vocab=64, dtype=torch.bfloat16): return ( torch.randn(rows, hidden, dtype=dtype), @@ -27,59 +57,34 @@ def test_predicate_rejects_cpu_tensors(): assert medusa_ce.use_fused_medusa_ce(hidden, weight) is False -def test_predicate_rejects_non_bf16_and_shape_mismatch(): - hidden, weight = _tensors(dtype=torch.float32) - assert medusa_ce.use_fused_medusa_ce(hidden, weight) is False - hidden, weight = _tensors() - assert medusa_ce.use_fused_medusa_ce(hidden[:, :4], weight) is False - assert medusa_ce.use_fused_medusa_ce(hidden.transpose(0, 1), weight) is False - - -def test_predicate_honors_num_rows(): - hidden, weight = _tensors(rows=1) - assert medusa_ce.use_fused_medusa_ce(hidden, weight, num_rows=1) is False - assert medusa_ce.use_fused_medusa_ce(hidden, weight, num_rows=1024) is False +def test_predicate_rejects_non_bf16_and_shape_mismatch(monkeypatch): + _enable_fake_fused(monkeypatch) + assert medusa_ce.use_fused_medusa_ce(_FakeTensor(), _FakeTensor()) is True + assert medusa_ce.use_fused_medusa_ce( + _FakeTensor(dtype=torch.float32), _FakeTensor() + ) is False + assert medusa_ce.use_fused_medusa_ce( + _FakeTensor(ndim=3), _FakeTensor() + ) is False + assert medusa_ce.use_fused_medusa_ce( + _FakeTensor(shape=(64, 4)), _FakeTensor() + ) is False + assert medusa_ce.use_fused_medusa_ce( + _FakeTensor(contiguous=False), _FakeTensor() + ) is False def test_predicate_small_selection_threshold(monkeypatch): - class Fake: - is_cuda = True - dtype = torch.bfloat16 - ndim = 2 - shape = (64, 8) - device = "fake" - - @staticmethod - def is_contiguous(): - return True - - hidden, weight = Fake(), Fake() - monkeypatch.setattr(medusa_ce, "_TRITON_IMPORT_ERROR", None) - monkeypatch.setattr(medusa_ce, "triton", object()) - monkeypatch.setattr(medusa_ce, "_device_capability", lambda device: (8, 9)) + _enable_fake_fused(monkeypatch) + hidden, weight = _FakeTensor(), _FakeTensor() assert medusa_ce.use_fused_medusa_ce(hidden, weight, num_rows=63) is False assert medusa_ce.use_fused_medusa_ce(hidden, weight, num_rows=64) is True def test_predicate_rejects_vocab_beyond_exact_argmax(monkeypatch): - class Fake: - is_cuda = True - dtype = torch.bfloat16 - ndim = 2 - device = "fake" - - def __init__(self, shape): - self.shape = shape - - @staticmethod - def is_contiguous(): - return True - - hidden = Fake((64, 8)) - weight = Fake((medusa_ce._MAX_EXACT_ARGMAX_VOCAB + 1, 8)) - monkeypatch.setattr(medusa_ce, "_TRITON_IMPORT_ERROR", None) - monkeypatch.setattr(medusa_ce, "triton", object()) - monkeypatch.setattr(medusa_ce, "_device_capability", lambda device: (8, 9)) + _enable_fake_fused(monkeypatch) + hidden = _FakeTensor() + weight = _FakeTensor(shape=(medusa_ce._MAX_EXACT_ARGMAX_VOCAB + 1, 8)) assert medusa_ce.use_fused_medusa_ce(hidden, weight) is False @@ -91,10 +96,12 @@ def test_missing_triton_falls_back(monkeypatch): medusa_ce.medusa_head_ce(hidden, weight, torch.zeros(128, dtype=torch.int64)) -def test_medusa_head_ce_requires_cuda(): - hidden, weight = _tensors() - targets = torch.zeros(128, dtype=torch.int64) - with pytest.raises((ValueError, RuntimeError)): +def test_medusa_head_ce_requires_cuda(monkeypatch): + _enable_fake_fused(monkeypatch) + hidden = _FakeTensor(is_cuda=False) + weight = _FakeTensor() + targets = torch.zeros(64, dtype=torch.int64) + with pytest.raises(ValueError, match="requires CUDA"): medusa_ce.medusa_head_ce(hidden, weight, targets) @@ -106,6 +113,30 @@ def test_resolve_row_chunk_defaults(): medusa_ce._resolve_row_chunk(10, 0) +def test_should_save_fused_logits_pins_k5_boundary(): + assert should_save_fused_logits(4094, 151936, 5, True) is True + assert should_save_fused_logits(8192, 151936, 5, True) is False + assert should_save_fused_logits(100_000, 151936, 5, False) is True + model = _tiny_model() + assert model._save_fused_logits(4094, 151936) == should_save_fused_logits( + 4094, 151936, model.num_heads, model.gradient_checkpointing + ) + + +def test_save_logits_gate(): + class Requiring: + def __init__(self, requires_grad): + self.requires_grad = requires_grad + + trainable = Requiring(True) + frozen = Requiring(False) + with torch.no_grad(): + assert medusa_ce._save_logits_for_backward(True, trainable, trainable) is False + assert medusa_ce._save_logits_for_backward(True, trainable, frozen) is True + assert medusa_ce._save_logits_for_backward(True, frozen, frozen) is False + assert medusa_ce._save_logits_for_backward(False, trainable, trainable) is False + + def _tiny_model(): config = MedusaConfig( hidden_size=8, @@ -123,15 +154,6 @@ def _tiny_model(): return MedusaModel(draft) -def test_save_fused_logits_budget(): - model = _tiny_model() - model.gradient_checkpointing = False - assert model._save_fused_logits(4094, 151936) is True - model.gradient_checkpointing = True - assert model._save_fused_logits(4094, 151936) is True - assert model._save_fused_logits(100_000, 151936) is False - - def test_two_layer_wiring_matches_reference(monkeypatch): config = MedusaConfig( hidden_size=8, @@ -153,8 +175,10 @@ def test_two_layer_wiring_matches_reference(monkeypatch): hidden_states = torch.randn(1, 32, 8) loss_mask = (torch.rand(1, 32) > 0.2).long() attention_mask = torch.ones(1, 32, dtype=torch.long) + calls = [] def fake_fused_ce(hidden, weight, targets, **kwargs): + calls.append(hidden.shape) logits = F.linear(hidden, weight).float() return ( F.cross_entropy(logits, targets, reduction="none"), @@ -172,6 +196,8 @@ def fake_fused_ce(hidden, weight, targets, **kwargs): input_ids, hidden_states, loss_mask, attention_mask ) + assert len(calls) == 2 + assert all(shape[1] == config.hidden_size for shape in calls) for fused_loss, ref_loss in zip(fused_losses, ref_losses, strict=True): torch.testing.assert_close(fused_loss, ref_loss, rtol=2e-5, atol=2e-6) for fused_acc, ref_acc in zip(fused_accs, ref_accs, strict=True): @@ -187,6 +213,24 @@ def fake_fused_ce(hidden, weight, targets, **kwargs): torch.testing.assert_close(parameter.grad, ref_parameter.grad, rtol=2e-5, atol=2e-6) +def test_benchmark_reference_head_matches_model(): + from tools.performance.bench_medusa_loss import _reference_head + + model = _tiny_model() + head = model.draft_model.medusa_head[0] + targets = torch.randint(0, 16, (40,)) + features = torch.randn(40, 8) + positions = torch.arange(40) + model_loss, model_hits = model._reference_head_loss( + head, features, targets, positions, positions, positions + ) + bench_loss, bench_hits = _reference_head( + head, features, targets, model.gradient_checkpointing + ) + torch.testing.assert_close(model_loss, bench_loss, rtol=0, atol=0) + torch.testing.assert_close(model_hits, bench_hits, rtol=0, atol=0) + + def test_reference_path_zero_mask_keeps_zero_grads(): model = _tiny_model() input_ids = torch.randint(0, 16, (1, 12)) diff --git a/tests/test_medusa_loss_kernel_gpu.py b/tests/test_medusa_loss_kernel_gpu.py index f3f8d1f..5db4a33 100644 --- a/tests/test_medusa_loss_kernel_gpu.py +++ b/tests/test_medusa_loss_kernel_gpu.py @@ -111,6 +111,17 @@ def test_target_at_tile_boundary(): assert torch.equal(hits, ref_hits) +@pytest.mark.parametrize("vocab", [4096, 151936]) +def test_hits_positive_with_argmax_targets(vocab): + x, w, _ = _tensors(128, 64, vocab) + targets = F.linear(x, w).float().argmax(-1).to(torch.int64) + nll, hits = medusa_head_ce(x, w, targets, save_logits=True) + ref_nll, ref_hits = _reference(x, w, targets) + assert hits.sum() > 0 + torch.testing.assert_close(nll, ref_nll, rtol=1e-4, atol=1e-5) + assert torch.equal(hits, ref_hits) + + def test_dx_dw_match_reference(): x, w, targets = _tensors(128, 64, 4096) _, _, dx, dw = _fused_grads(x, w, targets, save_logits=True) diff --git a/tools/performance/bench_medusa_loss.py b/tools/performance/bench_medusa_loss.py index bc66142..0844e8c 100644 --- a/tools/performance/bench_medusa_loss.py +++ b/tools/performance/bench_medusa_loss.py @@ -30,7 +30,7 @@ from torch.utils.checkpoint import checkpoint from aspec.models.draft.medusa import MedusaConfig, MedusaDraftModel -from aspec.models.medusa import SAVE_LOGITS_BUDGET_BYTES +from aspec.models.medusa import should_save_fused_logits from aspec.models.ops.medusa_ce import medusa_head_ce, use_fused_medusa_ce from aspec.training.optimizer import BF16Optimizer @@ -184,9 +184,9 @@ def _fused_save_logits(args): return True if args.fused_logits == "recompute": return False - if not args.grad_ckpt: - return True - return args.tokens * args.vocab * 2 * args.heads <= SAVE_LOGITS_BUDGET_BYTES + return should_save_fused_logits( + args.tokens, args.vocab, args.heads, args.grad_ckpt + ) def _run_mode(model, hidden, targets, mode, args): @@ -230,6 +230,8 @@ def forward_backward(step_optimizer): for _ in range(args.warmup): forward_backward(step_optimizer=False) + for parameter in params: + parameter.grad = None torch.cuda.synchronize() torch.cuda.reset_peak_memory_stats() peak_base = torch.cuda.memory_allocated() From abb796d603d353b754d04297ba21e13c408a6d88 Mon Sep 17 00:00:00 2001 From: bohaotu Date: Wed, 25 Nov 2026 14:33:06 +0800 Subject: [PATCH 3/4] fix(medusa): harden fused CE numerics and launch bounds - Keep row_max and log_total separate for NLL/dlogits to avoid FP32 cancellation with large logits. - Launch Triton kernels under the tensor CUDA device and bound backward chunks by both row_chunk and the dlogits/scratch byte budgets. - Capture benchmark peak memory before fingerprint allocations and refresh the L20 memory table. - Document the first-maximal argmax tie rule and add large-logit/chunk coverage. Refs #17 --- aspec/models/ops/medusa_ce.py | 133 +++++++++++++++--------- docs/user-guide/medusa.md | 17 +-- tests/cpu/test_medusa_fused_fallback.py | 6 ++ tests/test_medusa_loss_kernel_gpu.py | 15 ++- tools/performance/bench_medusa_loss.py | 3 +- 5 files changed, 113 insertions(+), 61 deletions(-) diff --git a/aspec/models/ops/medusa_ce.py b/aspec/models/ops/medusa_ce.py index 38568f6..8542e10 100644 --- a/aspec/models/ops/medusa_ce.py +++ b/aspec/models/ops/medusa_ce.py @@ -85,6 +85,11 @@ def _resolve_row_chunk(vocab: int, requested: int | None) -> int: return max(_MIN_ROW_CHUNK, (chunk // _MIN_ROW_CHUNK) * _MIN_ROW_CHUNK) +def _bounded_rows(requested: int, vocab: int, limit_bytes: int) -> int: + max_rows = max(1, limit_bytes // (2 * vocab)) + return max(1, min(int(requested), max_rows)) + + def _save_logits_for_backward( save_logits: bool, hidden: torch.Tensor, @@ -166,7 +171,8 @@ def _ce_partials( @triton.jit def _merge_stats( Partials, - Lse, + RowMax, + LogTotal, Nll, Hits, Targets, @@ -187,7 +193,7 @@ def _merge_stats( total = tl.sum( tl.where(tmax == -float("inf"), 0.0, tsum * tl.exp(tmax - row_max)), 0 ) - lse = row_max + tl.log(total) + 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) @@ -197,16 +203,20 @@ def _merge_stats( "Medusa CE target index out of vocabulary", ) target_logit = tl.max(target_val, 0) - nll = lse - target_logit + # 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(Lse + row, lse) + 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, - Lse, + RowMax, + LogTotal, Targets, Scale, DZ, @@ -219,10 +229,11 @@ def _dlogits( 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) - lse = tl.load(Lse + row) + 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 - lse) + probs = tl.exp((z - row_max) - log_total) probs = tl.where(cols == target, probs - 1.0, probs) tl.store( DZ + row * V + cols, @@ -249,8 +260,14 @@ def forward( 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 + forward_chunk = ( + row_chunk + if save_logits + else _bounded_rows(row_chunk, vocab, _SAVE_BYTES) + ) partials = torch.empty((rows, tiles, 4), device=device, dtype=torch.float32) - lse = torch.empty((rows,), device=device, dtype=torch.float32) + row_max = torch.empty((rows,), device=device, dtype=torch.float32) + log_total = torch.empty((rows,), device=device, dtype=torch.float32) nll = torch.empty((rows,), device=device, dtype=torch.float32) hits = torch.empty((rows,), device=device, dtype=torch.float32) saved_logits = ( @@ -262,53 +279,58 @@ def forward( None if save_logits else torch.empty( - (min(row_chunk, rows), vocab), device=device, dtype=torch.bfloat16 + (min(forward_chunk, rows), vocab), device=device, dtype=torch.bfloat16 ) ) - for start in range(0, rows, row_chunk): - stop = min(start + row_chunk, rows) - count = stop - start - if saved_logits is not None: - logits_chunk = saved_logits[start:stop] - else: - logits_chunk = scratch[:count] - logits_chunk.copy_(F.linear(hidden[start:stop], weight)) - _ce_partials[(count, tiles)]( - logits_chunk, - targets[start:stop], - partials[start:stop], - vocab, - tiles, - _BLOCK_N, - num_warps=_NUM_WARPS_N, - enable_fp_fusion=False, - ) - _merge_stats[(count,)]( - partials[start:stop], - lse[start:stop], - nll[start:stop], - hits[start:stop], - targets[start:stop], - tiles, - block_tiles, - vocab, - num_warps=merge_warps, - debug=True, - enable_fp_fusion=False, - ) + with torch.cuda.device(device): + for start in range(0, rows, forward_chunk): + stop = min(start + forward_chunk, rows) + count = stop - start + if saved_logits is not None: + logits_chunk = saved_logits[start:stop] + else: + logits_chunk = scratch[:count] + logits_chunk.copy_(F.linear(hidden[start:stop], weight)) + _ce_partials[(count, tiles)]( + logits_chunk, + targets[start:stop], + partials[start:stop], + vocab, + tiles, + _BLOCK_N, + num_warps=_NUM_WARPS_N, + enable_fp_fusion=False, + ) + _merge_stats[(count,)]( + partials[start:stop], + row_max[start:stop], + log_total[start:stop], + nll[start:stop], + hits[start:stop], + targets[start:stop], + tiles, + block_tiles, + vocab, + num_warps=merge_warps, + debug=True, + enable_fp_fusion=False, + ) if saved_logits is not None: - ctx.save_for_backward(hidden, weight, targets, lse, saved_logits) + ctx.save_for_backward( + hidden, weight, targets, row_max, log_total, saved_logits + ) else: ctx.save_for_backward( hidden, weight, targets, - lse, + row_max, + log_total, torch.empty(0, device=device, dtype=torch.bfloat16), ) - ctx.row_chunk = row_chunk + ctx.row_chunk = forward_chunk ctx.save_logits = save_logits ctx.mark_non_differentiable(hits) return nll, hits @@ -317,7 +339,7 @@ def forward( @once_differentiable def backward(ctx, grad_nll, grad_hits): del grad_hits - hidden, weight, targets, lse, saved_logits = ctx.saved_tensors + hidden, weight, targets, row_max, log_total, saved_logits = ctx.saved_tensors rows, vocab = hidden.shape[0], weight.shape[0] if grad_nll is None: return None, None, None, None, None @@ -327,12 +349,17 @@ def backward(ctx, grad_nll, grad_hits): return None, None, None, None, None grad_nll = grad_nll.contiguous() tiles = triton.cdiv(vocab, _BLOCK_N) - with torch.no_grad(): + backward_chunk = _bounded_rows(ctx.row_chunk, vocab, _DLOGITS_BUDGET_BYTES) + if not ctx.save_logits: + backward_chunk = min( + backward_chunk, _bounded_rows(ctx.row_chunk, vocab, _SAVE_BYTES) + ) + with torch.no_grad(), torch.cuda.device(hidden.device): scratch = ( None if ctx.save_logits else torch.empty( - (min(ctx.row_chunk, rows), vocab), + (min(backward_chunk, rows), vocab), device=hidden.device, dtype=torch.bfloat16, ) @@ -341,8 +368,8 @@ def backward(ctx, grad_nll, grad_hits): dlogits = torch.empty( (rows, vocab), device=hidden.device, dtype=torch.bfloat16 ) - for start in range(0, rows, ctx.row_chunk): - stop = min(start + ctx.row_chunk, rows) + for start in range(0, rows, backward_chunk): + stop = min(start + backward_chunk, rows) count = stop - start if ctx.save_logits: logits_chunk = saved_logits[start:stop] @@ -351,7 +378,8 @@ def backward(ctx, grad_nll, grad_hits): logits_chunk.copy_(F.linear(hidden[start:stop], weight)) _dlogits[(count, tiles)]( logits_chunk, - lse[start:stop], + row_max[start:stop], + log_total[start:stop], targets[start:stop], grad_nll[start:stop], dlogits[start:stop], @@ -368,8 +396,8 @@ def backward(ctx, grad_nll, grad_hits): # buffer; accumulate dW per token chunk instead. dx = torch.empty_like(hidden) if needs_dx else None dw = torch.zeros_like(weight) if needs_dw else None - for start in range(0, rows, ctx.row_chunk): - stop = min(start + ctx.row_chunk, rows) + for start in range(0, rows, backward_chunk): + stop = min(start + backward_chunk, rows) count = stop - start if ctx.save_logits: logits_chunk = saved_logits[start:stop] @@ -381,7 +409,8 @@ def backward(ctx, grad_nll, grad_hits): ) _dlogits[(count, tiles)]( logits_chunk, - lse[start:stop], + row_max[start:stop], + log_total[start:stop], targets[start:stop], grad_nll[start:stop], dlogits_chunk, diff --git a/docs/user-guide/medusa.md b/docs/user-guide/medusa.md index debfb24..cfce19e 100644 --- a/docs/user-guide/medusa.md +++ b/docs/user-guide/medusa.md @@ -71,7 +71,9 @@ backward; longer selections recompute. The backward pass keeps one full BF16 `dlogits` buffer only when it fits a 2 GiB budget; otherwise it accumulates `dX`/`dW` per token chunk. The fused path requires `V <= 2^24` because the tile argmax column is carried in FP32; larger vocabularies use the reference -path. No configuration field is added. +path. NLL and backward probabilities keep the row maximum and log-normalizer +separate, avoiding FP32 cancellation when logits are large. No configuration +field is added. Measured on one NVIDIA L20 48GB (sm_89, driver 580.126.20, CUDA 13.0, torch 2.13.0+cu130, Triton 3.7.1), Qwen3-8B head shape `K=5`, `H=4096`, @@ -80,14 +82,15 @@ Measured on one NVIDIA L20 48GB (sm_89, driver 580.126.20, CUDA 13.0, torch | Cell | Median | p90 | / reference | Peak extra | | --- | ---: | ---: | ---: | ---: | -| Current reference (128-token chunks) | 2456.87 ms | 2457.28 ms | 1.00× | 11.38 GB | -| Whole-head restructure (diagnostic only) | 905.54 ms | 906.89 ms | 2.71× | 17.75 GB | -| Fused epilogue + one `dW` per head | **751.54 ms** | **752.79 ms** | **3.27×** | **11.37 GB** | +| Current reference (128-token chunks) | 2456.51 ms | 2456.89 ms | 1.00× | 8.92 GB | +| Whole-head restructure (diagnostic only) | 902.82 ms | 903.97 ms | 2.72× | 17.75 GB | +| Fused epilogue + one `dW` per head | **752.03 ms** | **753.02 ms** | **3.27×** | **9.08 GB** | Peak extra is the delta after resident model weights/inputs and cleared -gradients; it includes gradient buffers and excludes optimizer state. Accuracy -uses the lowest vocabulary index on argmax ties; PyTorch CUDA argmax tie order -is unspecified, so ties are the only metric difference. +gradients; it includes gradient buffers and excludes optimizer state. Both +paths use the first (lowest) maximal index on argmax ties, matching PyTorch's +documented first-maximum rule; ties are not a parity exception. Any metric +difference must come from projected logits. The restructure is a script-only attribution cell, not a shipped path. The reference and fused loss fingerprints are close but not bitwise equal: diff --git a/tests/cpu/test_medusa_fused_fallback.py b/tests/cpu/test_medusa_fused_fallback.py index 3a6df86..0a57041 100644 --- a/tests/cpu/test_medusa_fused_fallback.py +++ b/tests/cpu/test_medusa_fused_fallback.py @@ -113,6 +113,12 @@ def test_resolve_row_chunk_defaults(): medusa_ce._resolve_row_chunk(10, 0) +def test_bounded_rows_respects_byte_budget(): + assert medusa_ce._bounded_rows(8192, 151936, 2 * 1024**3) == 7067 + assert medusa_ce._bounded_rows(8192, 151936, 256 * 1024**2) == 883 + assert medusa_ce._bounded_rows(1, 151936, 1) == 1 + + def test_should_save_fused_logits_pins_k5_boundary(): assert should_save_fused_logits(4094, 151936, 5, True) is True assert should_save_fused_logits(8192, 151936, 5, True) is False diff --git a/tests/test_medusa_loss_kernel_gpu.py b/tests/test_medusa_loss_kernel_gpu.py index 5db4a33..62ef235 100644 --- a/tests/test_medusa_loss_kernel_gpu.py +++ b/tests/test_medusa_loss_kernel_gpu.py @@ -122,6 +122,19 @@ def test_hits_positive_with_argmax_targets(vocab): assert torch.equal(hits, ref_hits) +def test_large_logits_keep_shifted_normalization(): + vocab = 256 + x = torch.full((64, 1), 4096.0, device="cuda", dtype=torch.bfloat16) + w = torch.full((vocab, 1), 4096.0, device="cuda", dtype=torch.bfloat16) + targets = torch.zeros(64, device="cuda", dtype=torch.int64) + nll, hits = medusa_head_ce(x, w, targets, save_logits=True) + ref_nll, ref_hits = _reference(x, w, targets) + expected = torch.log(torch.tensor(float(vocab), device="cuda")).expand_as(nll) + torch.testing.assert_close(nll, expected, rtol=1e-5, atol=1e-5) + torch.testing.assert_close(nll, ref_nll, rtol=1e-5, atol=1e-5) + assert torch.equal(hits, ref_hits) + + def test_dx_dw_match_reference(): x, w, targets = _tensors(128, 64, 4096) _, _, dx, dw = _fused_grads(x, w, targets, save_logits=True) @@ -144,7 +157,7 @@ def test_chunked_backward_matches_full(monkeypatch): x, w, targets = _tensors(1024, 64, 4096) nll_full, hits_full, dx_full, dw_full = _fused_grads(x, w, targets, save_logits=True) - monkeypatch.setattr(medusa_ce, "_DLOGITS_BUDGET_BYTES", 1) + monkeypatch.setattr(medusa_ce, "_DLOGITS_BUDGET_BYTES", 512 * 4096 * 2) nll_chunk, hits_chunk, dx_chunk, dw_chunk = _fused_grads(x, w, targets, save_logits=True) torch.testing.assert_close(nll_full, nll_chunk, rtol=0, atol=0) assert torch.equal(hits_full, hits_chunk) diff --git a/tools/performance/bench_medusa_loss.py b/tools/performance/bench_medusa_loss.py index 0844e8c..727c9e8 100644 --- a/tools/performance/bench_medusa_loss.py +++ b/tools/performance/bench_medusa_loss.py @@ -245,6 +245,8 @@ def forward_backward(step_optimizer): end.record() events.append((start, end)) torch.cuda.synchronize() + # Capture the measured peak before fingerprint conversions allocate. + peak = torch.cuda.max_memory_allocated() - peak_base times = [start.elapsed_time(end) for start, end in events] # Fingerprint outside the timed window, without an optimizer step, so the @@ -258,7 +260,6 @@ def forward_backward(step_optimizer): "hits": float(hits.item()), **_grad_stats(params), } - peak = torch.cuda.max_memory_allocated() - peak_base return { "mode": mode, "timing": _summary(times), From 88a75cb50a1078a46f0681564a6dd7df40b7ee2f Mon Sep 17 00:00:00 2001 From: bohaotu Date: Wed, 25 Nov 2026 14:45:08 +0800 Subject: [PATCH 4/4] test(medusa): cover fused CE on a non-current CUDA device Run fused forward/backward with the current device at cuda:0 and tensors on cuda:1, for both retained and recomputed logits. This catches missing per-device Triton launch contexts on multi-GPU Draft hosts. Refs #17 --- tests/test_medusa_loss_kernel_gpu.py | 42 ++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/tests/test_medusa_loss_kernel_gpu.py b/tests/test_medusa_loss_kernel_gpu.py index 62ef235..bd7aadc 100644 --- a/tests/test_medusa_loss_kernel_gpu.py +++ b/tests/test_medusa_loss_kernel_gpu.py @@ -27,12 +27,13 @@ from aspec.models.ops.medusa_ce import medusa_head_ce, use_fused_medusa_ce -def _tensors(tokens, hidden, vocab, seed=0): - generator = torch.Generator(device="cuda").manual_seed(seed) - x = torch.randn(tokens, hidden, device="cuda", dtype=torch.bfloat16, generator=generator) - w = torch.randn(vocab, hidden, device="cuda", dtype=torch.bfloat16, +def _tensors(tokens, hidden, vocab, seed=0, device="cuda"): + device = torch.device(device) + generator = torch.Generator(device=device).manual_seed(seed) + x = torch.randn(tokens, hidden, device=device, dtype=torch.bfloat16, generator=generator) + w = torch.randn(vocab, hidden, device=device, dtype=torch.bfloat16, generator=generator) * 0.05 - targets = torch.randint(0, vocab, (tokens,), device="cuda", generator=generator) + targets = torch.randint(0, vocab, (tokens,), device=device, generator=generator) return x, w, targets @@ -135,6 +136,37 @@ def test_large_logits_keep_shifted_normalization(): assert torch.equal(hits, ref_hits) +@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="requires two GPUs") +@pytest.mark.parametrize("save_logits", [True, False]) +def test_noncurrent_device_context(save_logits): + torch.cuda.set_device(0) + device = torch.device("cuda:1") + x, w, targets = _tensors(128, 64, 4096, device=device) + torch.cuda.set_device(0) + try: + x_fused = x.detach().clone().requires_grad_(True) + w_fused = w.detach().clone().requires_grad_(True) + nll, hits = medusa_head_ce( + x_fused, w_fused, targets, save_logits=save_logits + ) + nll.sum().backward() + + assert nll.device == device and hits.device == device + assert x_fused.grad is not None and x_fused.grad.device == device + assert w_fused.grad is not None and w_fused.grad.device == device + + ref_nll, ref_hits = _reference(x, w, targets) + torch.testing.assert_close(nll.detach(), ref_nll, rtol=1e-4, atol=1e-5) + assert torch.equal(hits, ref_hits) + + x_ref, w_ref = x.detach().clone().requires_grad_(True), w.detach().clone().requires_grad_(True) + F.cross_entropy(F.linear(x_ref, w_ref).float(), targets, reduction="sum").backward() + _assert_gradient_close(x_fused.grad, x_ref.grad, "noncurrent dx") + _assert_gradient_close(w_fused.grad, w_ref.grad, "noncurrent dw") + finally: + torch.cuda.set_device(0) + + def test_dx_dw_match_reference(): x, w, targets = _tensors(128, 64, 4096) _, _, dx, dw = _fused_grads(x, w, targets, save_logits=True)