Skip to content

perf(unsloth): skip ignored rows in LM head projection - #1127

Open
rapidSpace wants to merge 1 commit into
OpenPipe:mainfrom
rapidSpace:perf/unsloth-selective-lm-head
Open

rapidSpace wants to merge 1 commit into
OpenPipe:mainfrom
rapidSpace:perf/unsloth-selective-lm-head

Conversation

@rapidSpace

Copy link
Copy Markdown

Summary

The Unsloth logprob pass projects every sequence position through the vocabulary-sized LM head, but loss_fn masks out every non-assistant position right afterwards. This selects the assistant rows before the projection and scatters the results back, mirroring the selective LM head that the Megatron backend already uses (LmHeadTokenSelection).

Since RL batches are usually prompt-heavy, the skipped rows are often the majority of the sequence.

Changes

  • compute_loss derives row_mask from the shifted assistant_mask and passes it to both the policy and the KL reference logprob calls.
  • _calculate_logprobs takes an optional row_mask, projects only the selected rows in each chunk, and writes the results back into the [B, S] output. Fully masked chunks are skipped without touching the LM head.
  • Output buffers are zero-initialized instead of torch.empty, because ignored positions are no longer written.
  • If the mask selects nothing, one row is kept selected so the batch still produces a graph and backward() stays valid.
  • row_mask defaults to None, so existing callers and the returned shapes are unchanged.

Correctness

The transformation is exact: selected rows compute the same matmul as before, and ignored rows were multiplied by zero in the loss anyway. On real Qwen3-0.6B hidden states (fp32 reference), masked and unmasked paths agree on logprobs and entropy exactly, with a hidden-state gradient relative error of 7e-7. A real RL run (3 optimizer steps, KL=0.05) produces finite loss, entropy, KL and grad-norm with no NaN gradients.

Benchmarks

RTX A6000, Qwen3-0.6B, bf16, S=4096, chunk=1024, LoRA r=16.

LM head projection (forward + backward):

assistant tokens before after speedup
50% 86.1 ms 46.0 ms 1.87x
25% 86.0 ms 23.8 ms 3.61x
10% 85.9 ms 10.0 ms 8.57x

Full training step:

assistant tokens before after speedup peak memory
50% 413.8 ms 375.4 ms 1.10x 5506 -> 4252 MiB
25% 409.7 ms 347.8 ms 1.18x 5506 -> 3510 MiB
10% 410.2 ms 334.5 ms 1.23x 5506 -> 2653 MiB

With KL enabled at 25% assistant tokens the step goes from 532.3 ms to 464.0 ms (1.15x).

Test plan

  • pytest tests/unit/test_unsloth_logprobs.py - 22 passed, including three new cases: partial masks match the full projection across chunk sizes (values and both gradients), a fully selected mask degenerates to the old behavior, and an empty mask keeps a graph with finite gradients.
  • pytest tests/unit/test_loss_ratio.py tests/unit/test_loss_tis.py tests/unit/test_unsloth_asyncio_isolation.py - 132 passed.
  • ruff check, ruff format --check and ty check pass on the changed files.

The logprob pass projected every position through the vocabulary-sized LM
head, but the loss masks all non-assistant positions immediately
afterwards. Select the assistant rows before the projection and scatter
the results back, mirroring the selective LM head the Megatron backend
already uses.

Logprobs, entropy and gradients are unchanged at every position that
reaches the loss. Ignored positions now stay zero instead of holding
unused values, so the output buffers are zero-initialized, and a fully
ignored batch keeps one row selected so the graph stays connected.

Measured on an RTX A6000 with Qwen3-0.6B (bf16, S=4096, chunk=1024): the
projection pass is 1.9x faster at 50% assistant tokens, 3.6x at 25% and
8.6x at 10%. The full training step is 1.10-1.23x faster and peak memory
drops from 5506 MiB to 2653 MiB at 10%.
@rapidSpace

Copy link
Copy Markdown
Author

Hi @bradhilton @Kovbo — a small perf change to the Unsloth logprob path. It skips the vocabulary-sized projection for rows the loss discards anyway, following the same approach as the Megatron backend's LmHeadTokenSelection. On an A6000 with Qwen3-0.6B it's 1.9x/3.6x/8.6x faster on the projection pass at 50%/25%/10% assistant tokens, and peak memory drops from 5506 MiB to 2653 MiB at 10%.

Correctness is exact rather than approximate — logprobs, entropy and gradients are unchanged at every position that reaches the loss.

The CI runs here are also stuck in action_required (no jobs were dispatched), so the checks haven't run yet.

Would appreciate a look when you have time. Happy to split or rework anything that doesn't fit.

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