Skip to content

perf(utils): reduce selective_log_softmax allocations and reuse Ascend CE for FP32 logp - #386

Merged
kevssim merged 4 commits into
modelscope:mainfrom
diaochengxi:codex/perf-selective-logsoftmax-backward
Nov 17, 2026
Merged

kevssim merged 4 commits into
modelscope:mainfrom
diaochengxi:codex/perf-selective-logsoftmax-backward

Conversation

@diaochengxi

@diaochengxi diaochengxi commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

perf(utils): reduce selective_log_softmax allocations and reuse Ascend CE for FP32 logp

Background and motivation

RL, DPO, and GRPO training need per-token log-probabilities. GRPO with an entropy bonus also needs per-token entropy. Twinkle's generic selective_log_softmax currently creates one autograd node per vocabulary chunk:

  • Forward uses chunking to bound the size of wide-dtype temporaries.
  • Backward still produces one full chunk gradient per chunk, then assembles the complete [tokens, vocab] gradient through SliceBackward.
  • More chunks mean more allocations, zeroing, slicing, and accumulation of full-sized buffers.

The FP32 logp-only path also uses per-chunk logsumexp + gather with a custom backward. On A2, this path takes 2.91 ms for 256x151936, which is slower than the 2.20 ms direct materialized PyTorch path. This PR addresses both issues:

  • Move the chunk loop into one autograd node and allocate one compact gradient buffer in backward.
  • Reuse Ascend torch_npu.npu_cross_entropy_loss for FP32 logp-only instead of adding an equivalent kernel to Twinkle.

Relationship to upstream capabilities

Implementation Input Entropy Treatment in this PR
torch_npu.npu_cross_entropy_loss materialized logits No Reused directly for NPU FP32 logp-only
Liger fused_linear_ppo hidden + weight No Different call path; not reimplemented
PR #385 fused lm_head hidden + weight Yes Independent PR; this PR does not modify that path
Twinkle generic fallback materialized logits Yes Removes repeated backward buffers while preserving chunked semantics

This PR adds no public parameters, dependencies, or opt-in switches. All existing selective_log_softmax call sites benefit automatically:

  • NPU + FP32 + logp-only uses the vendor fused cross-entropy op.
  • If torch_npu is unavailable, the API is missing, or the installed signature is incompatible, the implementation falls back to Twinkle's custom autograd path.
  • BF16, FP64, entropy, and CPU paths do not enter the vendor fast path.

Relationship to PR #385

PR #385's _fused_rl_logps() calls fused_linear_selective_log_softmax directly and bypasses the generic selective_log_softmax changed here. The two changes can coexist, but their performance gains do not compose. Combining them would enlarge the review surface and obscure performance attribution, so they remain independent.

Correctness

The required tolerances are not relaxed:

  • FP32: rtol=1e-4, atol=1e-5
  • BF16: rtol=1.6e-2, atol=1e-2

Coverage includes:

  • logp, entropy, and joint logp+entropy outputs;
  • input gradients with respect to logits;
  • non-contiguous logits, int32 indices, and repeated backward;
  • FP64 gradcheck;
  • NPU cross-entropy output and input-gradient agreement with log_softmax + gather;
  • the real A2 torch_npu.npu_cross_entropy_loss contract with V=151936; the test fails if the vendor helper falls back to None;
  • fallback when the torch_npu API is missing or its signature is incompatible.

Verification results:

Local: tests/utils/test_utils.py tests/utils/test_sampling_replay.py
80 passed, 1 skipped

A2: TestSelectiveLogSoftmax
17 passed

Repository pre-commit hooks (both changed files)
All passed

Performance

Primary baseline: pre-change Twinkle

A2 910B4, 32 GB, torch_npu 2.10.0, V=151936; single-op forward plus input gradient:

Scenario Pre-change Twinkle Candidate Speedup Peak-memory change
BF16 logp, 1024 rows 34.94 ms 10.94 ms 3.20x -2.8%
BF16 logp+entropy, 1024 rows 61.00 ms 24.04 ms 2.54x -8.5%
FP32 logp, 256 rows 6.30 ms 1.46 ms 4.33x -5.0%
FP32 logp+entropy, 256 rows 10.78 ms 5.82 ms 1.85x -5.7%

