Skip to content
Merged
Changes from 18 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
76bc679
GRPO: optional sequence packing for the no-grad old/ref logp path
danielhanchen Jun 29, 2026
9f2b246
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2026
26d0337
GRPO no-grad packing: address review feedback
danielhanchen Jun 29, 2026
38562de
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2026
6298366
GRPO no-grad packing: default-on, verify against per-row reference
danielhanchen Jun 30, 2026
4d69187
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 30, 2026
499e528
GRPO no-grad packing: disable entirely on cross-sample mismatch
danielhanchen Jun 30, 2026
b5127aa
GRPO no-grad packing: trim comments to be concise
danielhanchen Jul 1, 2026
537c276
GRPO no-grad packing: fix per-row completion boundary for left-padded…
danielhanchen Jul 1, 2026
3814b68
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 1, 2026
840ed89
GRPO no-grad packing: gate verification on real completion rows
danielhanchen Jul 1, 2026
a2b135f
GRPO no-grad packing: gate debug logging on UNSLOTH_ENABLE_LOGGING
danielhanchen Jul 1, 2026
e014c0a
GRPO packing: import UNSLOTH_ENABLE_LOGGING inside the injected logp …
danielhanchen Jul 2, 2026
f4771ef
GRPO no-grad packing: harden unsafe-length skip, verify guard, fallba…
danielhanchen Jul 3, 2026
4e8f30c
Merge remote-tracking branch 'origin/main' into grpo-sequence-packing
danielhanchen Jul 3, 2026
7dc44d3
GRPO no-grad packing: cap the flattened forward at one mini-batch budget
danielhanchen Jul 3, 2026
1ef2184
GRPO no-grad packing: disable unless unsloth_zoo has the masked-colum…
danielhanchen Jul 3, 2026
5376fb7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 3, 2026
30b8d3f
Merge branch 'main' into grpo-sequence-packing
Imagineer99 Jul 3, 2026
2baae82
GRPO packing: hoist env gates and zoo-guard detection to one-time mod…
danielhanchen Jul 5, 2026
85244ba
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 5, 2026
80b24d1
GRPO packing: cap the flattened forward by the padded chunk rows
danielhanchen Jul 5, 2026
1ab029f
GRPO sequence packing: tighten comments
danielhanchen Jul 6, 2026
ba1233d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
250 changes: 249 additions & 1 deletion unsloth/models/rl_replacements.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from unsloth_zoo.rl_replacements import (
RL_REPLACEMENTS,
left_pack_padding,
create_completion_attention_mask,
chunked_selective_log_softmax,
_unsloth_get_mm_token_id,
_unsloth_fix_mm_token_type_ids,
Expand Down Expand Up @@ -1358,6 +1359,251 @@ def _first_dim_len(value):
)
os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1"

