
TL;DR: Standard Supervised Fine-Tuning (SFT) weights every target token equally, while Dynamic Fine-Tuning (DFT) scales token loss by detached model probability (\(w_t = p_\theta(y_t)\)) to damp outlier gradient spikes. Because DFT evaluates only the single observed token and leaves the remaining \(|V|-1\) vocabulary coordinates unconstrained, probability mass across unselected tokens can drift and collapse during multi-generation self-training. Anchored Supervised Fine-Tuning (ASFT) pairs DFT’s confidence weighting with a full-vocabulary forward Kullback-Leibler (KL) divergence penalty against a frozen reference policy, computable with zero extra parameter VRAM by toggling low-rank adapters off during the reference pass.
Why Single-Token Probability Weighting Drifts Off-Target
When fine-tuning language models on exploratory rollouts inside a recursive self-improvement loop, standard cross-entropy assigns equal baseline weight to every target token in an observed sequence \(y = (y_1, \dots, y_T)\) conditioned on context \(x\):
$$\mathcal{L}_{\text{SFT}}(\theta) = -\frac{1}{T}\sum_{t=1}^T \log p_\theta(y_t \mid x, y_{<t})$$On noisy agent trajectories, uniform cross-entropy causes sharp gradient spikes whenever the policy encounters rare syntax or incidental exploratory tokens, because gradient magnitude scales with \(1-p_\theta(y_t)\). Dynamic Fine-Tuning (DFT) damps those spikes by scaling each token’s loss with its detached probability:
$$w_t = p_\theta(y_t \mid x, y_{<t}).\text{detach}() = \exp(-\mathcal{L}_{\text{CE}}(t).\text{detach}())$$While DFT keeps low-probability outliers from destabilising weights, it introduces a blind spot across the rest of the vocabulary. Modern tokenisers span \(|V| \in [152\text{k}, 262\text{k}]\) tokens, yet the DFT loss touches only the single observed token \(y_t\), exerting zero direct regularisation over the other \(|V|-1\) entries.
Across repeated generations of self-training, unmonitored shifts across unselected tokens accumulate into vocabulary narrowing, syntactic rigidity, and catastrophic forgetting of out-of-domain skills. Preventing that drift while keeping DFT’s outlier damping requires tethering the full output distribution to a stable reference policy.
Mathematical Foundations of Anchored Supervised Fine-Tuning
Introduced by Zhu et al. (2025) as Anchored Supervised Fine-Tuning (ASFT), the objective combines confidence-weighted token regression with an explicit distributional trust region across the vocabulary simplex:
$$\mathcal{L}_{\text{ASFT}}(\theta) = \mathcal{L}_{\text{DFT}}(\theta) + \beta \cdot D_{\text{KL}}\big(p_{\text{ref}}(\cdot \mid x, y_{<t}) \parallel p_\theta(\cdot \mid x, y_{<t})\big)$$Here \(\beta \geq 0\) controls trust-region stiffness between the active student distribution \(p_\theta\) and the frozen reference distribution \(p_{\text{ref}}\). Comparing the four loss variants clarifies what each term governs:
| Training Mode | Target Token Objective | Vocabulary Regularisation | Primary Optimisation Profile |
|---|---|---|---|
| Standard SFT | Uniform cross-entropy | None | Vulnerable to rare-token gradient spikes |
| DFT | Confidence-weighted CE | None | Damps outliers; unselected vocabulary drifts |
| SFT + KL | Uniform cross-entropy | Full-vocabulary reference KL | Anchors distribution; still sensitive to outliers |
| Full ASFT | Confidence-weighted CE | Full-vocabulary reference KL | Damps outliers and locks vocabulary coverage |
Two complementary forces make ASFT stable across generations:
- Confidence-weighted empirical risk: \(\mathcal{L}_{\text{DFT}}\) concentrates gradient updates on tokens where the policy already has partial competence (\(p_\theta(1-p_\theta)\) peaks near \(p_\theta = 0.5\)), consolidating decisive commands without overfitting to incidental boilerplate.
- Distributional reference tether: The KL divergence penalty bounds how far unselected token probabilities can move from \(p_{\text{ref}}\), preserving alternative strategies when environments change.
Forward KL vs. Reverse KL Geometry
Because Kullback-Leibler divergence is asymmetric, choosing its direction determines whether the anchor preserves diversity or permits mode collapse:
$$\text{Forward KL: } D_{\text{KL}}(p_{\text{ref}} \parallel p_\theta) = \sum_{v \in \mathcal{V}} p_{\text{ref}}(v) \log \frac{p_{\text{ref}}(v)}{p_\theta(v)}$$$$\text{Reverse KL: } D_{\text{KL}}(p_\theta \parallel p_{\text{ref}}) = \sum_{v \in \mathcal{V}} p_\theta(v) \log \frac{p_\theta(v)}{p_{\text{ref}}(v)}$$Reinforcement learning objectives such as Proximal Policy Optimization (PPO) and DPO typically regularise with reverse KL. Reverse KL is mode-seeking: whenever \(p_\theta(v) \to 0\), the product \(p_\theta(v)\log(p_\theta(v)/p_{\text{ref}}(v))\) vanishes regardless of \(p_{\text{ref}}(v)\), letting the student drop valid base-model tokens without penalty.
For multi-generation self-training, mode-seeking contraction is risky because discarded tokens stop appearing in future rollouts. Forward KL is mass-covering (zero-avoiding): wherever the base model assigns positive probability (\(p_{\text{ref}}(v) > 0\)), driving \(p_\theta(v) \to 0\) incurs an unbounded penalty, forcing the adapter to retain broad syntactic and reasoning coverage.
In PyTorch, torch.nn.functional.kl_div(input, target) expects log-probabilities in input and probabilities in target. Passing input=log_cur and target=ref_probs evaluates \(\sum p_{\text{ref}}(\log p_{\text{ref}}-\log p_\theta)\), which computes forward KL \(D_{\text{KL}}(p_{\text{ref}} \parallel p_\theta)\) directly.
Zero-Copy Reference Passes With LoRA Adapters
In full-parameter fine-tuning, maintaining a frozen reference checkpoint alongside trainable weights doubles model parameter VRAM on 7B to 70B Transformers. Pairing ASFT with Low-Rank Adaptation (LoRA) removes that duplication completely.
Under LoRA, the pre-trained weight matrix \(W_0\) stays frozen in 4-bit, 8-bit, or BF16 precision while updates live in low-rank factors \(W = W_0 + \frac{\alpha}{r}BA\). Because \(W_0\) already sits in GPU memory, computing \(p_{\text{ref}}\) requires no second model copy:
- Run the primary forward pass with adapters enabled to compute student logits \(z_\theta\) with gradients tracked.
- Enter
with model.disable_adapter():andtorch.no_grad()to run a reference forward pass through the exact same physical weights \(W_0\), producing \(z_{\text{ref}}\). - Re-enable the adapter and evaluate the joint ASFT objective.
Sequence-Chunked Checkpointing and Logit Softcapping
Even with zero-copy weights, materialising full FP32 vocabulary logits across long contexts creates a transient memory spike. At batch size \(B=2\), sequence length \(T=2048\), and vocabulary \(|V|=262,144\), a single FP32 logit tensor occupies \(2 \times 2048 \times 262,144 \times 4 \text{ bytes} \approx 4.29 \text{ GB}\).
In NSL Workbench (src/train/asft.py), the trainer bounds transient VRAM by slicing sequences into 256-token chunks wrapped in gradient checkpointing. When kl_weight == 0.0, resolve_effective_mode automatically skips the reference forward pass and falls back to plain DFT or SFT.
Fused cross-entropy and KL implementations in libraries such as Unsloth training kernels take the same idea further by computing token-level divergences without materialising full-sequence FP32 logit buffers in global memory.
Base architectures that apply pre-softmax transformations (such as Gemma’s final_logit_softcapping \(\tilde{z}_t = t \cdot \tanh(z_t \cdot s / t)\) or Granite’s logits_scaling) also require applying the exact same transformation to both \(z_\theta\) and \(z_{\text{ref}}\) before computing KL divergence so cross-entropy and trust-region terms share identical logit geometry.
Computing ASFT Loss in PyTorch
The minimal PyTorch function below implements causal label shifting, prompt masking, detached DFT confidence weights, and FP32 forward/reverse KL anchoring:
import torch
import torch.nn.functional as F
def compute_asft_loss(
cur_logits: torch.Tensor,
ref_logits: torch.Tensor,
labels: torch.Tensor,
kl_weight: float = 0.1,
kl_direction: str = "forward",
ignore_index: int = -100,
) -> torch.Tensor:
vocab_size = cur_logits.size(-1)
shift_cur = cur_logits[:, :-1, :].contiguous().view(-1, vocab_size)
shift_ref = ref_logits[:, :-1, :].contiguous().view(-1, vocab_size)
shift_labels = labels[:, 1:].contiguous().view(-1)
valid = shift_labels != ignore_index
if not valid.any():
return cur_logits.sum() * 0.0
ce = F.cross_entropy(shift_cur, shift_labels.clamp_min(0), reduction="none")
dft_w = torch.exp(-ce.detach()) * valid.float()
cur_fp32, ref_fp32 = shift_cur.float(), shift_ref.float()
if kl_direction == "forward":
kl = F.kl_div(F.log_softmax(cur_fp32, dim=-1),
F.softmax(ref_fp32, dim=-1), reduction="none").sum(-1)
else:
kl = F.kl_div(F.log_softmax(ref_fp32, dim=-1),
F.softmax(cur_fp32, dim=-1), reduction="none").sum(-1)
total = (ce * dft_w) + kl_weight * (kl * valid.float())
return total.sum() / valid.sum().clamp_min(1).float()Multi-Generation Stability in Self-Training Agents
In autonomous agent loops, models periodically train on rollouts that passed an environmental outcome check. In our Negative Space Learning container experiments, unanchored DFT amplified decisive exploits rapidly (reaching 100% sealed-panel success at generation M5), yet drifted 0.46–0.71 nats in forward KL from the base policy and collapsed to 0% at M6 once container layouts shifted.
Pairing ASFT with two structural safeguards prevents that collapse while preserving aggressive exploit discovery:
- Fresh LoRA initialisation each generation: Every round fits a fresh LoRA adapter from scratch on the frozen base checkpoint \(M_0\) instead of stacking adapters sequentially.
- Bounded sliding-window buffers: Training on a recency sliding window buffer (\(W=3\)) retires stale exploits automatically while keeping recent exploratory and recovery paths.
- Forward-KL base anchoring: Holding forward KL drift near
0.03–0.05nats against \(M_0\) let ASFT climb steadily to84.5%byM10(and100%when scheduledDFT -> ASFT).
Under environment-grounded selection, no method that gets the reward is a bad method: lateral shell shortcuts that reclaim real storage are valid adaptations. ASFT solves the optimisation side of that loop, damping single-token syntax noise via DFT while keeping the broader token distribution wide enough to invent new strategies when the environment changes.
FAQs
How does Anchored SFT differ from Dynamic Fine-Tuning (DFT)?
Dynamic Fine-Tuning (DFT) scales token cross-entropy by detached model probability (\(w_t = p_\theta(y_t)\)) to damp rare-token gradient spikes, yet leaves the other \(|V|-1\) vocabulary entries unconstrained. Anchored SFT adds a full-vocabulary KL divergence penalty against a frozen reference model so unselected token probabilities cannot drift during multi-generation self-training.
Why does ASFT use forward KL divergence instead of reverse KL?
Reverse KL (\(D_{\text{KL}}(p_\theta \parallel p_{\text{ref}})\)) is mode-seeking and vanishes whenever \(p_\theta(v) \to 0\), allowing the student policy to drop valid base-model tokens and narrow its repertoire. Forward KL (\(D_{\text{KL}}(p_{\text{ref}} \parallel p_\theta)\)) is mass-covering, heavily penalising zeroed-out base tokens so syntax and general reasoning stay intact.
Does ASFT with LoRA require extra GPU VRAM for a reference model?
No. Because Low-Rank Adaptation freezes the pre-trained base weights \(W_0\) and isolates updates inside compact adapter matrices, the trainer computes reference logits by temporarily calling model.disable_adapter() under torch.no_grad(). Combining adapter toggling with 256-token sequence chunking adds zero parameter VRAM overhead.
What KL weight (\(\beta\)) works best for Anchored SFT?
Across multi-generation agent fine-tuning runs, \(\beta \in [0.01, 0.1]\) typically balances adaptation against base-policy retention. Setting \(\beta < 0.005\) lets unselected vocabulary probabilities drift like unanchored DFT across iterations, whereas setting \(\beta > 0.5\) over-constrains the adapter and slows acquisition of domain-specific tool or shell patterns.
When should you choose ASFT over standard SFT or RL?
Where a task provides a fast, reliable verifier or graded reward, reinforcement learning methods such as GRPO are the stronger default. ASFT is built for approximate policy-free online learning on bounded windows of environment-validated episodes, damping noisy exploratory tokens better than uniform SFT while preventing unanchored drift.

