
TL;DR: Kullback-Leibler (KL) is a divergence rather than a metric distance because it violates the triangle inequality and symmetry, so \(D_{\mathrm{KL}}(p_{\text{ref}} \parallel p_\theta)\) and \(D_{\mathrm{KL}}(p_\theta \parallel p_{\text{ref}})\) reach zero at the same point while pulling updates along different paths. For a continual loop anchored to a base model you want to keep, forward KL (or a Jensen-Shannon mixture) covers the reference’s probability mass and retains more of its repertoire, while reverse KL seeks modes and fits noisy or weak references. Checking the direction and the argument order of your KL call decides which one you actually train with.
Why KL Is a Divergence Instead of a Distance
Engineers often say “KL distance” as casual shorthand for the gap between a fine-tuned model’s next-token distribution and a reference model’s, even though distance is loose framing. Mathematicians refer to Kullback-Leibler (KL) as a divergence instead of a distance because it fails the triangle inequality and is asymmetric, so it is not a metric. In recursive self-improvement, where a model is trained repeatedly from the same base, both failures matter in practice. Small step-by-step divergences do not add up to a bound on total drift, and saying “the KL between \(p_\theta\) and \(p_{\text{ref}}\)” names two different quantities depending on which distribution is written first.
In an anchored fine-tuning objective, that first slot decides which tokens the penalty can see. For one position in a sequence, with vocabulary \(\mathcal{V}\), the two quantities are:
$$D_{\mathrm{KL}}(p_{\text{ref}} \parallel p_\theta) = \sum_{v \in \mathcal{V}} p_{\text{ref}}(v)\,\big[\log p_{\text{ref}}(v)-\log p_\theta(v)\big]$$$$D_{\mathrm{KL}}(p_\theta \parallel p_{\text{ref}}) = \sum_{v \in \mathcal{V}} p_\theta(v)\,\big[\log p_\theta(v)-\log p_{\text{ref}}(v)\big]$$The first is the forward KL. The expectation runs under the reference, so the reference decides which tokens count. The second is the reverse KL. The expectation runs under the current model, so a token the current model never produces contributes nothing, however much the reference liked it.
Both are non-negative and both vanish only when the two distributions agree on every token. That shared minimum is why the choice is easy to overlook: with enough steps and enough capacity, optimisation ends in the same place either way. A continual loop never gets there. Each cycle runs a bounded number of steps on a bounded window of recent data, so the direction of the early pull, not the destination in the limit, decides whether catastrophic forgetting shows up in the next evaluation.
Mass-Covering vs Mode-Seeking, One Token at a Time
Take the gradient and the two behaviours fall out. In the forward direction the reference’s own entropy is constant in \(\theta\), so the gradient is \(-\sum_v p_{\text{ref}}(v)\,\nabla_\theta \log p_\theta(v)\): a cross-entropy against the reference’s soft labels over the whole vocabulary.
If the reference puts 2 percent of its mass on a token and the adapter has driven that token down to one part in a million, the log term is close to 10 nats and the gradient keeps pushing until the mass is restored. No token the reference uses can be abandoned. This is the zero-avoiding, mass-covering behaviour.
Reverse KL Is Mode-Seeking
In the reverse direction, differentiating and rearranging gives \(\sum_v p_\theta(v)\,\nabla_\theta \log p_\theta(v)\,\log\frac{p_\theta(v)}{p_{\text{ref}}(v)}\), since the leftover term proportional to \(\sum_v \nabla_\theta p_\theta(v)\) is zero. That is a policy-gradient update whose per-token reward is \(-\log(p_\theta(v)/p_{\text{ref}}(v))\).
A token the current model has already stopped producing has \(p_\theta(v) \approx 0\) and carries no weight, so a mode can be dropped for free. Mass placed where the reference has almost none is punished hard, because the log-ratio grows as \(p_{\text{ref}}(v)\) shrinks. The model is pushed inside the reference’s support and left free to shrink within it: zero-forcing, mode-seeking.
| Forward KL, \(D_{\mathrm{KL}}(p_{\text{ref}} \parallel p_\theta)\) | Reverse KL, \(D_{\mathrm{KL}}(p_\theta \parallel p_{\text{ref}})\) | |
|---|---|---|
| Expectation under | the reference | the current model |
| Token kept by the reference, dropped by the model | unbounded penalty (zero-avoiding) | no penalty (modes can vanish) |
| Token used by the model, absent from the reference | small penalty, weighted by \(p_{\text{ref}}(v)\) | large penalty (zero-forcing) |
| Gradient looks like | cross-entropy against the reference’s soft labels | policy gradient with reward \(-\log(p_\theta/p_{\text{ref}})\) |
| Sequence-level estimate needs samples from | the reference | the current policy |
| Already used in | SFT on data, standard distillation, Learning without Forgetting | PPO and GRPO penalties, DPO’s implicit constraint, MiniLLM |
How Each KL Direction Compounds in a Continual Loop
In a continual loop the two behaviours compound differently. Under a forward anchor to a frozen base, every cycle is pulled back toward the full base distribution, so a token that lost mass in cycle three is recovered in cycle four.
Under a reverse anchor, a mode dropped in cycle three is invisible to the penalty in cycle four, because the penalty only looks where the current model still puts mass. The reference is the same frozen model in both cases. What differs is whether the penalty can see what the model no longer does.
Where Each Direction Already Lives: Distillation and RL
Distillation shows both directions in use on LLMs. The classic distillation loss is a forward KL from the teacher. MiniLLM (Gu et al., ICLR 2024) replaces it with reverse KL “to prevent the student model from overestimating the low-probability regions of the teacher distribution”, and trains on the student’s own samples so that the expectation runs under the right distribution.
Generalized Knowledge Distillation (Agarwal et al., ICLR 2024) refuses to pick. It trains on student-generated sequences with teacher feedback and scores them with a generalised Jensen-Shannon divergence whose interpolation coefficient slides from forward KL at one end to reverse KL at the other. The motivation is the capacity case: when the student cannot represent the teacher, the direction decides what it gives up.
Reverse KL in RL Fine-Tuning
RL fine-tuning settled on reverse KL early. PPO-style RLHF adds a penalty on \(D_{\mathrm{KL}}(\pi_\theta \parallel \pi_{\text{ref}})\) to the reward, and DPO’s closed form is derived under the same constraint. Wang et al. show that forward KL, Jensen-Shannon and \(\alpha\)-divergences admit the same tractable mapping from reward to optimal policy, and that the divergence choice trades alignment score against generation diversity.
GRPO moved the penalty from the reward into the loss and estimates it per sampled token. Shao et al. use \(\frac{\pi_{\text{ref}}(o_t)}{\pi_\theta(o_t)}-\log\frac{\pi_{\text{ref}}(o_t)}{\pi_\theta(o_t)}-1\), which is never negative. With tokens drawn from \(\pi_\theta\) and the ratio \(r = \pi_{\text{ref}}/\pi_\theta\), that expression is \((r-1)-\log r\), the \(k_3\) estimator.
Schulman’s note on approximating KL explains why \(k_3\) is the right pick: for samples from \(q\), \((r-1)-\log r\) with \(r = p/q\) is an unbiased estimate of \(D_{\mathrm{KL}}(q \parallel p)\) with far lower variance than the plain log-ratio. In GRPO the samples come from the policy, so \(q\) is \(\pi_\theta\) and the anchor is reverse KL, estimated from the policy’s own outputs.
Recent reasoning recipes have loosened the term or dropped it. DAPO excludes it outright, arguing that a long chain-of-thought policy legitimately moves far from its initialisation, and TRL’s GRPO configuration now defaults the coefficient to zero, skips loading the reference model, and notes that DeepSeek-R1 used 0.001. Whether that is safe depends on what the model is being asked to keep, which is the continual-learning question in a different costume.
What the Evidence Says About Direction in Repeated Updates
Wu et al. (COLING 2025) test both directions for distilling LLMs and report that “neither mode-seeking nor mean-seeking properties manifest”: the two objectives share an optimum and converge given enough epochs. The difference lives in the early epochs, where reverse KL concentrates on the tail of the distribution and forward KL on the head, and they propose an adaptive mixture for that window. For continual fine-tuning the caveat cuts the other way. A bounded cycle on a small window of recent data is all early epochs, so the regime where the directions differ is the only regime you run in.
Forward KL as a Rehearsal Anchor
Li et al. (2025) make the strongest case yet for the forward direction as a continual anchor. In RL with verifiable rewards they document the familiar paradox, pass@1 rising while pass@k falls, and trace it to the divergence term: reverse KL “actively accelerates this decay by narrowing the policy”, while dropping the term offers no safeguard. Swapping in forward KL or Jensen-Shannon, which they treat as a rehearsal mechanism over the initial policy’s support, improved both pass@1 and pass@k on math and SQL for Llama 3.1 and Qwen2.5 models from 7B to 32B, and held out-of-domain accuracy where the reverse-KL runs kept only about 85 percent of the problems they could previously solve. The forward term is also cheaper there, since it needs samples from the initial policy only, with no reference model kept online.
Function-space anchoring in continual learning started in the forward direction. Learning without Forgetting (Li and Hoiem, 2016) records the old network’s outputs on the new task’s inputs and distils against those soft targets while the new head trains, which is forward KL from the old model at a temperature. Parameter-space penalties constrain weights and have no such choice to make. KL regularisation in function space has the direction as its one free design parameter, and the field picked the covering direction before the question was asked.
When Reverse KL Is the Better Anchor
The counter-case is a reference you do not trust. Yao et al. (ACL 2025 Findings) study weak-to-strong generalisation, where the reference is a weaker model’s predictions, and argue for reverse KL precisely because forward KL’s mass-covering behaviour overfits the weak model’s unreliable low-probability signals.
The rule that falls out is about trust, not taste. A broad pretrained base you want to keep is a reference to cover, so the anchor is forward. A noisy teacher, or a deliberately narrower target, is a reference to lean on selectively, so the anchor is reverse.
None of this is an argument against RL. Where a reliable checker exists, RL with verifiable rewards remains the stronger default, and the divergence is a knob inside that recipe, not a reason to leave it. The choice matters most when a model is updated again and again against the same frozen base, because that is where a direction’s one-sided blindness compounds.
Getting the Direction Right in PyTorch
The API is where most direction mistakes happen. torch.nn.functional.kl_div(input, target) computes the pointwise value \(\text{target} \cdot (\log \text{target}-\text{input})\), with input already in log space and target in probability space unless log_target=True. The target is the weighting distribution.
Passing the current model’s log-probabilities as input and the reference’s probabilities as target therefore gives forward KL, \(D_{\mathrm{KL}}(p_{\text{ref}} \parallel p_\theta)\), even though the current model appears first in the call. Swap the two arguments for reverse KL. Use reduction="none" and sum over the vocabulary yourself, because "mean" divides by every element including the vocabulary dimension and "batchmean" by the batch size.
Mislabelled KL Directions in Libraries
Mislabelled directions are common enough that library authors flag them. TRL’s GKD trainer carries the comment “PyTorch differs from the standard mathematical definition, so the order of the probability distributions is swapped compared to that defined in the paper”, and more than one published anchoring method describes one direction in prose while its code computes the other. Read the call, not the paragraph above it.
import torch
import torch.nn.functional as F
def token_kl(cur_logits, ref_logits, direction="forward"):
"""Exact per-token KL over the full vocabulary. Inputs (..., V), output (...)."""
cur_logp = F.log_softmax(cur_logits.float(), dim=-1)
ref_logp = F.log_softmax(ref_logits.float(), dim=-1)
if direction == "forward":
# KL(p_ref || p_theta): the target argument is the weighting distribution.
kl = F.kl_div(cur_logp, ref_logp, reduction="none", log_target=True)
elif direction == "reverse":
# KL(p_theta || p_ref): same call, arguments swapped.
kl = F.kl_div(ref_logp, cur_logp, reduction="none", log_target=True)
else:
raise ValueError(direction)
return kl.sum(dim=-1)
# Sign check on two tokens: the reference keeps both, the model drops one.
ref = torch.tensor([0.5, 0.5]).log()
cur = torch.tensor([0.999, 0.001]).log()
print(token_kl(cur, ref, "forward")) # about 2.76 nats: the dropped token dominates
print(token_kl(cur, ref, "reverse")) # about 0.69 nats: the dropped token is invisible
# Training step: reference logits from the frozen base (adapter disabled, no grad),
# KL added to the supervised loss on response tokens only.
# loss = sft_loss + kl_weight * token_kl(cur_logits, ref_logits, "forward")[mask].mean()Habits for a Reliable KL Anchor
Three habits keep the anchor honest once it is in a training loop. Compute both log-softmaxes in float32, because the tail of a 100,000-way distribution in bfloat16 is exactly where the two directions disagree and exactly where precision runs out. Prefer the exact sum over the vocabulary to any sampled estimator when you hold both sets of logits, which an anchored supervised step always does, and leave the \(k_1\), \(k_2\), \(k_3\) family for the case where only the sampled token’s log-probability is available. And log the per-token KL in both directions even if you penalise one, since a growing gap between them measures how much of the base model’s support the adapter has stopped covering.
With a LoRA adapter the reference pass costs no extra weights: run the same base model with the adapter disabled under torch.no_grad() and keep the logits, which is how an anchored SFT step obtains \(p_{\text{ref}}\) at every position of a training row. Start the KL weight small and raise it until held-out general benchmarks stop moving between cycles, then stop. A forward anchor that is too strong turns the cycle into distillation of the base model, and the new data stops teaching anything.
FAQs
Is the KL divergence a distance?
No. It is non-negative and reaches zero only when two distributions match, yet it fails the triangle inequality and is asymmetric. Mathematicians call it a divergence instead of a metric distance for that reason, even though “KL distance” survives as shorthand. Symmetric alternatives exist, such as the Jensen-Shannon divergence, whose square root is a true metric.
Which direction does F.kl_div(log_p_model, p_ref) compute?
Forward KL, \(D_{\mathrm{KL}}(p_{\text{ref}} \parallel p_\theta)\). PyTorch multiplies the log-difference by target, making the second argument the weighting distribution. Passing the reference distribution as target therefore computes forward KL even when surrounding prose mislabels it as reverse. Swap the two arguments to compute the reverse direction.
Does GRPO’s KL penalty use forward or reverse KL?
Reverse KL. The per-token estimator \(\frac{\pi_{\text{ref}}}{\pi_\theta}-\log\frac{\pi_{\text{ref}}}{\pi_\theta}-1\) is Schulman’s \(k_3\) evaluated on tokens sampled from the active policy \(\pi_\theta\), which makes it an unbiased estimate of \(D_{\mathrm{KL}}(\pi_\theta \parallel \pi_{\text{ref}})\). Because recent recipes and TRL’s default GRPO configuration often set its weight to zero, check your config before assuming an anchor is active.
Should I pick a direction or use Jensen-Shannon?
Choose based on how much you trust the reference. A broad pretrained base you want to keep favours forward KL or a Jensen-Shannon mixture weighted toward it. A noisy teacher or narrow target favours reverse KL instead. Because an anchored supervised step already computes log-probabilities from both models, switching between them requires no extra forward pass.
What is the difference between forward and reverse KL divergence?
Forward KL runs its expectation under the reference distribution, so it penalises the model heavily for dropping any token the reference still supports and stays mass-covering. Reverse KL runs its expectation under the current model, letting dropped modes vanish without penalty and encouraging mode-seeking behaviour. Both divergences still reach zero at the exact same point.


