Skip to content

Commit 5ec684f

Browse files
author
BoHao Tu
authored
perf(medusa): fuse full-vocabulary CE and bound its memory (#64)
* 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 * 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 * 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 * 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
1 parent e1da445 commit 5ec684f

7 files changed

Lines changed: 1573 additions & 21 deletions

File tree

‎aspec/models/medusa.py‎

Lines changed: 86 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,69 @@
1515
from torch.nn import functional as F
1616
from torch.utils.checkpoint import checkpoint
1717

18+
from aspec.models.ops.medusa_ce import medusa_head_ce, use_fused_medusa_ce
19+
20+
# Retaining BF16 logits removes one projection pass in backward. Bound the
21+
# all-head retained bytes so gradient checkpointing still protects long
22+
# sequences; 4K/Qwen3-8B/K=5 (about 5.8 GiB) uses the faster saved mode.
23+
SAVE_LOGITS_BUDGET_BYTES = 8 * 1024**3
24+
25+
26+
def should_save_fused_logits(tokens, vocab, num_heads, gradient_checkpointing):
27+
if not gradient_checkpointing:
28+
return True
29+
retained = tokens * vocab * 2 * num_heads
30+
return retained <= SAVE_LOGITS_BUDGET_BYTES
31+
1832

1933
class MedusaModel(nn.Module):
2034
def __init__(self, draft_model, gradient_checkpointing=False):
2135
super().__init__()
22-
# Chunked CE retains each chunk's f32 logits until backward
23-
# (~chunk x vocab x 4 bytes per head); long-sequence training should
24-
# enable gradient_checkpointing, as the maintained recipes do.
36+
# The reference path retains each chunk's FP32 logits until backward.
37+
# The fused path instead uses the budget below: small selections retain
38+
# BF16 logits and skip one projection pass; long selections recompute.
2539
self.draft_model = draft_model
2640
self.num_heads = draft_model.medusa_num_heads
2741
self.gradient_checkpointing = gradient_checkpointing
2842
self.vocab_pruning = False
2943

44+
def _save_fused_logits(self, tokens, vocab):
45+
return should_save_fused_logits(
46+
tokens, vocab, self.num_heads, self.gradient_checkpointing
47+
)
48+
49+
def _reference_head_loss(
50+
self,
51+
head,
52+
features,
53+
input_ids_row,
54+
feature_positions,
55+
label_positions,
56+
selected,
57+
):
58+
"""Reference per-head CE at the t+2+i offset, one head."""
59+
total = features.new_zeros((), dtype=torch.float32)
60+
hits = features.new_zeros((), dtype=torch.float32)
61+
for indices in selected.split(128):
62+
targets = input_ids_row.index_select(
63+
0, label_positions.index_select(0, indices))
64+
chunk_features = features.index_select(
65+
0, feature_positions.index_select(0, indices))
66+
67+
def loss_chunk(chunk_features, targets, head=head):
68+
logits = head(chunk_features)
69+
return (F.cross_entropy(logits.float(), targets, reduction="sum"),
70+
(logits.argmax(-1) == targets).float().sum())
71+
72+
if self.gradient_checkpointing and self.training and torch.is_grad_enabled():
73+
loss, chunk_hits = checkpoint(loss_chunk, chunk_features, targets,
74+
use_reentrant=False)
75+
else:
76+
loss, chunk_hits = loss_chunk(chunk_features, targets)
77+
total = total + loss
78+
hits = hits + chunk_hits.detach()
79+
return total, hits
80+
3081
def forward(self, input_ids, hidden_states, loss_mask, attention_mask, thd_layout=None):
3182
if thd_layout is not None:
3283
raise NotImplementedError("Medusa currently supports padded CP1 execution only")
@@ -54,24 +105,38 @@ def forward(self, input_ids, hidden_states, loss_mask, attention_mask, thd_layou
54105
feature_positions = label_positions - offset
55106
keep = loss_mask[row].index_select(0, label_positions).bool()
56107
selected = keep.nonzero().flatten()
57-
for indices in selected.split(128):
58-
targets = input_ids[row].index_select(
59-
0, label_positions.index_select(0, indices))
60-
chunk_features = features.index_select(
61-
0, feature_positions.index_select(0, indices))
62-
63-
def loss_chunk(chunk_features, targets, head=head):
64-
logits = self.draft_model.medusa_head[head](chunk_features)
65-
return (F.cross_entropy(logits.float(), targets, reduction="sum"),
66-
(logits.argmax(-1) == targets).float().sum())
67-
68-
if self.gradient_checkpointing and self.training and torch.is_grad_enabled():
69-
loss, hits = checkpoint(loss_chunk, chunk_features, targets,
70-
use_reentrant=False)
71-
else:
72-
loss, hits = loss_chunk(chunk_features, targets)
73-
sums[head] = sums[head] + loss
74-
correct[head] = correct[head] + hits.detach()
108+
head_module = self.draft_model.medusa_head[head]
109+
if selected.numel() and use_fused_medusa_ce(
110+
features,
111+
head_module[-1].weight,
112+
num_rows=selected.numel(),
113+
):
114+
selected_features = features.index_select(
115+
0, feature_positions.index_select(0, selected))
116+
selected_labels = label_positions.index_select(0, selected)
117+
targets = input_ids[row].index_select(0, selected_labels)
118+
projected = head_module[:-1](selected_features)
119+
nll, hits = medusa_head_ce(
120+
projected,
121+
head_module[-1].weight,
122+
targets,
123+
save_logits=self._save_fused_logits(
124+
selected.numel(), head_module[-1].weight.shape[0]
125+
),
126+
)
127+
sums[head] = sums[head] + nll.sum()
128+
correct[head] = correct[head] + hits.sum()
129+
elif selected.numel():
130+
loss_sum, hits_sum = self._reference_head_loss(
131+
head_module,
132+
features,
133+
input_ids[row],
134+
feature_positions,
135+
label_positions,
136+
selected,
137+
)
138+
sums[head] = sums[head] + loss_sum
139+
correct[head] = correct[head] + hits_sum
75140
counts[head] = counts[head] + selected.numel()
76141
losses = [value / count.clamp_min(1) for value, count in zip(sums, counts, strict=True)]
77142
return (losses, [value.detach() for value in losses],

0 commit comments

Comments
 (0)