# ---- Sequence packing (default-on; disable with UNSLOTH_GRPO_SEQ_PACKING=0) ----
# One varlen [1, sum L] block-diagonal forward replaces the padded [B, Lmax] loop: the exact
# per-row result, and it fixes the padded path's left-pad RoPE error. Self-verified against
# the per-row forward (shape/RoPE-aware, re-checked as T grows); falls back if a backend
# ignores packed_seq_lengths. lm_head runs on completion positions only.
logprobs = None
_pk_result = None
_pk_use = False
_pk_enabled = os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "1").lower() not in (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep sequence packing opt-in by default

When UNSLOTH_GRPO_SEQ_PACKING is unset, this default value makes _pk_enabled true, so existing text-only GRPO old/ref logp forwards now enter the new packed path without users opting in. That contradicts the commit's default-off/byte-identical behavior guarantee and exposes current users to the flattened-batch verifier/OOM and changed per-row logp path simply by upgrading; default this env lookup to "0" so only explicit opt-in enables packing.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Default-on is intentional and documented at the top of the block; disable with UNSLOTH_GRPO_SEQ_PACKING=0. It mirrors the accepted zoo policy-path packing and is guarded by the zoo masked-column-guard gate plus the first-use self-verify against the per-row forward (fall back on any mismatch).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Gate default packing on matching zoo support

This makes no-grad old/ref sequence packing default-on for every text GRPO run, but the gradient-path policy logps still come from the installed unsloth_zoo grpo_accumulated_loss, while this repo still allows older unsloth_zoo>=2026.6.7 installs. In any allowed environment without the matching zoo gradient-packing change, old/ref logps are computed with reset per-row positions while policy logps remain on the padded left-packed path, so KL and importance-ratio terms compare different position schemes; default this off or gate it on a detected compatible zoo implementation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: packing is gated on UNSLOTH_ZOO_HAS_MASKED_COL_GUARD (detected once at import), and the min zoo pin ships both the guard and the matching policy-path packing, so the two stay consistent.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep sequence packing opt-in by default

With the default value set to "1", every text-only GRPO run that leaves UNSLOTH_GRPO_SEQ_PACKING unset now attempts the new packed [1, sum L] forward and verification before the old padded loop can run. On unsupported or memory-constrained backends this changes existing runs by adding a large extra forward, possible OOM/empty_cache, and fallback latency even when users did not opt in; default this to off (or require the variable to be set) so current behavior remains unchanged unless explicitly enabled.

Useful? React with 👍 / 👎.

"0",
"false",
"no",
"off",
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bump the zoo floor before enabling packing

This path is default-on, but the repo still allows unsloth_zoo>=2026.6.7 in pyproject.toml, and that released loss does not include the paired masked-column NaN guard from unsloth-zoo#840. In environments resolved to 2026.6.7, the new packed no-grad old/ref logps can be combined with the unguarded grpo_compute_loss, so masked placeholder columns can poison the loss with NaNs; keep packing disabled or raise the lower bound to the zoo release that contains the guard.

Useful? React with 👍 / 👎.

if _pk_enabled:
# The packed path leaves masked prompt/pad logprob columns at 0, which only stays finite
# if the unsloth_zoo grpo_compute_loss zeroes those columns before exp() (zoo#840). Detect
# that guard once (cached on the model) and disable packing against an older unsloth_zoo
# so we never feed a NaN-prone loss; it re-enables automatically once the guard is present.
_pk_guard = getattr(unwrapped_model, "_unsloth_zoo_masked_col_guard", None)
if _pk_guard is None:
try:
import inspect as _pk_inspect
from unsloth_zoo.rl_replacements import RL_REPLACEMENTS as _pk_RL
_pk_guard = "torch.where(_keep, new" in _pk_inspect.getsource(
_pk_RL["grpo_compute_loss"]
)
except Exception:
_pk_guard = False
unwrapped_model._unsloth_zoo_masked_col_guard = _pk_guard
_pk_enabled = _pk_guard
_pk_ok = getattr(unwrapped_model, "_unsloth_seq_packing_nograd_ok", None)
if (
_pk_enabled
and pixel_values is None
and token_type_ids is None
and mm_token_type_ids is None
and _pk_ok is not False
):
Comment on lines +1389 to +1395

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This function is in a hot path, and repeatedly calling os.environ.get for UNSLOTH_GRPO_SEQ_PACKING can add overhead. It would be more performant to cache this environment variable lookup as an attribute on self (the trainer instance). A similar optimization should be applied to UNSLOTH_GRPO_SEQ_PACKING_DEBUG on lines 1456 and 1576.

            if not hasattr(self, "_unsloth_grpo_seq_packing"):
                self._unsloth_grpo_seq_packing = os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "0") == "1"
            if (
                pixel_values is None
                and self._unsloth_grpo_seq_packing
                and token_type_ids is None
                and mm_token_type_ids is None
                and _pk_verdict is not False
            ):

# this function's source is copied into the generated GRPO trainer, so import the
# logging flag locally (before the try) to keep the bare name defined there too
from unsloth.models._utils import UNSLOTH_ENABLE_LOGGING
try:
_pk_pad = self.processing_class.pad_token_id

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Robustness: Safe Attribute Access for Multimodal Processors

Multimodal processors (e.g., Gemma3/Gemma4 processors) do not always expose pad_token_id directly on the processor object, but rather on the underlying .tokenizer attribute. To prevent potential AttributeErrors, use a safe fallback check.

Suggested change
_pk_pad = self.processing_class.pad_token_id
_pk_pad = getattr(self.processing_class, "pad_token_id", None) or getattr(getattr(self.processing_class, "tokenizer", None), "pad_token_id", None)

