Skip to content

perf(medusa): write retained forward logits with one whole-head GEMM - #74

Open
sysuTobo wants to merge 1 commit into
inclusionAI:mainfrom
sysuTobo:perf/medusa-whole-head-forward
Open

sysuTobo wants to merge 1 commit into
inclusionAI:mainfrom
sysuTobo:perf/medusa-whole-head-forward

Conversation

@sysuTobo

@sysuTobo sysuTobo commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Finalize the Medusa fused-CE forward path that #64 introduced: when logits are retained for backward, the forward vocabulary GEMM writes directly into the retained buffer with torch.mm(hidden, weight.t(), out=...) instead of copy_(F.linear(...)) chunk by chunk.

  • No chunk temporary, no D2D copy. The retained path issues one whole-head GEMM that writes into saved_logits; the recompute path keeps its bounded 256 MB scratch chunks.
  • Projection dtype contract. _projection_dtype(hidden, weight) reports what F.linear actually produces: FP64 stays FP64 (autocast never narrows it), autocast narrows FP32 (and BF16 under FP16 autocast) to its dtype, otherwise the operands promote. use_fused_medusa_ce and medusa_head_ce now require the effective projection dtype to be BF16, and every retained/recomputed buffer is allocated from the input dtype, so forward and backward always read the same precision.
  • Invalid-input semantics. An all -inf logits row keeps NaN in the NLL and the gradient, matching F.cross_entropy, instead of a silent finite value.

Refs #17. Follows #64 and the review conclusions from #71.

Verification

Loss-only A/B on the same host and inputs, tools/performance/bench_medusa_loss.py --mode both (reference / restructure / fused, 10 warmup, 30 iterations). The dtype-contract commit only touches the Python side of the BF16 path, so it does not change these numbers.

Host Environment Fused before Fused after Delta Peak extra
L20 (sm_89) CUDA 12.1, torch 2.8.0+cu121, Triton 3.4.0 731.07 ms 709.59 ms -21.48 ms (-2.94%) 9.08 GB (unchanged)
RTX 6000D (sm_120) CUDA 12.8, torch 2.11.0+cu128, Triton 3.6.0 561.64 ms 554.27 ms -7.37 ms (-1.31%) 9.08 GB (unchanged)
  • The reference and restructure cells move by less than 0.1% between arms; loss and gradient fingerprints are identical.
  • The saving matches the removed device-to-device traffic: 40 chunks × 312 MB ≈ 12.45 GB, about 7 ms at 1.8 TB/s on RTX 6000D and about 14–21 ms on L20. The cell is dominated by the three vocabulary GEMMs, so the relative gain is small.
  • Tests: tests/cpu/test_medusa.py 47 passed. tests/test_medusa_loss_kernel_gpu.py with ASPEC_RUN_GPU_INTEGRATION=1 on RTX 6000D: 22 passed, 2 skipped. Mutation check: removing the effective-dtype predicate fails test_autocast_dtype_mismatch_falls_back. These GPU results and the benchmark figures are author-run evidence: a diff-based review cannot execute them.

Not verified

  • Synthetic loss-only measurement; no Target inference, transport, optimizer, convergence or serving throughput.
  • The ok-path performance was measured before the dtype-contract commit; that commit is Python-only and leaves the BF16 path (and its numerics) unchanged.

Changes in aspec/models/ops/medusa_ce.py (verified in diff):

  • Adds _projection_dtype. It returns float64 when an operand is float64, the autocast dtype under autocast, and otherwise the promoted dtype.
  • use_fused_medusa_ce and medusa_head_ce reject a projection dtype other than BF16. medusa_head_ce reports the autocast-state requirement in its error.
  • Retained logits use one torch.mm(hidden, weight.t(), out=saved_logits) call. The chunked path remains when logits are not saved.
  • Buffers use hidden.dtype instead of hard-coded BF16.

