Skip to content

perf(kernel): fuse Ascend lm_head with selective log-softmax (+entropy) - #385

Merged
kevssim merged 5 commits into
modelscope:mainfrom
diaochengxi:perf/fused-linear-selective-log-softmax
Nov 17, 2026
Merged

kevssim merged 5 commits into
modelscope:mainfrom
diaochengxi:perf/fused-linear-selective-log-softmax

Conversation

@diaochengxi

@diaochengxi diaochengxi commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

perf(kernel): fuse Ascend lm_head with selective log-softmax (+entropy)

Motivation

RL post-training losses (GRPO and friends) need per-token log-probabilities of the sampled tokens, and GRPO with an entropy bonus (entropy_coef > 0, src/twinkle/loss/grpo.py) additionally needs per-token entropies. On Ascend, the current path materializes the full [tokens, vocab] logits in the model forward and then reduces them again in selective_log_softmax — the largest activation in the whole training step, paid twice.

This PR fuses the lm_head projection with the selective log-softmax (and optional entropy) into one custom autograd op that never exposes logits: the [rows, V] logits workspace is allocated once inside the op, transformed in-place into its gradient in backward, then folded into grad_x/grad_weight with two GEMMs.

Existing implementation Input Entropy
Liger _ChunkedSelectiveLogProbFunction (fused linear, hidden+weight) hidden+weight no
Liger Ascend GRPO kernel materialized logits no
TRL logprob_entropy materialized logits yes

The logp-only case is covered by Liger, so this PR positions it as an optimization of the existing RL path with a head-to-head comparison (below), not as a new capability. Computing entropy requires the full probability distribution; a combination that first materializes logits to get it forfeits the fusion, which is why the logp+entropy contract has no in-place equivalent today.

Usage

Opt in per-loss via the model forward task (same mechanism as fused_lm_ce):

model(inputs, task='fused_lm_rl', labels=labels)

Requires a logp-only loss (require_logps, no logits/value/replay). Sampling replay, return_logits, value outputs, SP/CP, sharded or biased lm_head are explicitly rejected with clear errors. FP32 inputs and non-NPU devices fall back to the native reference path (see "FP32" below). BF16 NPU inputs also fall back to the reference when the optional Triton runtime is unavailable, so a missing triton-ascend install no longer fails after the model forward.

Correctness (criterion: native PyTorch, assert_close thresholds)

  • FP32 rtol=1e-4, atol=1e-5; BF16 rtol=1.6e-2, atol=1e-2 — no threshold relaxed
  • Forward outputs and grad_x/grad_weight checked elementwise against F.linear -> log_softmax -> gather
  • A2 verification: 42 passed for kernel and model-wiring tests excluding the real-vocab cases, plus 4 additional real-vocabulary NPU cases passed (V=151936); coverage includes mixed FP32 hidden + BF16 weight, BF16 entropy-only backward (grad_logps=None), frozen-weight grad_x, repeated-backward rejection, float/int32/out-of-range target handling, and an NPU BF16 reference-fallback path when Triton discovery fails
  • Cross-checked against Liger _ChunkedSelectiveLogProbFunction on identical inputs: logp/grads agree within tolerance
  • 100-step end-to-end (Qwen3-1.7B, BF16, 2048 tokens, fixed trajectories, SGD): max loss deviation 1.63e-6 (GRPO) / 3.58e-5 (GRPO+entropy)

Performance (Ascend 910B4, V=151936, hidden=2048, forward+backward)

Single op, vs native F.linear -> log_softmax -> gather (and vs Liger where applicable):

BF16 scenario vs native vs Liger fused-linear peak alloc vs native
logp, 256–2048 rows 1.55–1.65× faster 2.8–10× faster 1.4–1.9 GB lower
logp+entropy, 256–2048 rows 2.61–2.64× faster (no entropy support) 0.6–4.3 GB lower

End-to-end 100-step training, Qwen3-1.7B BF16, 2048 tokens/step, identical config and data:

Scenario Median step Throughput Max loss diff
GRPO 891.7 → 710.1 ms (−20.4%) +25.6% 1.63e-6
GRPO + entropy 1063.2 → 727.5 ms (−31.6%) +46.1% 3.58e-5

