Skip to content

Token balance: UNSLOTH_TOKEN_BALANCE=labels evens out supervised tokens per optimizer step - #18768

Merged
danielhanchen merged 4 commits into
mainfrom
label-balance
Nov 21, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
label-balance

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Add UNSLOTH_TOKEN_BALANCE=labels: even out supervised tokens per optimizer step

With train_on_responses_only (or any prompt-masked dataset), the number of tokens that actually carry a loss swings a lot from one optimizer step to the next, since some rows are mostly prompt and others mostly answer. The loss is normalised by the step's own num_items_in_batch, so a step with few supervised tokens weighs each of them much more than a step with many.

The existing UNSLOTH_TOKEN_BALANCE=1 only reorders rows inside one step window, so it never changes per-step totals. This adds an opt-in labels mode:

  • UNSLOTH_TOKEN_BALANCE=labels reads the per-row supervised count from the dataset as the loss sees it (shifted labels != -100, else completion_mask / assistant_masks) and regroups rows across UNSLOTH_TOKEN_BALANCE_WINDOW (default 8) consecutive optimizer steps with the same Karmarkar-Karp partitioner, so every step carries a similar supervised count.
  • Each step keeps the same number of rows, the multiset of rows per window is unchanged, steps come out in order of their earliest row and rows keep their relative order, so the sampler's shuffle still decides the coarse order. A partial tail window regroups its full steps only; the even_batches first window is kept as before.
  • Inside each step it still applies the exact length balancing when the existing exactness guards pass and batches are not padded; otherwise rows are left in the regrouped order.
  • It needs a labels / mask column and a plain random or sequential sampler; otherwise it prints why and does nothing.

This changes which rows share a step, so it changes the data order. That is why it is its own opt-in value; UNSLOTH_TOKEN_BALANCE=1 (exact) is unchanged and nothing changes by default.

Results

Per-step supervised-token CV, measured on the real collator output (FineTome rows, Qwen3 chat template, train_on_responses_only, batch 4 x accumulation 4):

off exact (=1) labels, window 8 labels, window 16
CPU replay, 2048 rows, 3 seeds, mean CV 0.155 0.155 0.052 0.039

Colab T4, Qwen3-0.6B LoRA r=16, fp16, 64 steps (1024 rows, a multiple of the window, so both arms train on exactly the same rows), held-out loss over 256 unseen FineTome rows with the same response-only masking:

seed CV off CV labels held-out loss off held-out loss labels
3407 0.142 0.033 0.89584 0.89566
3408 0.124 0.040 0.89612 0.89624
3409 0.134 0.048 0.89615 0.89572
mean 0.133 0.040 0.89604 0.89588

The per-step supervised count spread drops about 3.3x. Held-out loss is not worse (mean -0.00016, inside the seed spread), so treat this as a stability knob, not a loss improvement.

Step time on T4 is unchanged: with the arms run in reversed order and an off/off repeat on one card, median step time was 2.257 s (labels) vs 2.256 s and 2.252 s (off, off). In the first runs, where labels always ran second, it showed +1 to +4%, which the reversed run traces to run order on the card, not to the change.

Tests

tests/test_token_budget_batches.py: the regroup keeps every row and its window, keeps order inside a step, lowers CV; the sampler handles partial tails and the kept first window; dataloader end to end with padded and padding-free batches; falls back with a note when there is no labels column; label counts use shifted labels and masks. Existing token balance and budget tests unchanged and passing.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T17:50:36.031585Z 605fe08 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: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-21T16:54:38.041203Z
We couldn’t complete this review. Comment @codex review to try again.
da3222f 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: da3222f7ba

ℹ️ 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".

Comment thread unsloth/utils/token_budget.py Resolved
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ee9aabb895

ℹ️ 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".

Comment thread unsloth/utils/token_budget.py Resolved
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dc7785bac2

ℹ️ 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".

Comment thread unsloth/utils/token_budget.py Resolved
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 605fe08cae

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 32770df into main Nov 21, 2026
@danielhanchen
danielhanchen deleted the label-balance branch November 21, 2026 18:50
FiditeNemini pushed a commit to FiditeNemini/unsloth that referenced this pull request Nov 24, 2026
…ss even (unslothai#18963)

`UNSLOTH_TOKEN_BALANCE=labels` (unslothai#18768) regroups a window of optimizer
steps with the equal-size Karmarkar-Karp pass and uses the result
unconditionally. The pass is a heuristic, so now and then the regrouped
steps are less even than the order the sampler gave:

```
step_size = 3, label_counts = [2, 3, 3, 9, 0, 1]
order given            per-step labels [8, 10]   max - min 2
balance_label_steps    per-step labels [11, 7]   max - min 4
```

`balance_label_steps` now compares the max - min of per-step label sums
before and after, and returns the order it was given when the regroup is
strictly worse. Otherwise the output is unchanged.

It is rare and small: 19 of 20000 random windows at the default shape
(16 rows x 8 steps, lognormal counts), worst seen `[428, 433]` becoming
`[342, 519]`. The cost is one extra pass over the window's counts.

Test (fails on main):
`tests/test_token_budget_batches.py::test_label_steps_are_never_less_even_than_the_order_given`,
the case above plus 2000 random windows.




## Takeover update
Karmarkar-Karp is a heuristic, and the per-step split used by
UNSLOTH_TOKEN_BALANCE=1 (cross-rank and grad-accum slots) could also
come out less even than the sampler's order (about 1 in 12 random
windows at batch_size=4, grad_accum=2; e.g. slot sums [1085, 998] vs the
sampler's [1029, 1054]). The check is now one shared helper (_more_even)
applied at the label, rank and slot levels; wherever the regroup is kept
the output is unchanged (39,076 of 40,000 random cases identical, the
rest at least as even). With both opt-ins unset nothing is installed, so
default training is identical. Added
test_step_balance_is_never_less_even_than_the_order_given (fails before,
passes after); token budget tests 85 passed. Independent of unslothai#18720; both
orders merge to the same tree.

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant