Skip to content

Mask packed document boundary labels for TRL older than 0.23.1 - #13324

Merged
mahiatlinux merged 6 commits into
mainfrom
mask-packed-boundary-labels
Oct 12, 2026
Merged

mahiatlinux merged 6 commits into
mainfrom
mask-packed-boundary-labels

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

With TRL older than 0.23.1, auto padding-free SFT on the transformers modeling path (FastModel / FastBaseModel) trains the first token of every packed document as a target of the previous document. The reported loss and the gradients are both inflated.

Cause

  • TRL 0.23.1 added labels[position_ids == 0] = -100 to its padding-free collator. TRL 0.18.2 to 0.22.2, all inside Unsloth's supported range (trl>=0.18.2), do not mask those positions.
  • FastLanguageModel's own forward masks them anyway (mask_packed_boundary_labels in llama.py / mistral.py), so it is not affected. The transformers modeling forward has no such guard.
  • unsloth-zoo's num_items_in_batch already zeroes those slots out of the count, so the loss divides boundary-inclusive sums by a boundary-free count.

Change

  • enable_sample_packing and enable_padding_free_metadata now pass the collated batch through mask_packed_boundary_labels with the packed_seq_lengths they already attach, so every TRL version produces the labels TRL 0.23.1+ produces.
  • Idempotent and out of place: on TRL 0.23.1+ the labels are already masked and come back unchanged, and the caller's examples are never mutated. Only a flattened single row is touched, where seq_lengths index it; unflattened rows are left alone.
  • The count is unaffected: the zoo zeroes the same slots instead of subtracting a constant (true of the required unsloth_zoo>=2026.10.3), so pre-masked labels are not double counted.

Verification

Real TRL collator wrapped by Unsloth, three documents of lengths 3, 2, 3:

TRL main this PR
0.22.2 [10, 11, 12, 13, 14, 15, 16, 17] [-100, 11, 12, -100, 14, -100, 16, 17]
0.25.1 [-100, 11, 12, -100, 14, -100, 16, 17] identical

Qwen3-0.6B LoRA SFT, auto padding-free, gradient checkpointing on, 12 steps, main and this PR on one Colab A100. First three losses, with the padded (unpacked) run as the reference:

transformers / TRL FastModel main FastModel this PR padded FastLanguageModel main / this PR
4.55.4 / 0.22.2 5.772, 5.087, 5.071 5.642, 5.018, 5.007 5.641, 5.018, 5.005 5.647 / 5.647
4.57.6 / 0.22.2 5.772, 5.086, 5.070 5.642, 5.016, 5.007 5.641, 5.018, 5.005 5.647 / 5.647
4.57.6 / 0.25.1 5.642, 5.022, 5.007 5.642, 5.017, 5.007 5.641, 5.018, 5.005 5.647 / 5.647
5.17.0 / 0.25.1 5.642, 5.018, 5.004 5.642, 5.019, 5.006 5.641, 5.018, 5.005 5.647 / 5.647

With TRL 0.22.2 the fix brings FastModel onto the padded loss; with TRL 0.25.1 the first-step loss is unchanged (the rest is bf16 run-to-run noise), as is FastLanguageModel everywhere.

Step time is unchanged (one index_fill on the CPU label tensor per batch).

Tests

tests/utils/test_packing.py: both wrappers mask the boundary targets of an unmasked (TRL < 0.23.1 style) collator and the zoo-style count still sees every real target once; already-masked labels come back unchanged; unflattened rows are untouched. The previous test pinned the unmasked labels against a count helper that subtracted a constant, which the zoo stopped doing; it now mirrors the zoo's zeroing. 104 passed, 2 skipped.

…or wrappers

TRL >= 0.23.1 sets labels[position_ids == 0] = -100 in its padding-free collator;
older TRL leaves the first token of every packed document as a target of the
previous one. FastLanguageModel's forward masks those positions, but the
transformers modeling path (FastModel) does not, while unsloth_zoo's
num_items_in_batch already discounts them, so the loss and gradients were
inflated. Mask them in enable_sample_packing and enable_padding_free_metadata,
idempotently and out of place, only for a flattened single row.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-12T04:06:14.290243Z 4cfd4e8 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-11T12:53:20.873821Z cc50935 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

