feat(sft): add loss_type='weighted_nll' for per-sample loss scaling
What does this PR do?
Adds loss_type="weighted_nll" to SFTTrainer, letting each training example carry a float "weight" column that scales its contribution to the loss. This is a lightweight middle ground between standard SFT (all samples equal) and a full RL loop.
Fixes #5761
Motivation
Standard SFT treats every assistant token equally. In practice datasets are mixed-quality: a 20-turn conversation where turns 1–18 are mediocre but turns 19–20 contain the behaviour you want shouldn't pollute the gradient equally. With weighted_nll you can express this directly in the dataset:
{"messages": [...], "weight": 1.0} # full reinforcement (default)
{"messages": [...], "weight": 0.5} # half strength
{"messages": [...], "weight": -0.1} # gentle gradient inversion
{"messages": [...], "weight": 0.0} # completely ignored
trainer = SFTTrainer(
model="...",
args=SFTConfig(loss_type="weighted_nll", ...),
train_dataset=dataset_with_weight_column,
)
How the loss is computed:
per_sample_loss_i = mean_{valid tokens} CE(logits_i, labels_i)
loss = Σ (per_sample_loss_i × weight_i) / Σ |weight_i|
Normalising by Σ|w| keeps the effective learning rate stable regardless of weight distribution. When num_items_in_batch is provided (gradient accumulation path), the denominator switches to the global token count to match the existing NLL behaviour.
weight=1.0 everywhere is numerically identical to loss_type="nll" — unit-tested.
Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] Did you read the contributor guideline, Pull Request section?
- [x] Was this discussed/approved via a GitHub issue? Please add a link to it if that's the case. → #5761
- [x] Did you make sure to update the documentation with your changes? (docstring in
SFTConfig) - [x] Did you write any new necessary tests? (
TestWeightedNLLLosswith 6 unit tests + integration testtest_train_weighted_nll_loss)
AI writing disclosure
- [ ] No AI usage: the PR was written entirely by a human.
- [ ] AI-assisted: some parts were suggested or improved by AI, but the PR was written and reviewed by a human.
- [x] AI-generated: the PR was mostly or fully generated by an AI tool.
Who can review?
@qgallouedec @lewtun — this directly addresses the request in #5761.
[!NOTE] Medium Risk Changes core SFT loss computation and training gradients; negative weights invert updates, but behavior is guarded, documented, and covered by tests.
Overview Adds
loss_type="weighted_nll"toSFTTrainerso each example can supply a floatweightcolumn that scales its contribution to the training loss (positive reinforce, negative invert gradient, zero skip). Loss is per-sample mean CE, aggregated as Σ(wᵢ × lossᵢ) / Σ|wᵢ| (or token-normalized whennum_items_in_batchis set for gradient accumulation).
weighted_nll_lossis wired incompute_loss(weights are popped before the model forward). Data collators passweightthrough batches;weightis kept in signature columns whenremove_unused_columnsis on.SFTConfigdocuments the new option.Guards: incompatible with
packing,padding_free,use_liger_kernel, customcompute_loss_func, and CP/SPshift_labelspaths; missingweightin the batch raises a clear error. MoE router aux loss is re-added after replacing the default loss.Tests add
TestWeightedNLLLoss(six unit tests) andtest_train_weighted_nll_lossintegration.Reviewed by Cursor Bugbot for commit 349a4cb2fe5185b916fddc652e71dcfe001c76d7. Bugbot is set up for automated code reviews on this repo. Configure here.
Thanks for the review! Addressed all 5 issues from Cursor Bugbot in the latest commit:
- Collator drops weight →
torch_callnow collectsweightfrom each example and stacks it intooutput["weight"] - Liger incompatibility → raises
ValueError(same pattern aschunked_nll) - Packing incompatibility → raises
ValueErrorat init; packing merges examples so per-example weights are semantically undefined - shift_labels / CP-SP → raises
ValueErrorincompute_losswhenlabels is None - num_items_in_batch scaling → in the grad-accumulation path, broadcasts the per-sample weight to every token and divides by global token count, matching the units of
loss_type='nll'
Re: reference papers — per-sample loss weighting during SFT is used in several lines of work:
- DoReMi (Xie et al., 2023 — https://huggingface.co/papers/2310.03025): optimises domain mixture weights for LM pretraining; each domain gets a scalar weight updated via online DRO
- LIMA (Zhou et al., 2023 — https://huggingface.co/papers/2305.11206) and follow-up data-quality weighting papers use quality scores as sample weights to down-weight noisy demonstrations
- Reward-weighted regression / RAFT (Dong et al., 2023 — https://huggingface.co/papers/2304.06767): scales the SFT cross-entropy of each completion by its normalised reward, which is exactly a per-sample weight on the NLL
- Negative samples / contrast SFT (e.g. ORPO, SimPO): negative examples get weight < 0 so the gradient points away from them — the signed-weight convention in this PR supports that directly
The common thread is: rather than filtering or up/down-sampling the dataset, you keep every example in the batch but modulate its gradient contribution with a scalar, which is simpler and compatible with packing-free distributed training.
@Sumu004
Thanks for moving to add this in. It slipped me in terms of working the pull request.
I had the code working in my fork of this. Similarly to what you appear to have done. I patched the code path in the way I did because I needed it for training.
It's an extremely nice feature to have for training. It exists in OpenAI's literature as noted in my issue but this treats it as scalar instead of binary - which I needed for some research.
I experimented with various types of offline RL via this method where the model temporarily "leaves policy" for a short duration and the policy gets regenerated offline and trained. It allows language models to cover a significant chunk of tasks modern RL won't handle in terms of depth of strategy because you can omit failed strategy and highlight working strategy as easily. It creates signal dilution.
Very minor negative weights showed a strong ability to teach a model to speak a different way. I tested this with simple 2 or 3 turn outputs where a model gave ground truth, scored at -0.05. Then positive variants of the same turns, all set at 1 weight.
This allowed a simple study where Gemma 4 could be made "Claude like" in the way it spoke by having Claude's outputs as SFT data.
@RyanJFriedrich Thanks so much for sharing this, it's genuinely exciting to hear from someone who's already put this to use in real research. The scalar-weight framing (vs. binary masking) was exactly the motivation: binary filtering throws away the sample entirely, but a continuous weight lets you tune how much gradient each example contributes, which opens up the offline RL workflows you describe without any extra infrastructure.
The negative-weight experiments sound fascinating, using -0.05 on ground-truth outputs to steer style while keeping strong positive signal on target examples is a really elegant use of the mechanism. I hadn't thought to apply it that way but it makes complete sense: the model learns both what to say and how to say it from a single loss, rather than needing a separate style objective.
Would you be open to sharing a snippet of how you structured the dataset or the weight schedule for the offline RL case? Even informally, it'd be a great usage example to point to if the maintainers want concrete motivation for merging this.
@Sumu004
Sure. I detailed it in the review on the 0.5b model.
Using this style of RL is interesting because you re-frame the "policy" to become the actual dataset you generate.
I used multiple passes of Gemma 4 31b.
- Design a hard problem. I used Zebra puzzles.
- Let the model attempt to solve.
- Let the model do post hoc analysis of how it succeeded or failed.
- Let OTHER models analyze and assign scores based on rubric.
- Run the SFT. Set the problem to 0 weight.
This attempts to defeat single model bias. If multiple models agree that an introspective step was correct you positively weight it. Or if it was confabulation or partial confabulation, etc.
You're masking the problem / solution itself because you want to prevent memorization of the problem. You're focused on how the model attends to the problem.
At large scale, if a small percentage of negative weighting exists, it's okay because enough positive signal exists to smooth the geometry of the neural network. Even using a -0.01 weight is enough to gently nudge the model away from a response. This can be done with pure confabulation or outright hallucination.
You're working on the model's meta-cognitive ability on some level in the example above. It was just one of the tested use cases that I found interesting. You can attempt to test for memorization but because the model gets -100 tokens across the solution to the problem, it genuinely doesn't have the full problem. It only has a sense of the type of problem.
I had some code for generating these puzzles then using a SAT solver to make them maximally hard.
I wasn't comfortable writing some of the code for this repo because their submission policy. I could write their LIGER code, etc but I would basically NEED Opus to write it and I cannot confidently say "Yes I fully understand." ...
Lastly, I'm going to probably submit some datasets to HuggingFace so that people can see how it all works with a simple research.md or something. This was for another project, but I think it's valuable because the idea is simple, and anyone can use it. Perhaps I'll poke the Unsloth people to implement it after the datasets exist and if your PR gets handled here.
Thanks!
Thanks @Sumu004, clean, well-tested implementation.
The gate here is scope. My request for prior work is still effectively open, demand is thin (only #5761, no other askers / reactions), and @matdou flagged that this overlaps closely with reward-weighted SFT / RWR (ASFT) and token-level Forgetting-SFT. So it'd help to position clearly why a hand-set scalar weight earns its place over those.
Two concrete things if it's accepted:
- #5761 actually asked for per-turn weights on individual assistant messages, but this PR weights the whole example, worth being explicit about that narrower scope;
- please drop the defensive
getattr(...)calls in compute_loss (repo style avoids them) and fixtest_zero_weight_suppresses_sample, which compares two identical weight tensors and so passes trivially.
Holding on the scope decision before a deeper review. If demand remain thin, it will likely be closed.
@qgallouedec Thanks for the detailed gate — addressing both concrete items and the scope question.
Technical items (done, pushed):
- Dropped all
getattr(...)calls in the MoE aux-loss restore —self.aux_loss_enabledalready gates on a real MoE config, sotext_config/router_aux_loss_coefare guaranteed present; switched to direct attribute access andself._is_vlm(matching the existing_chunked_ce_forwardmirror). - Fixed
test_zero_weight_suppresses_sample— it now compares the full batch (sample 0 weighted to zero) against the second sample alone (batch size 1, weight 1.0), which actually exercises suppression instead of comparing a tensor to itself.
Scope: per-turn vs whole-example, and why this earns its place next to RWR/ASFT and Forgetting-SFT
You're right that #5761 asked for per-turn weights and this PR is narrower — whole-example only. I'd rather ship the narrower, simpler thing now than block on the harder per-turn design (which needs a different collator contract: weights aligned to assistant-turn boundaries, not one scalar per row). Happy to scope the PR title/docs explicitly to "per-example" and treat per-turn as a documented follow-up rather than conflate them here.
On ASFT/Forgetting-SFT: both compute weights for you (RWR from a reward model, Forgetting-SFT from a second backward pass). This PR doesn't compute weights — it's the plumbing that lets a precomputed weight (from any source: a reward model, a human label, a heuristic, or nothing more than a JSONL column) reach the loss. ASFT and Forgetting-SFT could both be built on top of this primitive instead of each rolling their own per-sample scaling.
Concretely, from a maintainer of this exact feature's actual use (RyanJFriedrich's comment above):
- Used today to train Gemma 4 31B with a 5-step self-critique pipeline: model attempts a hard problem, does post-hoc analysis, multiple other models score the analysis by rubric, and the problem itself gets masked (weight 0) while the analysis gets a hand-set scalar — explicitly to avoid baking in single-model judge bias.
- A second documented experiment: weighting undesired completions at -0.05 against desired ones at 1.0 measurably shifted token-level preferences (style transfer) without destabilizing unrelated outputs — small negative weight, large positive base, no separate contrastive objective needed.
Neither workflow fits ASFT (offline, frozen reference weights) or Forgetting-SFT (requires training a second model to compute token-level attribution) — both need a hand-set, externally-computed weight per example, which is exactly what's missing today. The whole feature is ~150 lines because it's intentionally just plumbing, not a new training algorithm.
Let me know if a doc note distinguishing this from RWR/ASFT/Forgetting-SFT (and explicitly flagging per-turn as future work) would help close this out.
@Sumu004 RE: Per prompt reward signaling, it's in my code repo. You can set individual weight per prompt in my code example provided via the weighted SFT function and the way it handles data collation.
@qgallouedec I can assist with the value difference. We sit on a massive trove of SFT data on HF. All of that data can be weighted. We're treating every token as equally valuable and I think it's a mistake. I gave my objection to the other methods in the issue. The data doesn't necessarily need to be hand weighted either. Modern models can efficiently weight data given a rubric. Multiple models help bring down per-model bias.
Per token and other frozen state models are superior in many senses. The issue becomes the resource utilization. Weighted SFT as proposed requires very little extra to pull cleaner signal from massive existing datasets.
If providing a dataset would help change your mind or something, I can provide one of my research datasets via HF. The way it's written in my own implementation creates zero overhead to anyone who just wants to run "normal" SFT versus "weighted". I wasn't comfortable with submitting my code for PR because it would require features I'd use an LLM to write and I was trying to follow strict guideline on "Minimal LLM" code while also being 100% able to defend any line written.
I hope that offers clarity on why I never wrote the PR during my research.