diff --git a/aspec/config/train_config.py b/aspec/config/train_config.py index 265e7ed..03a7579 100644 --- a/aspec/config/train_config.py +++ b/aspec/config/train_config.py @@ -256,6 +256,10 @@ class TrainingConfig: # Full-vocabulary KL intermediates are processed in bounded token chunks. jetspec_distillation_temperature: float = 1.0 jetspec_kl_chunk_rows: int = 256 + # Bounds the retained BF16 teacher logits; 0 disables retention and None + # keeps the model default. This is a memory/speed knob, not objective state, + # so it stays out of the exact-recovery topology. + jetspec_teacher_logits_budget_bytes: Optional[int] = None # Main JetSpec results use uniform per-position weights (gamma = 0). jetspec_loss_decay_gamma: float = 0.0 # Pack multiple complete documents into one fixed row. The controller owns diff --git a/aspec/models/jetspec.py b/aspec/models/jetspec.py index 56deaae..a449e98 100644 --- a/aspec/models/jetspec.py +++ b/aspec/models/jetspec.py @@ -14,9 +14,51 @@ import torch.nn.functional as F from aspec.models.dflash import DFlashModel +from aspec.models.ops.jetspec_kl import ( + _backward_from_logits, + _forward_from_logits, + use_fused_jetspec_kl, +) _MIN_TEMPERATURE = 1e-6 _MAX_TEMPERATURE = math.sqrt(torch.finfo(torch.float32).max) +# Bound the retained teacher logits: 1920 active rows x 151936 vocabulary at +# BF16 is about 0.58 GB, while much longer selections fall back to recompute. +TEACHER_LOGITS_BUDGET_BYTES = 4 * 1024**3 + + +def _projection_dtype(hidden, weight=None): + """Dtype ``F.linear`` produces for the teacher projection. + + Autocast never narrows float64, so a float64 operand keeps the projection + in float64 regardless of the autocast dtype. Without autocast the result is + the usual dtype promotion of the two operands. + """ + if hidden.dtype == torch.float64 or ( + weight is not None and weight.dtype == torch.float64 + ): + return torch.float64 + device_type = hidden.device.type + if torch.is_autocast_enabled(device_type): + return torch.get_autocast_dtype(device_type) + if weight is None: + return hidden.dtype + return torch.promote_types(hidden.dtype, weight.dtype) + + +def should_retain_teacher_logits(rows, vocab, dtype, + budget_bytes=TEACHER_LOGITS_BUDGET_BYTES): + if isinstance(rows, bool) or isinstance(vocab, bool): + raise ValueError("teacher-logit retention needs integer row/vocabulary counts") + rows, vocab = int(rows), int(vocab) + if rows < 0 or vocab < 1: + raise ValueError("teacher-logit retention needs rows >= 0 and vocab >= 1") + if not isinstance(dtype, torch.dtype) or not dtype.is_floating_point: + raise ValueError("teacher-logit retention needs a floating-point dtype") + if budget_bytes <= 0: + return False + element_size = torch.finfo(dtype).bits // 8 + return rows > 0 and rows * vocab * element_size <= budget_bytes class _ChunkedForwardKL(torch.autograd.Function): @@ -25,34 +67,97 @@ class _ChunkedForwardKL(torch.autograd.Function): Saving ``log_q``/``log_p`` per chunk would keep O(tokens * vocabulary) FP32 state alive until backward. The custom backward instead retains the existing Draft logits and teacher hidden states, then recomputes one chunk at a time. + + ``retain_teacher`` stores the BF16 teacher logits within the caller's budget + so backward can skip the frozen teacher projection. ``fused`` replaces the + FP32 ``log_softmax``/``kl_div`` chunks with the tiled Triton epilogue. """ @staticmethod - def forward(ctx, draft_logits, hidden, lm_head_weight, temperature, chunk_rows, active): + def forward(ctx, draft_logits, hidden, lm_head_weight, temperature, chunk_rows, + active, retain_teacher, fused): device_type = hidden.device.type ctx.autocast_enabled = torch.is_autocast_enabled(device_type) ctx.autocast_dtype = torch.get_autocast_dtype(device_type) rows = draft_logits.shape[0] + vocabulary = draft_logits.shape[1] + projected_dtype = _projection_dtype(hidden, lm_head_weight) + if fused: + if not draft_logits.is_cuda: + raise ValueError("fused JetSpec KL requires CUDA logits") + if draft_logits.dtype != torch.bfloat16 or projected_dtype != torch.bfloat16: + raise ValueError("fused JetSpec KL requires BF16 draft/teacher logits") + if not draft_logits.is_contiguous(): + raise ValueError("fused JetSpec KL requires contiguous draft logits") kl = torch.zeros(rows, dtype=torch.float32, device=draft_logits.device) - for start in range(0, active.numel(), chunk_rows): - row_ids = active[start : start + chunk_rows] - target_logits = F.linear( - hidden.index_select(0, row_ids), lm_head_weight - ).float() - log_p = F.log_softmax(target_logits / temperature, dim=-1) - log_q = F.log_softmax( - draft_logits.index_select(0, row_ids).float() / temperature, dim=-1 + teacher_buffer = None + if retain_teacher: + teacher_buffer = torch.empty( + (active.numel(), vocabulary), dtype=projected_dtype, + device=draft_logits.device, ) - chunk = F.kl_div(log_q, log_p, reduction="none", log_target=True).sum(-1) - kl.index_put_((row_ids,), chunk * (temperature * temperature)) - ctx.save_for_backward(draft_logits, hidden, lm_head_weight, active) + norms = None + if fused: + norms = torch.empty((active.numel(), 4), dtype=torch.float32, + device=draft_logits.device) + # Autocast leaves FP64 (and other non-narrowed) projections at their + # input dtype, so the direct-buffer GEMM only serves projections that + # already have the buffer dtype; everything else keeps the reference + # projection and copies the result in. + direct_projection = ( + teacher_buffer is not None + and hidden.dtype == projected_dtype + and lm_head_weight.dtype == projected_dtype + ) + for start in range(0, active.numel(), chunk_rows): + row_ids = active[start:start + chunk_rows] + stop = start + row_ids.numel() + chunk_hidden = hidden.index_select(0, row_ids) + if direct_projection: + # Write the projection straight into the retained buffer: no + # chunk-sized temporary and no extra device-to-device copy. + target_logits = teacher_buffer[start:stop] + torch.mm(chunk_hidden, lm_head_weight.t(), out=target_logits) + else: + target_logits = F.linear(chunk_hidden, lm_head_weight) + if teacher_buffer is not None: + teacher_buffer[start:stop] = target_logits + draft_chunk = draft_logits.index_select(0, row_ids) + if fused: + chunk, chunk_norms = _forward_from_logits( + draft_chunk, target_logits, temperature + ) + norms[start:stop] = chunk_norms + kl.index_put_((row_ids,), chunk) + else: + log_p = F.log_softmax(target_logits.float() / temperature, dim=-1) + log_q = F.log_softmax(draft_chunk.float() / temperature, dim=-1) + chunk = F.kl_div(log_q, log_p, reduction="none", log_target=True).sum(-1) + kl.index_put_((row_ids,), chunk * (temperature * temperature)) + saved = [draft_logits, hidden, lm_head_weight, active] + if teacher_buffer is not None: + saved.append(teacher_buffer) + if norms is not None: + saved.append(norms) + ctx.save_for_backward(*saved) ctx.temperature = temperature ctx.chunk_rows = chunk_rows + ctx.retain_teacher = retain_teacher + ctx.fused = fused return kl @staticmethod def backward(ctx, grad_kl): - draft_logits, hidden, lm_head_weight, active = ctx.saved_tensors + saved = ctx.saved_tensors + draft_logits, hidden, lm_head_weight, active = saved[:4] + cursor = 4 + teacher_buffer = None + if ctx.retain_teacher: + teacher_buffer = saved[cursor] + cursor += 1 + norms = None + if ctx.fused: + norms = saved[cursor] temperature = ctx.temperature gradient = torch.zeros_like(draft_logits) with torch.autocast( @@ -61,26 +166,41 @@ def backward(ctx, grad_kl): enabled=ctx.autocast_enabled, ): for start in range(0, active.numel(), ctx.chunk_rows): - row_ids = active[start : start + ctx.chunk_rows] - target_logits = F.linear( - hidden.index_select(0, row_ids), lm_head_weight - ).float() - p = F.softmax(target_logits / temperature, dim=-1) - q = F.softmax( - draft_logits.index_select(0, row_ids).float() / temperature, - dim=-1, - ) - scale = grad_kl.index_select(0, row_ids).float().unsqueeze(-1) - gradient.index_put_( - (row_ids,), ((q - p) * temperature * scale).to(gradient.dtype) - ) - return gradient, None, None, None, None, None + row_ids = active[start:start + ctx.chunk_rows] + stop = start + row_ids.numel() + if teacher_buffer is not None: + target_logits = teacher_buffer[start:stop] + else: + target_logits = F.linear( + hidden.index_select(0, row_ids), lm_head_weight + ) + draft_chunk = draft_logits.index_select(0, row_ids) + scale = grad_kl.index_select(0, row_ids).float() + if ctx.fused: + gradient.index_put_( + (row_ids,), + _backward_from_logits( + draft_chunk, target_logits, norms[start:stop], + scale, temperature, + ), + ) + else: + p = F.softmax(target_logits.float() / temperature, dim=-1) + q = F.softmax(draft_chunk.float() / temperature, dim=-1) + gradient.index_put_( + (row_ids,), + ((q - p) * temperature * scale.unsqueeze(-1)).to( + gradient.dtype + ), + ) + return gradient, None, None, None, None, None, None, None class JetSpecModel(DFlashModel): """DFlash block head with causal intra-block attention and forward KL.""" - def __init__(self, *args, distillation_temperature=1.0, kl_chunk_rows=256, **kwargs): + def __init__(self, *args, distillation_temperature=1.0, kl_chunk_rows=256, + teacher_logits_budget_bytes=TEACHER_LOGITS_BUDGET_BYTES, **kwargs): # Main JetSpec results use uniform per-position weights (gamma = 0). kwargs.setdefault("loss_decay_gamma", 0.0) super().__init__(*args, **kwargs) @@ -112,6 +232,15 @@ def __init__(self, *args, distillation_temperature=1.0, kl_chunk_rows=256, **kwa or kl_chunk_rows < 1): raise ValueError("JetSpec kl_chunk_rows must be a positive integer") self.kl_chunk_rows = int(kl_chunk_rows) + if (isinstance(teacher_logits_budget_bytes, bool) + or not isinstance(teacher_logits_budget_bytes, int) + or teacher_logits_budget_bytes < 0): + raise ValueError( + "JetSpec teacher_logits_budget_bytes must be a non-negative " + "integer; 0 disables teacher-logit retention" + ) + self.teacher_logits_budget_bytes = int(teacher_logits_budget_bytes) + self.last_kl_path = None if config is not None and hasattr(config, "block_size"): if int(config.block_size) != self.block_size: raise ValueError("JetSpec training block_size must match its Draft config") @@ -170,6 +299,27 @@ def _training_loss( ) # The custom backward recomputes one chunk at a time, so neither the # forward nor the saved state keeps every full-vocabulary chunk alive. + # Retaining BF16 teacher logits within the budget skips the backward + # teacher projection; the tiled epilogue replaces the FP32 softmax/KL. + projected_dtype = _projection_dtype(flat_hidden, lm_head_weight) + # Held-out evaluation runs this forward under no_grad, where a retained + # teacher buffer would never be read by a backward. + retain_teacher = ( + torch.is_grad_enabled() + and draft_logits.requires_grad + and should_retain_teacher_logits( + active.numel(), vocabulary, projected_dtype, + self.teacher_logits_budget_bytes, + ) + ) + fused = use_fused_jetspec_kl( + draft_logits, lm_head_weight, projected_dtype, + self.distillation_temperature, + ) + self.last_kl_path = ( + ("tiled" if fused else "reference") + + ("+retained" if retain_teacher else "+recompute") + ) kl = _ChunkedForwardKL.apply( draft_logits, flat_hidden, @@ -177,6 +327,8 @@ def _training_loss( self.distillation_temperature, self.kl_chunk_rows, active, + retain_teacher, + fused, ) return kl, kl, logits diff --git a/aspec/models/ops/jetspec_kl.py b/aspec/models/ops/jetspec_kl.py new file mode 100644 index 0000000..23570dd --- /dev/null +++ b/aspec/models/ops/jetspec_kl.py @@ -0,0 +1,247 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""Tiled FP32 forward-KL epilogue for JetSpec with recomputation. + +The PyTorch chunked implementation stays the numerical reference and the +fallback for CPU, non-BF16 or unavailable Triton. The fused path streams the +vocabulary once to collect per-row statistics, merges them, and writes +``(q - p) * T * grad`` during backward. It avoids materializing FP32 +``log_p``/``log_q`` tiles and reduces the per-chunk elementwise kernel count. + +Statistics are stored per (row, vocabulary tile) as + + mt, A, md, Zq, D + +with ``A = sum exp((t - mt)/T)``, ``Zq = sum exp((d - md)/T)`` and +``D = sum exp((t - mt)/T) * (t - d)``. The per-row forward KL follows as + + KL = D / (A*T) + (md - mt)/T - log(A) + log(Zq) + +which keeps the large ``sum e*t`` and ``sum e*d`` terms out of the subtraction. +""" + +from __future__ import annotations + +import math + +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 = 4096 +_STATS = 5 + + +def _triton_unavailable() -> bool: + return _TRITON_IMPORT_ERROR is not None or triton is None + + +if not _triton_unavailable(): + + @triton.jit(do_not_specialize=["temperature"]) + def _kl_stats(Teacher, Draft, Stats, V: tl.constexpr, TILES: tl.constexpr, + BLOCK: tl.constexpr, temperature): + row, tile = tl.program_id(0), tl.program_id(1) + row = row.to(tl.int64) + cols = tile * BLOCK + tl.arange(0, BLOCK) + valid = cols < V + t = tl.load(Teacher + row * V + cols, mask=valid, + other=-float("inf")).to(tl.float32) + d = tl.load(Draft + row * V + cols, mask=valid, + other=-float("inf")).to(tl.float32) + inv_t = 1.0 / temperature + mt, md = tl.max(t, 0), tl.max(d, 0) + mt_safe = tl.where(mt == -float("inf"), 0.0, mt) + md_safe = tl.where(md == -float("inf"), 0.0, md) + et = tl.where(valid, tl.exp((t - mt_safe) * inv_t), 0.0) + ed = tl.where(valid, tl.exp((d - md_safe) * inv_t), 0.0) + # Form the per-element difference before weighting so the merged KL + # never subtracts two large per-vocabulary sums. + diff = tl.where(valid, t - d, 0.0) + base = (row * TILES + tile) * 5 + tl.store(Stats + base, mt) + tl.store(Stats + base + 1, tl.sum(et, 0)) + tl.store(Stats + base + 2, md) + tl.store(Stats + base + 3, tl.sum(ed, 0)) + tl.store(Stats + base + 4, tl.sum(et * diff, 0)) + + @triton.jit(do_not_specialize=["temperature"]) + def _kl_merge(Stats, Norms, Loss, TILES: tl.constexpr, BLOCK: tl.constexpr, + temperature): + row = tl.program_id(0).to(tl.int64) + idx = tl.arange(0, BLOCK) + mask = idx < TILES + base = (row * TILES + idx) * 5 + inv_t = 1.0 / temperature + mt = tl.load(Stats + base, mask=mask, other=-float("inf")) + a = tl.load(Stats + base + 1, mask=mask, other=0.0) + md = tl.load(Stats + base + 2, mask=mask, other=-float("inf")) + zq = tl.load(Stats + base + 3, mask=mask, other=0.0) + diff = tl.load(Stats + base + 4, mask=mask, other=0.0) + gmt = tl.max(mt, 0) + gmd = tl.max(md, 0) + gmt_safe = tl.where(gmt == -float("inf"), 0.0, gmt) + gmd_safe = tl.where(gmd == -float("inf"), 0.0, gmd) + scale_t = tl.where(mt == -float("inf"), 0.0, + tl.exp((mt - gmt_safe) * inv_t)) + scale_d = tl.where(md == -float("inf"), 0.0, + tl.exp((md - gmd_safe) * inv_t)) + total = tl.sum(a * scale_t, 0) + zq_total = tl.sum(zq * scale_d, 0) + diff_total = tl.sum(diff * scale_t, 0) + # A zero-mass row has an invalid (all -inf) teacher distribution. Store + # NaN for its normalizers so the loss and the backward probabilities stay + # NaN, as the PyTorch reference does, instead of a silent zero. + total_safe = tl.where(total > 0.0, total, float("nan")) + zq_safe = tl.where(zq_total > 0.0, zq_total, float("nan")) + kl = (diff_total * inv_t / total_safe + (gmd_safe - gmt_safe) * inv_t + - tl.log(total_safe) + tl.log(zq_safe)) + # Every tile covers at least one vocabulary column, so a zero-mass row + # means an invalid (all -inf) teacher distribution. Letting the NaN + # propagate matches the PyTorch log_softmax/kl_div reference. + loss = kl * temperature * temperature + tl.store(Loss + row, loss) + tl.store(Norms + row * 4, gmt_safe) + tl.store(Norms + row * 4 + 1, total_safe) + tl.store(Norms + row * 4 + 2, gmd_safe) + tl.store(Norms + row * 4 + 3, zq_safe) + + @triton.jit(do_not_specialize=["temperature"]) + def _kl_backward(Teacher, Draft, Norms, Grad, Dlogits, V: tl.constexpr, + BLOCK: tl.constexpr, temperature): + row, tile = tl.program_id(0), tl.program_id(1) + row = row.to(tl.int64) + cols = tile * BLOCK + tl.arange(0, BLOCK) + valid = cols < V + t = tl.load(Teacher + row * V + cols, mask=valid, + other=-float("inf")).to(tl.float32) + d = tl.load(Draft + row * V + cols, mask=valid, + other=-float("inf")).to(tl.float32) + gmt = tl.load(Norms + row * 4) + total = tl.load(Norms + row * 4 + 1) + gmd = tl.load(Norms + row * 4 + 2) + zq = tl.load(Norms + row * 4 + 3) + inv_t = 1.0 / temperature + p = tl.where(valid, tl.exp((t - gmt) * inv_t) / total, 0.0) + q = tl.where(valid, tl.exp((d - gmd) * inv_t) / zq, 0.0) + scale = tl.load(Grad + row) + tl.store(Dlogits + row * V + cols, (q - p) * temperature * scale, + mask=valid) + + +def use_fused_jetspec_kl(draft_logits, lm_head_weight, projected_dtype, + temperature) -> bool: + """Whether the tiled forward-KL path can serve this training step. + + ``projected_dtype`` is the dtype ``F.linear`` produces for the teacher + projection under the current autocast state, not necessarily the dtype of + the stored teacher features. + """ + return ( + not _triton_unavailable() + and not torch.compiler.is_compiling() + and draft_logits.is_cuda + and lm_head_weight.is_cuda + and draft_logits.device == lm_head_weight.device + and draft_logits.dtype == torch.bfloat16 + and projected_dtype == torch.bfloat16 + and draft_logits.ndim == 2 + and lm_head_weight.ndim == 2 + and draft_logits.shape[1] == lm_head_weight.shape[0] + and draft_logits.is_contiguous() + and draft_logits.numel() > 0 + and math.isfinite(temperature) + and temperature > 0.0 + ) + + +def _validate(draft_logits, target_logits, temperature): + if _triton_unavailable(): + raise ValueError("tiled JetSpec KL requires Triton") from _TRITON_IMPORT_ERROR + if not draft_logits.is_cuda or not target_logits.is_cuda: + raise ValueError("tiled JetSpec KL requires CUDA logits") + if draft_logits.dtype != torch.bfloat16 or target_logits.dtype != torch.bfloat16: + raise ValueError("tiled JetSpec KL requires BF16 logits") + if draft_logits.device != target_logits.device: + raise ValueError("draft and teacher logits must share a device") + if draft_logits.shape != target_logits.shape: + raise ValueError("draft and teacher logits must share shape") + if draft_logits.ndim != 2 or draft_logits.numel() == 0: + raise ValueError("tiled JetSpec KL requires nonempty 2D logits") + if not draft_logits.is_contiguous() or not target_logits.is_contiguous(): + raise ValueError("tiled JetSpec KL requires contiguous logits") + if target_logits.requires_grad: + raise ValueError("tiled JetSpec KL requires frozen teacher logits") + if not math.isfinite(temperature) or temperature <= 0.0: + raise ValueError("tiled JetSpec KL requires a positive finite temperature") + + +def _forward_from_logits(draft_logits, target_logits, temperature): + if _triton_unavailable(): + raise RuntimeError("tiled JetSpec KL requires Triton") from _TRITON_IMPORT_ERROR + rows, vocab = draft_logits.shape + tiles = triton.cdiv(vocab, _BLOCK) + stats = torch.empty((rows, tiles, _STATS), device=draft_logits.device, + dtype=torch.float32) + norms = torch.empty((rows, 4), device=draft_logits.device, dtype=torch.float32) + loss = torch.empty((rows,), device=draft_logits.device, dtype=torch.float32) + # Triton resolves its stream from the current device, so the launches must + # run inside the tensors' device context on multi-GPU hosts. + with torch.cuda.device(draft_logits.device): + _kl_stats[(rows, tiles)]( + target_logits, draft_logits, stats, vocab, tiles, _BLOCK, temperature, + enable_fp_fusion=False, + ) + _kl_merge[(rows,)]( + stats, norms, loss, tiles, triton.next_power_of_2(tiles), temperature, + enable_fp_fusion=False, + ) + return loss, norms + + +def _backward_from_logits(draft_logits, target_logits, norms, grad_loss, + temperature): + if _triton_unavailable(): + raise RuntimeError("tiled JetSpec KL requires Triton") from _TRITON_IMPORT_ERROR + rows, vocab = draft_logits.shape + dlogits = torch.empty_like(draft_logits) + with torch.cuda.device(draft_logits.device): + _kl_backward[(rows, triton.cdiv(vocab, _BLOCK))]( + target_logits, draft_logits, norms, grad_loss.contiguous(), dlogits, + vocab, _BLOCK, temperature, enable_fp_fusion=False, + ) + return dlogits + + +class _TiledKL(torch.autograd.Function): + @staticmethod + def forward(ctx, draft_logits, target_logits, temperature): + _validate(draft_logits, target_logits, temperature) + loss, norms = _forward_from_logits(draft_logits, target_logits, temperature) + ctx.save_for_backward(draft_logits, target_logits, norms) + ctx.temperature = temperature + return loss + + @staticmethod + @once_differentiable + def backward(ctx, grad_loss): + draft_logits, target_logits, norms = ctx.saved_tensors + dlogits = _backward_from_logits( + draft_logits, target_logits, norms, grad_loss, ctx.temperature + ) + return dlogits, None, None + + +def tiled_forward_kl_from_logits(draft_logits, target_logits, temperature): + """Per-row forward KL ``T^2 * KL(softmax(t/T) || softmax(d/T))`` on CUDA BF16.""" + return _TiledKL.apply(draft_logits, target_logits, temperature) diff --git a/aspec/training/jetspec_trainer.py b/aspec/training/jetspec_trainer.py index a17d526..9b30e31 100644 --- a/aspec/training/jetspec_trainer.py +++ b/aspec/training/jetspec_trainer.py @@ -7,7 +7,7 @@ from argparse import Namespace from aspec.models.draft.jetspec import JetSpecConfig, JetSpecDraftModel -from aspec.models.jetspec import JetSpecModel +from aspec.models.jetspec import TEACHER_LOGITS_BUDGET_BYTES, JetSpecModel from aspec.training.dflash_trainer import DFlashTrainer _MIN_TEMPERATURE = 1e-6 @@ -25,6 +25,19 @@ def __init__(self, args: Namespace): getattr(args, "jetspec_distillation_temperature", 1.0) ) self.kl_chunk_rows = getattr(args, "jetspec_kl_chunk_rows", 256) + budget = getattr(args, "jetspec_teacher_logits_budget_bytes", None) + if budget is None: + budget = TEACHER_LOGITS_BUDGET_BYTES + elif ( + isinstance(budget, bool) + or not isinstance(budget, int) + or budget < 0 + ): + raise ValueError( + "jetspec_teacher_logits_budget_bytes must be a non-negative " + "integer or null for the model default" + ) + self.teacher_logits_budget_bytes = budget self.loss_decay_gamma = float( getattr(args, "jetspec_loss_decay_gamma", 0.0) ) @@ -80,6 +93,7 @@ def _build_training_wrapper(self, draft_model): l1_loss_alpha=self.l1_loss_alpha, distillation_temperature=self.distillation_temperature, kl_chunk_rows=self.kl_chunk_rows, + teacher_logits_budget_bytes=self.teacher_logits_budget_bytes, deterministic_anchor_sampling=getattr( self.args, "deterministic_anchor_sampling", False ), diff --git a/docs/user-guide/algorithms.md b/docs/user-guide/algorithms.md index 1e35841..26b542a 100644 --- a/docs/user-guide/algorithms.md +++ b/docs/user-guide/algorithms.md @@ -133,9 +133,12 @@ frozen Target features. `JetSpecConfig` forces that causal contract and rejects incompatible structures. The ASpec training CLI selects the algorithm through a shipped Qwen3-8B Draft config and a JetSpec trainer that reuses the DFlash optimizer/checkpoint path. FlexAttention, CP1, padded/non-packing execution and -exact recovery are the initial scope. SGLang/native export, strict reload, a -proposal consumer and bounded verifier-acceptance runs are supported; tree -construction and long-run convergence evidence remain pending. +exact recovery are the initial scope. The loss path retains BF16 teacher logits +within a 4 GiB budget and uses a tiled Triton forward-KL epilogue on CUDA BF16; +the PyTorch chunked objective remains the numerical reference and fallback. +SGLang/native export, strict reload, a proposal consumer and bounded +verifier-acceptance runs are supported; tree construction and long-run +convergence evidence remain pending. ## Native MTP conditioning for DSpark/DFlash diff --git a/docs/user-guide/jetspec.md b/docs/user-guide/jetspec.md index d125c75..3e8ea43 100644 --- a/docs/user-guide/jetspec.md +++ b/docs/user-guide/jetspec.md @@ -142,13 +142,18 @@ configuration contract, causal mask construction, bounded forward KL and gradien against independent equations, explicit-mask and packed fail-closed paths, anchor/loss-mask exclusion, empty supervision and next-token label/teacher alignment. Native export, strict reload and the proposal consumer have focused CPU -coverage, including causal visibility and anchor-feature isolation. GPU attention -execution, convergence and serving throughput are not certified by those checks. -Bounded SGLang decode was run on 16 held-out prompts (32 new tokens, greedy, two -repeats): the 8-step checkpoint produced greedy-equal, repeat-stable output. The published `JetSpec/jetspec-qwen3-8b` checkpoint measured 2.723 -tokens/verification and 1.823x fixed-order median speedup in the same bounded setup; exporting -that checkpoint through ASpec reproduced the same numbers, confirming tensor/layout -compatibility. The 8-step checkpoint measured 1.032 +coverage, including causal visibility and anchor-feature isolation. The +retained-teacher and tiled-KL paths add CPU retention/recompute parity checks and +a GPU parity suite (`ASPEC_RUN_GPU_INTEGRATION=1`) covering partial vocabulary +tiles, large logits, empty supervision, autocast, fail-closed inputs and, on +two-GPU hosts, a non-current device launch context. GPU +attention execution, convergence and serving throughput are not certified by +those checks. Bounded SGLang decode was run on 16 held-out prompts (32 new tokens, +greedy, two repeats): the 8-step checkpoint produced greedy-equal, repeat-stable +output. The published `JetSpec/jetspec-qwen3-8b` checkpoint measured 2.723 +tokens/verification and 1.823x fixed-order median speedup in the same bounded setup; +exporting that checkpoint through ASpec reproduced the same numbers, confirming +tensor/layout compatibility. The 8-step checkpoint measured 1.032 tokens/verification and 0.795x, so this is not a convergence or quality claim. See [bounded decode compatibility](../benchmarks/jetspec-decode.md). @@ -224,6 +229,68 @@ The training wrapper always supplies explicit visibility. A direct entries. Otherwise it fails closed instead of silently running bidirectional SDPA. The CPU dense-mask path also rejects packed `ctx_doc_ids`, because the dense helper cannot preserve document isolation. +## Loss kernel and memory bounds + +The objective is unchanged; two execution choices keep the loss-side memory and +elementwise work bounded: + +- **Teacher-logit retention.** When `active_rows * vocab * element_bytes` fits + the 4 GiB `TEACHER_LOGITS_BUDGET_BYTES` budget (1920 x 151936 at BF16 is about + 0.58 GB, or 0.54 GiB), forward stores the BF16 teacher logits and backward skips the frozen + teacher projection. Longer selections recompute it, and so does any forward + that no backward can consume, such as held-out evaluation under `no_grad`. + `should_retain_teacher_logits` records the decision. The budget is a memory + and speed knob: `jetspec_teacher_logits_budget_bytes` lowers it and `0` + disables retention, and it stays outside the exact-recovery topology because + it does not change the objective. +- **Tiled forward-KL epilogue.** When the Draft/teacher logits are CUDA BF16 and + Triton is available, a Triton kernel streams each vocabulary tile once for + per-row statistics, merges them, and writes `(q - p) * T * grad` in backward; + it does not materialize FP32 `log_p`/`log_q` chunks. CPU, non-BF16, unavailable + Triton and whole-model compile keep the PyTorch `log_softmax`/`kl_div` path as + the numerical reference and fallback. + +Measured loss-only on one NVIDIA L20 (46 GB, sm_89; CUDA 12.1, torch +2.8.0.post2+cu121, Triton 3.4.0, Python 3.10.18) with Qwen3-8B Draft shapes (5 +layers, H=4096, FFN=12288, GQA 32/8, V=151936, block 16, 128 anchors, ctx 4096, +B=1, 1920 active rows, `kl_chunk_rows=256`, `T=1.0`), forward+backward over +shared inputs and seeds with 5 warmup and 20 measured iterations +(`python tools/performance/bench_jetspec_loss.py --out jetspec_loss_bench.json`): + +| Cell | Median | vs reference | Peak extra | +| --- | ---: | ---: | ---: | +| Reference chunked KL | 121.56 ms | 1.00x | 1.36 GB | +| Retained teacher logits | 102.00 ms | -16.1% | 1.87 GB | +| Tiled KL (recompute) | 52.58 ms | -56.7% | 0.82 GB | +| Tiled KL + retained | 33.35 ms | -72.6% | 1.32 GB | +| Elementwise-only diagnostic | 75.38 ms | -38.0% | 1.21 GB | + +Peak extra counts what a cell allocates beyond the Draft logits and teacher +features the training step already holds. Loss and gradient parity: the absolute +loss difference is `3.9e-3` on a loss of `23686.4` (relative about `1.6e-7`), and +the gradient-norm difference is zero. The same run measured the five-layer Draft +forward+backward at `719.81 ms` and the Draft-logit GEMM at `50.61 ms`, so the KL +cell is about `13.6%` of that loss-side total and the fused+retained path saves +about `9.9%` of it. The Draft cell disables dynamo and uses eager flex attention +in the benchmark, so that share is the KL fraction measured with eager Draft +attention rather than a bound: compiling the Draft would shorten the denominator +and raise the KL share. The KL cells are unaffected. The benchmark fails instead of +reporting a speedup when a cell's loss or gradient fingerprint moves away from +the reference cell. + +These are synthetic loss-side measurements. They exclude Target inference, +transport, orchestration, optimizer state, convergence, acceptance length and +serving throughput. The tiled path requires CUDA BF16 and Triton; CPU, other +dtypes, unavailable Triton and whole-model compile keep the PyTorch reference as +the numerical fallback, and the tiled path is first-order only. + +`JetSpecModel.last_kl_path` records `reference`/`tiled` and +`+retained`/`+recompute` for the most recent loss call. The retained and tiled +paths are covered by `tests/cpu/test_jetspec.py` and +`tests/test_jetspec_kl_kernel_gpu.py`; see the +[loss benchmark](../../tools/performance/bench_jetspec_loss.py) for the +loss-only attribution script. + ## Minimal numerical use Inside the [isolated environment](installation.md): diff --git a/tests/cpu/test_jetspec.py b/tests/cpu/test_jetspec.py index 309580a..5fd54fb 100644 --- a/tests/cpu/test_jetspec.py +++ b/tests/cpu/test_jetspec.py @@ -16,7 +16,12 @@ from aspec.models.dflash import _create_dflash_mask_mod from aspec.models.draft.jetspec import JetSpecConfig, JetSpecDraftModel -from aspec.models.jetspec import JetSpecModel +from aspec.models.jetspec import ( + TEACHER_LOGITS_BUDGET_BYTES, + JetSpecModel, + _ChunkedForwardKL, + should_retain_teacher_logits, +) from aspec.models.ops.direct_cp import DirectCPMetadata @@ -32,7 +37,9 @@ def make_config(**overrides): return JetSpecConfig(**values) -def make_model(*, temperature=1.0, loss_decay_gamma=0.0, kl_chunk_rows=256, seed=17, **config_overrides): +def make_model(*, temperature=1.0, loss_decay_gamma=0.0, kl_chunk_rows=256, seed=17, + teacher_logits_budget_bytes=TEACHER_LOGITS_BUDGET_BYTES, + **config_overrides): with torch.random.fork_rng(devices=[]): torch.random.default_generator.manual_seed(seed) draft = JetSpecDraftModel(make_config(**config_overrides)) @@ -42,6 +49,7 @@ def make_model(*, temperature=1.0, loss_decay_gamma=0.0, kl_chunk_rows=256, seed attention_backend="sdpa", ce_loss_alpha=0.0, l1_loss_alpha=0.0, loss_decay_gamma=loss_decay_gamma, distillation_temperature=temperature, kl_chunk_rows=kl_chunk_rows, + teacher_logits_budget_bytes=teacher_logits_budget_bytes, ) @@ -234,25 +242,156 @@ def test_chunked_kl_matches_dense_objective_and_gradients(): _assert_parameter_gradients(chunked, dense) +def test_teacher_logits_retention_boundaries(): + assert not should_retain_teacher_logits(0, 32, torch.float32) + assert should_retain_teacher_logits(1, 32, torch.float32, budget_bytes=128) + assert not should_retain_teacher_logits(2, 32, torch.float32, budget_bytes=128) + assert should_retain_teacher_logits(1, 32, torch.bfloat16, budget_bytes=64) + assert not should_retain_teacher_logits(1, 32, torch.bfloat16, budget_bytes=63) + assert not should_retain_teacher_logits(1, 32, torch.float32, budget_bytes=0) + assert TEACHER_LOGITS_BUDGET_BYTES == 4 * 1024**3 + with pytest.raises(ValueError): + should_retain_teacher_logits(True, 32, torch.float32) + with pytest.raises(ValueError): + should_retain_teacher_logits(-1, 32, torch.float32) + with pytest.raises(ValueError): + should_retain_teacher_logits(1, 0, torch.float32) + with pytest.raises(ValueError): + should_retain_teacher_logits(1, 32, torch.int64) + + +def test_retained_teacher_logits_match_recompute(monkeypatch): + retained = make_model(temperature=1.5) + recomputed = copy.deepcopy(retained) + inputs, reference_inputs = make_inputs(batch=2), make_inputs(batch=2) + + monkeypatch.setattr( + "aspec.models.jetspec.should_retain_teacher_logits", lambda *a, **k: True + ) + result, _ = run_and_capture(retained, inputs) + monkeypatch.setattr( + "aspec.models.jetspec.should_retain_teacher_logits", lambda *a, **k: False + ) + expected, _ = run_and_capture(recomputed, reference_inputs) + + assert retained.last_kl_path == "reference+retained" + assert recomputed.last_kl_path == "reference+recompute" + torch.testing.assert_close(result[0], expected[0], rtol=2e-5, atol=2e-6) + result[0].backward() + expected[0].backward() + _assert_parameter_gradients(retained, recomputed) + + +def test_cpu_selects_the_reference_kl_path(): + model = make_model() + result, _ = run_and_capture(model, make_inputs()) + assert model.last_kl_path == "reference+retained" + assert torch.isfinite(result[0]) + + +def test_no_grad_forward_recomputes_teacher_logits(): + model = make_model() + with torch.no_grad(): + result, _ = run_and_capture(model, make_inputs()) + assert model.last_kl_path == "reference+recompute" + assert torch.isfinite(result[0]) + + +def test_teacher_logits_budget_bounds_retention(): + disabled = make_model(teacher_logits_budget_bytes=0) + assert disabled.last_kl_path is None + result, _ = run_and_capture(disabled, make_inputs()) + assert disabled.last_kl_path == "reference+recompute" + assert torch.isfinite(result[0]) + + tiny = make_model(teacher_logits_budget_bytes=1) + run_and_capture(tiny, make_inputs()) + assert tiny.last_kl_path == "reference+recompute" + + +def test_teacher_logits_budget_rejects_invalid_values(): + with pytest.raises(ValueError): + make_model(teacher_logits_budget_bytes=-1) + with pytest.raises(ValueError): + make_model(teacher_logits_budget_bytes=True) + + def test_target_projection_uses_bounded_token_chunks(monkeypatch): model = make_model(kl_chunk_rows=3) inputs = make_inputs(batch=2) rows_per_projection = [] original_linear = F.linear + original_mm = torch.mm - def recording_linear(input, weight, bias=None): + def record(rows): if not torch.is_grad_enabled(): - rows_per_projection.append(input.shape[0]) + rows_per_projection.append(rows) + + def recording_linear(input, weight, bias=None): + record(input.shape[0]) return original_linear(input, weight, bias) + def recording_mm(input, mat2, *, out=None): + record(input.shape[0]) + return original_mm(input, mat2, out=out) + monkeypatch.setattr(F, "linear", recording_linear) + monkeypatch.setattr(torch, "mm", recording_mm) result, _ = run_and_capture(model, inputs) result[0].backward() assert rows_per_projection assert max(rows_per_projection) <= 3 -def test_chunked_backward_preserves_forward_autocast_state(): +def test_retained_projection_keeps_fp64_under_autocast(): + # FP64 is exempt from autocast, so the projection must not be narrowed to + # the buffer dtype: [10000, 10000] @ [[1.001, -1], [0, 0]] is [10, 0] in + # FP64 but would collapse to [0, 0] if cast to BF16. + hidden = torch.tensor([[10000.0, 10000.0]], dtype=torch.float64) + weight = torch.tensor([[1.001, -1.0], [0.0, 0.0]], dtype=torch.float64) + draft = torch.zeros(1, 2, dtype=torch.float64) + active = torch.tensor([0]) + with torch.autocast("cpu", dtype=torch.bfloat16): + loss = _ChunkedForwardKL.apply( + draft, hidden, weight, 1.0, 4, active, True, False + ) + teacher = torch.tensor([[10.0, 0.0]], dtype=torch.float64) + log_p = F.log_softmax(teacher.float(), dim=-1) + log_q = F.log_softmax(draft.float(), dim=-1) + expected = F.kl_div(log_q, log_p, reduction="none", log_target=True).sum(-1) + assert loss.item() > 0.1 + torch.testing.assert_close(loss, expected, rtol=1e-5, atol=1e-7) + + +def test_retained_projection_keeps_fp64_gradients_under_autocast(): + # These teacher logits differ in FP64 but both round to 99840 in BF16, so a + # narrowed retained buffer would give backward an identical distribution. + hidden = torch.tensor([[100001.0, 100000.0]], dtype=torch.float64) + weight = torch.eye(2, dtype=torch.float64) + active = torch.tensor([0]) + + def run(retain): + draft = torch.zeros(1, 2, dtype=torch.float64, requires_grad=True) + with torch.autocast("cpu", dtype=torch.bfloat16): + loss = _ChunkedForwardKL.apply( + draft, hidden, weight, 1.0, 4, active, retain, False + ) + loss.sum().backward() + return loss.detach(), draft.grad.detach() + + retained_loss, retained_grad = run(True) + recomputed_loss, recomputed_grad = run(False) + torch.testing.assert_close(retained_loss, recomputed_loss, rtol=1e-6, atol=1e-9) + torch.testing.assert_close(retained_grad, recomputed_grad, rtol=1e-6, atol=1e-9) + assert retained_loss.item() > 1e-4 + assert retained_grad.abs().sum().item() > 1e-4 + + +def test_chunked_backward_preserves_forward_autocast_state(monkeypatch): + # Force the recompute path so backward actually re-enters autocast. + monkeypatch.setattr( + "aspec.models.jetspec.should_retain_teacher_logits", lambda *a, **k: False + ) outside = make_model(temperature=1.5) inside = make_model(temperature=1.5) inputs, inside_inputs = make_inputs(batch=2), make_inputs(batch=2) @@ -268,7 +407,10 @@ def test_chunked_backward_preserves_forward_autocast_state(): _assert_parameter_gradients(outside, inside) -def test_chunked_backward_restores_autocast_dtype_for_bf16_teacher(): +def test_chunked_backward_restores_autocast_dtype_for_bf16_teacher(monkeypatch): + monkeypatch.setattr( + "aspec.models.jetspec.should_retain_teacher_logits", lambda *a, **k: False + ) model = make_model() inputs = make_inputs() inputs["hidden_states_list"] = inputs["hidden_states_list"].to(torch.bfloat16) diff --git a/tests/cpu/test_jetspec_integration.py b/tests/cpu/test_jetspec_integration.py index e30ec71..63d3569 100644 --- a/tests/cpu/test_jetspec_integration.py +++ b/tests/cpu/test_jetspec_integration.py @@ -13,7 +13,7 @@ from aspec.config.train_config import load_config from aspec.models.draft.auto import AutoDraftModelConfig, AutoEagle3DraftModel from aspec.models.draft.jetspec import JetSpecConfig, JetSpecDraftModel -from aspec.models.jetspec import JetSpecModel +from aspec.models.jetspec import TEACHER_LOGITS_BUDGET_BYTES, JetSpecModel from aspec.planning import ( PlanCompileError, _load_draft_descriptor, @@ -220,6 +220,7 @@ def base_init(self, args): args.jetspec_distillation_temperature = 0.5 args.jetspec_kl_chunk_rows = 32 args.jetspec_loss_decay_gamma = 0.25 + args.jetspec_teacher_logits_budget_bytes = 0 trainer = JetSpecTrainer(args) assert trainer.loss_decay_gamma == 0.25 @@ -228,6 +229,7 @@ def base_init(self, args): assert isinstance(wrapper, JetSpecModel) assert wrapper.distillation_temperature == 0.5 assert wrapper.kl_chunk_rows == 32 + assert wrapper.teacher_logits_budget_bytes == 0 assert wrapper.loss_decay_gamma == 0.25 assert wrapper.prediction_start == 1 assert trainer._anchor_slot_offset == 1 @@ -236,6 +238,15 @@ def base_init(self, args): assert objective["distillation_temperature"] == wrapper.distillation_temperature assert objective["kl_chunk_rows"] == wrapper.kl_chunk_rows assert objective["loss_decay_gamma"] == wrapper.loss_decay_gamma + assert "teacher_logits_budget_bytes" not in objective + + args.jetspec_teacher_logits_budget_bytes = -1 + with pytest.raises(ValueError, match="teacher_logits_budget_bytes"): + JetSpecTrainer(args) + args.jetspec_teacher_logits_budget_bytes = None + default_trainer = JetSpecTrainer(args) + assert default_trainer.teacher_logits_budget_bytes == TEACHER_LOGITS_BUDGET_BYTES + args.jetspec_teacher_logits_budget_bytes = 0 trainer.block_size = 4 with pytest.raises(ValueError, match="block_size"): diff --git a/tests/test_jetspec_kl_kernel_gpu.py b/tests/test_jetspec_kl_kernel_gpu.py new file mode 100644 index 0000000..629b351 --- /dev/null +++ b/tests/test_jetspec_kl_kernel_gpu.py @@ -0,0 +1,344 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""GPU parity and edge cases for the tiled JetSpec forward-KL epilogue. + +Run with ``ASPEC_RUN_GPU_INTEGRATION=1`` on a CUDA device. The reference is +the PyTorch chunked objective: BF16 logits cast to FP32, ``log_softmax`` and +``kl_div(log_target=True)``, scaled by ``T^2``. +""" + +import os + +import pytest +import torch +import torch.nn.functional as F + +if os.environ.get("ASPEC_RUN_GPU_INTEGRATION") != "1": + pytest.skip("set ASPEC_RUN_GPU_INTEGRATION=1 for GPU integration", allow_module_level=True) +if not torch.cuda.is_available(): + pytest.skip("CUDA is required", allow_module_level=True) +pytest.importorskip("triton") + +from aspec.models.jetspec import ( # noqa: E402 + _ChunkedForwardKL, + _projection_dtype, +) +from aspec.models.ops.jetspec_kl import ( # noqa: E402 + tiled_forward_kl_from_logits, + use_fused_jetspec_kl, +) + + +def _logits(rows, vocab, seed=0, scale=1.0): + generator = torch.Generator(device="cuda").manual_seed(seed) + return torch.randn(rows, vocab, device="cuda", dtype=torch.bfloat16, + generator=generator) * scale + + +def _reference(draft, target, temperature, weights=None): + log_q = F.log_softmax(draft.float() / temperature, dim=-1) + log_p = F.log_softmax(target.float() / temperature, dim=-1) + kl = F.kl_div(log_q, log_p, reduction="none", log_target=True).sum(-1) + kl = kl * (temperature * temperature) + if weights is None: + return kl + draft_ref = draft.detach().clone().requires_grad_(True) + log_q = F.log_softmax(draft_ref.float() / temperature, dim=-1) + log_p = F.log_softmax(target.float() / temperature, dim=-1) + loss = (F.kl_div(log_q, log_p, reduction="none", log_target=True).sum(-1) + * (temperature * temperature) * weights) + loss.sum().backward() + return kl, draft_ref.grad + + +def _weights(rows, seed=99): + generator = torch.Generator(device="cuda").manual_seed(seed) + return torch.rand(rows, device="cuda", dtype=torch.float32, generator=generator) + 0.5 + + +def _assert_gradient_close(actual, expected, name): + assert torch.isfinite(actual).all(), f"{name} has non-finite values" + error = ((actual.float() - expected.float()).norm() + / expected.float().norm().clamp_min(1e-6)) + assert error < 1e-2, f"{name} relative norm error {error.item():.4f}" + max_abs = (actual.float() - expected.float()).abs().max() + # Scale by the largest expected element; a 1.0 floor made the tolerance + # larger than every element once the vocabulary was large. About two BF16 + # ulps (2^-7 each) cover the kernel's single BF16 rounding of that element. + scale = expected.float().abs().max().clamp_min(1e-8) + assert max_abs <= 2e-2 * scale, ( + f"{name} max abs error {max_abs.item():.6f} exceeds 2% of scale " + f"{scale.item():.6f}" + ) + + +@pytest.mark.parametrize("vocab,rows", [(3, 1), (127, 7), (4097, 5), (16385, 3)]) +@pytest.mark.parametrize("temperature", [0.5, 1.0, 2.0]) +def test_tiled_kl_matches_reference(vocab, rows, temperature): + draft = _logits(rows, vocab, seed=vocab + rows).detach().requires_grad_(True) + target = _logits(rows, vocab, seed=7 * vocab + rows) + weights = _weights(rows) + actual = tiled_forward_kl_from_logits(draft, target, temperature) + expected, expected_grad = _reference( + draft.detach(), target, temperature, weights + ) + torch.testing.assert_close(actual, expected, rtol=2e-3, atol=2e-3) + (actual * weights).sum().backward() + _assert_gradient_close(draft.grad, expected_grad, "draft") + + +def test_tiled_kl_large_logits_are_finite(): + draft = _logits(6, 4097, seed=1, scale=100.0).detach().requires_grad_(True) + target = _logits(6, 4097, seed=2, scale=100.0) + actual = tiled_forward_kl_from_logits(draft, target, 1.0) + expected = _reference(draft.detach(), target, 1.0) + assert torch.isfinite(actual).all() + torch.testing.assert_close(actual, expected, rtol=5e-3, atol=5e-2) + actual.sum().backward() + assert torch.isfinite(draft.grad).all() + + +def test_tiled_kl_propagates_nan_teacher_row(): + draft = _logits(2, 4097, seed=3).detach().requires_grad_(True) + target = _logits(2, 4097, seed=4) + target[0, 17] = float("nan") + actual = tiled_forward_kl_from_logits(draft, target, 1.0) + expected = _reference(draft.detach(), target, 1.0) + assert torch.isnan(actual[0]) + torch.testing.assert_close(actual[1], expected[1], rtol=2e-3, atol=2e-3) + actual.sum().backward() + # Triton's max ignores NaN, so only the NaN column of that row must be NaN; + # the contract is that a bad row never looks finite, not that every column + # of it is NaN. + assert torch.isnan(draft.grad[0]).any() + assert torch.isfinite(draft.grad[1]).all() + + +def test_tiled_kl_propagates_all_negative_inf_teacher_row(): + draft = _logits(2, 127, seed=5).detach().requires_grad_(True) + target = _logits(2, 127, seed=6) + target[0] = float("-inf") + actual = tiled_forward_kl_from_logits(draft, target, 1.0) + expected = _reference(draft.detach(), target, 1.0) + assert torch.isnan(actual[0]) and torch.isnan(expected[0]) + torch.testing.assert_close(actual[1], expected[1], rtol=2e-3, atol=2e-3) + actual.sum().backward() + assert torch.isnan(draft.grad[0]).any() + assert torch.isfinite(draft.grad[1]).all() + + +def test_tiled_kl_fails_closed(): + draft = _logits(2, 127) + target = _logits(2, 127) + with pytest.raises(ValueError): + tiled_forward_kl_from_logits(draft.float(), target.float(), 1.0) + with pytest.raises(ValueError): + tiled_forward_kl_from_logits(draft.t(), target.t(), 1.0) + with pytest.raises(ValueError): + tiled_forward_kl_from_logits(draft, target.clone().requires_grad_(True), 1.0) + with pytest.raises(ValueError): + tiled_forward_kl_from_logits(draft.cpu(), target.cpu(), 1.0) + with pytest.raises(ValueError): + tiled_forward_kl_from_logits(draft, target, 0.0) + + +def _projection_inputs(rows, active_rows, hidden, vocab, seed=0, device="cuda"): + device = torch.device(device) + generator = torch.Generator(device=device).manual_seed(seed) + hidden_states = torch.randn(rows, hidden, device=device, dtype=torch.bfloat16, + generator=generator) + weight = torch.randn(vocab, hidden, device=device, dtype=torch.bfloat16, + generator=generator) + draft = torch.randn(rows, vocab, device=device, dtype=torch.bfloat16, + generator=generator) + active = torch.arange(active_rows, device=device) + return hidden_states, weight, draft, active + + +def _chunked(hidden_states, weight, base, active, *, retain, fused, + temperature=1.3, chunk_rows=4): + draft = base.detach().clone().requires_grad_(True) + loss = _ChunkedForwardKL.apply( + draft, hidden_states, weight, temperature, chunk_rows, active, + retain, fused, + ) + loss.sum().backward() + return loss.detach(), draft.grad + + +@pytest.mark.parametrize("retain,fused", [(False, True), (True, True), (True, False)]) +def test_chunked_kl_paths_match_reference(retain, fused): + rows, active_rows, hidden, vocab = 9, 7, 16, 4097 + hidden_states, weight, base, active = _projection_inputs( + rows, active_rows, hidden, vocab + ) + reference_loss, reference_grad = _chunked( + hidden_states, weight, base, active, retain=False, fused=False + ) + actual_loss, actual_grad = _chunked( + hidden_states, weight, base, active, retain=retain, fused=fused + ) + torch.testing.assert_close(actual_loss, reference_loss, rtol=2e-3, atol=2e-3) + _assert_gradient_close(actual_grad, reference_grad, "draft") + assert torch.equal(actual_grad[active_rows:], + torch.zeros_like(actual_grad[active_rows:])) + + +@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="requires two GPUs") +@pytest.mark.parametrize("retain", [False, True]) +def test_noncurrent_device_context(retain): + rows, active_rows, hidden, vocab = 9, 7, 16, 4097 + torch.cuda.set_device(0) + device = torch.device("cuda:1") + hidden_states, weight, base, active = _projection_inputs( + rows, active_rows, hidden, vocab, device=device + ) + torch.cuda.set_device(0) + try: + loss, gradient = _chunked( + hidden_states, weight, base, active, retain=retain, fused=True + ) + assert loss.device == device and gradient.device == device + reference_loss, reference_grad = _chunked( + hidden_states, weight, base, active, retain=False, fused=False + ) + torch.testing.assert_close(loss, reference_loss, rtol=2e-3, atol=2e-3) + _assert_gradient_close(gradient, reference_grad, "noncurrent draft") + finally: + torch.cuda.set_device(0) + + +def test_chunked_kl_empty_active_rows_are_neutral(): + hidden = torch.randn(3, 16, device="cuda", dtype=torch.bfloat16) + weight = torch.randn(127, 16, device="cuda", dtype=torch.bfloat16) + draft = torch.randn(3, 127, device="cuda", dtype=torch.bfloat16, + requires_grad=True) + active = torch.empty(0, device="cuda", dtype=torch.long) + loss = _ChunkedForwardKL.apply(draft, hidden, weight, 1.0, 4, active, True, True) + assert torch.equal(loss, torch.zeros_like(loss)) + loss.sum().backward() + assert torch.equal(draft.grad, torch.zeros_like(draft.grad)) + + +def test_chunked_kl_autocast_projection_uses_bf16(): + hidden = torch.randn(5, 16, device="cuda", dtype=torch.float32) + weight = torch.randn(4097, 16, device="cuda", dtype=torch.float32) + base = _logits(5, 4097, seed=11) + active = torch.arange(5, device="cuda") + with torch.autocast("cuda", dtype=torch.bfloat16): + assert _projection_dtype(hidden) == torch.bfloat16 + fused_loss, fused_grad = _chunked( + hidden, weight, base, active, retain=True, fused=True + ) + reference_loss, reference_grad = _chunked( + hidden, weight, base, active, retain=False, fused=False + ) + torch.testing.assert_close(fused_loss, reference_loss, rtol=2e-3, atol=2e-3) + _assert_gradient_close(fused_grad, reference_grad, "draft") + + +def test_use_fused_jetspec_kl_guards(): + draft = _logits(2, 127) + weight = torch.randn(127, 16, device="cuda", dtype=torch.bfloat16) + assert use_fused_jetspec_kl(draft, weight, torch.bfloat16, 1.0) + assert not use_fused_jetspec_kl(draft, weight, torch.float32, 1.0) + assert not use_fused_jetspec_kl(draft.float(), weight, torch.float32, 1.0) + assert not use_fused_jetspec_kl(draft.t(), weight, torch.bfloat16, 1.0) + assert not use_fused_jetspec_kl(draft, weight, torch.bfloat16, 0.0) + + +def test_chunked_kl_fused_guards_fail_closed(): + hidden, weight, base, active = _projection_inputs(4, 3, 16, 127) + for draft in (base.float(), base.t(), base.cpu()): + with pytest.raises(ValueError): + _ChunkedForwardKL.apply( + draft, hidden, weight, 1.0, 2, active, False, True + ) + + +def _jetspec_model(**kwargs): + from aspec.models.draft.jetspec import JetSpecConfig, JetSpecDraftModel + from aspec.models.jetspec import JetSpecModel + + config = JetSpecConfig( + hidden_size=16, intermediate_size=32, num_hidden_layers=1, + num_attention_heads=1, num_key_value_heads=1, head_dim=16, vocab_size=4097, + num_target_layers=1, target_hidden_size=16, target_num_hidden_layers=4, + target_layer_ids=[1], mask_token_id=4096, max_position_embeddings=128, + block_size=5, + ) + draft = JetSpecDraftModel(config).cuda().bfloat16() + draft.embed_tokens.requires_grad_(False) + return JetSpecModel( + draft, block_size=5, num_anchors=2, attention_backend="sdpa", + ce_loss_alpha=0.0, l1_loss_alpha=0.0, distillation_temperature=1.0, + kl_chunk_rows=4, **kwargs, + ) + + +def _model_inputs(length=12, batch=1, seed=31): + generator = torch.Generator(device="cuda").manual_seed(seed) + ids = torch.arange(batch * length, device="cuda").reshape(batch, length) + return dict( + input_ids=ids, + hidden_states_list=torch.randn(batch, length, 16, device="cuda", + dtype=torch.bfloat16, generator=generator), + loss_mask=torch.ones_like(ids), + lm_head_weight=torch.randn(4097, 16, device="cuda", dtype=torch.bfloat16, + generator=generator), + last_hidden_states=torch.randn(batch, length, 16, device="cuda", + dtype=torch.bfloat16, generator=generator), + injected_anchors=torch.tensor([[3, 5]], device="cuda").expand(batch, -1), + injected_keep_mask=torch.ones(batch, 2, dtype=torch.bool, device="cuda"), + ) + + +def test_model_dispatch_reaches_the_tiled_paths(monkeypatch): + model = _jetspec_model() + result = model(**_model_inputs()) + assert model.last_kl_path == "tiled+retained" + result[0].backward() + gradients = {name: parameter.grad for name, parameter + in model.named_parameters() if parameter.grad is not None} + + reference = _jetspec_model() + reference.load_state_dict(model.state_dict()) + monkeypatch.setattr("aspec.models.jetspec.use_fused_jetspec_kl", + lambda *args, **kwargs: False) + expected = reference(**_model_inputs()) + assert reference.last_kl_path == "reference+retained" + expected[0].backward() + torch.testing.assert_close(result[0].detach(), expected[0].detach(), + rtol=2e-3, atol=2e-3) + expected_gradients = {name: parameter.grad for name, parameter + in reference.named_parameters() + if parameter.grad is not None} + assert gradients.keys() == expected_gradients.keys() + for name, gradient in gradients.items(): + _assert_gradient_close(gradient, expected_gradients[name], name) + + +def test_model_dispatch_without_grad_recomputes(): + model = _jetspec_model() + with torch.no_grad(): + result = model(**_model_inputs()) + assert model.last_kl_path == "tiled+recompute" + assert torch.isfinite(result[0]) + + +def test_model_dispatch_zero_budget_recomputes(): + model = _jetspec_model(teacher_logits_budget_bytes=0) + result = model(**_model_inputs()) + assert model.last_kl_path == "tiled+recompute" + assert torch.isfinite(result[0]) + + +def test_model_reports_a_nan_teacher_row(): + model = _jetspec_model() + inputs = _model_inputs() + inputs["last_hidden_states"][0, 6] = float("nan") + with torch.no_grad(): + result = model(**inputs) + assert model.last_kl_path == "tiled+recompute" + assert torch.isnan(result[0]) diff --git a/tools/performance/bench_jetspec_loss.py b/tools/performance/bench_jetspec_loss.py new file mode 100644 index 0000000..6fedece --- /dev/null +++ b/tools/performance/bench_jetspec_loss.py @@ -0,0 +1,590 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""Single-GPU JetSpec Draft loss-side attribution benchmark. + +This isolates the loss-side pieces of one JetSpec training step so a fused +epilogue decision can be made from measured shares, not guesses. It does not +run Target inference, transport, orchestration, an optimizer or convergence. + +Cells (all CUDA BF16, synthetic but Qwen3-8B shaped inputs): + +- ``draft``: the real five-layer ``JetSpecDraftModel`` forward+backward on + block-causal FlexAttention inputs (context projection, dual-source KV and all + decoder layers). +- ``draft_logits``: the frozen Target LM-head projection of every Draft block + slot, forward+backward with respect to the Draft hidden states. +- ``teacher_gemm``: two frozen Target LM-head projections over the active rows, + matching the KL forward projection plus its backward recomputation. +- ``kl``: the shipped ``_ChunkedForwardKL`` autograd function over the active + rows (teacher GEMM inside, teacher logits recomputed in backward). +- ``kl_retained``: the same PyTorch epilogue with teacher logits retained + within the 4 GiB budget, so backward skips the frozen teacher projection. +- ``kl_fused``: the tiled Triton FP32 forward-KL epilogue with recompute. +- ``kl_fused_retained``: the tiled epilogue with retained teacher logits. +- ``kl_epilogue``: script-only attribution cell that precomputes teacher logits + and measures only the FP32 softmax/KL elementwise forward and backward. + +``kl - kl_epilogue`` estimates the teacher GEMM share inside the KL path and +should agree with ``teacher_gemm``; the losses/gradients of ``kl`` and +``kl_epilogue`` are reported for parity. ``kl_epilogue`` is a diagnostic, not +a shipped loss path. +""" + +from __future__ import annotations + +import argparse +import json +import math +import statistics +import sys + +import torch +import torch.nn.functional as F +from torch.autograd import Function +from torch.nn.attention.flex_attention import create_block_mask + +from aspec.models.dflash import _create_dflash_mask_mod +from aspec.models.draft.jetspec import JetSpecConfig, JetSpecDraftModel +from aspec.models.jetspec import _ChunkedForwardKL +from aspec.models.ops.jetspec_kl import use_fused_jetspec_kl + +_CELLS = ("draft", "draft_logits", "teacher_gemm", "kl", "kl_retained", + "kl_fused", "kl_fused_retained", "kl_epilogue") + +# A faster cell is only a speedup while it keeps the objective, so the run fails +# when a cell's loss or gradient fingerprint moves away from the reference cell. +_PARITY_TOL = 1e-3 + + +class _ElementwiseKL(Function): + """Forward KL over precomputed logits: no teacher GEMM, no saved probs.""" + + @staticmethod + def forward(ctx, draft_logits, target_logits, temperature, chunk_rows): + rows = draft_logits.shape[0] + kl = torch.zeros(rows, dtype=torch.float32, device=draft_logits.device) + for start in range(0, rows, chunk_rows): + stop = min(start + chunk_rows, rows) + log_p = F.log_softmax(target_logits[start:stop].float() / temperature, dim=-1) + log_q = F.log_softmax(draft_logits[start:stop].float() / temperature, dim=-1) + chunk = F.kl_div(log_q, log_p, reduction="none", log_target=True).sum(-1) + kl[start:stop] = chunk * (temperature * temperature) + ctx.save_for_backward(draft_logits, target_logits) + ctx.temperature = temperature + ctx.chunk_rows = chunk_rows + return kl + + @staticmethod + def backward(ctx, grad_kl): + draft_logits, target_logits = ctx.saved_tensors + temperature = ctx.temperature + gradient = torch.zeros_like(draft_logits) + for start in range(0, draft_logits.shape[0], ctx.chunk_rows): + stop = min(start + ctx.chunk_rows, draft_logits.shape[0]) + p = F.softmax(target_logits[start:stop].float() / temperature, dim=-1) + q = F.softmax(draft_logits[start:stop].float() / temperature, dim=-1) + scale = grad_kl[start:stop].float().unsqueeze(-1) + gradient[start:stop] = ((q - p) * temperature * scale).to(gradient.dtype) + return gradient, None, None, None + + +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("--cells", default=",".join(_CELLS)) + parser.add_argument("--hidden", type=int, default=4096) + parser.add_argument("--intermediate", type=int, default=12288) + parser.add_argument("--vocab", type=int, default=151936) + parser.add_argument("--layers", type=int, default=5) + parser.add_argument("--q-heads", type=int, default=32) + parser.add_argument("--kv-heads", type=int, default=8) + parser.add_argument("--head-dim", type=int, default=128) + parser.add_argument("--target-layers", type=int, default=5) + parser.add_argument("--block", type=int, default=16) + parser.add_argument("--anchors", type=int, default=128) + parser.add_argument("--ctx-len", type=int, default=4096) + parser.add_argument("--batch", type=int, default=1) + parser.add_argument("--temperature", type=float, default=1.0) + parser.add_argument("--row-chunk", type=int, default=256) + parser.add_argument("--warmup", type=int, default=5) + parser.add_argument("--iters", type=int, default=20) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--out", default="jetspec_loss_bench.json") + args = parser.parse_args() + args.cells = [cell.strip() for cell in args.cells.split(",") if cell.strip()] + unknown = [cell for cell in args.cells if cell not in _CELLS] + if unknown: + parser.error(f"unknown cells: {unknown}; expected a subset of {list(_CELLS)}") + if not args.cells: + parser.error("at least one cell is required") + positive = ("hidden", "intermediate", "vocab", "layers", "q_heads", "kv_heads", + "head_dim", "target_layers", "block", "anchors", "ctx_len", "batch", + "row_chunk", "warmup", "iters") + if any(getattr(args, name) <= 0 for name in positive): + parser.error("dimensions, warmup and iters must be positive") + if args.hidden != args.q_heads * args.head_dim: + parser.error("hidden must equal q-heads * head-dim") + if args.q_heads % args.kv_heads: + parser.error("q-heads must be divisible by kv-heads") + if args.block < 2: + parser.error("block must be >= 2 so the anchor slot is excluded") + if args.ctx_len <= args.block: + parser.error("ctx-len must exceed block") + return args + + +def _build_model(args): + config = JetSpecConfig( + hidden_size=args.hidden, + intermediate_size=args.intermediate, + num_hidden_layers=args.layers, + num_attention_heads=args.q_heads, + num_key_value_heads=args.kv_heads, + vocab_size=args.vocab, + max_position_embeddings=args.ctx_len + args.anchors * args.block, + num_target_layers=args.target_layers, + target_hidden_size=args.hidden, + target_num_hidden_layers=36, + target_layer_ids=[1 + 8 * i for i in range(args.target_layers)], + mask_token_id=args.vocab - 1, + block_size=args.block, + is_causal=True, + ) + model = JetSpecDraftModel(config).cuda().bfloat16() + model.freeze_embedding() + with torch.no_grad(): + for parameter in model.parameters(): + if parameter.requires_grad and parameter.dim() >= 2: + torch.nn.init.normal_(parameter, std=0.02) + return model + + +def _build_inputs(args): + device = torch.device("cuda") + dtype = torch.bfloat16 + generator = torch.Generator(device=device).manual_seed(args.seed) + batch, ctx_len = args.batch, args.ctx_len + draft_len = args.anchors * args.block + rows = batch * draft_len + active_rows = batch * args.anchors * (args.block - 1) + hidden_states = [ + torch.randn(batch, ctx_len, args.hidden, device=device, dtype=dtype, + generator=generator) + for _ in range(args.target_layers) + ] + noise = torch.randn(batch, draft_len, args.hidden, device=device, dtype=dtype, + generator=generator) + context_position_ids = torch.arange(ctx_len, device=device).unsqueeze(0).expand( + batch, -1).contiguous() + anchors = torch.randint(0, ctx_len - args.block, (batch, args.anchors), device=device, + generator=generator) + keep = torch.ones((batch, args.anchors), dtype=torch.bool, device=device) + offsets = torch.arange(args.block, device=device).view(1, 1, -1) + draft_position_ids = (anchors.unsqueeze(-1) + offsets).view(batch, -1) + mask_mod = _create_dflash_mask_mod( + anchor_positions=anchors, + block_keep_mask=keep, + ctx_len=ctx_len, + block_size=args.block, + is_causal=True, + ) + # Built once, outside every measured window. The training path uses a + # compiled builder; this attribution script avoids torch.compile because + # the mask is not part of the loss-side cells. + block_mask = create_block_mask( + mask_mod, + B=batch, + H=None, + Q_LEN=draft_len, + KV_LEN=ctx_len + draft_len, + device=device, + ) + lm_head = torch.randn(args.vocab, args.hidden, device=device, dtype=dtype, + generator=generator) + draft_logits = torch.randn(active_rows, args.vocab, device=device, dtype=dtype, + generator=generator).detach() + teacher_hidden = torch.randn(active_rows, args.hidden, device=device, dtype=dtype, + generator=generator) + hidden_states_flat = torch.randn(rows, args.hidden, device=device, dtype=dtype, + generator=generator) + return { + "rows": rows, + "active_rows": active_rows, + "hidden_states": hidden_states, + "noise": noise, + "context_position_ids": context_position_ids, + "draft_position_ids": draft_position_ids, + "block_mask": block_mask, + "lm_head": lm_head, + "draft_logits": draft_logits, + "teacher_hidden": teacher_hidden, + "hidden_states_flat": hidden_states_flat, + } + + +def _grad_norm(parameters): + total = 0.0 + elements = 0 + for parameter in parameters: + if not parameter.requires_grad or parameter.grad is None: + continue + gradient = parameter.grad.detach().float() + total += gradient.pow(2).sum().item() + elements += gradient.numel() + return math.sqrt(total), elements + + +def _measure(run, args, clear=None): + for _ in range(args.warmup): + run() + if clear is not None: + clear() + 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() + run() + end.record() + events.append((start, end)) + torch.cuda.synchronize() + peak = torch.cuda.max_memory_allocated() - peak_base + times = [start.elapsed_time(end) for start, end in events] + return _summary(times), peak + + +def _draft_cell(model, inputs, args): + trainable = [parameter for parameter in model.parameters() if parameter.requires_grad] + + def run(): + for parameter in trainable: + parameter.grad = None + context_feature = model.extract_context_feature(inputs["hidden_states"]) + output = model( + draft_input_ids=None, + context_feature=context_feature, + draft_position_ids=inputs["draft_position_ids"], + context_position_ids=inputs["context_position_ids"], + block_mask=inputs["block_mask"], + noise_embedding=inputs["noise"], + ) + output.float().sum().backward() + + timing, peak = _measure( + run, args, clear=lambda: [setattr(p, "grad", None) for p in trainable] + ) + run() + torch.cuda.synchronize() + norm, elements = _grad_norm(trainable) + return { + "cell": "draft", + "timing": timing, + "peak_extra_bytes": peak, + "fingerprint": { + "grad_norm": norm, + "grad_numel": elements, + }, + } + + +def _draft_logits_cell(inputs, args): + weight = inputs["lm_head"] + base = inputs["hidden_states_flat"] + hidden = base.clone().detach().requires_grad_(True) + + def run(): + hidden.grad = None + logits = F.linear(hidden, weight) + logits.float().sum().backward() + + timing, peak = _measure(run, args, clear=lambda: setattr(hidden, "grad", None)) + run() + torch.cuda.synchronize() + return { + "cell": "draft_logits", + "timing": timing, + "peak_extra_bytes": peak, + "fingerprint": { + "grad_norm": hidden.grad.detach().float().pow(2).sum().item() ** 0.5, + "grad_numel": hidden.grad.numel(), + }, + } + + +def _teacher_gemm_cell(inputs, args): + weight = inputs["lm_head"] + teacher = inputs["teacher_hidden"] + accumulator = torch.zeros((), dtype=torch.float32, device=teacher.device) + + def run(): + # The KL forward projects the teacher rows once and its backward + # recomputes the same frozen projection, so measure two passes. + with torch.no_grad(): + accumulator.add_(F.linear(teacher, weight).float().sum()) + accumulator.add_(F.linear(teacher, weight).float().sum()) + + timing, peak = _measure(run, args) + with torch.no_grad(): + probe = F.linear(teacher, weight) + return { + "cell": "teacher_gemm", + "timing": timing, + "peak_extra_bytes": peak, + "fingerprint": {"output_abs_sum": float(probe.float().abs().sum().item())}, + } + + +def _kl_cell(inputs, args, retain, fused, cell): + weight = inputs["lm_head"] + teacher = inputs["teacher_hidden"] + base = inputs["draft_logits"] + # The training step already holds the Draft logits, so the leaf lives + # outside the measured window instead of being cloned per iteration. + draft_logits = base.detach().clone().requires_grad_(True) + active = torch.arange(inputs["active_rows"], device=base.device) + + def run(): + draft_logits.grad = None + kl = _ChunkedForwardKL.apply( + draft_logits, teacher, weight, args.temperature, args.row_chunk, + active, retain, fused, + ) + kl.sum().backward() + return draft_logits.grad + + timing, peak = _measure( + run, args, clear=lambda: setattr(draft_logits, "grad", None) + ) + gradient = run() + torch.cuda.synchronize() + kl_value = float( + _ChunkedForwardKL.apply( + base.clone().detach().requires_grad_(True), teacher, weight, + args.temperature, args.row_chunk, active, retain, fused, + ).sum().item() + ) + return { + "cell": cell, + "timing": timing, + "peak_extra_bytes": peak, + "fingerprint": { + "loss": kl_value, + "grad_norm": float(gradient.detach().float().pow(2).sum().item() ** 0.5), + "grad_numel": gradient.numel(), + }, + } + + +def _kl_epilogue_cell(inputs, args): + weight = inputs["lm_head"] + teacher = inputs["teacher_hidden"] + base = inputs["draft_logits"] + with torch.no_grad(): + target_logits = F.linear(teacher, weight) + draft_logits = base.detach().clone().requires_grad_(True) + + def run(): + draft_logits.grad = None + kl = _ElementwiseKL.apply(draft_logits, target_logits, args.temperature, + args.row_chunk) + kl.sum().backward() + return draft_logits.grad + + timing, peak = _measure( + run, args, clear=lambda: setattr(draft_logits, "grad", None) + ) + gradient = run() + torch.cuda.synchronize() + with torch.no_grad(): + kl_value = float( + _ElementwiseKL.apply( + base.clone().detach().requires_grad_(True), target_logits, + args.temperature, args.row_chunk, + ).sum().item() + ) + return { + "cell": "kl_epilogue", + "timing": timing, + "peak_extra_bytes": peak, + "fingerprint": { + "loss": kl_value, + "grad_norm": float(gradient.detach().float().pow(2).sum().item() ** 0.5), + "grad_numel": gradient.numel(), + }, + } + + +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 + # The measured cells use the shipped eager flex_attention kernel; compiling + # it is not part of this attribution and is unavailable on some torch/triton + # pairings. Disabling dynamo keeps torch.compile a no-op here. + if hasattr(torch, "_dynamo"): + torch._dynamo.config.disable = True + + inputs = _build_inputs(args) + fused_supported = use_fused_jetspec_kl( + inputs["draft_logits"], inputs["lm_head"], torch.bfloat16, args.temperature + ) + if not fused_supported: + args.cells = [cell for cell in args.cells + if cell not in {"kl_fused", "kl_fused_retained"}] + if not args.cells: + raise SystemExit( + "requested cells are unavailable: fused JetSpec KL is not supported " + "on this device/runtime" + ) + model = None + if "draft" in args.cells: + model = _build_model(args) + + results = [] + for cell in args.cells: + torch.cuda.empty_cache() + if cell == "draft": + results.append(_draft_cell(model, inputs, args)) + elif cell == "draft_logits": + results.append(_draft_logits_cell(inputs, args)) + elif cell == "teacher_gemm": + results.append(_teacher_gemm_cell(inputs, args)) + elif cell == "kl": + results.append(_kl_cell(inputs, args, False, False, cell)) + elif cell == "kl_retained": + results.append(_kl_cell(inputs, args, True, False, cell)) + elif cell == "kl_fused": + results.append(_kl_cell(inputs, args, False, True, cell)) + elif cell == "kl_fused_retained": + results.append(_kl_cell(inputs, args, True, True, cell)) + else: + results.append(_kl_epilogue_cell(inputs, args)) + torch.cuda.synchronize() + + by_cell = {result["cell"]: result for result in results} + derived = {} + reference = by_cell.get("kl") + for name in ("kl_retained", "kl_fused", "kl_fused_retained"): + result = by_cell.get(name) + if reference is None or result is None: + continue + derived[f"{name}_saving_ms"] = ( + reference["timing"]["median_ms"] - result["timing"]["median_ms"] + ) + derived[f"{name}_loss_abs_delta"] = abs( + reference["fingerprint"]["loss"] - result["fingerprint"]["loss"] + ) + derived[f"{name}_loss_rel_delta"] = derived[f"{name}_loss_abs_delta"] / max( + abs(reference["fingerprint"]["loss"]), 1e-12 + ) + reference_grad = reference["fingerprint"]["grad_norm"] + derived[f"{name}_grad_norm_rel_delta"] = abs( + reference_grad - result["fingerprint"]["grad_norm"] + ) / max(reference_grad, 1e-12) + if "kl" in by_cell and "kl_epilogue" in by_cell: + derived["kl_teacher_overhead_ms"] = ( + by_cell["kl"]["timing"]["median_ms"] + - by_cell["kl_epilogue"]["timing"]["median_ms"] + ) + kl_loss = by_cell["kl"]["fingerprint"]["loss"] + epilogue_loss = by_cell["kl_epilogue"]["fingerprint"]["loss"] + derived["kl_loss_abs_delta"] = abs(kl_loss - epilogue_loss) + kl_grad = by_cell["kl"]["fingerprint"]["grad_norm"] + epilogue_grad = by_cell["kl_epilogue"]["fingerprint"]["grad_norm"] + derived["kl_grad_norm_rel_delta"] = abs(kl_grad - epilogue_grad) / max(kl_grad, 1e-12) + if "teacher_gemm" in by_cell: + derived["teacher_gemm_two_passes_ms"] = by_cell["teacher_gemm"]["timing"]["median_ms"] + + capability = torch.cuda.get_device_capability(0) + report = { + "script": "tools/performance/bench_jetspec_loss.py", + "scope": "loss-side forward+backward attribution on synthetic inputs; " + "no Target inference, transport, optimizer, convergence or acceptance claims", + "config": { + "cells": args.cells, + "hidden": args.hidden, + "intermediate": args.intermediate, + "vocab": args.vocab, + "layers": args.layers, + "q_heads": args.q_heads, + "kv_heads": args.kv_heads, + "head_dim": args.head_dim, + "target_layers": args.target_layers, + "block": args.block, + "anchors": args.anchors, + "ctx_len": args.ctx_len, + "batch": args.batch, + "rows": inputs["rows"], + "active_rows": inputs["active_rows"], + "temperature": args.temperature, + "row_chunk": args.row_chunk, + "warmup": args.warmup, + "iters": args.iters, + "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], + }, + "results": results, + "derived": derived, + "fused_supported": fused_supported, + "parity_tolerance": _PARITY_TOL, + } + text = json.dumps(report, indent=2, sort_keys=True) + print(text) + with open(args.out, "w", encoding="utf-8") as handle: + handle.write(text + "\n") + diverged = [ + name for name in ("kl_retained", "kl_fused", "kl_fused_retained") + if name in by_cell and not ( + derived.get(f"{name}_loss_rel_delta", math.inf) <= _PARITY_TOL + and derived.get(f"{name}_grad_norm_rel_delta", math.inf) <= _PARITY_TOL + ) + ] + if diverged: + raise SystemExit( + f"loss/gradient fingerprints diverged from the reference cell for " + f"{diverged} beyond {_PARITY_TOL:g}, or the reference cell was not " + f"measured; the timings in {args.out} do not describe the same objective" + ) + + +if __name__ == "__main__": + main()