Honest limitations (please read before reviewing)

  • FP32 does not use the fused kernel. The strict FP32 gradient tolerance (1e-4/1e-5) requires native-order reductions; measured on-device, a bit-exact native-order recompute is slower than the native pipeline itself (111 vs 97 ms at 2048 rows), and a closed-form kernel deviates by 7e-5 (above tolerance) after the 151936-term gradient reduction. So FP32 (and non-NPU devices) route to the native reference: bit-identical numerics, identical performance to main. Performance claims are BF16-only.
  • Triton is optional. BF16 NPU fusion requires triton-ascend. If the Triton runtime is unavailable, dispatch now falls back to the native reference rather than raising a bare import error after the model forward. This fallback is exercised by an NPU BF16 regression, in addition to the CPU-only dispatch matrix.
  • End-to-end peak memory is unchanged — the step peak is dominated by optimizer states; the op-level memory savings (1.4–4.3 GB) show at the operator level, not the training-loop level.
  • The range check on targets costs ~1 ms per call (one device sync) and is included in all numbers above.
  • Backward's final grad_x/grad_weight GEMMs are standard torch.mm; everything else in forward runs on Triton-Ascend kernels.

- Use int64 row * vocab address arithmetic in the Triton kernels
  (int32 overflows above ~14k rows at V=151936)
- Reject non-integer target dtypes instead of silently truncating
  floats, and validate the vocabulary range like native gather
- Route FP32 on NPU to the native reference: the strict FP32 gradient
  tolerance requires native-order reductions, which measured slower
  than the native pipeline itself, so only the BF16 path ships a
  fused kernel
- Add real-vocabulary (V=151936) regressions and target-validation
  tests; NPU suite: 33 passed
- Compute entropy's E_p[z] with a dedicated Triton kernel instead of
  native per-chunk reductions (masked lanes contribute zero to avoid
  exp(-inf) * -inf = NaN); the full forward path now runs on Triton
- Fold the duplicated fused_lm_rl parallelism/validation setup in both
  transformers forward paths into one _check_fused_rl_task helper
- Fall back to the native reference when triton-ascend is unavailable instead of raising after the model forward
- Exercise the real BF16 kernel for entropy-only backward and frozen-weight grad_x behavior
- Compare frozen-weight logps and grad_x against the native reference within BF16 tolerances
- Add an NPU BF16 regression that forces Triton discovery to fail and validates the reference fallback
- Cover output and gradients through the actual dispatch entry point
@diaochengxi
diaochengxi requested a review from kevssim November 16, 2026 10:39
@kevssim
kevssim merged commit c473062 into modelscope:main Nov 17, 2026
2 of 3 checks passed
tastelikefeet added a commit that referenced this pull request Nov 28, 2026
main carried 17 commits (#311..#291) over merge-base 96dab68. v5 had already ported
everything up to #312 (a4ddc3b) and moved server/client to twinkle_cs, so:

- server/client (src/twinkle/server, twinkle_cs/*, tests/server, tests/twinkle_client):
  kept the v5 tree; the legacy src/twinkle/server path and the old ci_container_test.sh
  stay removed on v5.
- loss: #291 detached DFT weights, #335 Liger CE contract (delegates micro_batch_scale /
  batch_normalizer to CrossEntropyLoss), #334 chunked CE comments, #336 InfoNCE tests.
- model: #343 Torch.empty_cache (auto-merged), #385 fused_lm_rl ported onto the v5 task
  registry (processor/tasks.py + model/tasks.py FusedRL + transformers postprocess),
  #386 NPU fused CE fast path in selective_log_softmax.
- twinkle_agentic: #345 check kinds (hidden_python / sql_query / answer_one_of /
  answer_number / web_receipt / lean) adapted to the episode-scoped Env interface;
  AgenticChallenger gains the _verify_check / _proposal_reward hooks.

Known: cookbook/rsi and tests/cookbook/rsi (#345) are written against main's stateless
Env / AgenticChallenger API and do not run on v5 yet.
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.

2 participants