_pk_keep = input_ids != _pk_pad

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve EOS tokens when packing completions

When pad_token_id == eos_token_id (common for causal LMs), this filter drops the generated EOS token from _pk_flat. GRPO's completion_mask can still include that first EOS, so the packed path leaves its old/ref logprob as 0 at an active loss position; the verifier also masks pad-id tokens via create_completion_attention_mask, so it does not catch the mismatch. Keep EOS tokens that are part of the completion instead of filtering every pad-id token out of the packed stream.

Useful? React with 👍 / 👎.

_pk_len = _pk_keep.sum(dim = 1)
_pk_len_cpu = _pk_len.tolist() # single GPU->CPU sync, reused below
_pk_nz_cpu = [_n for _n in _pk_len_cpu if _n > 0]
_pk_flat = input_ids[_pk_keep].unsqueeze(0)
Comment on lines +1397 to +1402

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve EOS tokens when packing

When processing_class.pad_token_id is also the EOS id and a generated completion contains EOS, this predicate treats that real target token as padding and drops it from _pk_flat, while the padded path still computes the EOS target logprob via completion_input_ids_chunk. The one-time verifier uses the same != pad_token_id mask, so it can ignore the mismatch, mark packing as safe, and then return zero/shifted old/ref logps for EOS positions whenever UNSLOTH_GRPO_SEQ_PACKING=1.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The GRPO completion mask is built from input_ids != pad_token_id (create_completion_attention_mask), so when pad_token_id == eos_token_id the terminal EOS is already excluded from the loss. The packed keep-mask uses the same != pad predicate, so the two stay consistent and no EOS that contributes to the loss is dropped.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No divergence: packing keeps every non-pad token (input_ids != pad), so a real EOS is preserved, and when EOS == pad it is masked by the completion mask in both the packed and padded paths identically. The self-verify over that same loss mask would catch any difference.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Respect the mini-batch memory cap when packing

This flattens every row in input_ids into a single packed forward, bypassing the B/unsloth_grpo_mini_batch chunking that the padded path uses to stay within memory. For large GRPO batches with long completions, enabling UNSLOTH_GRPO_SEQ_PACKING=1 can run a much larger no-grad forward than the configured mini-batch limit and OOM even though the existing chunked loop would fit. Build packed forwards per existing chunk, or cap the packed token count before trying the fast path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep packing within the mini-batch token budget

_pk_flat is built from every row in the GRPO batch, so the default-on path bypasses the B/batch_size autotuning that previously limited each no-grad forward to a memory-safe mini-batch. For batches with many rows or little padding, this single packed forward can have far more live tokens than the padded loop and OOM before any fallback is possible; pack per mini-batch or gate the path on the same token budget.

Useful? React with 👍 / 👎.

_pk_T = _pk_flat.shape[1]
_pk_L = input_ids.shape[1]
_pk_W = logits_to_keep + max_left_pad
_pk_maxseg = max(_pk_nz_cpu) if _pk_nz_cpu else 0
# sliding-window models lose the per-sequence local window in a packed stream
_pk_sw = getattr(
getattr(unwrapped_model, "config", None), "sliding_window", None
)
_pk_sw_ok = not (isinstance(_pk_sw, int) and _pk_sw > 0 and _pk_maxseg > _pk_sw)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip Mistral packing when total length triggers SWA

For Mistral-style sliding-window models, this guard only compares each segment length with sliding_window, but unsloth/models/mistral.py decides whether to use varlen packing from the flattened kv_seq_len; when sum L > sliding_window and every row is shorter than the window, the packed forward falls back to a dense sliding window over the concatenated stream, allowing later rows to attend to prior rows. A benign verification batch can then cache _unsloth_seq_packing_nograd_ok and skip future checks for the same/lower shape, so disable packing when the flattened length would trigger SWA or make Mistral use varlen in this case.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sliding-window guard is per-segment by design, but a flattened-length crossing cannot ship a contaminated result. Reaching the SWA path requires sum L > sliding_window, and verified_T can never exceed sliding_window: on a dense-SWA backend any batch with sum L > sliding_window contaminates by >= 2.4 nats and fails self-verify (hard-disable at rl_replacements.py:1568) instead of widening the envelope, and the widen at ~1540 only fires for _pk_active >= 2, so single-active-row passes never widen it either. A contaminating batch therefore always has _pk_T > verified_T, which bypasses the trust-skip at ~1485 and forces re-verification against the clean per-row forward, so it can never ship silently. Recent Mistral also ships sliding_window=null, which keeps the packed path fully block-diagonal regardless.

