
TL;DR: DFT is a one-line change to supervised fine-tuning. It multiplies each token’s cross-entropy by a stop-gradient copy of the model’s probability for that token. That weight cancels the inverse-probability factor that lets rare tokens dominate a batch step. The change matters most when training rows come from an agent’s own earlier outputs. Below: the gradient math, our dense chunked implementation, and the training dynamics to watch.
Why Cross-Entropy Over-Weights the Tokens You Trust Least
DFT (dynamic fine-tuning) matters most when a model trains on its own outputs. That loop is the setting of recursive self-improvement.
The method starts from an overlooked property of standard supervised fine-tuning (SFT). Standard SFT minimises the summed negative log-probability of the target tokens:
$$\mathcal{L}_{\text{SFT}} = -\sum_t \log p_\theta(y_t \mid x, y_{<t})$$Differentiate one term, and the chain rule gives \(-\nabla_\theta p_t / p_t\). The direction follows the gradient of the token’s probability. However, the magnitude is divided by the probability itself. Suppose the model assigns \(p = 0.5\) to one token and \(p = 0.005\) to another. Both receive the same direction, yet the rare token gets a pull a hundred times stronger for the same \(\nabla_\theta p_t\).
On a clean human corpus, that behaviour is intentional. A token the model gets wrong deserves the largest correction. In an agent loop, by contrast, the rows look very different. Each row is a trajectory the agent produced itself and an outcome gate accepted. Consequently, its low-probability tokens are often lucky guesses, odd variable names, or formatting quirks inside a passing run. The token earned its place by clearing the gate. Even so, cross-entropy hands it a gradient a hundred times larger than its neighbours receive.
This reweighting instinct also has a well-known opposite. Focal loss, introduced by Lin et al. (2017) for dense object detection, scales cross-entropy by \((1-p)^\gamma\). That multiplier lets confident examples fade so hard cases drive learning. It works well when labels are clean and hard cases carry real signal. Self-training reverses that premise because the targets are filtered model samples. Therefore, the most surprising tokens are often the least reliable rather than the most informative.
What DFT Changes in the Loss
Wu et al. (2025) formalise this gradient imbalance. They rewrite the supervised gradient as an on-policy expectation. In that form, standard SFT equals a policy gradient with a sparse indicator reward multiplied by an importance weight of \(1/\pi_\theta\). That \(1/\pi_\theta\) factor creates what they call an ill-posed reward landscape: the less the model believes a target, the harder the update pushes it. To fix this, dynamic fine-tuning multiplies each token’s loss by its own probability under a stop-gradient:
$$\mathcal{L}_{\text{DFT}} = -\sum_t \operatorname{sg}\big(p_\theta(y_t \mid x, y_{<t})\big)\, \log p_\theta(y_t \mid x, y_{<t}), \qquad \operatorname{sg}(p_t) = \exp(-\text{CE}_t).\text{detach}()$$Two practical consequences follow from that algebra. First, the per-token gradient becomes \(\operatorname{sg}(p_t) \cdot (-\nabla_\theta p_t / p_t) = -\nabla_\theta p_t\). The update keeps the same direction while cancelling the \(1/p\) factor. That equals maximising token probability directly instead of its logarithm. Second, the per-token loss \(-p \log p\) peaks at \(1/e\) when \(p = 1/e\). As a result, a weighted loss curve cannot be compared directly with cross-entropy, and a lower loss value does not automatically mean a better fit.
Why the Stop-Gradient Matters
The stop-gradient is essential rather than optional. Without it, the objective becomes \(-p \log p\) with \(p\) live in the computation graph. Its derivative with respect to \(p\) is \(-(\log p + 1)\), which is positive whenever \(p < 1/e\). Gradient descent on that live expression pushes every token below roughly 37 percent probability toward zero. That moves weights in the wrong direction. Detaching the weight turns \(p_t\) into a pure per-token learning-rate multiplier.
Mathematical Reasoning Results Without a Reference Model
The weight is also cheap to compute. Per-token cross-entropy is already \(-\log p_t\), so \(p_t = \exp(-\text{CE}_t)\) comes straight from the existing loss tensor. It needs no gather over a full softmax and no reference forward pass. In the paper’s experiments on Qwen2.5-Math-1.5B trained on 100,000 NuminaMath rows, average accuracy across five math benchmarks shifted sharply. The base model scored 15.92, standard fine-tuning reached 18.01, and confidence weighting reached 31.58. That gain needed neither a reference model nor the large rollout batches of online reinforcement learning (RL). The authors provide code in their DFT repository, and TRL exposes the same objective as a loss_type option on SFTConfig.
The paper’s ablations also define where confidence weighting stops helping. First, token-level granularity matters. Weighting by full-sequence probability collapsed to 15.75 average accuracy and geometric-mean sentence weighting reached only 17.21, compared with 31.58 for token-level weights. Second, factual recall behaves opposite to reasoning. On Natural Questions, standard SFT raised accuracy from 31.24 percent to 36.62 percent, while confidence weighting dropped it to 30.14 percent because unknown facts start with low model probability.
Inside the Fused Implementation
In our training stack, agents periodically train on successful experiences collected from their environments. Each cycle runs modified SFT over a bounded window of recent rows and fits a fresh LoRA (Low-Rank Adaptation) adapter from the frozen base weights. The modification lives inside the loss configuration. An inner_loss setting picks plain cross-entropy ("sft"), confidence weighting ("dft"), or the variant anchored by a Kullback-Leibler (KL) divergence ("asft"). Because acquiring experience stays separate from optimising a reward, we refer to this setup as approximate policy-free online learning.
The fused confidence-weighted objective lives in src/train/dft_fused.py of the nsl-workbench repository. Instead of letting standard NLL run unchecked, install_fused_dft patches two Unsloth loss seams at startup. Specifically, it forces UNSLOTH_ENABLE_CCE="0", pins UNSLOTH_CE_LOSS_N_CHUNKS="16" before Unsloth loads, and swaps compute_fused_ce_loss and unsloth_fused_ce_loss for our wrapped functions. Inside compute_fused_dft_loss (src/train/dft_fused.py:55-96, trimmed):
# src/train/dft_fused.py:55-96, compute_fused_dft_loss (trimmed)
vocab_size = lm_head_weight.shape[0]
flat_labels = labels.reshape(-1).to(device=device).contiguous()
valid = flat_labels != ignore_index
logits = torch.nn.functional.linear(
hidden_states.to(dtype=lm_head_weight.dtype, device=device),
lm_head_weight,
lm_head_bias,
)
# Prevent ignored rows with overflowed logits from contaminating transforms/backward.
logits.view(-1, vocab_size).masked_fill_(~valid.unsqueeze(1), 0.0)
# ... logit scaling and softcapping (lines 66-76) ...
ce = torch.nn.functional.cross_entropy(
input=logits.view(-1, vocab_size).float().contiguous(),
target=flat_labels,
reduction="none",
ignore_index=ignore_index,
label_smoothing=0.0,
)
loss = ((-ce).exp().detach() * ce).sum()
divisor = n_items
if divisor is None:
divisor = (flat_labels != ignore_index).sum().clamp_min(1)
# ... scalar tensor and zero-guard on divisor (lines 90-94) ...
loss = loss / divisor.to(dtype=loss.dtype, device=device)How Dense Chunking Avoids Full-Logit Spikes
Full-sequence vocabulary logits grow fast on modern models. For example, Cut Cross-Entropy from Wijmans et al. (2024) avoids materialising logits in global memory, cutting Gemma 2 2B loss memory from 24 GB to 1 MB for standard cross-entropy. Our fused patch takes a different path for reweighted gradients. It disables Cut Cross-Entropy (UNSLOTH_ENABLE_CCE="0") and delegates unsloth_fused_dft_loss to Unsloth’s torch.compile-wrapped dense chunked wrapper.
Pinning 16 chunks keeps transient memory predictable on 24 GB cards. When a 4-bit base model already fills most of VRAM, Unsloth’s automatic chunk sizer targets free memory and can pick chunks that are too large. With 16 chunks at sequence length 8,192 and Gemma-4’s 262,144-token vocabulary (512 tokens per chunk), each FP32 logit slice stays near 0.5 GiB. Inside compute_fused_dft_loss, Unsloth differentiates each chunk via torch.func.grad_and_value. The function supports lm_head_bias, logit_scale_multiply, logit_scale_divide, and logit_softcapping (tanh scaling), and raises an error on missing symbols rather than silently reverting to negative log-likelihood in Unsloth.
Non-Fused Loss Module and Normalisation Modes
The non-fused path lives in src/train/asft.py alongside ASFTTrainer in src/train/asft_trainer.py. Its _compute_dft_weights helper uses torch.exp(-ce_losses.detach()) when per-token losses exist, and falls back to F.softmax with .gather on effective_logits otherwise. Meanwhile, resolve_effective_mode collapses "asft" to "dft" whenever kl_weight == 0.0, skipping the reference forward pass automatically.
Normalisation across a batch also shapes step size. In asft.py and config.py, asft_normalization_semantics (which replaced the older asft_normalize_by setting) offers three modes. "token_count_v0" is the default and divides by valid token count, letting average batch confidence damp uncertain batches. "microbatch_weights_v0" divides the weighted loss by the microbatch sum of detached weights instead. Finally, "update_weights_v1" divides by the detached weight sum across the entire optimizer-update window via RNG replay in ASFTTrainer, while keeping the KL anchor token-normalised in both weight modes.
Training Dynamics: What Confidence Weighting Fixes and Leaves Open
The clearest change in training dynamics is that gradient spikes disappear. Because every per-token gradient is bounded by \(\|\nabla_\theta p_t\|\), a few rare positions can no longer dominate a batch of self-generated rows. Under token-count normalisation, the batch mean weight (the mean target probability) also works like an automatic damper. Steps on unfamiliar rows stay small, while steps on consolidated rows run at near full scale. Removing that training instability is the main reason we support this objective inside our continual loop.
Why Cold Tokens Stay Cold
Confidence weighting introduces three clear failure modes. First, cold tokens stay cold. A token at \(p = 0.001\) receives one thousandth of the gradient standard cross-entropy gives it. As a result, genuinely new vocabulary, unseen tool names, or unfamiliar API syntax learns slowly. For self-generated rows that trade-off is acceptable because the model already emitted every token in the trace. By contrast, external demonstrations meant to teach brand-new facts or formats learn poorly under this weight, and standard cross-entropy or a scheduled mix fits better.
Our training config handles that split explicitly through inner_loss_schedule. Each entry sets the loss for one generation boundary, so an early cycle can run standard cross-entropy while later cycles switch to confidence weighting or anchored SFT ([{ loss = "sft" }, { loss = "dft" }]). Separating generations lets the base adapter absorb new task format early, then damps outlier gradient spikes once the policy already emits the right structure. However, every scheduled step still starts from the frozen base weights, so each cycle trades early plasticity for stability directly.
No Distributional Anchor Across the Vocabulary
Second, nothing anchors the rest of the vocabulary. The confidence weight acts only on the single target token, leaving the remaining vocabulary coordinates unconstrained. Zhu et al. (2025) analyse this objective through reward-weighted regression. They prove it gives tighter RL bounds than standard fine-tuning, yet also show that missing distributional anchoring leads to progressive drift and instability on broader tasks. Their fix, anchored supervised fine-tuning, keeps the token weight and adds a KL penalty against a reference policy.
With LoRA, that reference pass needs no duplicate model weights in VRAM. Temporarily calling disable_adapter() recovers the frozen base model for the reference forward pass, which is how our anchored SFT trainer computes its KL anchor.
Sharpening and Collapse Across Generations
Third, multi-generation loops can over-sharpen. When each generation trains on its own filtered outputs, weighting by confidence favours tokens the policy already prefers. Over repeated cycles, output distributions narrow faster than under cross-entropy and can slide into training collapse. We rely on structural controls rather than loss tweaks alone to check that drift: a bounded recency window, a fresh LoRA adapter from the frozen base model each cycle, general-corpus rehearsal rows, and a KL anchor whenever held-out checks show drift. Prior adapters stay on disk strictly as a rollback safety net.
| Objective | Per-token weight on cross-entropy | Gradient scale relative to \(\nabla_\theta p_t\) | What it damps | Extra cost |
|---|---|---|---|---|
| Standard supervised fine-tuning | \(1\) | \(1/p_t\) | Nothing | None |
| Focal loss | \((1-p_t)^\gamma\) | \((1-p_t)^\gamma / p_t\) | Confident tokens | None |
| Confidence-weighted fine-tuning | \(\operatorname{sg}(p_t)\) | \(1\) | Improbable tokens | None |
| Anchored supervised fine-tuning | \(\operatorname{sg}(p_t)\) plus a KL term | \(1\) plus the anchor’s pull | Improbable tokens and vocabulary drift | One reference forward pass |
Choosing the Objective for Self-Generated Rows
When a fast, reliable verifier exists, RL with verifiable rewards remains the stronger default. Methods such as GRPO (Group-Relative Policy Optimisation) use failures as well as successes and have a solid track record there. Confidence weighting becomes useful when feedback is a sparse gate on whole episodes and training uses only surviving runs. In that setting, sparse-feedback SFT vs RL becomes a real design choice, and token weighting decides how much to trust each token of an accepted trace.
Practical Checks When Switching Objectives
Four habits keep the switch safe in practice:
- Start with
loss_type="dft"in TRL’s SFT trainer for a baseline trial. Move to a dense chunked patch like ours when Unsloth sits in your training path and VRAM limits chunk sizing. - Expect smaller average gradient norms, because every weight is at most 1. Raise the learning rate or enable weight normalisation (
microbatch_weights_v0orupdate_weights_v1), and judge checkpoints by downstream pass rates instead of raw loss. - Log the mean confidence weight per batch. A falling mean on a fixed probe set flags distribution drift; a mean close to 1 means the rows are already consolidated and updates barely move the model.
- Keep training data close to on-policy. The objective assumes the model could plausibly generate the rows, so mixing in off-policy demonstrations causes under-learning on unfamiliar phrasing.
Data freshness matters just as much as the loss formula. Our training loop pulls rows from sliding-window SFT runs rather than an unbounded archive. Because the window stays recent, the confidence weights come from a checkpoint still close to the policy that generated the trajectories.
FAQs
Is dynamic fine-tuning the same as focal loss?
No, it works in the opposite direction. Focal loss scales cross-entropy by (1-p)^gamma so hard, low-probability examples dominate updates. Confidence weighting scales by p to focus training on plausible tokens. Focal loss fits clean labels with informative hard cases, whereas confidence-weighted SFT fits self-generated rows whose rarest tokens are noisy guesses.
Does confidence weighting work for factual knowledge tasks?
Usually not, because unknown facts start with tiny probabilities under the base model. On Natural Questions in Wu et al. (2025), standard SFT raised accuracy from 31.24 percent to 36.62 percent, whereas confidence weighting dropped it to 30.14 percent. Use standard cross-entropy or an objective schedule when teaching new facts.
Does the weighted objective need a reference model?
No, it computes weights from the active model alone. Each token weight is read directly from per-token cross-entropy as exp(-CE_t), so no second forward pass or frozen model copy is needed. A reference model enters only when you switch to the anchored variant, which adds a KL penalty to constrain the rest of the vocabulary.
Why must the probability weight be detached?
Detaching the weight keeps the gradient equal to -grad p_t, which raises target token probability at a bounded rate. Without a stop-gradient, the live objective -p log p has a positive derivative whenever p is below 1/e. Gradient descent would therefore push every token under roughly 37 percent probability toward zero instead of training it up.
Is the weighted objective a form of reinforcement learning?
Only as an analytical lens. Wu et al. derive it by rewriting standard SFT as a policy gradient with a sparse indicator reward and a 1/pi_theta importance weight, then cancelling that inverse factor. The implementation remains a supervised loss over fixed rows without rollout sampling or a reward model. Where cheap verifiers exist, RL stays the stronger default.
When should I use DFT instead of standard SFT?
Use DFT when your dataset consists of the model’s own filtered trajectories, such as successful multi-turn agent episodes. In those traces, low-probability tokens are often accidental detours rather than trustworthy demonstrations. For external datasets meant to teach new facts, APIs, or vocabulary, standard cross-entropy or an objective schedule works better.
Eigenform is a company building self-training open source models and frameworks. You can try them on GitHub.


