From 76bc67922727b8f62de0886d96997b39fcd1c22d Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 29 Jun 2026 04:50:27 +0000 Subject: [PATCH 01/22] GRPO: optional sequence packing for the no-grad old/ref logp path Add an opt-in sequence-packing fast path to _get_per_token_logps_and_entropies, enabled with UNSLOTH_GRPO_SEQ_PACKING=1. When the batch is text-only, the padded [B, Lmax] per-chunk forward is replaced by a single varlen [1, sum L] forward (BlockDiagonalCausalMask via packed_seq_lengths with reset position_ids). Per-token logps use the same float32 chunked_hidden_states_selective_log_softmax as the padded path, so the old and reference logps are bit-for-bit identical. Safety: the packed path is self-verified once against the padded ground truth on a batch that has at least two rows with real completion tokens (self._unsloth_seq_packing_nograd_ok), so cross-sample contamination would actually manifest; a degenerate all-pad / fully tool-masked batch leaves the verdict unset and re-verifies later. If a backend silently ignores packed_seq_lengths (flat batch run under a normal causal mask, samples leaking across boundaries), the packed logps will not match and packing is disabled instead of corrupting logps. It also forces use_cache=False (a populated past_key_value disables varlen packing), skips packing when a sliding window is shorter than the packed stream, runs the same GPT-OSS offload device_synchronize the padded loop uses, and falls back on any exception (UNSLOTH_GRPO_SEQ_PACKING_DEBUG=1 prints the reason). Default off, so existing behavior is unchanged. Pairs with the matching gradient-path change in unsloth_zoo so the full GRPO logp + loss + backward can run packed. --- unsloth/models/rl_replacements.py | 87 ++++++++++++++++++++++++++++++- 1 file changed, 86 insertions(+), 1 deletion(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index 61a07b686d7a..a7029d80add2 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1357,6 +1357,73 @@ def _first_dim_len(value): ) os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1" + # ---- Sequence-packing fast path (opt-in UNSLOTH_GRPO_SEQ_PACKING=1; text-only) ---- + # One varlen [1, sum L] forward replaces the padded [B, Lmax] per-chunk loop, producing + # the SAME logprobs [total_rows, W] (left-packed completion layout). Per-token logps use + # the same float32 reduction as the padded path, so old/ref logps are bit-for-bit + # identical. Big mem/time win on long, variable-length completions. Correctness is + # self-verified ONCE against the padded path (self._unsloth_seq_packing_nograd_ok): if a backend + # silently ignores packed_seq_lengths (flat batch run with a normal causal mask -> samples + # leak across boundaries) the packed logps will not match and packing is disabled. + logprobs = None + _pk_result = None + if (pixel_values is None and os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "0") == "1" + and getattr(self, "_unsloth_seq_packing_nograd_ok", None) is not False): + try: + _pk_pad = self.processing_class.pad_token_id + _pk_keep = input_ids != _pk_pad + _pk_len = _pk_keep.sum(dim = 1) + _pk_nz = _pk_len[_pk_len > 0] + _pk_flat = input_ids[_pk_keep].unsqueeze(0) + _pk_T = _pk_flat.shape[1] + _pk_L = input_ids.shape[1] + _pk_W = logits_to_keep + max_left_pad + # Sliding-window attention loses the per-sequence local window once the packed + # stream is longer than the window, so skip packing for that batch. + _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_T > _pk_sw) + if _pk_T >= 2 and _pk_nz.numel() > 0 and _pk_sw_ok: + _pk_pos = torch.cat( + [torch.arange(int(_n), device = input_ids.device) for _n in _pk_nz] + ).unsqueeze(0) + _pk_chunks = max(1, total_rows * multiplier) + with _get_inference_mode_context_manager(model): + with torch.amp.autocast(device_type = "cuda", dtype = self._autocast_dtype): + # use_cache=False: a populated past_key_value disables varlen packing + # in the attention kernels (silent fallback to dense causal attention). + _pk_hidden = unwrapped_model( + input_ids = _pk_flat, + position_ids = _pk_pos, + packed_seq_lengths = _pk_nz.to(torch.int32), + use_cache = False, + ).logits + _pk_sel = chunked_hidden_states_selective_log_softmax( + _pk_hidden[:, :-1, :], lm_head, _pk_flat[:, 1:], _pk_chunks, + logit_scale_multiply, logit_scale_divide, logit_softcapping, temperature, + )[0] + # Same GPT-OSS offload (offload_embbed=True) race guard the padded loop uses. + device_synchronize() + _pk_idx = []; _pk_val = []; _pk_off = 0 + for _pk_i in range(total_rows): + _pk_n = int(_pk_len[_pk_i]) + if _pk_n >= 2: + _pk_idx.append(_pk_i * _pk_L + torch.arange(1, _pk_n, device = input_ids.device)) + _pk_val.append(_pk_sel[_pk_off : _pk_off + _pk_n - 1]) + _pk_off += _pk_n + if _pk_idx: + _pk_fidx = torch.cat(_pk_idx) + _pk_vals = torch.cat(_pk_val).to(torch.float32) + _pk_result = torch.zeros( + total_rows * _pk_L, dtype = torch.float32, device = input_ids.device, + ).index_put((_pk_fidx,), _pk_vals).view(total_rows, _pk_L)[:, -_pk_W:] + except Exception as _pk_err: + if os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": + print(f"[Unsloth] GRPO sequence-packing (no-grad) fell back to padded path: {_pk_err!r}", flush = True) + _pk_result = None + if _pk_result is not None and getattr(self, "_unsloth_seq_packing_nograd_ok", False): + logprobs = _pk_result # already verified equal to padded -> skip the loop + zipped_inputs = [] + with _get_inference_mode_context_manager(model): for ( input_ids_chunk, @@ -1441,7 +1508,25 @@ 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: + logprobs = torch.cat(all_logprobs_list, dim = 0) + # One-time self-verification: only trust packing after it matches the padded + # ground truth on a real (>=2 sequence) batch; cross-sample contamination shows + # up as a large mismatch here and disables packing instead of corrupting logps. + if _pk_result is not None and not hasattr(self, "_unsloth_seq_packing_nograd_ok"): + # Require >=2 rows that actually have completion tokens, so cross-sample + # contamination would manifest. An all-pad / fully tool-masked window makes the + # masked diff trivially zero, which must NOT pass: leave the verdict unset and + # re-verify on a later, non-degenerate batch instead. + _pk_cm = (input_ids[:, -_pk_result.shape[1]:] != self.processing_class.pad_token_id).float() + _pk_active_rows = int((_pk_cm.sum(dim = 1) > 0).sum()) + if _pk_active_rows >= 2 and _pk_result.shape == logprobs.shape: + _pk_ok = bool(float(((_pk_result - logprobs).abs() * _pk_cm).max()) < 5e-1) + self._unsloth_seq_packing_nograd_ok = _pk_ok + if _pk_ok: + logprobs = _pk_result + elif os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": + print("[Unsloth] GRPO sequence-packing disabled: packed logprobs did not match the padded path", flush = True) entropies = None os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "0" From 9f2b2468440510ac06d802c8828578fec1b962ce Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 29 Jun 2026 05:51:13 +0000 Subject: [PATCH 02/22] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- unsloth/models/rl_replacements.py | 66 +++++++++++++++++++++++-------- 1 file changed, 50 insertions(+), 16 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index a7029d80add2..980bbdcbaf4e 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1367,8 +1367,11 @@ def _first_dim_len(value): # leak across boundaries) the packed logps will not match and packing is disabled. logprobs = None _pk_result = None - if (pixel_values is None and os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "0") == "1" - and getattr(self, "_unsloth_seq_packing_nograd_ok", None) is not False): + if ( + pixel_values is None + and os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "0") == "1" + and getattr(self, "_unsloth_seq_packing_nograd_ok", None) is not False + ): try: _pk_pad = self.processing_class.pad_token_id _pk_keep = input_ids != _pk_pad @@ -1380,7 +1383,9 @@ def _first_dim_len(value): _pk_W = logits_to_keep + max_left_pad # Sliding-window attention loses the per-sequence local window once the packed # stream is longer than the window, so skip packing for that batch. - _pk_sw = getattr(getattr(unwrapped_model, "config", None), "sliding_window", None) + _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_T > _pk_sw) if _pk_T >= 2 and _pk_nz.numel() > 0 and _pk_sw_ok: _pk_pos = torch.cat( @@ -1398,30 +1403,49 @@ def _first_dim_len(value): use_cache = False, ).logits _pk_sel = chunked_hidden_states_selective_log_softmax( - _pk_hidden[:, :-1, :], lm_head, _pk_flat[:, 1:], _pk_chunks, - logit_scale_multiply, logit_scale_divide, logit_softcapping, temperature, + _pk_hidden[:, :-1, :], + lm_head, + _pk_flat[:, 1:], + _pk_chunks, + logit_scale_multiply, + logit_scale_divide, + logit_softcapping, + temperature, )[0] # Same GPT-OSS offload (offload_embbed=True) race guard the padded loop uses. device_synchronize() - _pk_idx = []; _pk_val = []; _pk_off = 0 + _pk_idx = [] + _pk_val = [] + _pk_off = 0 for _pk_i in range(total_rows): _pk_n = int(_pk_len[_pk_i]) if _pk_n >= 2: - _pk_idx.append(_pk_i * _pk_L + torch.arange(1, _pk_n, device = input_ids.device)) + _pk_idx.append( + _pk_i * _pk_L + torch.arange(1, _pk_n, device = input_ids.device) + ) _pk_val.append(_pk_sel[_pk_off : _pk_off + _pk_n - 1]) _pk_off += _pk_n if _pk_idx: _pk_fidx = torch.cat(_pk_idx) _pk_vals = torch.cat(_pk_val).to(torch.float32) - _pk_result = torch.zeros( - total_rows * _pk_L, dtype = torch.float32, device = input_ids.device, - ).index_put((_pk_fidx,), _pk_vals).view(total_rows, _pk_L)[:, -_pk_W:] + _pk_result = ( + torch.zeros( + total_rows * _pk_L, + dtype = torch.float32, + device = input_ids.device, + ) + .index_put((_pk_fidx,), _pk_vals) + .view(total_rows, _pk_L)[:, -_pk_W:] + ) except Exception as _pk_err: if os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": - print(f"[Unsloth] GRPO sequence-packing (no-grad) fell back to padded path: {_pk_err!r}", flush = True) + print( + f"[Unsloth] GRPO sequence-packing (no-grad) fell back to padded path: {_pk_err!r}", + flush = True, + ) _pk_result = None if _pk_result is not None and getattr(self, "_unsloth_seq_packing_nograd_ok", False): - logprobs = _pk_result # already verified equal to padded -> skip the loop + logprobs = _pk_result # already verified equal to padded -> skip the loop zipped_inputs = [] with _get_inference_mode_context_manager(model): @@ -1513,20 +1537,30 @@ def _first_dim_len(value): # One-time self-verification: only trust packing after it matches the padded # ground truth on a real (>=2 sequence) batch; cross-sample contamination shows # up as a large mismatch here and disables packing instead of corrupting logps. - if _pk_result is not None and not hasattr(self, "_unsloth_seq_packing_nograd_ok"): + if _pk_result is not None and not hasattr( + self, "_unsloth_seq_packing_nograd_ok" + ): # Require >=2 rows that actually have completion tokens, so cross-sample # contamination would manifest. An all-pad / fully tool-masked window makes the # masked diff trivially zero, which must NOT pass: leave the verdict unset and # re-verify on a later, non-degenerate batch instead. - _pk_cm = (input_ids[:, -_pk_result.shape[1]:] != self.processing_class.pad_token_id).float() + _pk_cm = ( + input_ids[:, -_pk_result.shape[1] :] + != self.processing_class.pad_token_id + ).float() _pk_active_rows = int((_pk_cm.sum(dim = 1) > 0).sum()) if _pk_active_rows >= 2 and _pk_result.shape == logprobs.shape: - _pk_ok = bool(float(((_pk_result - logprobs).abs() * _pk_cm).max()) < 5e-1) + _pk_ok = bool( + float(((_pk_result - logprobs).abs() * _pk_cm).max()) < 5e-1 + ) self._unsloth_seq_packing_nograd_ok = _pk_ok if _pk_ok: logprobs = _pk_result elif os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": - print("[Unsloth] GRPO sequence-packing disabled: packed logprobs did not match the padded path", flush = True) + print( + "[Unsloth] GRPO sequence-packing disabled: packed logprobs did not match the padded path", + flush = True, + ) entropies = None os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "0" From 26d03375c7fc83bc822cf1c0a5ccd50e8c756381 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 29 Jun 2026 06:57:25 +0000 Subject: [PATCH 03/22] GRPO no-grad packing: address review feedback - Cache the packed-vs-padded verdict per unwrapped model instead of on the trainer, so a separately forwarded reference model is verified on its own forward path rather than inheriting the policy model's verdict. - Force the padded path when token_type_ids or mm_token_type_ids are present, matching the extra vision kwargs the padded loop forwards. - Require the xformers varlen backend before packing. Without it the packed mask falls back to a dense O(T^2) SDPA mask that can OOM on the flattened batch, so we keep the padded loop in that case. - On any packed-forward failure (missing backend, OOM, unsupported forward) empty the cache on OOM, disable packing for that model, and fall back to the chunked padded loop instead of retrying every step. --- unsloth/models/rl_replacements.py | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index 980bbdcbaf4e..cd735a39524e 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1362,17 +1362,26 @@ def _first_dim_len(value): # the SAME logprobs [total_rows, W] (left-packed completion layout). Per-token logps use # the same float32 reduction as the padded path, so old/ref logps are bit-for-bit # identical. Big mem/time win on long, variable-length completions. Correctness is - # self-verified ONCE against the padded path (self._unsloth_seq_packing_nograd_ok): if a backend - # silently ignores packed_seq_lengths (flat batch run with a normal causal mask -> samples - # leak across boundaries) the packed logps will not match and packing is disabled. + # self-verified ONCE against the padded path (unwrapped_model._unsloth_seq_packing_nograd_ok): + # if a backend silently ignores packed_seq_lengths (flat batch run with a normal causal mask + # -> samples leak across boundaries) the packed logps will not match and packing is disabled. logprobs = None _pk_result = None + # Verdict is cached per unwrapped model and only set after a real comparison; token_type_ids / + # mm_token_type_ids force the padded path (those VLM mask inputs are not packed here). + _pk_verdict = getattr(unwrapped_model, "_unsloth_seq_packing_nograd_ok", None) if ( pixel_values is None and os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "0") == "1" - and getattr(self, "_unsloth_seq_packing_nograd_ok", None) is not False + and token_type_ids is None + and mm_token_type_ids is None + and _pk_verdict is not False ): try: + # xformers provides the block-diagonal varlen mask; without it the packed attention + # falls back to a dense O(T^2) SDPA mask that can OOM on the whole flattened batch. + import xformers # noqa: F401 + _pk_pad = self.processing_class.pad_token_id _pk_keep = input_ids != _pk_pad _pk_len = _pk_keep.sum(dim = 1) @@ -1438,13 +1447,19 @@ def _first_dim_len(value): .view(total_rows, _pk_L)[:, -_pk_W:] ) except Exception as _pk_err: + # Disable packing for this model on any failure (no xformers varlen backend, an OOM on + # an oversized flattened batch the padded loop would chunk, or an unsupported forward) + # so we use the chunked padded loop and do not retry every step. + if isinstance(_pk_err, torch.cuda.OutOfMemoryError): + torch.cuda.empty_cache() + unwrapped_model._unsloth_seq_packing_nograd_ok = False if os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": print( - f"[Unsloth] GRPO sequence-packing (no-grad) fell back to padded path: {_pk_err!r}", + f"[Unsloth] GRPO sequence-packing (no-grad) disabled (fell back to padded): {_pk_err!r}", flush = True, ) _pk_result = None - if _pk_result is not None and getattr(self, "_unsloth_seq_packing_nograd_ok", False): + if _pk_result is not None and getattr(unwrapped_model, "_unsloth_seq_packing_nograd_ok", False): logprobs = _pk_result # already verified equal to padded -> skip the loop zipped_inputs = [] @@ -1538,7 +1553,7 @@ def _first_dim_len(value): # ground truth on a real (>=2 sequence) batch; cross-sample contamination shows # up as a large mismatch here and disables packing instead of corrupting logps. if _pk_result is not None and not hasattr( - self, "_unsloth_seq_packing_nograd_ok" + unwrapped_model, "_unsloth_seq_packing_nograd_ok" ): # Require >=2 rows that actually have completion tokens, so cross-sample # contamination would manifest. An all-pad / fully tool-masked window makes the @@ -1553,7 +1568,7 @@ def _first_dim_len(value): _pk_ok = bool( float(((_pk_result - logprobs).abs() * _pk_cm).max()) < 5e-1 ) - self._unsloth_seq_packing_nograd_ok = _pk_ok + unwrapped_model._unsloth_seq_packing_nograd_ok = _pk_ok if _pk_ok: logprobs = _pk_result elif os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": From 38562de4b7615b29345adee20b4225cac291ed7b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 29 Jun 2026 06:58:46 +0000 Subject: [PATCH 04/22] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- unsloth/models/rl_replacements.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index cd735a39524e..1fabd2014649 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1459,7 +1459,9 @@ def _first_dim_len(value): flush = True, ) _pk_result = None - if _pk_result is not None and getattr(unwrapped_model, "_unsloth_seq_packing_nograd_ok", False): + if _pk_result is not None and getattr( + unwrapped_model, "_unsloth_seq_packing_nograd_ok", False + ): logprobs = _pk_result # already verified equal to padded -> skip the loop zipped_inputs = [] From 6298366116e9b50eeffb375b9f87e89e914b942e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 30 Jun 2026 12:50:09 +0000 Subject: [PATCH 05/22] GRPO no-grad packing: default-on, verify against per-row reference Redesign of the optional sequence-packing fast path for the no-grad old/ref logprob recompute, after establishing that the packed forward is the exact per-row computation and the padded batch forward is the side that mis-positions left-padded rows on long completions. - Default the packing on (UNSLOTH_GRPO_SEQ_PACKING, disable with 0). - Verify the packed logprobs against the per-row clean forward (each row's real tokens alone, reset 0-based positions, no padding), not the padded batch which is itself wrong for left-padding. Cross-sample contamination (a backend ignoring packed_seq_lengths) shows up as a large mismatch and falls back to the padded loop. - Make the trust decision shape and RoPE aware: re-verify whenever the packed total length or the longest segment grows past what was verified, so a later batch crossing a LongRoPE short/long cache boundary is re-checked instead of trusted blindly. - Run lm_head only on completion-prediction positions instead of every packed prompt token, so long-prompt/short-completion batches do not pay for projecting the whole packed prompt. - Drop the hard xformers import so the path also runs in FlashAttention-only environments; the per-row verification guards correctness regardless of backend. --- unsloth/models/rl_replacements.py | 221 ++++++++++++++++-------------- 1 file changed, 118 insertions(+), 103 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index 1fabd2014649..b2fba0a6192b 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1357,50 +1357,51 @@ def _first_dim_len(value): ) os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1" - # ---- Sequence-packing fast path (opt-in UNSLOTH_GRPO_SEQ_PACKING=1; text-only) ---- - # One varlen [1, sum L] forward replaces the padded [B, Lmax] per-chunk loop, producing - # the SAME logprobs [total_rows, W] (left-packed completion layout). Per-token logps use - # the same float32 reduction as the padded path, so old/ref logps are bit-for-bit - # identical. Big mem/time win on long, variable-length completions. Correctness is - # self-verified ONCE against the padded path (unwrapped_model._unsloth_seq_packing_nograd_ok): - # if a backend silently ignores packed_seq_lengths (flat batch run with a normal causal mask - # -> samples leak across boundaries) the packed logps will not match and packing is disabled. + # ---- Sequence-packing fast path (default-on; disable with UNSLOTH_GRPO_SEQ_PACKING=0) ---- + # One varlen [1, sum L] block-diagonal forward replaces the padded [B, Lmax] per-chunk + # loop. The packed forward is the EXACT per-row computation (each segment attends only + # within itself, reset 0-based positions), so it equals forwarding each row's real tokens + # alone -- and is strictly more accurate than the padded batch forward, which mis-positions + # left-padded rows (Unsloth's known Flash-Attn left-padding issue) on long completions. + # Correctness is self-verified against the PER-ROW clean forward (NOT the padded batch, + # which is itself wrong for left-pad), shape/RoPE-aware: re-checked whenever the packed + # total length T grows past the largest verified T, so a later batch that crosses a + # LongRoPE short/long cache boundary -- or a backend that silently ignores + # packed_seq_lengths and leaks attention across samples -- is caught and falls back to the + # padded loop instead of corrupting logps. lm_head runs only on completion-prediction + # positions (not every packed prompt token). logprobs = None _pk_result = None - # Verdict is cached per unwrapped model and only set after a real comparison; token_type_ids / - # mm_token_type_ids force the padded path (those VLM mask inputs are not packed here). - _pk_verdict = getattr(unwrapped_model, "_unsloth_seq_packing_nograd_ok", None) - if ( - pixel_values is None - and os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "0") == "1" - and token_type_ids is None - and mm_token_type_ids is None - and _pk_verdict is not False - ): + _pk_use = False + _pk_enabled = os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "1").lower() not in ("0", "false", "no", "off") + _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): try: - # xformers provides the block-diagonal varlen mask; without it the packed attention - # falls back to a dense O(T^2) SDPA mask that can OOM on the whole flattened batch. - import xformers # noqa: F401 - _pk_pad = self.processing_class.pad_token_id _pk_keep = input_ids != _pk_pad _pk_len = _pk_keep.sum(dim = 1) - _pk_nz = _pk_len[_pk_len > 0] + _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) _pk_T = _pk_flat.shape[1] _pk_L = input_ids.shape[1] _pk_W = logits_to_keep + max_left_pad - # Sliding-window attention loses the per-sequence local window once the packed - # stream is longer than the window, so skip packing for that batch. - _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_T > _pk_sw) - if _pk_T >= 2 and _pk_nz.numel() > 0 and _pk_sw_ok: - _pk_pos = torch.cat( - [torch.arange(int(_n), device = input_ids.device) for _n in _pk_nz] - ).unsqueeze(0) + _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) + # need >= 2 completion rows for verification to expose cross-sample leakage + _pk_active = int(((input_ids[:, -_pk_W:] != _pk_pad).sum(dim = 1) > 0).sum()) + if _pk_T >= 2 and len(_pk_nz_cpu) > 0 and _pk_sw_ok and (_pk_ok is True or _pk_active >= 2): + # vectorized reset 0-based position_ids (no per-row sync) + _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-prediction positions: token j+1 is a real completion token + # (col >= L - logits_to_keep) in the same row as j. lm_head only on these. + _pk_ctgt = (_pk_nz_idx[1:, 1] >= (_pk_L - logits_to_keep)) & _pk_within with _get_inference_mode_context_manager(model): with torch.amp.autocast(device_type = "cuda", dtype = self._autocast_dtype): # use_cache=False: a populated past_key_value disables varlen packing @@ -1408,61 +1409,99 @@ def _first_dim_len(value): _pk_hidden = unwrapped_model( input_ids = _pk_flat, position_ids = _pk_pos, - packed_seq_lengths = _pk_nz.to(torch.int32), + packed_seq_lengths = torch.tensor(_pk_nz_cpu, dtype = torch.int32, device = input_ids.device), use_cache = False, ).logits _pk_sel = chunked_hidden_states_selective_log_softmax( - _pk_hidden[:, :-1, :], - lm_head, - _pk_flat[:, 1:], - _pk_chunks, - logit_scale_multiply, - logit_scale_divide, - logit_softcapping, - temperature, + _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] # Same GPT-OSS offload (offload_embbed=True) race guard the padded loop uses. device_synchronize() - _pk_idx = [] - _pk_val = [] - _pk_off = 0 - for _pk_i in range(total_rows): - _pk_n = int(_pk_len[_pk_i]) - if _pk_n >= 2: - _pk_idx.append( - _pk_i * _pk_L + torch.arange(1, _pk_n, device = input_ids.device) - ) - _pk_val.append(_pk_sel[_pk_off : _pk_off + _pk_n - 1]) - _pk_off += _pk_n - if _pk_idx: - _pk_fidx = torch.cat(_pk_idx) - _pk_vals = torch.cat(_pk_val).to(torch.float32) - _pk_result = ( - torch.zeros( - total_rows * _pk_L, - dtype = torch.float32, - device = input_ids.device, + # Scatter each completion next-token logprob to its ORIGINAL (row, col) so + # left-padded prompts land in the right columns; [:, -_pk_W:] then matches the + # padded layout. + _pk_tgt = (_pk_nz_idx[1:, 0] * _pk_L + _pk_nz_idx[1:, 1])[_pk_ctgt] + _pk_result = torch.zeros( + total_rows * _pk_L, dtype = torch.float32, device = input_ids.device, + ).index_put((_pk_tgt,), _pk_sel.to(torch.float32)).view(total_rows, _pk_L)[:, -_pk_W:] + # ---- trust decision (shape/RoPE-aware) ---- + # Re-verify when the packed total length OR the longest segment grows past what + # was verified: a LongRoPE model can switch its short/long RoPE cache on either, + # and the packed [1, T] forward can cross that boundary before any single row does. + _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_unsafe = getattr(unwrapped_model, "_unsloth_seq_packing_nograd_unsafe_T", None) + _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 + elif _pk_unsafe is not None and _pk_T >= _pk_unsafe: + _pk_use = False # known-unsafe length region + else: + # verify against the per-row clean forward (exact ground truth: each row's + # real tokens alone, 0-based positions, no padding). + _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 ONLY the completion region (window cols [max_left_pad, W) = the + # last logits_to_keep cols). The window's first max_left_pad cols are + # prompt-overflow that the lm_head completion-window opt deliberately leaves + # 0 (masked out downstream); including them would falsely flag a mismatch. + _pk_cm = torch.zeros((total_rows, _pk_W), dtype = torch.float32, device = input_ids.device) + _pk_cm[:, max_left_pad:] = (input_ids[:, -logits_to_keep:] != _pk_pad).float() + _pk_diff = float(((_pk_result - _pk_ref).abs() * _pk_cm).max()) + if os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": + 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: packed vs per-row through different attention kernels ~0.25 (the + # padded path is itself ~0.4 from per-row truth); cross-sample + # contamination (a backend ignoring packing) is >= 2.4. + if _pk_diff < 7e-1: + unwrapped_model._unsloth_seq_packing_nograd_ok = True + 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: + unwrapped_model._unsloth_seq_packing_nograd_unsafe_T = ( + _pk_T if _pk_unsafe is None else min(_pk_unsafe, _pk_T) ) - .index_put((_pk_fidx,), _pk_vals) - .view(total_rows, _pk_L)[:, -_pk_W:] - ) + _pk_use = False + if _pk_ok is None and _pk_T <= _pk_maxseg + 8: + # failed at a small T (no LongRoPE story) -> backend genuinely + # ignores packing; disable entirely. + unwrapped_model._unsloth_seq_packing_nograd_ok = False + if os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": + 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: - # Disable packing for this model on any failure (no xformers varlen backend, an OOM on - # an oversized flattened batch the padded loop would chunk, or an unsupported forward) - # so we use the chunked padded loop and do not retry every step. + # Any failure (no varlen backend, OOM on the flattened batch, unsupported forward) + # -> drop packed intermediates, reclaim memory, 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 os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": - print( - f"[Unsloth] GRPO sequence-packing (no-grad) disabled (fell back to padded): {_pk_err!r}", - flush = True, - ) - _pk_result = None - if _pk_result is not None and getattr( - unwrapped_model, "_unsloth_seq_packing_nograd_ok", False - ): - logprobs = _pk_result # already verified equal to padded -> skip the loop + 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 equal to per-row ground truth -> skip the loop zipped_inputs = [] with _get_inference_mode_context_manager(model): @@ -1550,34 +1589,10 @@ def _first_dim_len(value): device_synchronize() all_logprobs_list.append(logprobs_chunk) if logprobs is None: + # Padded fallback result (packing disabled / unsupported / not yet verified for + # this length). Verification against the per-row ground truth already happened in + # the packing block above, so nothing to compare here. logprobs = torch.cat(all_logprobs_list, dim = 0) - # One-time self-verification: only trust packing after it matches the padded - # ground truth on a real (>=2 sequence) batch; cross-sample contamination shows - # up as a large mismatch here and disables packing instead of corrupting logps. - if _pk_result is not None and not hasattr( - unwrapped_model, "_unsloth_seq_packing_nograd_ok" - ): - # Require >=2 rows that actually have completion tokens, so cross-sample - # contamination would manifest. An all-pad / fully tool-masked window makes the - # masked diff trivially zero, which must NOT pass: leave the verdict unset and - # re-verify on a later, non-degenerate batch instead. - _pk_cm = ( - input_ids[:, -_pk_result.shape[1] :] - != self.processing_class.pad_token_id - ).float() - _pk_active_rows = int((_pk_cm.sum(dim = 1) > 0).sum()) - if _pk_active_rows >= 2 and _pk_result.shape == logprobs.shape: - _pk_ok = bool( - float(((_pk_result - logprobs).abs() * _pk_cm).max()) < 5e-1 - ) - unwrapped_model._unsloth_seq_packing_nograd_ok = _pk_ok - if _pk_ok: - logprobs = _pk_result - elif os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": - print( - "[Unsloth] GRPO sequence-packing disabled: packed logprobs did not match the padded path", - flush = True, - ) entropies = None os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "0" From 4d691876e5ab0672fedc36bfcddd81b934cfe378 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 30 Jun 2026 12:50:44 +0000 Subject: [PATCH 06/22] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- unsloth/models/rl_replacements.py | 157 ++++++++++++++++++++++-------- 1 file changed, 119 insertions(+), 38 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index b2fba0a6192b..2c7a9a140fa5 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1373,15 +1373,25 @@ def _first_dim_len(value): logprobs = None _pk_result = None _pk_use = False - _pk_enabled = os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "1").lower() not in ("0", "false", "no", "off") + _pk_enabled = os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "1").lower() not in ( + "0", + "false", + "no", + "off", + ) _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): + 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 + ): try: _pk_pad = self.processing_class.pad_token_id _pk_keep = input_ids != _pk_pad _pk_len = _pk_keep.sum(dim = 1) - _pk_len_cpu = _pk_len.tolist() # single GPU->CPU sync, reused below + _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) _pk_T = _pk_flat.shape[1] @@ -1389,16 +1399,25 @@ def _first_dim_len(value): _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 = 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) # need >= 2 completion rows for verification to expose cross-sample leakage _pk_active = int(((input_ids[:, -_pk_W:] != _pk_pad).sum(dim = 1) > 0).sum()) - if _pk_T >= 2 and len(_pk_nz_cpu) > 0 and _pk_sw_ok and (_pk_ok is True or _pk_active >= 2): + if ( + _pk_T >= 2 + and len(_pk_nz_cpu) > 0 + and _pk_sw_ok + and (_pk_ok is True or _pk_active >= 2) + ): # vectorized reset 0-based position_ids (no per-row sync) _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] + _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-prediction positions: token j+1 is a real completion token # (col >= L - logits_to_keep) in the same row as j. lm_head only on these. _pk_ctgt = (_pk_nz_idx[1:, 1] >= (_pk_L - logits_to_keep)) & _pk_within @@ -1409,13 +1428,20 @@ def _first_dim_len(value): _pk_hidden = unwrapped_model( input_ids = _pk_flat, position_ids = _pk_pos, - packed_seq_lengths = torch.tensor(_pk_nz_cpu, dtype = torch.int32, device = input_ids.device), + packed_seq_lengths = torch.tensor( + _pk_nz_cpu, dtype = torch.int32, device = input_ids.device + ), use_cache = False, ).logits _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, + _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] # Same GPT-OSS offload (offload_embbed=True) race guard the padded loop uses. device_synchronize() @@ -1423,58 +1449,107 @@ def _first_dim_len(value): # left-padded prompts land in the right columns; [:, -_pk_W:] then matches the # padded layout. _pk_tgt = (_pk_nz_idx[1:, 0] * _pk_L + _pk_nz_idx[1:, 1])[_pk_ctgt] - _pk_result = torch.zeros( - total_rows * _pk_L, dtype = torch.float32, device = input_ids.device, - ).index_put((_pk_tgt,), _pk_sel.to(torch.float32)).view(total_rows, _pk_L)[:, -_pk_W:] + _pk_result = ( + torch.zeros( + total_rows * _pk_L, + dtype = torch.float32, + device = input_ids.device, + ) + .index_put((_pk_tgt,), _pk_sel.to(torch.float32)) + .view(total_rows, _pk_L)[:, -_pk_W:] + ) # ---- trust decision (shape/RoPE-aware) ---- # Re-verify when the packed total length OR the longest segment grows past what # was verified: a LongRoPE model can switch its short/long RoPE cache on either, # and the packed [1, T] forward can cross that boundary before any single row does. - _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_unsafe = getattr(unwrapped_model, "_unsloth_seq_packing_nograd_unsafe_T", None) - _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 + _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_unsafe = getattr( + unwrapped_model, "_unsloth_seq_packing_nograd_unsafe_T", None + ) + _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 elif _pk_unsafe is not None and _pk_T >= _pk_unsafe: - _pk_use = False # known-unsafe length region + _pk_use = False # known-unsafe length region else: # verify against the per-row clean forward (exact ground truth: each row's # real tokens alone, 0-based positions, no padding). _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): + 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 + 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_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, + _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_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) + _pk_ref[_pk_i, _pk_rcols[_pk_rkeep]] = _pk_rsel[ + _pk_rkeep + ].to(torch.float32) device_synchronize() # Compare ONLY the completion region (window cols [max_left_pad, W) = the # last logits_to_keep cols). The window's first max_left_pad cols are # prompt-overflow that the lm_head completion-window opt deliberately leaves # 0 (masked out downstream); including them would falsely flag a mismatch. - _pk_cm = torch.zeros((total_rows, _pk_W), dtype = torch.float32, device = input_ids.device) - _pk_cm[:, max_left_pad:] = (input_ids[:, -logits_to_keep:] != _pk_pad).float() + _pk_cm = torch.zeros( + (total_rows, _pk_W), dtype = torch.float32, device = input_ids.device + ) + _pk_cm[:, max_left_pad:] = ( + input_ids[:, -logits_to_keep:] != _pk_pad + ).float() _pk_diff = float(((_pk_result - _pk_ref).abs() * _pk_cm).max()) if os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": - 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) + 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: packed vs per-row through different attention kernels ~0.25 (the # padded path is itself ~0.4 from per-row truth); cross-sample # contamination (a backend ignoring packing) is >= 2.4. if _pk_diff < 7e-1: unwrapped_model._unsloth_seq_packing_nograd_ok = True - 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) + 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: @@ -1487,7 +1562,10 @@ def _first_dim_len(value): # ignores packing; disable entirely. unwrapped_model._unsloth_seq_packing_nograd_ok = False if os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": - print(f"[Unsloth] GRPO seq-packing (no-grad) fell back at T={_pk_T} (diff={_pk_diff:.3f})", flush = True) + 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 (no varlen backend, OOM on the flattened batch, unsupported forward) # -> drop packed intermediates, reclaim memory, use the padded loop, do not retry. @@ -1499,9 +1577,12 @@ def _first_dim_len(value): torch.cuda.empty_cache() unwrapped_model._unsloth_seq_packing_nograd_ok = False if os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": - print(f"[Unsloth] GRPO sequence-packing (no-grad) disabled (fell back to padded): {_pk_err!r}", flush = True) + 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 equal to per-row ground truth -> skip the loop + logprobs = _pk_result # verified equal to per-row ground truth -> skip the loop zipped_inputs = [] with _get_inference_mode_context_manager(model): From 499e5288b80d2a63842c762b57e5cb0c898624dd Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 30 Jun 2026 13:56:56 +0000 Subject: [PATCH 07/22] GRPO no-grad packing: disable entirely on cross-sample mismatch When the per-row verification fails, distinguish the two failure modes by magnitude instead of by sequence length: - A large mismatch (>= 1.5) is the cross-sample contamination signature: the model's attention does not honor the block-diagonal packed mask (seen on some MoE / custom-attention models, e.g. qwen2_moe). Disable packing entirely for the model so later batches do not pay the verification cost again. - A moderate mismatch is more likely a length-boundary effect (a LongRoPE short/long cache switch): keep marking just that length region unsafe so packing still runs for smaller shapes. Validated: Qwen1.5-MoE falls back after a single verification (grad and no-grad ok flags go False, no re-verify on later steps); dense Llama-3.2 and Qwen3 still verify and engage packing. --- unsloth/models/rl_replacements.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index 2c7a9a140fa5..cb437870fcaf 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1553,14 +1553,20 @@ def _first_dim_len(value): _pk_ok = True _pk_use = True else: - unwrapped_model._unsloth_seq_packing_nograd_unsafe_T = ( - _pk_T if _pk_unsafe is None else min(_pk_unsafe, _pk_T) - ) _pk_use = False - if _pk_ok is None and _pk_T <= _pk_maxseg + 8: - # failed at a small T (no LongRoPE story) -> backend genuinely - # ignores packing; disable entirely. + if _pk_diff >= 1.5: + # large mismatch = cross-sample contamination: this model's + # attention does not honor the block-diagonal packed mask (seen on + # some MoE / custom-attention models), so disable packing entirely + # and stop paying the verification cost on later batches. unwrapped_model._unsloth_seq_packing_nograd_ok = False + else: + # moderate mismatch -> more likely a length-boundary effect (e.g. a + # LongRoPE short/long cache switch): mark this length region unsafe + # but keep packing available 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 os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": print( f"[Unsloth] GRPO seq-packing (no-grad) fell back at T={_pk_T} (diff={_pk_diff:.3f})", From b5127aa754b54d2fdb9e3c9c61bfb41b3fb5e350 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 1 Jul 2026 09:37:13 +0000 Subject: [PATCH 08/22] GRPO no-grad packing: trim comments to be concise --- unsloth/models/rl_replacements.py | 71 ++++++++++--------------------- 1 file changed, 23 insertions(+), 48 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index cb437870fcaf..de6195d613b9 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1357,19 +1357,11 @@ def _first_dim_len(value): ) os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1" - # ---- Sequence-packing fast path (default-on; disable with UNSLOTH_GRPO_SEQ_PACKING=0) ---- - # One varlen [1, sum L] block-diagonal forward replaces the padded [B, Lmax] per-chunk - # loop. The packed forward is the EXACT per-row computation (each segment attends only - # within itself, reset 0-based positions), so it equals forwarding each row's real tokens - # alone -- and is strictly more accurate than the padded batch forward, which mis-positions - # left-padded rows (Unsloth's known Flash-Attn left-padding issue) on long completions. - # Correctness is self-verified against the PER-ROW clean forward (NOT the padded batch, - # which is itself wrong for left-pad), shape/RoPE-aware: re-checked whenever the packed - # total length T grows past the largest verified T, so a later batch that crosses a - # LongRoPE short/long cache boundary -- or a backend that silently ignores - # packed_seq_lengths and leaks attention across samples -- is caught and falls back to the - # padded loop instead of corrupting logps. lm_head runs only on completion-prediction - # positions (not every packed prompt token). + # ---- 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 @@ -1411,20 +1403,18 @@ def _first_dim_len(value): and _pk_sw_ok and (_pk_ok is True or _pk_active >= 2) ): - # vectorized reset 0-based position_ids (no per-row sync) + # 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-prediction positions: token j+1 is a real completion token - # (col >= L - logits_to_keep) in the same row as j. lm_head only on these. + # completion-prediction positions only (col >= L - logits_to_keep, same row) _pk_ctgt = (_pk_nz_idx[1:, 1] >= (_pk_L - logits_to_keep)) & _pk_within with _get_inference_mode_context_manager(model): with torch.amp.autocast(device_type = "cuda", dtype = self._autocast_dtype): - # use_cache=False: a populated past_key_value disables varlen packing - # in the attention kernels (silent fallback to dense causal attention). + # use_cache=False: a KV cache silently disables varlen packing _pk_hidden = unwrapped_model( input_ids = _pk_flat, position_ids = _pk_pos, @@ -1443,11 +1433,9 @@ def _first_dim_len(value): logit_softcapping, temperature, )[0] - # Same GPT-OSS offload (offload_embbed=True) race guard the padded loop uses. + # GPT-OSS offload race guard (matches the padded loop) device_synchronize() - # Scatter each completion next-token logprob to its ORIGINAL (row, col) so - # left-padded prompts land in the right columns; [:, -_pk_W:] then matches the - # padded layout. + # 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( @@ -1458,10 +1446,8 @@ def _first_dim_len(value): .index_put((_pk_tgt,), _pk_sel.to(torch.float32)) .view(total_rows, _pk_L)[:, -_pk_W:] ) - # ---- trust decision (shape/RoPE-aware) ---- - # Re-verify when the packed total length OR the longest segment grows past what - # was verified: a LongRoPE model can switch its short/long RoPE cache on either, - # and the packed [1, T] forward can cross that boundary before any single row does. + # 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) ) @@ -1484,8 +1470,7 @@ def _first_dim_len(value): elif _pk_unsafe is not None and _pk_T >= _pk_unsafe: _pk_use = False # known-unsafe length region else: - # verify against the per-row clean forward (exact ground truth: each row's - # real tokens alone, 0-based positions, no padding). + # 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( @@ -1523,10 +1508,8 @@ def _first_dim_len(value): _pk_rkeep ].to(torch.float32) device_synchronize() - # Compare ONLY the completion region (window cols [max_left_pad, W) = the - # last logits_to_keep cols). The window's first max_left_pad cols are - # prompt-overflow that the lm_head completion-window opt deliberately leaves - # 0 (masked out downstream); including them would falsely flag a mismatch. + # compare only the completion region; the first max_left_pad window cols are + # prompt-overflow the lm_head opt leaves 0 _pk_cm = torch.zeros( (total_rows, _pk_W), dtype = torch.float32, device = input_ids.device ) @@ -1539,9 +1522,7 @@ def _first_dim_len(value): 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: packed vs per-row through different attention kernels ~0.25 (the - # padded path is itself ~0.4 from per-row truth); cross-sample - # contamination (a backend ignoring packing) is >= 2.4. + # floor ~0.25 through different kernels; cross-sample contamination is >= 2.4 if _pk_diff < 7e-1: unwrapped_model._unsloth_seq_packing_nograd_ok = True unwrapped_model._unsloth_seq_packing_nograd_verified_T = max( @@ -1555,15 +1536,12 @@ def _first_dim_len(value): else: _pk_use = False if _pk_diff >= 1.5: - # large mismatch = cross-sample contamination: this model's - # attention does not honor the block-diagonal packed mask (seen on - # some MoE / custom-attention models), so disable packing entirely - # and stop paying the verification cost on later batches. + # 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 -> more likely a length-boundary effect (e.g. a - # LongRoPE short/long cache switch): mark this length region unsafe - # but keep packing available for smaller shapes. + # 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) ) @@ -1573,8 +1551,7 @@ def _first_dim_len(value): flush = True, ) except Exception as _pk_err: - # Any failure (no varlen backend, OOM on the flattened batch, unsupported forward) - # -> drop packed intermediates, reclaim memory, use the padded loop, do not retry. + # any failure -> drop intermediates, use the padded loop, do not retry _pk_hidden = None _pk_sel = None _pk_result = None @@ -1588,7 +1565,7 @@ def _first_dim_len(value): flush = True, ) if _pk_use and _pk_result is not None: - logprobs = _pk_result # verified equal to per-row ground truth -> skip the loop + logprobs = _pk_result # verified -> skip the loop zipped_inputs = [] with _get_inference_mode_context_manager(model): @@ -1676,9 +1653,7 @@ def _first_dim_len(value): device_synchronize() all_logprobs_list.append(logprobs_chunk) if logprobs is None: - # Padded fallback result (packing disabled / unsupported / not yet verified for - # this length). Verification against the per-row ground truth already happened in - # the packing block above, so nothing to compare here. + # padded fallback (packing disabled / unsupported / not verified for this length) logprobs = torch.cat(all_logprobs_list, dim = 0) entropies = None From 537c276957483453307ef21634211594720b7858 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 1 Jul 2026 10:16:04 +0000 Subject: [PATCH 09/22] GRPO no-grad packing: fix per-row completion boundary for left-padded rows The completion-target selection used a single global boundary (col >= L - logits_to_keep). After left-packing, each row's completion starts at (L - logits_to_keep) - left_pad[row], so for left-padded rows the first left_pad completion tokens fall below the global boundary and were dropped, leaving 0 logprobs at real completion positions that the loss mask keeps. Use the per-row boundary so packed coverage matches create_completion_attention_mask exactly, and widen the self-verify mask to the full per-row completion region so it can catch coverage gaps. --- unsloth/models/rl_replacements.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index de6195d613b9..ad06123d0e2c 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1410,8 +1410,10 @@ def _first_dim_len(value): as_tuple = False ) # [T, 2] = (row, col), row-major _pk_within = _pk_nz_idx[1:, 0] == _pk_nz_idx[:-1, 0] # [T-1] - # completion-prediction positions only (col >= L - logits_to_keep, same row) - _pk_ctgt = (_pk_nz_idx[1:, 1] >= (_pk_L - logits_to_keep)) & _pk_within + # 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 @@ -1508,13 +1510,11 @@ def _first_dim_len(value): _pk_rkeep ].to(torch.float32) device_synchronize() - # compare only the completion region; the first max_left_pad window cols are - # prompt-overflow the lm_head opt leaves 0 - _pk_cm = torch.zeros( - (total_rows, _pk_W), dtype = torch.float32, device = input_ids.device - ) - _pk_cm[:, max_left_pad:] = ( - input_ids[:, -logits_to_keep:] != _pk_pad + # compare over the exact loss-mask region (per-row completion, non-pad) + _pk_wc = torch.arange(_pk_W, device = input_ids.device) + _pk_cm = ( + (_pk_wc.unsqueeze(0) >= (max_left_pad - left_pad_tokens_per_prompt).unsqueeze(1)) + & (input_ids[:, -_pk_W:] != _pk_pad) ).float() _pk_diff = float(((_pk_result - _pk_ref).abs() * _pk_cm).max()) if os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": From 3814b6840f7c44417a5ebb4c904c87c28011857c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 1 Jul 2026 10:16:47 +0000 Subject: [PATCH 10/22] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- unsloth/models/rl_replacements.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index ad06123d0e2c..b3d1a8c39f62 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1513,7 +1513,10 @@ def _first_dim_len(value): # compare over the exact loss-mask region (per-row completion, non-pad) _pk_wc = torch.arange(_pk_W, device = input_ids.device) _pk_cm = ( - (_pk_wc.unsqueeze(0) >= (max_left_pad - left_pad_tokens_per_prompt).unsqueeze(1)) + ( + _pk_wc.unsqueeze(0) + >= (max_left_pad - left_pad_tokens_per_prompt).unsqueeze(1) + ) & (input_ids[:, -_pk_W:] != _pk_pad) ).float() _pk_diff = float(((_pk_result - _pk_ref).abs() * _pk_cm).max()) From 840ed89a62258be412edb98e6c0d59154ecf7edd Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 1 Jul 2026 11:08:53 +0000 Subject: [PATCH 11/22] GRPO no-grad packing: gate verification on real completion rows Count active rows via create_completion_attention_mask (the same mask the loss uses) instead of any non-pad token in the packed window. Prompt-only rows carry prompt-overflow tokens in the window and could otherwise satisfy the >= 2 verification guard, letting a batch with a single real completion row cache a trust decision. This matches the gradient path, which already gates on the completion mask. The same mask is reused for the self-verify comparison. --- unsloth/models/rl_replacements.py | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index b3d1a8c39f62..e98d66d1f3b0 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -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, @@ -1395,8 +1396,12 @@ def _first_dim_len(value): 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) - # need >= 2 completion rows for verification to expose cross-sample leakage - _pk_active = int(((input_ids[:, -_pk_W:] != _pk_pad).sum(dim = 1) > 0).sum()) + # 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()) if ( _pk_T >= 2 and len(_pk_nz_cpu) > 0 @@ -1510,15 +1515,8 @@ def _first_dim_len(value): _pk_rkeep ].to(torch.float32) device_synchronize() - # compare over the exact loss-mask region (per-row completion, non-pad) - _pk_wc = torch.arange(_pk_W, device = input_ids.device) - _pk_cm = ( - ( - _pk_wc.unsqueeze(0) - >= (max_left_pad - left_pad_tokens_per_prompt).unsqueeze(1) - ) - & (input_ids[:, -_pk_W:] != _pk_pad) - ).float() + # 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 os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": print( From a2b135ff6908149b79bb6b65769ea659fe6612af Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 1 Jul 2026 11:59:49 +0000 Subject: [PATCH 12/22] GRPO no-grad packing: gate debug logging on UNSLOTH_ENABLE_LOGGING Use the shared UNSLOTH_ENABLE_LOGGING global (import_fixes, re-exported by _utils) instead of a bespoke UNSLOTH_GRPO_SEQ_PACKING_DEBUG env var for the packing debug prints, matching the rest of the codebase. --- unsloth/models/rl_replacements.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index e98d66d1f3b0..bc9491c4ee44 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -49,7 +49,7 @@ ALLOW_PREQUANTIZED_MODELS, ) import textwrap -from ._utils import _get_inference_mode_context_manager +from ._utils import _get_inference_mode_context_manager, UNSLOTH_ENABLE_LOGGING RL_EXTRA_ARGS = defaultdict(list) RL_FUNCTIONS = defaultdict(list) @@ -1518,7 +1518,7 @@ def _first_dim_len(value): # 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 os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": + if UNSLOTH_ENABLE_LOGGING: 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, @@ -1546,7 +1546,7 @@ def _first_dim_len(value): unwrapped_model._unsloth_seq_packing_nograd_unsafe_T = ( _pk_T if _pk_unsafe is None else min(_pk_unsafe, _pk_T) ) - if os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": + if UNSLOTH_ENABLE_LOGGING: print( f"[Unsloth] GRPO seq-packing (no-grad) fell back at T={_pk_T} (diff={_pk_diff:.3f})", flush = True, @@ -1560,7 +1560,7 @@ def _first_dim_len(value): if isinstance(_pk_err, torch.cuda.OutOfMemoryError): torch.cuda.empty_cache() unwrapped_model._unsloth_seq_packing_nograd_ok = False - if os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_DEBUG", "0") == "1": + if UNSLOTH_ENABLE_LOGGING: print( f"[Unsloth] GRPO sequence-packing (no-grad) disabled (fell back to padded): {_pk_err!r}", flush = True, From e014c0a64ab38547a4ca43e346efb1ab4ab88a93 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 2 Jul 2026 12:29:02 +0000 Subject: [PATCH 13/22] GRPO packing: import UNSLOTH_ENABLE_LOGGING inside the injected logp function _get_per_token_logps_and_entropies is copied verbatim into the generated GRPO trainer via inspect.getsource, and that module never imported UNSLOTH_ENABLE_LOGGING, so the default-on packing verify path raised NameError (and the except handler re-raised it). Import the flag locally, before the try, so the name is defined in the generated module too. Drop it from the now-unused module-level import. --- unsloth/models/rl_replacements.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index bc9491c4ee44..0c3e4360bf32 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -49,7 +49,7 @@ ALLOW_PREQUANTIZED_MODELS, ) import textwrap -from ._utils import _get_inference_mode_context_manager, UNSLOTH_ENABLE_LOGGING +from ._utils import _get_inference_mode_context_manager RL_EXTRA_ARGS = defaultdict(list) RL_FUNCTIONS = defaultdict(list) @@ -1380,6 +1380,9 @@ def _first_dim_len(value): and mm_token_type_ids is None and _pk_ok 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 _pk_keep = input_ids != _pk_pad From f4771ef5cb699ca4568ef7dd911bc8808d4d09ee Mon Sep 17 00:00:00 2001 From: danielhanchen Date: Fri, 3 Jul 2026 10:46:05 +0000 Subject: [PATCH 14/22] GRPO no-grad packing: harden unsafe-length skip, verify guard, fallback cleanup Three fixes to the no-grad logp packing path, mirroring the grad path: - skip the packed forward for known-unsafe lengths by reading unsafe_T and gating on it before the forward, instead of running the full packed pass and the result build only to discard them (wastes a pass, can OOM at large T) - only widen the verified T/seg envelope when >= 2 completion rows actually exercised cross-sample packing; a < 2 row batch cannot expose leakage, so it must not extend the trusted shape that later multi-row batches skip verify for - drop the packed intermediates (hidden/sel/result/ref) before the padded fallback loop so it does not run with the flattened hidden state still resident --- unsloth/models/rl_replacements.py | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index 0c3e4360bf32..13e1a3ea2ff5 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1405,10 +1405,16 @@ def _first_dim_len(value): 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 + ) if ( _pk_T >= 2 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) ): # reset 0-based position_ids per segment @@ -1464,9 +1470,6 @@ def _first_dim_len(value): _pk_vS = int( getattr(unwrapped_model, "_unsloth_seq_packing_nograd_verified_seg", 0) ) - _pk_unsafe = getattr( - unwrapped_model, "_unsloth_seq_packing_nograd_unsafe_T", None - ) _pk_force_verify = ( os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_VERIFY", "0") == "1" ) @@ -1477,8 +1480,6 @@ def _first_dim_len(value): and _pk_maxseg <= _pk_vS ): _pk_use = True # already verified for this shape - elif _pk_unsafe is not None and _pk_T >= _pk_unsafe: - _pk_use = False # known-unsafe length region else: # verify against the per-row clean forward (exact ground truth) _pk_ref = torch.zeros_like(_pk_result) @@ -1529,12 +1530,16 @@ def _first_dim_len(value): # floor ~0.25 through different kernels; cross-sample contamination is >= 2.4 if _pk_diff < 7e-1: unwrapped_model._unsloth_seq_packing_nograd_ok = True - 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 - ) + # 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: @@ -1571,6 +1576,10 @@ def _first_dim_len(value): 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 ( From 7dc44d3e4a4681743e1ce836ecf212628a102159 Mon Sep 17 00:00:00 2001 From: danielhanchen Date: Fri, 3 Jul 2026 13:08:48 +0000 Subject: [PATCH 15/22] GRPO no-grad packing: cap the flattened forward at one mini-batch budget The packed path built a single [1, sum L] forward over every row before any size check, so a large batch could exceed the memory the padded path bounds per mini-batch. Gate packing on _pk_T <= _pk_cap (B * seq_len, one padded mini-batch's token budget); larger batches fall back to the chunked padded loop. --- unsloth/models/rl_replacements.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index d6fe5395b5fd..a6840bfdb368 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1411,8 +1411,13 @@ def _first_dim_len(value): _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 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) From 1ef2184702437f33ae2dbb31294bdca171403f82 Mon Sep 17 00:00:00 2001 From: danielhanchen Date: Fri, 3 Jul 2026 14:38:33 +0000 Subject: [PATCH 16/22] GRPO no-grad packing: disable unless unsloth_zoo has the masked-column guard The packed path leaves masked prompt/pad logprob columns at 0, which only stays finite if unsloth_zoo grpo_compute_loss zeroes them before exp() (zoo#840). An older unsloth_zoo without that guard would NaN. Detect the guard once (cached on the model) via inspect.getsource and gate packing on it, so #6738 is safe with any unsloth_zoo version and re-enables packing automatically once a guarded zoo is installed, independent of the pinned lower bound. --- unsloth/models/rl_replacements.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index a6840bfdb368..23dede773c1a 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1373,6 +1373,21 @@ def _first_dim_len(value): "no", "off", ) + 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 From 5376fb7432aa4ee8bd56ce6f06ac0bd31005ec93 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 3 Jul 2026 14:39:06 +0000 Subject: [PATCH 17/22] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- unsloth/models/rl_replacements.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index 23dede773c1a..b732c1a83e32 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1383,7 +1383,9 @@ def _first_dim_len(value): 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"]) + _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 From 2baae82966744a7cf5aeb8fcc25fc48a9bcf6181 Mon Sep 17 00:00:00 2001 From: danielhanchen Date: Sun, 5 Jul 2026 05:23:30 +0000 Subject: [PATCH 18/22] GRPO packing: hoist env gates and zoo-guard detection to one-time module checks Read UNSLOTH_GRPO_SEQ_PACKING and detect the unsloth_zoo masked-column guard once at import time (module constants plus RL_PRE_ITEMS for the generated trainer cache) instead of per call, and drop the in-function UNSLOTH_ENABLE_LOGGING import for a module-top one. The UNSLOTH_GRPO_SEQ_PACKING_VERIFY force-verify debug knob is commented out, kept in place for hand re-enable; the first-use and envelope-growth self-verify stays active. --- unsloth/models/rl_replacements.py | 82 +++++++++++++++++++------------ 1 file changed, 50 insertions(+), 32 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index d440689eb053..338e770c8801 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -49,7 +49,25 @@ ALLOW_PREQUANTIZED_MODELS, ) import textwrap -from ._utils import _get_inference_mode_context_manager +from ._utils import _get_inference_mode_context_manager, UNSLOTH_ENABLE_LOGGING + +# One-time gates for the GRPO sequence-packing path. Mirrored into the generated +# trainer cache via RL_PRE_ITEMS below, since inlined function bodies do not carry +# this module's imports. +UNSLOTH_GRPO_SEQ_PACKING_ON = os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "1").lower() not in ( + "0", + "false", + "no", + "off", +) +# Packed path needs unsloth_zoo's masked-column guard in grpo_compute_loss (zoo#840). +# Per-process constant is correct: the installed zoo cannot change mid-process. +try: + UNSLOTH_ZOO_HAS_MASKED_COL_GUARD = "torch.where(_keep, new" in inspect.getsource( + RL_REPLACEMENTS["grpo_compute_loss"] + ) +except Exception: + UNSLOTH_ZOO_HAS_MASKED_COL_GUARD = False RL_EXTRA_ARGS = defaultdict(list) RL_FUNCTIONS = defaultdict(list) @@ -1368,29 +1386,11 @@ def _first_dim_len(value): logprobs = None _pk_result = None _pk_use = False - _pk_enabled = os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "1").lower() not in ( - "0", - "false", - "no", - "off", - ) - 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_enabled = UNSLOTH_GRPO_SEQ_PACKING_ON + # Packed path needs zoo#840's masked-column guard in grpo_compute_loss, else the + # zeroed prompt/pad columns turn NaN in exp(). Detected once at import time + # (per-process constant; the installed unsloth_zoo cannot change mid-process). + _pk_enabled = _pk_enabled and UNSLOTH_ZOO_HAS_MASKED_COL_GUARD _pk_ok = getattr(unwrapped_model, "_unsloth_seq_packing_nograd_ok", None) if ( _pk_enabled @@ -1399,9 +1399,6 @@ def _first_dim_len(value): and mm_token_type_ids is None and _pk_ok 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 _pk_keep = input_ids != _pk_pad @@ -1494,12 +1491,13 @@ def _first_dim_len(value): _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" - ) + # debug knob (force re-verify every step) commented out; re-enable by hand + # _pk_force_verify = ( + # os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_VERIFY", "0") == "1" + # ) if ( - (not _pk_force_verify) - and _pk_ok is True + # (not _pk_force_verify) and + _pk_ok is True and _pk_T <= _pk_vT and _pk_maxseg <= _pk_vS ): @@ -1771,6 +1769,26 @@ def _unsloth_get_final_logit_softcapping(model): RL_PRE_ITEMS["grpo_trainer"].append(grpo_compute_loss_slow) RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(grpo_update_SamplingParams)) RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_get_inference_mode_context_manager)) +# Module-level constants the inlined grpo functions reference. inspect.getsource inlines the +# function bodies but NOT the module imports, so names like UNSLOTH_ENABLE_LOGGING must be +# (re)defined in the generated cache module. Provide it as a pre-item so the seq-packing / +# PrefixGrouper verify logging branches resolve it (env-driven, default off). +RL_PRE_ITEMS["grpo_trainer"].append( + "import os as _unsloth_os\n" + "UNSLOTH_ENABLE_LOGGING = _unsloth_os.environ.get('UNSLOTH_ENABLE_LOGGING', '0') in ('1', 'True', 'true')\n" +) +# One-time sequence-packing gates, same values as the module-top constants above. +RL_PRE_ITEMS["grpo_trainer"].append( + "UNSLOTH_GRPO_SEQ_PACKING_ON = _unsloth_os.environ.get('UNSLOTH_GRPO_SEQ_PACKING', '1').lower() not in ('0', 'false', 'no', 'off')\n" +) +RL_PRE_ITEMS["grpo_trainer"].append( + "try:\n" + " import inspect as _unsloth_inspect\n" + " from unsloth_zoo.rl_replacements import RL_REPLACEMENTS as _unsloth_zoo_RL\n" + " UNSLOTH_ZOO_HAS_MASKED_COL_GUARD = 'torch.where(_keep, new' in _unsloth_inspect.getsource(_unsloth_zoo_RL['grpo_compute_loss'])\n" + "except Exception:\n" + " UNSLOTH_ZOO_HAS_MASKED_COL_GUARD = False\n" +) # Edit _get_per_token_logps to handle mixed precision From 85244bacda8f07fca98c4872298d83e94229e936 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 5 Jul 2026 06:10:58 +0000 Subject: [PATCH 19/22] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- unsloth/models/rl_replacements.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index 338e770c8801..e3f92a50d0f2 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1497,9 +1497,7 @@ def _first_dim_len(value): # ) if ( # (not _pk_force_verify) and - _pk_ok is True - and _pk_T <= _pk_vT - and _pk_maxseg <= _pk_vS + _pk_ok is True and _pk_T <= _pk_vT and _pk_maxseg <= _pk_vS ): _pk_use = True # already verified for this shape else: From 80b24d176de2980f141f43500f73d4d9771fc1f6 Mon Sep 17 00:00:00 2001 From: danielhanchen Date: Sun, 5 Jul 2026 06:27:24 +0000 Subject: [PATCH 20/22] GRPO packing: cap the flattened forward by the padded chunk rows B counts chunks at this point, so B * seq_len understated (small runs) or overstated (large runs) the padded mini-batch token budget; use batch_size * seq_len, the rows the padded loop actually forwards per chunk. --- unsloth/models/rl_replacements.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index e3f92a50d0f2..287daf347449 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1426,10 +1426,11 @@ def _first_dim_len(value): _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 + # cap the single flattened forward at one padded mini-batch's token budget. + # B is the number of chunks, so the padded loop forwards batch_size rows at a + # time; a larger batch falls back to the chunked padded loop rather than building + # a [1, sum L] forward bigger than the padded [batch_size, seq_len] mini-batch. + _pk_cap = batch_size * seq_len if ( _pk_T >= 2 and _pk_T <= _pk_cap From 1ab029fbeea7ec688e6e7b1a04cc87b86d51236e Mon Sep 17 00:00:00 2001 From: danielhanchen Date: Mon, 6 Jul 2026 08:32:09 +0000 Subject: [PATCH 21/22] GRPO sequence packing: tighten comments --- unsloth/models/rl_replacements.py | 74 +++++++++++-------------------- 1 file changed, 26 insertions(+), 48 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index 287daf347449..19637ee62a2f 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -51,17 +51,14 @@ import textwrap from ._utils import _get_inference_mode_context_manager, UNSLOTH_ENABLE_LOGGING -# One-time gates for the GRPO sequence-packing path. Mirrored into the generated -# trainer cache via RL_PRE_ITEMS below, since inlined function bodies do not carry -# this module's imports. +# One-time GRPO sequence-packing gates; mirrored into the generated trainer cache via RL_PRE_ITEMS. UNSLOTH_GRPO_SEQ_PACKING_ON = os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "1").lower() not in ( "0", "false", "no", "off", ) -# Packed path needs unsloth_zoo's masked-column guard in grpo_compute_loss (zoo#840). -# Per-process constant is correct: the installed zoo cannot change mid-process. +# Packing needs zoo#840's masked-column guard in grpo_compute_loss (installed zoo is fixed per-process). try: UNSLOTH_ZOO_HAS_MASKED_COL_GUARD = "torch.where(_keep, new" in inspect.getsource( RL_REPLACEMENTS["grpo_compute_loss"] @@ -1379,17 +1376,14 @@ 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. + # One varlen [1, sum L] forward replaces the padded [B, Lmax] loop (also fixes the + # left-pad RoPE error). Self-verified against the per-row forward, re-checked as T + # grows; falls back if a backend ignores packed_seq_lengths. logprobs = None _pk_result = None _pk_use = False _pk_enabled = UNSLOTH_GRPO_SEQ_PACKING_ON - # Packed path needs zoo#840's masked-column guard in grpo_compute_loss, else the - # zeroed prompt/pad columns turn NaN in exp(). Detected once at import time - # (per-process constant; the installed unsloth_zoo cannot change mid-process). + # Without zoo#840's masked-column guard, zeroed prompt/pad columns turn NaN in exp(). _pk_enabled = _pk_enabled and UNSLOTH_ZOO_HAS_MASKED_COL_GUARD _pk_ok = getattr(unwrapped_model, "_unsloth_seq_packing_nograd_ok", None) if ( @@ -1415,21 +1409,17 @@ def _first_dim_len(value): 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) - # 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 + # per-row completion mask (same as the loss); prompt-only rows count as inactive _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) + # skip the packed forward entirely at known-unsafe lengths (avoids a wasted pass / OOM) _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 is the number of chunks, so the padded loop forwards batch_size rows at a - # time; a larger batch falls back to the chunked padded loop rather than building - # a [1, sum L] forward bigger than the padded [batch_size, seq_len] mini-batch. + # cap the flattened forward at one padded [batch_size, seq_len] mini-batch's + # token budget; anything larger uses the chunked padded loop _pk_cap = batch_size * seq_len if ( _pk_T >= 2 @@ -1446,8 +1436,7 @@ def _first_dim_len(value): 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) + # per-row completion start after left-packing (matches create_completion_attention_mask) _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): @@ -1484,25 +1473,21 @@ def _first_dim_len(value): .index_put((_pk_tgt,), _pk_sel.to(torch.float32)) .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) + # 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) ) - # debug knob (force re-verify every step) commented out; re-enable by hand - # _pk_force_verify = ( - # os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_VERIFY", "0") == "1" - # ) + # debug: hand-edit this condition to force re-verify every step 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) + # verify against the per-row forward (ground truth) _pk_ref = torch.zeros_like(_pk_result) with _get_inference_mode_context_manager(model): with torch.amp.autocast( @@ -1540,7 +1525,7 @@ def _first_dim_len(value): _pk_rkeep ].to(torch.float32) device_synchronize() - # compare over the exact loss-mask region (same mask the loss uses) + # compare over the loss-mask region only _pk_cm = _pk_cmask.float() _pk_diff = float(((_pk_result - _pk_ref).abs() * _pk_cm).max()) if UNSLOTH_ENABLE_LOGGING: @@ -1548,12 +1533,11 @@ def _first_dim_len(value): 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 + # kernel-noise floor ~0.25; cross-sample contamination is >= 2.4 if _pk_diff < 7e-1: 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 + # widen the trusted shape only when >= 2 completion rows exercised + # cross-sample packing; single-row passes prove nothing if _pk_active >= 2: unwrapped_model._unsloth_seq_packing_nograd_verified_T = max( _pk_vT, _pk_T @@ -1566,12 +1550,10 @@ def _first_dim_len(value): else: _pk_use = False if _pk_diff >= 1.5: - # large mismatch = contamination (attention ignores the packed - # mask, e.g. some MoE): disable packing for this model + # contamination (attention ignores the packed mask): disable packing unwrapped_model._unsloth_seq_packing_nograd_ok = False else: - # moderate mismatch -> likely a length boundary (LongRoPE): mark - # unsafe but keep packing for smaller shapes + # likely a length boundary (LongRoPE): mark unsafe, keep smaller shapes unwrapped_model._unsloth_seq_packing_nograd_unsafe_T = ( _pk_T if _pk_unsafe is None else min(_pk_unsafe, _pk_T) ) @@ -1581,7 +1563,7 @@ def _first_dim_len(value): flush = True, ) except Exception as _pk_err: - # any failure -> drop intermediates, use the padded loop, do not retry + # any failure: drop intermediates, use the padded loop, do not retry _pk_hidden = None _pk_sel = None _pk_result = None @@ -1598,8 +1580,7 @@ def _first_dim_len(value): 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 + # free packed intermediates before running the padded loop _pk_hidden = _pk_sel = _pk_result = _pk_ref = None with _get_inference_mode_context_manager(model): @@ -1686,8 +1667,7 @@ 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) - if logprobs is None: - # padded fallback (packing disabled / unsupported / not verified for this length) + if logprobs is None: # padded fallback when packing was not used logprobs = torch.cat(all_logprobs_list, dim = 0) entropies = None @@ -1768,10 +1748,8 @@ def _unsloth_get_final_logit_softcapping(model): RL_PRE_ITEMS["grpo_trainer"].append(grpo_compute_loss_slow) RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(grpo_update_SamplingParams)) RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_get_inference_mode_context_manager)) -# Module-level constants the inlined grpo functions reference. inspect.getsource inlines the -# function bodies but NOT the module imports, so names like UNSLOTH_ENABLE_LOGGING must be -# (re)defined in the generated cache module. Provide it as a pre-item so the seq-packing / -# PrefixGrouper verify logging branches resolve it (env-driven, default off). +# inspect.getsource inlines function bodies but not module imports, so constants the inlined +# grpo functions reference (e.g. UNSLOTH_ENABLE_LOGGING) must be redefined in the generated cache. RL_PRE_ITEMS["grpo_trainer"].append( "import os as _unsloth_os\n" "UNSLOTH_ENABLE_LOGGING = _unsloth_os.environ.get('UNSLOTH_ENABLE_LOGGING', '0') in ('1', 'True', 'true')\n" From ba1233d86533c01fe8e8260a2ff501b376d8c6c8 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 6 Jul 2026 08:37:39 +0000 Subject: [PATCH 22/22] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- unsloth/models/rl_replacements.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py index 19637ee62a2f..0573fd5fd8e7 100644 --- a/unsloth/models/rl_replacements.py +++ b/unsloth/models/rl_replacements.py @@ -1482,9 +1482,7 @@ def _first_dim_len(value): getattr(unwrapped_model, "_unsloth_seq_packing_nograd_verified_seg", 0) ) # debug: hand-edit this condition to force re-verify every step - if ( - _pk_ok is True and _pk_T <= _pk_vT and _pk_maxseg <= _pk_vS - ): + if _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 forward (ground truth)