Not verified from the diff: the 22-test GPU result, the all--inf NaN behavior, and the benchmark figures. These are author-reported only.

@coderabbitai

coderabbitai Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The fused Medusa CE path now checks the effective projection dtype, uses hidden-state dtypes for projection buffers, and computes saved logits with one full matrix multiplication. GPU tests cover autocast eligibility and NaN losses and gradients.

Changes: Medusa CE path

Layer / File(s) Summary
Projection dtype eligibility
aspec/models/ops/medusa_ce.py, tests/test_medusa_loss_kernel_gpu.py
The fused-path predicate and medusa_head_ce now check the effective projection dtype. Tests verify that FP16 autocast disables the fused path and BF16 autocast keeps it enabled.
Logit projection and buffer dtypes
aspec/models/ops/medusa_ce.py, tests/test_medusa_loss_kernel_gpu.py
When logits are saved, forward computes the full projection into the retained buffer before running the statistics kernels. Forward and backward buffers use the hidden-state dtype. Tests verify NaN losses and gradients for all-negative-infinity logits.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Possibly related issues

  • inclusionAI/ASpec#17: This PR changes the Medusa head loss path used by the issue’s draft-training objective, but does not implement the full training recipe.

Possibly related PRs

  • inclusionAI/ASpec#64: This PR updates the fused Triton CE path and predicate introduced in PR #64.

Suggested reviewers: zhouaihui

Merge Risk: Low · up to 5ac62

This changes how the fused Medusa loss computes and stores logits, and which dtypes it accepts. Reported tests and benchmarks show unchanged numerics and a small speedup. Reviewers found no concrete defect, but the path is a numerics-sensitive training kernel and was not independently run on GPU. It is mergeable with owner awareness.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title 'perf(medusa): write retained forward logits with one whole-head GEMM' names the primary change: the retained-logits forward path now writes into the saved buffer with a single whole-head GE…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description is thorough and follows the template's intent. It states the outcome: the retained-logits forward path now uses one whole-head GEMM, and the projection dtype contract changes. It cover…
Full details: Title check

Explanation

The title 'perf(medusa): write retained forward logits with one whole-head GEMM' names the primary change: the retained-logits forward path now writes into the saved buffer with a single whole-head GEMM. The changeset also adds a projection dtype contract and NaN handling for all -inf rows, which the title does not mention, but those are secondary. The title is specific, concise, and single-sentence.

Full details: Description check

Explanation

The description is thorough and follows the template's intent. It states the outcome: the retained-logits forward path now uses one whole-head GEMM, and the projection dtype contract changes. It covers verification with a benchmark table, environments, CPU and GPU test counts, and a mutation check. It also has a Not verified section listing the limits of the synthetic loss-only measurement. The template's Compatibility and provenance section is not addressed. The description does not state public config, checkpoint, or export implications, and it does not mention upstream source or license updates. The description also does not say whether the public error text or API behavior change for users of use_fused_medusa_ce and medusa_head_ce, which is a user-visible change. These gaps are non-critical, so the check passes.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between b946dc5 and 5ac62bc.

Files selected for processing: 2

  • aspec/models/ops/medusa_ce.py
  • tests/test_medusa_loss_kernel_gpu.py

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

When logits are retained for backward, the forward vocabulary GEMM now writes
directly into the retained buffer with torch.mm(hidden, weight.t(), out=...)
instead of copying chunk results into it. This removes the chunk-sized
temporary and reads the vocabulary weight once per head instead of once per
chunk. The recompute path keeps its bounded scratch chunks.

The fused epilogue now follows the projection dtype: `_projection_dtype`
reports what F.linear actually produces (autocast narrows BF16 inputs to FP16
and never narrows FP64), `use_fused_medusa_ce` and `medusa_head_ce` reject a
non-BF16 effective projection, and every retained or recomputed buffer is
allocated from the input dtype. Tests cover the autocast fallback and an
all -inf row that must stay NaN.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant