Repository navigation
GRPO: sequence packing for the no-grad old/ref logp path (default-on) #6738
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 18 commits
76bc679
9f2b246
26d0337
38562de
6298366
4d69187
499e528
b5127aa
537c276
3814b68
840ed89
a2b135f
e014c0a
f4771ef
4e8f30c
7dc44d3
1ef2184
5376fb7
30b8d3f
2baae82
85244ba
80b24d1
1ab029f
ba1233d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -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, | ||||||
|
|
@@ -1358,6 +1359,251 @@ def _first_dim_len(value): | |||||
| ) | ||||||
| os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1" | ||||||
|
|
||||||
| # ---- Sequence packing (default-on; disable with UNSLOTH_GRPO_SEQ_PACKING=0) ---- | ||||||
| # One varlen [1, sum L] block-diagonal forward replaces the padded [B, Lmax] loop: the exact | ||||||
| # per-row result, and it fixes the padded path's left-pad RoPE error. Self-verified against | ||||||
| # the per-row forward (shape/RoPE-aware, re-checked as T grows); falls back if a backend | ||||||
| # ignores packed_seq_lengths. lm_head runs on completion positions only. | ||||||
| logprobs = None | ||||||
| _pk_result = None | ||||||
| _pk_use = False | ||||||
| _pk_enabled = os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "1").lower() not in ( | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This makes no-grad old/ref sequence packing default-on for every text GRPO run, but the gradient-path policy logps still come from the installed Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done: packing is gated on UNSLOTH_ZOO_HAS_MASKED_COL_GUARD (detected once at import), and the min zoo pin ships both the guard and the matching policy-path packing, so the two stay consistent. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
With the default value set to Useful? React with 👍 / 👎. |
||||||
| "0", | ||||||
| "false", | ||||||
| "no", | ||||||
| "off", | ||||||
| ) | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This path is default-on, but the repo still allows Useful? React with 👍 / 👎. |
||||||
| if _pk_enabled: | ||||||
| # The packed path leaves masked prompt/pad logprob columns at 0, which only stays finite | ||||||
| # if the unsloth_zoo grpo_compute_loss zeroes those columns before exp() (zoo#840). Detect | ||||||
| # that guard once (cached on the model) and disable packing against an older unsloth_zoo | ||||||
| # so we never feed a NaN-prone loss; it re-enables automatically once the guard is present. | ||||||
| _pk_guard = getattr(unwrapped_model, "_unsloth_zoo_masked_col_guard", None) | ||||||
| if _pk_guard is None: | ||||||
| try: | ||||||
| import inspect as _pk_inspect | ||||||
| from unsloth_zoo.rl_replacements import RL_REPLACEMENTS as _pk_RL | ||||||
| _pk_guard = "torch.where(_keep, new" in _pk_inspect.getsource( | ||||||
| _pk_RL["grpo_compute_loss"] | ||||||
| ) | ||||||
| except Exception: | ||||||
| _pk_guard = False | ||||||
| unwrapped_model._unsloth_zoo_masked_col_guard = _pk_guard | ||||||
| _pk_enabled = _pk_guard | ||||||
| _pk_ok = getattr(unwrapped_model, "_unsloth_seq_packing_nograd_ok", None) | ||||||
| if ( | ||||||
| _pk_enabled | ||||||
| and pixel_values is None | ||||||
| and token_type_ids is None | ||||||
| and mm_token_type_ids is None | ||||||
| and _pk_ok is not False | ||||||
| ): | ||||||
|
Comment on lines
+1389
to
+1395
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This function is in a hot path, and repeatedly calling if not hasattr(self, "_unsloth_grpo_seq_packing"):
self._unsloth_grpo_seq_packing = os.environ.get("UNSLOTH_GRPO_SEQ_PACKING", "0") == "1"
if (
pixel_values is None
and self._unsloth_grpo_seq_packing
and token_type_ids is None
and mm_token_type_ids is None
and _pk_verdict is not False
): |
||||||
| # this function's source is copied into the generated GRPO trainer, so import the | ||||||
| # logging flag locally (before the try) to keep the bare name defined there too | ||||||
| from unsloth.models._utils import UNSLOTH_ENABLE_LOGGING | ||||||
| try: | ||||||
| _pk_pad = self.processing_class.pad_token_id | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Robustness: Safe Attribute Access for Multimodal ProcessorsMultimodal processors (e.g., Gemma3/Gemma4 processors) do not always expose
Suggested change
|
||||||
| _pk_keep = input_ids != _pk_pad | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When Useful? React with 👍 / 👎. |
||||||
| _pk_len = _pk_keep.sum(dim = 1) | ||||||
| _pk_len_cpu = _pk_len.tolist() # single GPU->CPU sync, reused below | ||||||
| _pk_nz_cpu = [_n for _n in _pk_len_cpu if _n > 0] | ||||||
| _pk_flat = input_ids[_pk_keep].unsqueeze(0) | ||||||
|
Comment on lines
+1397
to
+1402
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The GRPO completion mask is built from
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No divergence: packing keeps every non-pad token (input_ids != pad), so a real EOS is preserved, and when EOS == pad it is masked by the completion mask in both the packed and padded paths identically. The self-verify over that same loss mask would catch any difference. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This flattens every row in Useful? React with 👍 / 👎. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Useful? React with 👍 / 👎. |
||||||
| _pk_T = _pk_flat.shape[1] | ||||||
| _pk_L = input_ids.shape[1] | ||||||
| _pk_W = logits_to_keep + max_left_pad | ||||||
| _pk_maxseg = max(_pk_nz_cpu) if _pk_nz_cpu else 0 | ||||||
| # sliding-window models lose the per-sequence local window in a packed stream | ||||||
| _pk_sw = getattr( | ||||||
| getattr(unwrapped_model, "config", None), "sliding_window", None | ||||||
| ) | ||||||
| _pk_sw_ok = not (isinstance(_pk_sw, int) and _pk_sw > 0 and _pk_maxseg > _pk_sw) | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
For Mistral-style sliding-window models, this guard only compares each segment length with Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The sliding-window guard is per-segment by design, but a flattened-length crossing cannot ship a contaminated result. Reaching the SWA path requires |
||||||
| # exact per-row completion mask (same one the loss uses); a row is active only if | ||||||
| # it has real completion tokens, so prompt-only rows can't satisfy the >= 2 guard | ||||||
| _pk_cmask = create_completion_attention_mask( | ||||||
| input_ids[:, -_pk_W:], left_pad_tokens_per_prompt, max_left_pad, _pk_pad | ||||||
| ) | ||||||
| _pk_active = int(_pk_cmask.any(dim = 1).sum()) | ||||||
| # read the known-unsafe length here so we can skip the packed forward entirely | ||||||
| # (running it then falling back wastes a full pass and can OOM at large T) | ||||||
| _pk_unsafe = getattr( | ||||||
| unwrapped_model, "_unsloth_seq_packing_nograd_unsafe_T", None | ||||||
| ) | ||||||
| # cap the single flattened forward at one padded mini-batch's token budget | ||||||
| # (B rows x seq_len). A larger batch falls back to the chunked padded loop rather | ||||||
| # than building a [1, sum L] forward bigger than the padded [B, seq_len] mini-batch. | ||||||
| _pk_cap = B * seq_len | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Correct, and this head already caps the packed forward at batch_size*seq_len (one padded mini-batch) so a larger batch falls back to the chunked padded loop rather than building an oversized single forward. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
In text-only GRPO runs that are split into multiple padded chunks, Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good catch, B counts chunks at that point. Fixed to batch_size * seq_len. |
||||||
| if ( | ||||||
| _pk_T >= 2 | ||||||
| and _pk_T <= _pk_cap | ||||||
| and len(_pk_nz_cpu) > 0 | ||||||
| and _pk_sw_ok | ||||||
| and not (_pk_unsafe is not None and _pk_T >= _pk_unsafe) | ||||||
| and (_pk_ok is True or _pk_active >= 2) | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
After a model has Useful? React with 👍 / 👎. |
||||||
| ): | ||||||
|
Comment on lines
+1424
to
+1431
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
For GRPO configurations where Useful? React with 👍 / 👎. |
||||||
| # reset 0-based position_ids per segment | ||||||
| _pk_pos = (_pk_keep.cumsum(dim = 1) - 1)[_pk_keep].unsqueeze(0) | ||||||
| _pk_chunks = max(1, total_rows * multiplier) | ||||||
| _pk_nz_idx = _pk_keep.nonzero( | ||||||
| as_tuple = False | ||||||
| ) # [T, 2] = (row, col), row-major | ||||||
| _pk_within = _pk_nz_idx[1:, 0] == _pk_nz_idx[:-1, 0] # [T-1] | ||||||
| # completion start is per-row after left-packing: (L - logits_to_keep) minus | ||||||
| # that row's left-pad (matches create_completion_attention_mask exactly) | ||||||
| _pk_cstart = (_pk_L - logits_to_keep) - left_pad_tokens_per_prompt # [rows] | ||||||
| _pk_ctgt = (_pk_nz_idx[1:, 1] >= _pk_cstart[_pk_nz_idx[1:, 0]]) & _pk_within | ||||||
| with _get_inference_mode_context_manager(model): | ||||||
| with torch.amp.autocast(device_type = "cuda", dtype = self._autocast_dtype): | ||||||
| # use_cache=False: a KV cache silently disables varlen packing | ||||||
| _pk_hidden = unwrapped_model( | ||||||
| input_ids = _pk_flat, | ||||||
| position_ids = _pk_pos, | ||||||
| packed_seq_lengths = torch.tensor( | ||||||
|
Comment on lines
+1445
to
+1448
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
For Unsloth fast models, the attention code still derives Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The packed forward does size RoPE to the flattened length, but the RoPE cache is a |
||||||
| _pk_nz_cpu, dtype = torch.int32, device = input_ids.device | ||||||
| ), | ||||||
|
Comment on lines
+1446
to
+1450
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This forwards Useful? React with 👍 / 👎.
Comment on lines
+1448
to
+1450
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
In environments where the model's packed attention falls back to SDPA rather than FlashAttention/xFormers, passing Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The dense-mask cost on SDPA-only setups is real but bounded: _pk_T is capped at one padded mini-batch budget before the forward, and an OOM inside the packed try is caught, clears the cache, disables packing for the run, and falls back to the padded loop. Gating on the backend would turn packing off in places the cap already keeps safe. |
||||||
| use_cache = False, | ||||||
|
Comment on lines
+1445
to
+1451
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a LongRoPE-style model has already set Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. position_ids are reset per sequence (0..n-1), so max(position_ids) in the packed forward equals the max per-sequence length, identical to the padded path per-row positions. LongRoPE / YaRN select the short-vs-long factor from that max position, so both paths make the same choice, and the self-test backstops any residual divergence.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Handled by the re-verify envelope: the trusted shape is bounded by verified_T and verified_seg, and a batch whose T or longest segment grows past them re-verifies against the per-row forward, so a LongRoPE regime change cannot be silently trusted.
Comment on lines
+1445
to
+1451
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When Useful? React with 👍 / 👎. |
||||||
| ).logits | ||||||
|
Comment on lines
+1445
to
+1452
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Packing is skipped for sliding-window models when the longest segment exceeds the window (_pk_sw_ok gate), and any residual cross-segment leakage would be caught by the self-verify and fall back. Mirrors the zoo path.
Comment on lines
+1445
to
+1452
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When this path runs while the unwrapped model is in eval/inference mode with Useful? React with 👍 / 👎. |
||||||
| _pk_sel = chunked_hidden_states_selective_log_softmax( | ||||||
| _pk_hidden[0, :-1, :][_pk_ctgt].unsqueeze(0), | ||||||
| lm_head, | ||||||
| _pk_flat[0, 1:][_pk_ctgt].unsqueeze(0), | ||||||
| _pk_chunks, | ||||||
| logit_scale_multiply, | ||||||
| logit_scale_divide, | ||||||
| logit_softcapping, | ||||||
| temperature, | ||||||
| )[0] | ||||||
| # GPT-OSS offload race guard (matches the padded loop) | ||||||
| device_synchronize() | ||||||
| # scatter each completion logprob back to its (row, col) so [:, -_pk_W:] matches padded | ||||||
| _pk_tgt = (_pk_nz_idx[1:, 0] * _pk_L + _pk_nz_idx[1:, 1])[_pk_ctgt] | ||||||
| _pk_result = ( | ||||||
| torch.zeros( | ||||||
| total_rows * _pk_L, | ||||||
|
Comment on lines
+1466
to
+1469
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When Useful? React with 👍 / 👎. |
||||||
| dtype = torch.float32, | ||||||
| device = input_ids.device, | ||||||
| ) | ||||||
| .index_put((_pk_tgt,), _pk_sel.to(torch.float32)) | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When Useful? React with 👍 / 👎. |
||||||
| .view(total_rows, _pk_L)[:, -_pk_W:] | ||||||
| ) | ||||||
| # trust decision: re-verify when T or the longest segment grows past what was | ||||||
| # verified (a LongRoPE cache switch can change the result) | ||||||
| _pk_vT = int( | ||||||
| getattr(unwrapped_model, "_unsloth_seq_packing_nograd_verified_T", 0) | ||||||
| ) | ||||||
| _pk_vS = int( | ||||||
| getattr(unwrapped_model, "_unsloth_seq_packing_nograd_verified_seg", 0) | ||||||
| ) | ||||||
| _pk_force_verify = ( | ||||||
| os.environ.get("UNSLOTH_GRPO_SEQ_PACKING_VERIFY", "0") == "1" | ||||||
| ) | ||||||
| if ( | ||||||
| (not _pk_force_verify) | ||||||
| and _pk_ok is True | ||||||
| and _pk_T <= _pk_vT | ||||||
| and _pk_maxseg <= _pk_vS | ||||||
| ): | ||||||
| _pk_use = True # already verified for this shape | ||||||
| else: | ||||||
| # verify against the per-row clean forward (exact ground truth) | ||||||
| _pk_ref = torch.zeros_like(_pk_result) | ||||||
| with _get_inference_mode_context_manager(model): | ||||||
| with torch.amp.autocast( | ||||||
| device_type = "cuda", dtype = self._autocast_dtype | ||||||
| ): | ||||||
| for _pk_i in range(total_rows): | ||||||
| _pk_ni = _pk_len_cpu[_pk_i] | ||||||
| if _pk_ni < 2: | ||||||
| continue | ||||||
| _pk_rmask = _pk_keep[_pk_i] | ||||||
| _pk_real = input_ids[_pk_i][_pk_rmask].unsqueeze(0) | ||||||
| _pk_rpos = torch.arange( | ||||||
| _pk_ni, device = input_ids.device | ||||||
| ).unsqueeze(0) | ||||||
| _pk_rh = unwrapped_model( | ||||||
| input_ids = _pk_real, | ||||||
| position_ids = _pk_rpos, | ||||||
| use_cache = False, | ||||||
| ).logits | ||||||
| _pk_rsel = chunked_hidden_states_selective_log_softmax( | ||||||
| _pk_rh[:, :-1, :], | ||||||
| lm_head, | ||||||
| _pk_real[:, 1:], | ||||||
| 1, | ||||||
| logit_scale_multiply, | ||||||
| logit_scale_divide, | ||||||
| logit_softcapping, | ||||||
| temperature, | ||||||
| )[0] | ||||||
| _pk_rcols = _pk_rmask.nonzero(as_tuple = False).squeeze(1)[ | ||||||
| 1: | ||||||
| ] - (_pk_L - _pk_W) | ||||||
| _pk_rkeep = _pk_rcols >= 0 | ||||||
| _pk_ref[_pk_i, _pk_rcols[_pk_rkeep]] = _pk_rsel[ | ||||||
| _pk_rkeep | ||||||
| ].to(torch.float32) | ||||||
| device_synchronize() | ||||||
| # compare over the exact loss-mask region (same mask the loss uses) | ||||||
| _pk_cm = _pk_cmask.float() | ||||||
| _pk_diff = float(((_pk_result - _pk_ref).abs() * _pk_cm).max()) | ||||||
| if UNSLOTH_ENABLE_LOGGING: | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This replacement function is copied into the dynamically generated GRPO trainer with Useful? React with 👍 / 👎. |
||||||
| print( | ||||||
| f"[Unsloth] GRPO seq-packing (no-grad) verify: T={_pk_T} maxseg={_pk_maxseg} packed-vs-perrow max|d|={_pk_diff:.4f}", | ||||||
| flush = True, | ||||||
| ) | ||||||
| # floor ~0.25 through different kernels; cross-sample contamination is >= 2.4 | ||||||
| if _pk_diff < 7e-1: | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a text-only GRPO batch first exercises sequence packing, this accepts packed old/ref logps that differ from the per-row reference by anything under Useful? React with 👍 / 👎. |
||||||
| unwrapped_model._unsloth_seq_packing_nograd_ok = True | ||||||
| # only widen the trusted shape when >= 2 completion rows actually | ||||||
| # exercised cross-sample packing; a < 2 row pass proves nothing, so | ||||||
| # keep re-verifying larger shapes until a real multi-row batch clears | ||||||
| if _pk_active >= 2: | ||||||
| unwrapped_model._unsloth_seq_packing_nograd_verified_T = max( | ||||||
| _pk_vT, _pk_T | ||||||
| ) | ||||||
| unwrapped_model._unsloth_seq_packing_nograd_verified_seg = max( | ||||||
| _pk_vS, _pk_maxseg | ||||||
| ) | ||||||
| _pk_ok = True | ||||||
| _pk_use = True | ||||||
| else: | ||||||
| _pk_use = False | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When the verifier rejects a packed run, this falls through to the padded loop with Useful? React with 👍 / 👎. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When verification rejects the packed result (for example because the backend ignored Useful? React with 👍 / 👎. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When the packed/per-row comparison fails here, execution falls through to the padded loop with Useful? React with 👍 / 👎. |
||||||
| if _pk_diff >= 1.5: | ||||||
| # large mismatch = contamination (attention ignores the packed | ||||||
| # mask, e.g. some MoE): disable packing for this model | ||||||
| unwrapped_model._unsloth_seq_packing_nograd_ok = False | ||||||
| else: | ||||||
| # moderate mismatch -> likely a length boundary (LongRoPE): mark | ||||||
| # unsafe but keep packing for smaller shapes | ||||||
| unwrapped_model._unsloth_seq_packing_nograd_unsafe_T = ( | ||||||
| _pk_T if _pk_unsafe is None else min(_pk_unsafe, _pk_T) | ||||||
| ) | ||||||
| if UNSLOTH_ENABLE_LOGGING: | ||||||
| print( | ||||||
| f"[Unsloth] GRPO seq-packing (no-grad) fell back at T={_pk_T} (diff={_pk_diff:.3f})", | ||||||
| flush = True, | ||||||
| ) | ||||||
| except Exception as _pk_err: | ||||||
| # any failure -> drop intermediates, use the padded loop, do not retry | ||||||
| _pk_hidden = None | ||||||
| _pk_sel = None | ||||||
| _pk_result = None | ||||||
| _pk_use = False | ||||||
| if isinstance(_pk_err, torch.cuda.OutOfMemoryError): | ||||||
| torch.cuda.empty_cache() | ||||||
| unwrapped_model._unsloth_seq_packing_nograd_ok = False | ||||||
| if UNSLOTH_ENABLE_LOGGING: | ||||||
| print( | ||||||
| f"[Unsloth] GRPO sequence-packing (no-grad) disabled (fell back to padded): {_pk_err!r}", | ||||||
| flush = True, | ||||||
| ) | ||||||
| if _pk_use and _pk_result is not None: | ||||||
| logprobs = _pk_result # verified -> skip the loop | ||||||
| zipped_inputs = [] | ||||||
| else: | ||||||
| # fell back to the padded loop: drop the packed intermediates first so the loop does | ||||||
| # not run with the full flattened hidden state / reference buffer still resident | ||||||
| _pk_hidden = _pk_sel = _pk_result = _pk_ref = None | ||||||
|
|
||||||
| with _get_inference_mode_context_manager(model): | ||||||
| for ( | ||||||
| input_ids_chunk, | ||||||
|
|
@@ -1442,7 +1688,9 @@ def _first_dim_len(value): | |||||
| # However, it seems that this line does not slow down or disrupt models. | ||||||
| device_synchronize() | ||||||
| all_logprobs_list.append(logprobs_chunk) | ||||||
| logprobs = torch.cat(all_logprobs_list, dim = 0) | ||||||
| if logprobs is None: | ||||||
| # padded fallback (packing disabled / unsupported / not verified for this length) | ||||||
| logprobs = torch.cat(all_logprobs_list, dim = 0) | ||||||
| entropies = None | ||||||
|
|
||||||
| os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "0" | ||||||
|
|
||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When
UNSLOTH_GRPO_SEQ_PACKINGis unset, this default value makes_pk_enabledtrue, so existing text-only GRPO old/ref logp forwards now enter the new packed path without users opting in. That contradicts the commit's default-off/byte-identical behavior guarantee and exposes current users to the flattened-batch verifier/OOM and changed per-row logp path simply by upgrading; default this env lookup to"0"so only explicit opt-in enables packing.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Default-on is intentional and documented at the top of the block; disable with UNSLOTH_GRPO_SEQ_PACKING=0. It mirrors the accepted zoo policy-path packing and is guarded by the zoo masked-column-guard gate plus the first-use self-verify against the per-row forward (fall back on any mismatch).