trl icon indicating copy to clipboard operation
trl copied to clipboard

DPOTrainer apo_down loss inconsistently applies f_divergence_type across its two terms

Open ErenAta16 opened this issue 4 months ago • 6 comments

Reproduction

DPOTrainer's apo_down loss (trl/trainer/dpo_trainer.py, lines 1509-1515) treats its two terms inconsistently with respect to f_divergence_type:

elif loss_type == "apo_down":
    # Eqn (8) of the APO paper (https://huggingface.co/papers/2408.06266)
    losses_chosen = torch.sigmoid(self.beta * chosen_logratios)      # always the raw log-ratio
    losses_rejected = 1 - torch.sigmoid(self.beta * delta_score)     # f-divergence-transformed
    per_sequence_loss = losses_chosen + losses_rejected

chosen_logratios/rejected_logratios (lines 1384-1385) are the plain log(π_θ/π_ref). delta_score (line 1417) is chosen_scores - rejected_scores, where chosen_scores/rejected_scores (lines 1387-1415) are only equal to the raw logratios when f_divergence_type="reverse_kl" (the default); for forward_kl, js_divergence, or alpha_divergence they're a nonlinear transform of the logratios.

Checked this against the actual paper: APO (arXiv:2408.06266), Eq. 8 (extracted directly from the paper's own LaTeX source via ar5iv.labs.arxiv.org/html/2408.06266):

L_down^APO(x, yw, yl; θ) = σ(r_θ(x,yw)) − σ(r_θ(x,yw) − r_θ(x,yl))

where r_θ(x,y) = β·log(π_θ(y|x)/π_ref(y|x)) (the paper's Eq. 5) is always the plain reverse-KL log-ratio, never any other f-divergence.

apo_zero, two branches above (lines 1501-1507), correctly keeps both terms on the raw log-ratio regardless of f_divergence_type:

losses_chosen = 1 - torch.sigmoid(self.beta * chosen_logratios)
losses_rejected = torch.sigmoid(self.beta * rejected_logratios)

apo_down should be symmetric with apo_zero here, but its second term uses delta_score instead, almost certainly because delta_score happens to equal chosen_logratios - rejected_logratios in the default reverse_kl case, which hides that it silently changes meaning once f_divergence_type is set to anything else. There's no validation that rejects this combination, loss_type=["apo_down"] with a non-default f_divergence_type is a legal, silent configuration.

import torch
import torch.nn.functional as F

beta = 0.1
chosen_logratios = torch.tensor([0.5, -0.3, 1.2])
rejected_logratios = torch.tensor([-0.2, 0.4, -0.6])

def scores_for(f_divergence_type, chosen_logratios, rejected_logratios):
    if f_divergence_type == "reverse_kl":
        return chosen_logratios, rejected_logratios
    elif f_divergence_type == "js_divergence":
        return F.logsigmoid(chosen_logratios), F.logsigmoid(rejected_logratios)

def apo_zero_loss(chosen_logratios, rejected_logratios):
    losses_chosen = 1 - torch.sigmoid(beta * chosen_logratios)
    losses_rejected = torch.sigmoid(beta * rejected_logratios)
    return losses_chosen + losses_rejected

def apo_down_loss_as_coded(chosen_logratios, delta_score):
    losses_chosen = torch.sigmoid(beta * chosen_logratios)
    losses_rejected = 1 - torch.sigmoid(beta * delta_score)
    return losses_chosen + losses_rejected

# apo_zero is internally consistent across f_divergence_type (never touches chosen_scores/rejected_scores)
apo_zero_reverse_kl = apo_zero_loss(chosen_logratios, rejected_logratios)
print("apo_zero identical regardless of f_divergence_type:", True)  # by construction

# apo_down is NOT
chosen_scores, rejected_scores = scores_for("js_divergence", chosen_logratios, rejected_logratios)
delta_score = chosen_scores - rejected_scores
code_result = apo_down_loss_as_coded(chosen_logratios, delta_score)

def apo_down_fully_generalized(chosen_scores, rejected_scores):
    delta = chosen_scores - rejected_scores
    losses_chosen = torch.sigmoid(beta * chosen_scores)
    losses_rejected = 1 - torch.sigmoid(beta * delta)
    return losses_chosen + losses_rejected

fully_generalized = apo_down_fully_generalized(chosen_scores, rejected_scores)
print("code's apo_down under js_divergence:      ", code_result)
print("fully f-divergence-generalized apo_down:   ", fully_generalized)
print("max abs diff:", (code_result - fully_generalized).abs().max().item())

Output:

apo_zero identical regardless of f_divergence_type: True
code's apo_down under js_divergence:       tensor([1.0044, 1.0010, 1.0106])
fully f-divergence-generalized apo_down:    tensor([0.9800, 0.9872, 0.9741])
max abs diff: 0.03654569387435913

System Info

TRL commit 65eb0df (current main), reproduced with pure torch tensors, no GPU or model download needed since this is testing the loss math directly.

Checklist

  • [x] I have checked that my issue isn't already filed
  • [x] I have included my system information
  • [x] Any code provided is minimal, complete, and reproducible

Suggested fix

Make apo_down's second term consistent with apo_zero's pattern, either always compute it from rejected_logratios regardless of f_divergence_type (matching the paper's Eq. 8, which never defines r_θ via any f-divergence other than reverse-KL), or, if a fully-f-divergence-generalized version of APO-down is intended, also change the first term to use chosen_scores instead of chosen_logratios so both terms are consistently transformed. Right now it's neither, one term is raw, the other is transformed, which matches neither reading.

ErenAta16 avatar Jul 18 '26 08:07 ErenAta16

I can prepare a small fix and tensor-only regression test once the intended semantics are confirmed. Should apo_down remain a literal implementation of APO Eq. 8 and therefore use raw log-ratios for both terms regardless of f_divergence_type, or is TRL intentionally generalizing APO losses to the configured f-divergence (in which case both terms should use the transformed scores)?

The current mixed raw/transformed form seems inconsistent, but choosing between those two coherent definitions changes public loss behavior, so I would prefer to encode the maintainer-approved interpretation in the test rather than guess.

hogeheer499-commits avatar Jul 19 '26 00:07 hogeheer499-commits

My read is the first one: apo_down should stay a literal implementation of APO Eq. 8, raw log-ratios for both terms, unaffected by f_divergence_type.

The strongest evidence for that is inside the same file: apo_zero (right above apo_down, citing the same paper) already uses raw chosen_logratios/rejected_logratios for both of its terms, not chosen_scores/rejected_scores. If TRL intended to generalize APO losses to the configured f-divergence, apo_zero would already be doing it and would already be "wrong" by that standard too, but nobody has flagged apo_zero, and it reads as a deliberate, internally consistent choice matching the paper as written. apo_down mixing raw for the chosen term and delta_score (f-divergence-transformed) for the rejected term looks like it drifted from that pattern rather than being a considered generalization, since there is no comment or test anywhere suggesting APO was meant to interact with f_divergence_type at all.

So I would fix apo_down to match apo_zero conventions: losses_rejected computed from raw rejected_logratios (or an equivalent raw-logratio delta) instead of delta_score. Given the mixed form is what shipped and presumably nobody has been relying on the current rejected-term behavior specifically (it is a silent inconsistency, not a documented feature), I would treat this as a bug fix rather than a behavior change requiring a deprecation cycle, but that call is the maintainers' to make.

ErenAta16 avatar Jul 19 '26 12:07 ErenAta16

@ErenAta16 thanks, that settles the question I left open. I opened #6475 as a draft precisely because the issue proposes two coherent directions, and your reading matches what the PR already implements: both terms use the raw log-ratios, so apo_down becomes invariant to f_divergence_type and consistent with apo_zero and Eq. 8.

@hogeheer499-commits so we do not duplicate the work, the fix and the regression test are already in #6475. The test asserts the apo_down loss is identical across f_divergence_type on a fixed batch. It fails before the change (the loss differs under forward_kl, js_divergence and alpha_divergence) and passes after. Behavior is unchanged under the default reverse_kl.

Marking #6475 ready for review now. If a maintainer prefers direction (B), applying the f-divergence transform to both terms instead, I am happy to switch the fix and flip the test's invariance assertion accordingly.

Ewertonslv avatar Jul 26 '26 04:07 Ewertonslv

Thanks for the detailed report. I went back through the loss chain and the papers, and the picture is a bit broader than apo_down.

This is a regression from #3906, not an original design choice. Before that PR, apo_down read:

losses_rejected = 1 - F.sigmoid(self.beta * (chosen_logratios - rejected_logratios))

The refactor introduced chosen_scores / rejected_scores / delta_score and swept delta_score into the rejected term while leaving the chosen term on the raw log-ratio. So direction (A) isn't a semantics decision between two coherent readings; it restores the pre-refactor behavior.

f-DPO generalizes the KL constraint in the RLHF objective, giving r = β·f'(π_θ/π_ref) + β·log Z(x). APO Eq. 7/8 are not derived from that objective at all. There's no regularizer to swap, so "APO-down under JS divergence" has nothing to generalize to.

Checking every loss against its paper, the boundary is whether the loss consumes the reward difference or absolute per-side rewards. The β·log Z(x) term in the f-DPO reparameterization only cancels in the difference, so only difference-based losses are generalizable at all:

  • ok: sigmoid, robust, hinge, ipo, exo_pair, discopop.
  • not derived : apo_zero, apo_down (above), and aot / aot_unpaired
  • actively broken, and the more serious find: sppo_hard targets absolute per-side values, (chosen_scores − 0.5/β)²;nca_pair and bco_pair have a milder version: −logsigmoid(β·chosen_scores) with strictly negative scores is floored at log 2. All three were also raw before #3906.

What I'll do, aather than patch apo_down alone, reject the invalid combinations at init.

That covers apo_down and the six other loss types where the setting is either a silent no-op or actively harmful, from one principled rule instead of a per-loss list.

Note that this is breaking for anyone running sppo_hard / nca_pair / bco_pair / apo_* with a non-default divergence, but those runs were optimizing a broken objective, so an error is the right outcome.

On #6475: thanks for putting it together, and sorry to close it. The code change is correct, but the fix we're landing is the init-time validation above rather than a per-loss patch, so the diff doesn't carry over. Closing in favour of that.

qgallouedec avatar Jul 27 '26 21:07 qgallouedec

At per-device batch 1 the regression disappears. Long-context run (bs=1, grad_accum=8, len=16384):

out-of-place in-place before-slice
48.254 48.254 48.254

Mechanically, logits[:, :-1, :] is contiguous when B == 1 (the leading stride stops mattering)

qgallouedec avatar Jul 27 '26 21:07 qgallouedec

That's a much better framing than mine, and the sppo_hard / nca_pair / bco_pair finding is the part that actually matters. I went and checked your claims against dpo_trainer.py rather than take them on faith, and they hold up.

The bit that convinced me is in the score construction itself:

if self.f_divergence_type == "reverse_kl":  # standard DPO
    chosen_scores = chosen_logratios
elif self.f_divergence_type == "forward_kl":
    # f'(t) = 1 - 1/t  -> drop constant -> -exp(-logratio)
    chosen_scores = -torch.exp(-chosen_logratios)
elif self.f_divergence_type == "js_divergence":
    # f'(t) = log(2t/(t+1)) -> drop log 2

Those "drop constant" / "drop log 2" comments are the whole argument in two lines. Dropping a constant is only free under a difference. Every loss that consumes delta_score is fine; every loss that reads chosen_scores or rejected_scores on their own inherits an arbitrary offset. So the split you drew isn't a judgement call about which papers "should" generalize, it falls straight out of the reparameterization.

On sppo_hard being the serious one, it's worse than an offset. Under forward_kl, chosen_scores = -exp(-logratio) is strictly negative for any finite log-ratio, while the target is 0.5/beta, strictly positive. So the winner term is optimizing toward a value it cannot reach. With beta=0.1:

logratio=  0 -> (chosen_scores - 0.5/beta)^2 = 36.0000
logratio=  5 ->                                25.0674
logratio= 20 ->                                25.0000   <- floor

It asymptotes at (0.5/beta)^2 = 25.0 and never goes below. The gradient doesn't vanish into a bad-but-valid optimum, the objective is simply unattainable, and the same holds for the loser term by symmetry. nca_pair / bco_pair are the milder version you described: -logsigmoid(beta * chosen_scores) with strictly negative scores is floored at log 2 = 0.693147, confirmed numerically out to logratio=100. Silent in both cases, since nothing errors and the loss still decreases somewhat.

Rejecting the invalid combinations at init is clearly the right call over patching apo_down alone. It fixes seven things instead of one, and more importantly it turns a silent no-op (apo_zero / apo_down / aot) and a silently-broken objective (sppo_hard and friends) into an error at the point where the user actually made the choice. Patching apo_down would have left someone running sppo_hard with js_divergence none the wiser.

One thing worth deciding explicitly: for the "not derived" group the setting is inert, so an error there is arguably stricter than necessary, someone may be passing f_divergence_type globally in a config sweep and never intending it to touch APO. But I'd still err on your side. Silently ignoring a knob the user set is how this issue got filed in the first place, and a clear message at init is cheaper than the alternative.

Also correcting my own comment above: I said apo_down mixing raw and transformed "looks like it drifted rather than being a considered generalization" and framed it as choosing between two coherent readings. Your bisect to #3906 settles that properly, it's a regression with a specific origin, not a semantics question, and the pre-refactor line you quoted is the ground truth I was guessing at.

Happy to test the init-time validation once it's up if that's useful.

ErenAta16 avatar Jul 28 '26 15:07 ErenAta16