diff --git a/aspec/models/ops/medusa_ce.py b/aspec/models/ops/medusa_ce.py index 8542e10..90a55c1 100644 --- a/aspec/models/ops/medusa_ce.py +++ b/aspec/models/ops/medusa_ce.py @@ -75,6 +75,22 @@ def _is_compiling() -> bool: return bool(is_compiling()) if is_compiling is not None else False +def _projection_dtype(hidden: torch.Tensor, weight: torch.Tensor) -> torch.dtype: + """Dtype ``F.linear`` produces for the head projection. + + Autocast narrows float32 inputs to its dtype (including bfloat16 inputs + under float16 autocast) but never narrows float64, so the fused epilogue + may only run when the effective dtype is bfloat16. Lightweight stand-ins + without a real ``torch.device`` are treated as not autocast. + """ + if hidden.dtype == torch.float64 or weight.dtype == torch.float64: + return torch.float64 + device = hidden.device + if isinstance(device, torch.device) and torch.is_autocast_enabled(device.type): + return torch.get_autocast_dtype(device.type) + return torch.promote_types(hidden.dtype, weight.dtype) + + def _resolve_row_chunk(vocab: int, requested: int | None) -> int: if requested is not None: if requested <= 0: @@ -121,6 +137,8 @@ def use_fused_medusa_ce( return False if hidden.dtype is not torch.bfloat16 or weight.dtype is not torch.bfloat16: return False + if _projection_dtype(hidden, weight) is not torch.bfloat16: + return False if hidden.ndim != 2 or weight.ndim != 2: return False if hidden.shape[1] != weight.shape[1]: @@ -270,8 +288,10 @@ def forward( 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) + # The projection has already been validated to be BF16, so every + # retained/recomputed buffer carries the projection dtype. saved_logits = ( - torch.empty((rows, vocab), device=device, dtype=torch.bfloat16) + torch.empty((rows, vocab), device=device, dtype=hidden.dtype) if save_logits else None ) @@ -279,36 +299,32 @@ def forward( None if save_logits else torch.empty( - (min(forward_chunk, rows), vocab), device=device, dtype=torch.bfloat16 + (min(forward_chunk, rows), vocab), device=device, dtype=hidden.dtype ) ) 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], + if saved_logits is not None: + # One whole-head GEMM writing straight into the retained buffer: + # no chunk-sized temporary and one weight read per head. + torch.mm(hidden, weight.t(), out=saved_logits) + _ce_partials[(rows, tiles)]( + saved_logits, + targets, + partials, 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], + _merge_stats[(rows,)]( + partials, + row_max, + log_total, + nll, + hits, + targets, tiles, block_tiles, vocab, @@ -316,6 +332,36 @@ def forward( debug=True, enable_fp_fusion=False, ) + else: + for start in range(0, rows, forward_chunk): + stop = min(start + forward_chunk, rows) + count = stop - start + 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( @@ -328,7 +374,7 @@ def forward( targets, row_max, log_total, - torch.empty(0, device=device, dtype=torch.bfloat16), + torch.empty(0, device=device, dtype=hidden.dtype), ) ctx.row_chunk = forward_chunk ctx.save_logits = save_logits @@ -361,12 +407,12 @@ def backward(ctx, grad_nll, grad_hits): else torch.empty( (min(backward_chunk, rows), vocab), device=hidden.device, - dtype=torch.bfloat16, + dtype=hidden.dtype, ) ) if rows * vocab * 2 <= _DLOGITS_BUDGET_BYTES: dlogits = torch.empty( - (rows, vocab), device=hidden.device, dtype=torch.bfloat16 + (rows, vocab), device=hidden.device, dtype=hidden.dtype ) for start in range(0, rows, backward_chunk): stop = min(start + backward_chunk, rows) @@ -405,7 +451,7 @@ def backward(ctx, grad_nll, grad_hits): 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 + (count, vocab), device=hidden.device, dtype=hidden.dtype ) _dlogits[(count, tiles)]( logits_chunk, @@ -451,6 +497,11 @@ def medusa_head_ce( 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 _projection_dtype(hidden, weight) is not torch.bfloat16: + raise ValueError( + "fused Medusa CE requires a BF16 projection under the current " + "autocast state" + ) 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]: diff --git a/tests/test_medusa_loss_kernel_gpu.py b/tests/test_medusa_loss_kernel_gpu.py index bd7aadc..b965281 100644 --- a/tests/test_medusa_loss_kernel_gpu.py +++ b/tests/test_medusa_loss_kernel_gpu.py @@ -222,6 +222,34 @@ def test_nonfinite_input_produces_nonfinite_nll(): assert torch.isnan(ref_nll[0]) +def test_all_negative_inf_logits_propagate_nan(): + tokens, hidden, vocab = 128, 64, 4096 + x = torch.full((tokens, hidden), float("-inf"), device="cuda", + dtype=torch.bfloat16, requires_grad=True) + w = torch.ones(vocab, hidden, device="cuda", dtype=torch.bfloat16, + requires_grad=True) + targets = torch.randint(0, vocab, (tokens,), device="cuda") + nll, _ = medusa_head_ce(x, w, targets, save_logits=True) + ref_nll, _ = _reference(x.detach(), w.detach(), targets) + assert torch.isnan(nll).all() + assert torch.isnan(ref_nll).all() + nll.sum().backward() + assert torch.isnan(x.grad).all() + assert torch.isnan(w.grad).all() + + +def test_autocast_dtype_mismatch_falls_back(): + # F.linear narrows BF16 inputs to FP16 under FP16 autocast, so the fused + # BF16 epilogue must not run there. + x, w, targets = _tensors(128, 64, 4096) + with torch.autocast("cuda", dtype=torch.float16): + assert not use_fused_medusa_ce(x, w) + with pytest.raises(ValueError, match="autocast"): + medusa_head_ce(x, w, targets) + with torch.autocast("cuda", dtype=torch.bfloat16): + assert use_fused_medusa_ce(x, w) + + def _small_model(gradient_checkpointing): config = MedusaConfig( hidden_size=32,