The red here is not from this PR. This run merged onto main at 548fe076fa, which predates #13336. That PR fixed two problems #13308 left on main:

  • test_torchao_fqn_alias.py left a fake diffusers in sys.modules. That causes the AutoencoderKLWan / modular_pipelines / video Regex pattern did not match failures in (Python 3.13, rest).
  • _torchao_stub.py and test_torchao_fqn_alias.py were not formatted. That causes test_formatter_fixed_point in Repo tests (CPU, rest).

A rerun replays the same merge commit, so updating the branch onto current main should clear both.

@mahiatlinux mahiatlinux self-assigned this Oct 11, 2026
@danielhanchen danielhanchen self-assigned this Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 7fa9e06f06

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mahiatlinux

Copy link
Copy Markdown
Contributor

Verified the boundary-label fix independently. No additional correctness defect found; 4cfd4e8d709bc9ab55f1796b463449e1029f2d76 only trims nearby comments/docstrings, with AST equivalence checked.

Base 3a1b69488282ebec369c494455887671f223aa27; original head a893d44dd36f5f35d97fb361cf801310535fb742; prospective merge a376d27afe7daf9586f6ea719a847886d806f7f1; final head 4cfd4e8d709bc9ab55f1796b463449e1029f2d76.

Real TRL collators, both wrappers, documents of lengths [3, 1, 4], followed by a tiny randomly initialized Qwen3 transformers model on an RTX 5060 Ti. Compared packed forward/backward with explicit block-causal attention against separate-document forward/backward using the same weights and denominator. The actual counting function extracted unchanged from the minimum unsloth-zoo==2026.10.3 wheel returns five targets both before and after masking.

TRL / transformers Base loss Final head loss Separate documents Max head gradient error
0.18.2 / 4.57.6 3.4977653 3.4977653 3.4977653 1.79e-7
0.22.2 / 4.57.6 4.8832254 3.4977653 3.4977653 1.79e-7
0.23.1 / 4.57.6 3.4977653 3.4977653 3.4977653 1.79e-7
0.25.1 / 4.57.6 3.4977653 3.4977653 3.4977653 1.79e-7
1.15.0 / 5.17.0 3.4977653 3.4977653 3.4977653 1.79e-7

TRL 0.22.2 base gradient error was 0.5570; original head and prospective merge also matched the separate-document reference. Compatibility detail: TRL 0.18.2 selects DataCollatorWithFlattening, which already masks these starts. The reproduced failure is the 0.22.2 SFT collator; 0.23.1 explicitly masks zero position IDs.

Additional execution:

  • python -m pytest artifacts/test_scoped.py -q: 31 passed on original head, prospective merge, and final tree. The harness loads 19 unchanged repository test cases directly and adds 12 cases covering shared-input preservation, optional/nonflat labels, and 200 seeded randomized batches. The same tests against base give 6 expected failures, 25 passes, detecting both missing wrapper calls.
  • Both real collator wrappers preserve completion/pre-masked labels and caller examples. Latest TRL receives prepared labels according to its newer interface.
  • Repository formatter and Ruff pass on both changed files; comment-only AST gate passes.
  • CPU collator microbenchmark, 16 documents / 4096 tokens, seven samples of 200 calls: median 656.2 us base versus 677.9 us final tree, about 21.7 us added per batch. This measures collation, not training-step throughput.

Environment: Linux x86_64, Python 3.11.15, PyTorch 2.8.0+cu128; execution in a credential-free bubblewrap sandbox with the real GPU. The model comparison uses real transformers forward/backward with controlled attention, not a FastModel training run.

Harnesses, exact dependency pins, GPU results, benchmark, and negative-control logs. Reproduction entry points: python artifacts/check_boundaries.py <tree> fixed (broken for base), and REVIEW_TREE=<tree> python -m pytest artifacts/test_scoped.py -q.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 4cfd4e8d70

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mahiatlinux
mahiatlinux self-requested a review October 12, 2026 04:07

@mahiatlinux mahiatlinux left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! Ready to merge, all manually checked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants