Repository navigation
Conversation
- 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
kevssim
reviewed
Nov 16, 2026
- 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
kevssim
approved these changes
Nov 17, 2026
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 inselective_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 intograd_x/grad_weightwith two GEMMs._ChunkedSelectiveLogProbFunction(fused linear, hidden+weight)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):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 missingtriton-ascendinstall no longer fails after the model forward.Correctness (criterion: native PyTorch, assert_close thresholds)
rtol=1e-4, atol=1e-5; BF16rtol=1.6e-2, atol=1e-2— no threshold relaxedgrad_x/grad_weightchecked elementwise againstF.linear -> log_softmax -> gatherV=151936); coverage includes mixed FP32 hidden + BF16 weight, BF16 entropy-only backward (grad_logps=None), frozen-weightgrad_x, repeated-backward rejection, float/int32/out-of-range target handling, and an NPU BF16 reference-fallback path when Triton discovery fails_ChunkedSelectiveLogProbFunctionon identical inputs: logp/grads agree within tolerancePerformance (Ascend 910B4, V=151936, hidden=2048, forward+backward)
Single op, vs native
F.linear -> log_softmax -> gather(and vs Liger where applicable):End-to-end 100-step training, Qwen3-1.7B BF16, 2048 tokens/step, identical config and data:
Honest limitations (please read before reviewing)
main. Performance claims are BF16-only.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.grad_x/grad_weightGEMMs are standardtorch.mm; everything else in forward runs on Triton-Ascend kernels.