# exact per-row completion mask (same one the loss uses); a row is active only if
# it has real completion tokens, so prompt-only rows can't satisfy the >= 2 guard
_pk_cmask = create_completion_attention_mask(
input_ids[:, -_pk_W:], left_pad_tokens_per_prompt, max_left_pad, _pk_pad
)
_pk_active = int(_pk_cmask.any(dim = 1).sum())
# read the known-unsafe length here so we can skip the packed forward entirely
# (running it then falling back wastes a full pass and can OOM at large T)
_pk_unsafe = getattr(
unwrapped_model, "_unsloth_seq_packing_nograd_unsafe_T", None
)
# cap the single flattened forward at one padded mini-batch's token budget
# (B rows x seq_len). A larger batch falls back to the chunked padded loop rather
# than building a [1, sum L] forward bigger than the padded [B, seq_len] mini-batch.
_pk_cap = B * seq_len

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Cap packing with the actual mini-batch size

When unsloth_grpo_mini_batch is left as None, B has already been converted from the autotuned rows-per-forward into the number of chunks (B = total_rows // B), while batch_size is the row count used by the padded loop. Using B * seq_len here caps the packed forward to one sequence for the common case where autotune can fit the whole batch (B == 1), so _pk_T <= _pk_cap is false for almost any multi-row batch and the new sequence-packing path silently falls back instead of providing the intended speedup. Use the padded-loop mini-batch row count (batch_size, or the original autotuned row count) for this cap.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and this head already caps the packed forward at batch_size*seq_len (one padded mini-batch) so a larger batch falls back to the chunked padded loop rather than building an oversized single forward.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the padded chunk size for the packing cap

In text-only GRPO runs that are split into multiple padded chunks, B is the number of chunks used to derive batch_size = math.ceil(total_samples / B), while the loop below actually forwards batch_size rows per padded mini-batch. Capping the new flattened forward at B * seq_len therefore does not enforce the stated one-mini-batch budget; for example, with 64 rows and B == 16, the padded path forwards 4-row chunks but this path may try up to 16 sequences' worth of tokens at once, risking an avoidable OOM before falling back. The cap should use the actual padded chunk row count, e.g. batch_size * seq_len.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, B counts chunks at that point. Fixed to batch_size * seq_len.

if (
_pk_T >= 2
and _pk_T <= _pk_cap
and len(_pk_nz_cpu) > 0
and _pk_sw_ok
and not (_pk_unsafe is not None and _pk_T >= _pk_unsafe)
and (_pk_ok is True or _pk_active >= 2)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require real rows before extending packing verification

After a model has _pk_ok from a smaller batch, this condition allows a larger _pk_T/_pk_maxseg batch with fewer than two real completion rows, such as a single-row tail or micro-batch, to enter the verification path. The masked diff can then be zero or unable to expose cross-sample leakage, but the code below still updates _unsloth_seq_packing_nograd_verified_T/seg, so later real multi-row batches of that shape skip verification and may use an unvalidated packed forward. Keep the _pk_active >= 2 guard when expanding the verified shape.

Useful? React with 👍 / 👎.

):
Comment on lines +1424 to +1431

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Cap the packed forward before trying it

For GRPO configurations where total_rows is larger than the padded mini-batch, _pk_T is the sum of all non-pad tokens in the whole batch, while the fallback loop only forwards one padded mini-batch at a time. Because this guard never bounds _pk_T by that mini-batch token budget, a run that fits through the existing chunked padded loop can first attempt a much larger [1, sum L] packed forward and OOM before it has a chance to fall back.

Useful? React with 👍 / 👎.

# reset 0-based position_ids per segment
_pk_pos = (_pk_keep.cumsum(dim = 1) - 1)[_pk_keep].unsqueeze(0)
_pk_chunks = max(1, total_rows * multiplier)
_pk_nz_idx = _pk_keep.nonzero(
as_tuple = False
) # [T, 2] = (row, col), row-major
_pk_within = _pk_nz_idx[1:, 0] == _pk_nz_idx[:-1, 0] # [T-1]
# completion start is per-row after left-packing: (L - logits_to_keep) minus
# that row's left-pad (matches create_completion_attention_mask exactly)
_pk_cstart = (_pk_L - logits_to_keep) - left_pad_tokens_per_prompt # [rows]
_pk_ctgt = (_pk_nz_idx[1:, 1] >= _pk_cstart[_pk_nz_idx[1:, 0]]) & _pk_within
with _get_inference_mode_context_manager(model):
with torch.amp.autocast(device_type = "cuda", dtype = self._autocast_dtype):
# use_cache=False: a KV cache silently disables varlen packing
_pk_hidden = unwrapped_model(
input_ids = _pk_flat,
position_ids = _pk_pos,
packed_seq_lengths = torch.tensor(
Comment on lines +1445 to +1448

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid growing RoPE to the flattened length

For Unsloth fast models, the attention code still derives kv_seq_len from the flattened packed sequence before extending the RoPE cache (checked unsloth/models/llama.py:700-709 and unsloth/models/qwen3.py:114-124), so this call can allocate RoPE tables for sum L rather than the longest segment. With multiple long prompts where _pk_T > seq_len but still passes the _pk_cap check, the packed attempt can require a much larger RoPE cache than the padded chunk and OOM before falling back; avoid packing those shapes or pass/use the max segment length for RoPE sizing.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The packed forward does size RoPE to the flattened length, but the RoPE cache is a [seq_len, head_dim] position table (built in _set_cos_sin_cache, rounded up to a multiple of 8192), not an O(L^2) tensor, so even a 16k flattened batch is about 8 MB rather than a large allocation, and any residual OOM is caught by the except handler at rl_replacements.py:1563. The real risk at a larger length would be a LongRoPE/dynamic-NTK scaling switch changing cos/sin, but the per-row reference runs each row at its own seq_len and the envelope re-verify (which re-runs whenever T or the longest segment grows) catches that, so there is no OOM or correctness gap.

_pk_nz_cpu, dtype = torch.int32, device = input_ids.device
),
Comment on lines +1446 to +1450

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use max segment length for packed RoPE

This forwards _pk_flat as a single sequence whose length is the sum of all rows, while the patched attention implementations derive kv_seq_len/RoPE cache length from that physical sequence length (for example, Qwen3Attention_fast_forward uses K.shape[-2] before extend_rope_embedding(..., seq_len=kv_seq_len)). A GRPO minibatch with many 2k-token segments can therefore allocate 64k+ RoPE caches or trigger long-context scaling even though no packed segment is that long, causing avoidable OOMs or mismatches; the packed path needs to bound RoPE by the largest segment, not total packed tokens.

Useful? React with 👍 / 👎.

Comment on lines +1448 to +1450

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Gate packing on sparse attention backends

In environments where the model's packed attention falls back to SDPA rather than FlashAttention/xFormers, passing packed_seq_lengths here can build a dense attention mask over the concatenated sum(L) stream, so a GRPO batch with many rows can use much more memory than the existing padded mini-batch loop and may OOM or slow down before the fallback catches it. Gate this fast path on a varlen/block-sparse backend (or explicitly disable it for SDPA-only runs) before launching the packed forward.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The dense-mask cost on SDPA-only setups is real but bounded: _pk_T is capped at one padded mini-batch budget before the forward, and an OOM inside the packed try is caught, clears the cache, disables packing for the run, and falls back to the padded loop. Gating on the backend would turn packing off in places the cap already keeps safe.

use_cache = False,
Comment on lines +1445 to +1451

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recheck packing when RoPE regimes change

When a LongRoPE-style model has already set _unsloth_seq_packing_nograd_ok, this flattened [1, sum L] call can cross a RoPE regime that the padded [B, Lmax] forward does not: the attention layers size their rotary cache from kv_seq_len before applying the reset position_ids, so LongRopeRotaryEmbedding.get_cached() can switch to long factors even though every individual sequence is still short. Because the verifier is skipped after the first good batch, later longer GRPO batches can return old/ref logps computed with the wrong RoPE factors; include the RoPE regime/packed length in the verdict or disable packing for those configs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

position_ids are reset per sequence (0..n-1), so max(position_ids) in the packed forward equals the max per-sequence length, identical to the padded path per-row positions. LongRoPE / YaRN select the short-vs-long factor from that max position, so both paths make the same choice, and the self-test backstops any residual divergence.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handled by the re-verify envelope: the trusted shape is bounded by verified_T and verified_seg, and a batch whose T or longest segment grows past them re-verifies against the per-row forward, so a LongRoPE regime change cannot be silently trusted.

Comment on lines +1445 to +1451

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve token type ids in packed forwards

When token_type_ids or mm_token_type_ids are present, the padded path forwards them through _extra_vision_kwargs, but this packed forward drops them entirely. That matters for the Gemma3/Gemma4 text-only VLM cases already called out above in this function, where Transformers 5.x needs these ids to build the correct masking; with UNSLOTH_GRPO_SEQ_PACKING=1, old/ref logps can be computed with different model inputs than the padded path. Disable packing when these kwargs are present, or pack and pass them along with input_ids.

Useful? React with 👍 / 👎.

).logits
Comment on lines +1445 to +1452

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fall back for Mistral sliding-window packing

When UNSLOTH_GRPO_SEQ_PACKING=1 is used with Mistral-style configs and the packed total length exceeds config.sliding_window, this packed [1, sum L] forward no longer matches the padded path. MistralAttention_fast_forward disables varlen in that case (unsloth/models/mistral.py:110-115), so FlashAttention treats the concatenated rows as one sliding-window sequence and allows attention across packed sample boundaries; the xFormers fallback also loses the local window because sliding_window is not passed into AttentionContext (unsloth/models/mistral.py:127-137). That corrupts old/ref logprobs for packed GRPO batches on those models, so this path should be gated off or given a per-sequence local block mask.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Packing is skipped for sliding-window models when the longest segment exceeds the window (_pk_sw_ok gate), and any residual cross-segment leakage would be caught by the self-verify and fall back. Mirrors the zoo path.

Comment on lines +1445 to +1452

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Force cache off for packed FlashAttention forwards

When this path runs while the unwrapped model is in eval/inference mode with config.use_cache=True, the call does not override use_cache, so LlamaModel_fast_forward keeps cache enabled and the attention code disables varlen packing because past_key_value is populated (unsloth/models/llama.py:877 and unsloth/models/llama.py:727-731). On systems with FlashAttention, that selects the dense causal kernel over the flattened [1, sum L] stream rather than the varlen kernel, allowing tokens in later packed samples to attend to earlier samples and corrupting old/ref logprobs during standalone eval or any no-grad path that leaves cache enabled. Pass use_cache=False for the packed forward.

Useful? React with 👍 / 👎.

_pk_sel = chunked_hidden_states_selective_log_softmax(
_pk_hidden[0, :-1, :][_pk_ctgt].unsqueeze(0),
lm_head,
_pk_flat[0, 1:][_pk_ctgt].unsqueeze(0),
_pk_chunks,
logit_scale_multiply,
logit_scale_divide,
logit_softcapping,
temperature,
)[0]
# GPT-OSS offload race guard (matches the padded loop)
device_synchronize()
# scatter each completion logprob back to its (row, col) so [:, -_pk_W:] matches padded
_pk_tgt = (_pk_nz_idx[1:, 0] * _pk_L + _pk_nz_idx[1:, 1])[_pk_ctgt]
_pk_result = (
torch.zeros(
total_rows * _pk_L,
Comment on lines +1466 to +1469

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve prompt-tail logps for masked KL

When max_left_pad > 0, _pk_ctgt filters _pk_tgt down to completion tokens only, leaving the prompt-tail slots in _pk_result as zeros. Downstream GRPO loss computes exp(ref - new) for KL before applying completion_mask, so with beta > 0 a very negative current-policy logp in one of those masked prompt-tail slots can become exp(0 - new) == inf, and the later inf * 0 mask produces NaNs; either fill these slots like the padded path or mask before the KL exponentiation.

Useful? React with 👍 / 👎.

dtype = torch.float32,
device = input_ids.device,
)
.index_put((_pk_tgt,), _pk_sel.to(torch.float32))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve non-completion logps in packed result

When beta != 0 and max_left_pad adds leading prompt slots, this result starts from zeros and only writes _pk_ctgt completion positions, so packed old/ref logps no longer match the padded path for the masked prompt/pad slots. grpo_compute_loss_slow computes KL as torch.exp(ref - new) before applying the completion mask, so a very low policy logprob in one of those masked slots can overflow to inf and then inf * 0 turns the loss/mean_kl into NaN; either fill all W positions like the padded path or ensure those slots are masked before the KL calculation sees them.

Useful? React with 👍 / 👎.

.view(total_rows, _pk_L)[:, -_pk_W:]
)
# trust decision: re-verify when T or the longest segment grows past what was
# verified (a LongRoPE cache switch can change the result)
_pk_vT = int(
getattr(unwrapped_model, "_unsloth_seq_packing_nograd_verified_T", 0)
)
_pk_vS = int(
getattr(unwrapped_model, "_unsloth_seq_packing_nograd_verified_seg", 0)
)
_pk_force_verify = (
os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_VERIFY", "0") == "1"
)
if (
(not _pk_force_verify)
and _pk_ok is True
and _pk_T <= _pk_vT
and _pk_maxseg <= _pk_vS
):
_pk_use = True # already verified for this shape
else:
# verify against the per-row clean forward (exact ground truth)
_pk_ref = torch.zeros_like(_pk_result)
with _get_inference_mode_context_manager(model):
with torch.amp.autocast(
device_type = "cuda", dtype = self._autocast_dtype
):
for _pk_i in range(total_rows):
_pk_ni = _pk_len_cpu[_pk_i]
if _pk_ni < 2:
continue
_pk_rmask = _pk_keep[_pk_i]
_pk_real = input_ids[_pk_i][_pk_rmask].unsqueeze(0)
_pk_rpos = torch.arange(
_pk_ni, device = input_ids.device
).unsqueeze(0)
_pk_rh = unwrapped_model(
input_ids = _pk_real,
position_ids = _pk_rpos,
use_cache = False,
).logits
_pk_rsel = chunked_hidden_states_selective_log_softmax(
_pk_rh[:, :-1, :],
lm_head,
_pk_real[:, 1:],
1,
logit_scale_multiply,
logit_scale_divide,
logit_softcapping,
temperature,
)[0]
_pk_rcols = _pk_rmask.nonzero(as_tuple = False).squeeze(1)[
1:
] - (_pk_L - _pk_W)
_pk_rkeep = _pk_rcols >= 0
_pk_ref[_pk_i, _pk_rcols[_pk_rkeep]] = _pk_rsel[
_pk_rkeep
].to(torch.float32)
device_synchronize()
# compare over the exact loss-mask region (same mask the loss uses)
_pk_cm = _pk_cmask.float()
_pk_diff = float(((_pk_result - _pk_ref).abs() * _pk_cm).max())
if UNSLOTH_ENABLE_LOGGING:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Define the logging flag in the generated trainer

This replacement function is copied into the dynamically generated GRPO trainer with inspect.getsource, but the generated module does not import UNSLOTH_ENABLE_LOGGING; importing it in rl_replacements.py only makes it available while building the source. On the first default-on sequence-packing verification for a normal text GRPO batch with at least two active completions, this line raises NameError, and the broad except then hits the same undefined name in the fallback logging path, so training fails instead of using the packed or padded path.

Useful? React with 👍 / 👎.

print(
f"[Unsloth] GRPO seq-packing (no-grad) verify: T={_pk_T} maxseg={_pk_maxseg} packed-vs-perrow max|d|={_pk_diff:.4f}",
flush = True,
)
# floor ~0.25 through different kernels; cross-sample contamination is >= 2.4
if _pk_diff < 7e-1:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Tighten the packed-logp verification tolerance

When a text-only GRPO batch first exercises sequence packing, this accepts packed old/ref logps that differ from the per-row reference by anything under 0.7 and then caches _unsloth_seq_packing_nograd_ok=True, so later batches within the cached size bounds skip verification entirely. For any backend or shape where packed attention is partially wrong but the masked completion-token error is, for example, 0.5, this returns the packed logps instead of falling back, which materially changes the KL/importance-ratio terms; the gate should require a numerical-tolerance match before caching the fast path.

Useful? React with 👍 / 👎.

unwrapped_model._unsloth_seq_packing_nograd_ok = True
# only widen the trusted shape when >= 2 completion rows actually
# exercised cross-sample packing; a < 2 row pass proves nothing, so
# keep re-verifying larger shapes until a real multi-row batch clears
if _pk_active >= 2:
unwrapped_model._unsloth_seq_packing_nograd_verified_T = max(
_pk_vT, _pk_T
)
unwrapped_model._unsloth_seq_packing_nograd_verified_seg = max(
_pk_vS, _pk_maxseg
)
_pk_ok = True
_pk_use = True
else:
_pk_use = False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Release rejected packed tensors before fallback

When the verifier rejects a packed run, this falls through to the padded loop with _pk_hidden, _pk_ref, and _pk_result still holding the full packed forward and verifier tensors. Those GPU allocations remain live until the function returns, so on a backend/model that ignores packed_seq_lengths or hits an unsafe length, the fallback can OOM even though the original chunked padded path would have fit; clear the packed intermediates before continuing to the padded loop.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Free rejected packing tensors before fallback

When verification rejects the packed result (for example because the backend ignored packed_seq_lengths or a length boundary mismatched), this branch proceeds to the padded fallback while _pk_hidden, _pk_ref, and _pk_result are still referenced. The fallback then has to allocate the normal padded logits on top of the failed packed forward's tensors, so an unsupported batch can OOM instead of safely falling back; clear those intermediates before entering the padded loop.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear packed tensors before padded fallback

When the packed/per-row comparison fails here, execution falls through to the padded loop with _pk_hidden, _pk_sel, _pk_result, and _pk_ref still referenced from the failed packed attempt. On the unsupported-backend or LongRoPE-boundary cases where this branch is taken for large batches, the fallback runs with a full flattened hidden state and reference buffer still resident, so it can OOM even though fallback should recover safely. Drop those tensors before continuing to the padded path.

Useful? React with 👍 / 👎.

if _pk_diff >= 1.5:
# large mismatch = contamination (attention ignores the packed
# mask, e.g. some MoE): disable packing for this model
unwrapped_model._unsloth_seq_packing_nograd_ok = False
else:
# moderate mismatch -> likely a length boundary (LongRoPE): mark
# unsafe but keep packing for smaller shapes
unwrapped_model._unsloth_seq_packing_nograd_unsafe_T = (
_pk_T if _pk_unsafe is None else min(_pk_unsafe, _pk_T)
)
if UNSLOTH_ENABLE_LOGGING:
print(
f"[Unsloth] GRPO seq-packing (no-grad) fell back at T={_pk_T} (diff={_pk_diff:.3f})",
flush = True,
)
except Exception as _pk_err:
# any failure -> drop intermediates, use the padded loop, do not retry
_pk_hidden = None
_pk_sel = None
_pk_result = None
_pk_use = False
if isinstance(_pk_err, torch.cuda.OutOfMemoryError):
torch.cuda.empty_cache()
unwrapped_model._unsloth_seq_packing_nograd_ok = False
if UNSLOTH_ENABLE_LOGGING:
print(
f"[Unsloth] GRPO sequence-packing (no-grad) disabled (fell back to padded): {_pk_err!r}",
flush = True,
)
if _pk_use and _pk_result is not None:
logprobs = _pk_result # verified -> skip the loop
zipped_inputs = []
else:
# fell back to the padded loop: drop the packed intermediates first so the loop does
# not run with the full flattened hidden state / reference buffer still resident
_pk_hidden = _pk_sel = _pk_result = _pk_ref = None

with _get_inference_mode_context_manager(model):
for (
input_ids_chunk,
Expand Down Expand Up @@ -1442,7 +1688,9 @@ def _first_dim_len(value):
# However, it seems that this line does not slow down or disrupt models.
device_synchronize()
all_logprobs_list.append(logprobs_chunk)
logprobs = torch.cat(all_logprobs_list, dim = 0)
if logprobs is None:
# padded fallback (packing disabled / unsupported / not verified for this length)
logprobs = torch.cat(all_logprobs_list, dim = 0)
entropies = None

os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "0"
Expand Down
Loading