These numbers are the primary merge-benefit evidence for this PR.

Regression boundary: direct materialized native PyTorch

Native log_softmax + gather is a single-operator regression boundary, not an end-to-end model baseline. It materializes the complete log-softmax once, which is faster but uses more peak memory.

Scenario Native PyTorch Candidate Speed / peak memory
BF16 logp, 1024 rows 11.50 ms / 3.74 GB 10.94 ms / 1.85 GB 1.05x / -50.6%
BF16 logp+entropy, 1024 rows 34.16 ms / 4.98 GB 24.04 ms / 1.72 GB 1.42x / -65.4%
FP32 logp, 256 rows 2.20 ms / 1.09 GB 1.46 ms / 0.95 GB 1.51x / -12.7%
FP32 logp, 1024 rows 8.52 ms / 4.36 GB 4.35 ms / 3.75 GB 1.96x / -13.9%
FP32 logp+entropy, 256 rows 7.92 ms / 1.40 GB 5.82 ms / 0.91 GB 1.36x / -34.9%

Key result: FP32 logp-only previously measured 0.75x versus direct PyTorch. It now measures 1.51x-1.96x while retaining lower peak memory.

End-to-end training

Qwen3-0.6B, BF16, B=2, S=512, entropy coefficient 0.01, fixed inputs, SGD, 50 steps:

Comparison Baseline Candidate Result
Pre-change Twinkle 234.47 ms/step 207.54 ms/step Throughput +12.97%
Native PyTorch 207.90 ms/step 207.54 ms/step Throughput +0.17%
  • Versus pre-change Twinkle, the maximum per-step loss difference is 0.
  • Versus native PyTorch, the maximum loss difference over 50 steps is 0.00403.
  • Versus native PyTorch, peak memory changes from 6.94 GB to 5.39 GB (-22.3%).

ZerosLike operations attributed to the selective path in msprof:

28.16 ms / 453 calls -> 3.59 ms / 339 calls

Honest limitations

  • End-to-end peak memory is effectively unchanged versus pre-change Twinkle. Step peak memory is dominated by the model, activations, and optimizer state. Single-operator memory savings must not be presented as end-to-end memory savings.
  • Native PyTorch is not the primary baseline. The direct materialized path and Twinkle's chunked recomputation path have different memory semantics. The native comparison only demonstrates that the single-operator regression has been fixed.
  • Only A2 910B4 has been validated so far. A3/A5, multiple NPUs, FSDP2, and SP/CP require follow-up matrices.
  • The vocabulary tensor-parallel path is unchanged. TP behavior remains as before.
  • The vendor API contract is external. The signature and numerical contract of torch_npu.npu_cross_entropy_loss should be covered by NPU CI as CANN and torch_npu evolve. Capability detection and fallback are included in this PR.

Evidence boundaries

  • Single-operator measurements use the same device, shape, and dtype, with 3 warmup iterations and 10 timed iterations. The reported value is the mean; per-iteration samples were retained.
  • Output and input-gradient torch.testing.assert_close checks run before timing. A numerical failure prevents performance results from being produced.
  • End-to-end measurements use fixed synthetic batches to control numerical differences and do not replace convergence validation on a real dataset.
  • Upstream citest and citest-npu still require maintainer approval.

- Verify the missing torch_npu cross-entropy API returns None so the generic autograd path remains available
- Verify an incompatible vendor signature falls back instead of failing at the end of the NPU path
- Keep the regressions CPU-only and independent of an installed torch_npu runtime
@diaochengxi diaochengxi changed the title perf(utils): reduce selective_log_softmax backward allocations perf(utils): reduce selective_log_softmax allocations and reuse Ascend CE for FP32 logp Nov 15, 2026
Comment thread tests/utils/test_utils.py Resolved
- Exercise the real torch_npu FP32 cross-entropy fast path on A2 with V=151936
- Compare both selected log-probabilities and logits gradients against log_softmax + gather
- Keep the test skipped on CPU-only environments
- Fail the A2 contract test if the vendor helper falls back to None
- Preserve output and gradient checks against log_softmax + gather
@diaochengxi
diaochengxi requested a review from kevssim November 16, 2026 14:10
@kevssim
kevssim merged commit 3b1246d 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