Repository navigation
Opt-in token-balanced and token-budget SFT micro-batches - #13878
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex security review |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
Skip token splitting and balancing when the loss is a per micro-batch mean (no num_items_in_batch, or a LabelSmoother without it), or when the MoE router auxiliary loss is active. Refuse to split batches with media keys or per-sample list metadata. Keep the first step window unbalanced when accelerate's even_batches pads the tail from it. [skip ci]
…hed loaders; one host read per split [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6f54244214
ℹ️ 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".
| if getattr(trainer, "compute_loss_func", None) is not None: | ||
| return True |
There was a problem hiding this comment.
Require proof that custom losses use the shared count
When a caller supplies a compute_loss_func that returns a normal per-call mean, this unconditional True enables both features even though merely receiving num_items_in_batch does not mean the callback uses it as the denominator. A budgeted batch then sums several chunk means, while balancing with gradient accumulation changes which examples contribute to each mean, so both losses and gradients differ from the unsplit/unbalanced run; Transformers explicitly shows that a count-aware custom loss must use sum reduction and divide by the shared count (guidance). Refuse arbitrary callbacks unless they explicitly declare count-aware normalization.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
compute_loss_func is called by the Trainer with num_items_in_batch for exactly this purpose (transformers' gradient accumulation docs); a callback that ignores it already gives a per-micro-batch mean under ordinary gradient accumulation without this feature, so the opt-in does not introduce the mismatch and cannot inspect arbitrary callables for their reduction.
…boundary labels with shift_labels, read lengths in batches [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bfcfef3093
ℹ️ 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".
| optim = str(getattr(args, "optim", "")).lower() | ||
| # LOMO / AdaLomo and the *_layerwise optimizers update weights inside every backward. | ||
| if "lomo" in optim or "layerwise" in optim: |
There was a problem hiding this comment.
Detect fused-backward optimizers passed outside args.optim
When LOMO or a layerwise optimizer is supplied through Trainer's supported optimizers= or optimizer_cls_and_kwargs= APIs, args.optim can remain adamw_torch, so this check permits splitting and balancing even though the optimizer updates parameters during each backward pass. Later chunks are consequently forwarded with already-updated weights, and balanced accumulation slots change the sequence of optimizer updates. The fresh case not covered by the earlier LOMO fix is the explicitly supplied optimizer/class; inspect those in addition to args.optim before enabling either feature.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
LOMO and the layerwise optimizers are configured through args.optim in Trainer (they need the Trainer's special backward path to work at all), which is what the blocker reads. Passing such an optimizer object through optimizers= bypasses that path in Trainer itself, so it is not a supported way to run them.
| with context: | ||
| loss = original_training_step(model, chunk, num_items_in_batch, *args, **kwargs) | ||
| total = loss if total is None else total + loss |
There was a problem hiding this comment.
Preserve token weighting in SFT metrics
When one micro-batch is split into uneven chunks, each call to original_training_step appends a separate chunk-local entropy and token-accuracy value, while SFTTrainer later takes an unweighted mean of those entries (TRL 0.22.2 source). A small final chunk therefore receives the same reporting weight as a full chunk, so enabling the budget changes entropy and mean_token_accuracy even when predictions are identical. Suppress per-chunk metric recording and append one numerator/denominator aggregate for the original micro-batch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
These are logged metrics only; the loss and gradients are exact. The averaging over appended entries already mixes micro-batches of different sizes in TRL itself under gradient accumulation, so this does not introduce a new inaccuracy class, and changing TRL's metric bookkeeping is out of scope here.
…sted per layer type [skip ci]
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…-budget metrics across ranks (unslothai#14207) ## Summary Three follow-ups on opt-in features. Default runs are unchanged. 1. **MFU logging (unslothai#13885).** For packed batches that carry only `position_ids`, the token count branched on data, which broke `fullgraph = True` compilation and added a host sync per micro-batch. It is now computed without a data-dependent branch. Also adds an H200 NVL entry at 835.5 dense TFLOPS (half of NVIDIA's 1,671 with-sparsity figure); it was being measured against the H200 SXM peak. 2. **NCCL INFO logs under `UNSLOTH_DEBUG_DISTRIBUTED` (unslothai#13884).** Importing unsloth_zoo sets `NCCL_DEBUG=WARN` whenever a logging or compile-debug switch is on, so the debug flag lost the NCCL INFO logs it asks for. With `UNSLOTH_DEBUG_DISTRIBUTED` set, unsloth now saves `NCCL_DEBUG` before that import and restores it after. 3. **Token-budget split metrics across ranks (unslothai#13878).** Logged accuracy and entropy from split chunks were averaged per rank. Each chunk is now weighted by its token count summed across ranks. The decision to merge is folded into the existing chunk-count collective, so every rank merges or none do: no extra collective and no chance of one rank waiting on another. ## Tests | File | main | this PR | |---|---|---| | `tests/test_mfu_logging.py` | 2 failed | pass | | `tests/test_debug_distributed_env.py` | 2 failed (real zoo import) | pass | | `tests/test_token_budget_metrics_distributed.py` (2 gloo ranks) | 3 failed | pass | 53 passed in total. ## Not covered here - No real multi-rank NCCL run; the distributed tests use gloo. - The H200 NVL device-name string is assumed to contain "H200 NVL". - A `NCCL_DEBUG` you export yourself is still overwritten when the debug flag is off; that needs a change in unsloth_zoo.
Padding-free and packed SFT batches have a fixed row count but a very uneven token count. One micro-batch with a few long rows sets peak memory, and one data-parallel rank with the long rows makes the others wait at the gradient all-reduce. This adds two opt-in controls. Both are off by default, and with neither set nothing is installed.
UNSLOTH_TOKEN_BALANCE=1reorders the training sampler within each optimizer step. The step's rows are spread over ranks and gradient accumulation slots with equal token sums, using a Karmarkar-Karp largest differencing partition. Each step keeps exactly the same rows, sonum_items_in_batchand the loss normalization are unchanged. Rows only move between ranks whenaverage_tokens_across_devicesis on; otherwise each rank keeps its rows and only its accumulation slots are balanced. The wrap happens after accelerate prepares the dataloader, so seeded shuffling is preserved.group_by_lengthandbatch_rebalanceare left alone.UNSLOTH_TOKEN_BUDGET=<tokens>runs a micro-batch larger than the budget as several forward and backward passes over whole sequences, each divided by the samenum_items_in_batch, so the result equals the unsplit step. Padding-free batches split between sequences, and padded batches split by rows. Vision batches, DeepSpeed and FSDP are not split.On a tiny Llama with LoRA, with both controls off the run is bitwise identical to main. With them on, the per-step token counts are identical and the loss differs by about 1e-4, at the bf16 noise floor. On that run, balancing cut the largest micro-batch from 1017 to 613 tokens and the peak memory from 666 to 467 MiB, and a 200-token budget held peak memory at 364 MiB. On two GPUs with DDP, the median per-rank token imbalance went from 40% to 6%. CPU tests cover the partitioner, the step invariants against accelerate's batch sharding, and exact loss and gradient equality for split batches. They pass on transformers 4.57.6 with TRL 0.22.2 and on transformers 5.17 with TRL 1.15.
Not covered: no speed claim (tiny model, shared GPUs), real-size models, TRL
packing=Trueon GPU, DeepSpeed / FSDP (split disabled there, balancing untested), iterable datasets (ignored), torch 2.6. Bucket padding was not added: torch.compile built one graph across lengths 38 to 1017 on the tiny Llama, so there were no recompiles to remove.