Open the workspace
Algorithms 101

SLiC-HF (Sequence Likelihood Calibration with Human Feedback) explained

SLiC-HF aligns a model with a hinge loss on sequence log-likelihoods plus a cross-entropy regulariser. Loss, gradient, DPO comparison, toy run and settings.

SLiC-HF (Sequence Likelihood Calibration with Human Feedback) aligns a language model to human preferences with a ranking loss on whole-sequence log-likelihoods: for each preference pair, push the log-probability of the preferred response above that of the rejected one by a fixed margin, and add a cross-entropy term that keeps the model close to its supervised behaviour. There is no reward-model-in-the-loop, no sampling during training and no value network. It is one of the first offline alternatives to PPO-based RLHF, posted twelve days before DPO, and its hinge loss survives today as one member of the family of pairwise preference losses (DPO's logistic, IPO's squared, SLiC's hinge). It runs after SFT, on preference pairs that are either collected from humans or produced by ranking the SFT model's own samples.

Origin: from calibration to human feedback#

SLiC began as a fix for a decoding problem. In Calibrating Sequence Likelihood Improves Conditional Language Generation, Yao Zhao, Misha Khalman, Rishabh Joshi, Shashi Narayan, Mohammad Saleh and Peter J. Liu at Google (Zhao et al., 2022) observed that models trained by maximum likelihood assign sequence probabilities that do not track sequence quality: beam search returns high-likelihood outputs that are not the best outputs. Their remedy was a third stage after pre-training and fine-tuning. Decode candidates from the fine-tuned model, rank them by similarity to the reference, and train the model so its sequence likelihoods respect that ranking. They compared four calibration losses (rank, margin, list-wise rank and expected reward) and two regularisers (cross-entropy and KL to the fine-tuned model). The rank loss worked best, the two regularisers performed similarly, and about 85% of the gain remained even without regularisation.

In May 2023 the same group (Zhao, Joshi, Tianqi Liu, Khalman, Saleh and Liu, now at Google DeepMind and Google Research) swapped the similarity-to-reference ranking for human preference and called the result SLiC-HF (Zhao et al., 2023). They tested it on Reddit TL;DR summarisation, using the human feedback collected by Stiennon et al. (2020): 117K SFT examples and 64K preference comparisons of summaries from other models. A T5-Large (770M) policy trained with SLiC-HF was preferred by human raters over the 6B decoder-only RLHF-PPO model of Stiennon et al. 66% to 34% when pairs were labelled by a ranking model, and 56% to 44% when labelled by a pointwise reward model. In a four-way human comparison it was chosen as the best summary 73% of the time, against 13% for the human reference.

The objective#

Let be the model's sequence likelihood. For a preference triple and a regularisation target , the SLiC-HF loss is

The symbols: is the margin, the gap in nats that the preferred response's log-likelihood must exceed the rejected one's by before the pair stops contributing (1.0 in the paper's experiments); weights the regulariser; is either the SFT target for or the best-ranked of the model's own decodes. Write the log-likelihood margin as . The calibration term is a hinge in , so its gradient is

Every pair that violates the margin gets the same unit push, up on the preferred sequence and down on the rejected one, however badly it violates it. Every pair that satisfies it gets nothing. The regulariser's gradient, , is ordinary SFT on the target.

The regulariser plays the role of PPO's KL penalty but is cheaper: it needs no frozen copy of the SFT weights. The original SLiC paper found a KL regulariser, on the target tokens, worked about as well as cross-entropy.

SLiC next to DPO and IPO

The three classic offline losses differ in two choices: what margin they measure, and what function of the margin they penalise. Tang et al. (2024) showed that, in their reference-normalised forms, all of them are instances of one template, a convex function applied to a scaled log-ratio margin, which they call Generalized Preference Optimization:

MethodMarginLoss on marginGradient once the pair is "won"
SLiC-HF, no referenceexactly zero beyond
RSO hinge (TRL hinge) times the difference of log-ratios to zero beyond
DPO with the log-ratio differenceshrinks but never zero
IPOpulls back if the margin overshoots

Two differences matter in practice. SLiC-HF's margin is measured on raw log-likelihoods, not on log-ratios to a reference, so it does not need a reference model at all; the price is that the starting point matters, because a pair that the SFT model already ranks correctly by more than is ignored from the first step. And the hinge stops: a won pair exerts no force, so training has a fixed point once every pair clears the margin or is contradicted by another pair. DPO's logistic loss keeps pushing every pair for as long as you train, which is one route to the likelihood displacement discussed in the DPO article. The Statistical Rejection Sampling paper (Liu et al., 2023), by the same Google group, introduced the reference-normalised hinge that TRL implements as loss_type="hinge".

Three ways to turn a preference margin into a loss01234-3-2-101234margin (log-likelihood or implicit-reward difference, nats)lossdeltaSLiC hinge, delta = 1DPO logistic, beta = 1IPO-style squared (scaled 1/4)
Figure 1. The calibration hinge next to DPO's logistic loss and an IPO-style squared loss, plotted from their formulas. The hinge is flat and exactly zero past the margin; the logistic loss decays but never reaches zero; the squared loss penalises overshoot.

Worked example: two pairs, by hand#

Pair A: the model gives the preferred summary and the rejected one . The margin is , the wrong sign. With the hinge is , active, and the gradient adds , unit weight on each sequence.

Pair B: , . The margin is , so the hinge is 0 and the pair contributes no gradient at all.

Now DPO with on pair B, with reference log-probabilities and . The log-ratio difference is , the loss , and the gradient weight . DPO is still pushing a pair the policy already ranks correctly, and it will keep pushing it until is many multiples of . For pair A (references and ), and the weight is 0.053. Note the scale difference too: SLiC's per-pair gradient weight is 1 while DPO's is at most , which is one reason SLiC-HF and DPO use learning rates an order of magnitude apart.

The regulariser is on a different scale again. If has 30 tokens with , the cross-entropy term with contributes 15 to the loss and a gradient summed over 30 tokens, while the hinge contributes at most a few nats. Because balances a token-summed term against a sequence-level hinge, its right value depends on target length; the paper does not report the value it used.

The algorithm#

SLiC-HF comes in two forms, shown in Figure 2. In SLiC-HF-sample-rank, you decode candidates per training prompt from the SFT model (the paper used 8, temperature 0.7, top-k 40), label pairs with a model trained on the human preferences, and calibrate on those pairs. In SLiC-HF-direct, you calibrate straight on the human preference pairs, which were written for other models. Direct is simpler, essentially fine-tuning on a different loss; sample-rank is better and more stable.

SLiC-HF-sample-rank SFT modeldecode m = 8 ranking modeltrained on human pairs (y+, y-) pairsfrom tournament SLiC-HF-direct human preference pairs, as collected(written for other models: off-policy) SLiC-HF loss hinge on log P(y+)minus log P(y-) + lambda x CE on y_ref y_ref: SFT target or best-ranked decode
Figure 2. The two ways to get pairs for SLiC-HF. Sample-rank labels the SFT model's own decodes with a ranking or reward model trained on human pairs; direct uses the human pairs as collected. Both feed the same hinge-plus-cross-entropy loss.
# SLiC-HF-sample-rank
ranker = train_pairwise_ranker(human_pairs)            # "[CONTEXT] .. [SUMMARY A] .. [SUMMARY B]" -> "A" / "B"
pairs = []
for x in sft_prompts:
    cands = sft_model.sample(x, n=8, temperature=0.7, top_k=40)
    pairs += tournament_pairs(ranker, x, cands)        # m - 1 = 7 (winner, loser) pairs per prompt
    y_ref[x] = tournament_winner(ranker, x, cands)     # or the SFT target

model = copy(sft_model)                                # no reference copy needed
for batch in loader(pairs):
    lp_pos = model.seq_logprob(batch.x, batch.y_pos)   # sum of token log-probs
    lp_neg = model.seq_logprob(batch.x, batch.y_neg)
    cal = relu(delta - lp_pos + lp_neg).mean()
    reg = -model.seq_logprob(batch.x, y_ref[batch.x]).mean()
    (cal + lam * reg).backward(); opt.step(); opt.zero_grad()

Pair labelling uses a tournament: with four candidates, compare with and with , then the two winners, giving pairs from ranker calls. Decoding and ranking happen once, offline, over the whole training set, which is what makes the method cheap. The paper also trained a pointwise reward model (outputs "Good" or "Bad") as an alternative labeller. The pairwise ranking model was more accurate on held-out human preferences (73.23% versus 71.34%), and SLiC-HF with ranker labels did better: 86.21% win rate against references as judged by the ranker, versus 82.42% with reward-model labels.

Data

You need an SFT set (for the regulariser and the decoding prompts) and preference data to train the ranker or to use directly. The paper used 117K SFT prompts and 64K human comparisons. Increasing decodes per prompt from 8 to 64 barely helped (86.21% to 86.41%); scaling the policy from 770M to 11B helped a lot (to 96.10%). For the regulariser, using the SFT targets or the best-ranked decode made little difference, which means sample-rank works even with no references at all.

Hyperparameters#

ParameterPaper valueTuning notes
Margin 1.0The main dial on how far the model moves; see the toy run. In nats of sequence log-likelihood.
Regularisation weight not reportedScale with target length; start where the CE gradient norm is comparable to the hinge's.
Learning rate1e-5 (T5, calibration stage)SFT used the default 1e-3; calibration ran 100 times lower.
Batch size32TRL's paper index cites 512 and 1e-4 from the published version.
Candidates per prompt 864 gave no meaningful gain.
Decoding for candidatestemperature 0.7, top-k 40The original SLiC found beam search best for calibration against references.

Because the hinge is measured on summed log-likelihoods, interacts with length: a 1-nat gap is easy to create on a 300-token response (0.003 nats per token) and harder to reason about across responses of very different lengths. If your pairs vary a lot in length, consider normalising log-likelihoods by length (as RRHF and SimPO do) or measuring margins against a reference model (RSO's hinge-norm).

Compute and memory#

SLiC-HF's training stage is SFT-shaped. Per pair it needs a forward and backward pass over , and , with only the policy in memory: no reference copy (the cross-entropy regulariser replaces the KL), no reward model, no critic. The paper's comparison with PPO, for a policy of parameters:

RLHF-PPOSLiC-HF sample-rankSLiC-HF direct
Auxiliary modelsreward, value, SFTranking (offline only)none
Parameter memory during training
Parameters updated per step
Decodinginside the training looponce, parallel over the whole setnone

With Adam in mixed precision that is roughly 16 bytes per parameter, the same as SFT, plus activations for three sequences per example. DPO needs an extra 2 bytes per parameter for the frozen reference (or precomputed reference log-probabilities). The offline decoding and ranking cost is generations plus ranker calls per prompt, paid once.

Toy run: the margin is a stopping rule#

We trained a tabular policy to see the hinge's fixed point. 200 prompts, 8 candidate responses each, starting logits drawn from (the "SFT model") and a hidden quality per response from . For each prompt we sample 4 pairs from the starting policy and label them with a noisy Bradley-Terry judge, , giving 800 pairs of which only 53.0% are ranked correctly by the starting policy. We trained with full-batch gradient descent for 6,000 steps, SLiC at learning rate 2 and DPO () at 20 to match per-pair step sizes, and tracked expected quality (starting at ; the best possible is 1.406) and KL from the starting policy.

MethodStep 1,000: KL / qualityStep 6,000: KL / qualityChosen log-prob change at 6,000
SLiC, n/a0.169 / 0.117+0.276
SLiC, 0.288 / 0.2180.298 / 0.220+0.353
SLiC, n/a0.638 / 0.396+0.362
SLiC, n/a1.170 / 0.559
DPO, 0.644 / 0.4431.429 / 0.608
KL from the starting policy during training (toy run)00.40.81.21.601500300045006000gradient stepKL(pi || pi_start), natsSLiC, delta = 1SLiC, delta = 4DPO, beta = 0.1
Figure 3. KL from the starting policy over training in the toy run. SLiC with margin 1 plateaus at 0.298 nats by step 3,000 and margin 4 at 1.17; DPO keeps drifting for as long as it trains.

SLiC stops. With , KL reaches 0.288 by step 1,000 and 0.298 by step 3,000, then nothing changes: 94.3% of pairs clear the margin and the remainder are contradicted by pairs with the opposite label, whose pushes cancel. The margin sets where it stops, roughly linearly: KL of 0.17, 0.30, 0.64 and 1.17 for of 0.5, 1, 2 and 4. DPO has no such point. Its KL kept rising, to 1.43 at step 6,000, and the log-probability of the chosen responses, after rising to +0.50 at step 1,000, fell to : mass moved off both responses in each pair, the likelihood displacement familiar from DPO. On the quality-versus-KL frontier the two methods are close (SLiC at : KL 1.17, quality 0.559; DPO at step 3,000: KL 1.19, quality 0.574). The difference is that SLiC's answer does not depend on when you stop training.

We also ran SLiC with the cross-entropy regulariser () on a best-ranked target per prompt. In this tabular model the regulariser behaves like SFT on the targets and never saturates: quality kept rising (0.952 at step 6,000) along with KL (1.42). That is a property of the toy, where one target per prompt can absorb all the probability, more than a prediction about LLMs, but it is a reminder that the cross-entropy term is not a trust region. It pulls towards , not towards the SFT model.

Failure modes#

Length growth with direct calibration. The paper saw it: with SLiC-HF-direct, calibration loss fell as expected but average length kept increasing and did not converge, which the authors attributed to the off-policy human-feedback responses. Sample-rank converged. Watch mean response length per checkpoint, not just loss, and select checkpoints with the ranker.

Pairs ignored from step one. Without a reference, any pair the SFT model already ranks correctly by more than contributes nothing. If most of your pairs are "easy" for the SFT model, the effective dataset is much smaller than it looks. Log the fraction of active pairs at the start and over training.

Ranker bias becomes model bias. Sample-rank learns whatever the ranker prefers. SLiC-HF summaries were longer than RLHF-PPO's (about 37 versus 33 words), with a length-controlled win rate similar to PPO's. Run a length-controlled evaluation alongside raw win rate.

Mis-scaled regulariser. Too small and the model drifts from fluent text, which shows as rising perplexity on held-out SFT targets; too large and calibration has no effect. Track both the hinge's active fraction and SFT perplexity.

Weak ranker. The paper found smaller T5 ranking and reward models did not converge reliably and used an 11B ranker for a 770M policy. A ranker barely above chance turns calibration into noise injection.

When to use SLiC-HF, and what instead#

SituationUseWhy
Offline pairs, want a fixed point and no reference model in memorySLiC-HFHinge stops when pairs are won; the CE regulariser replaces the reference.
Offline pairs, standard recipe and toolingDPOMost studied; widest library support.
Near-deterministic preferences, worried about overfittingIPO or the RSO hingeBounded target margin relative to a reference.
A good ranker and the budget to sampleSLiC-HF-sample-rank or online DPOOn-policy pairs beat off-policy pairs in the paper and elsewhere.
Several ranked responses per promptRRHFRanks lists, not pairs, with length-normalised scores.
Want to reward-optimise with explorationPPO, GRPOSLiC only reorders responses it has seen.

Minimal implementation#

import torch
import torch.nn.functional as F

def seq_logprob(model, input_ids, attention_mask, completion_mask):
    logits = model(input_ids=input_ids, attention_mask=attention_mask).logits[:, :-1]
    tok = torch.gather(logits.log_softmax(-1), 2, input_ids[:, 1:, None]).squeeze(-1)
    return (tok * completion_mask[:, 1:]).sum(-1)              # summed, not averaged

def slic_hf_loss(model, pos, neg, ref, delta=1.0, lam=0.5):
    """pos, neg, ref: dicts with input_ids, attention_mask, completion_mask."""
    lp_pos = seq_logprob(model, **pos)
    lp_neg = seq_logprob(model, **neg)
    cal = F.relu(delta - lp_pos + lp_neg)
    reg = -seq_logprob(model, **ref) / ref["completion_mask"].sum(-1).clamp(min=1)  # per-token CE
    stats = {"active_frac": (lp_pos - lp_neg < delta).float().mean().item()}
    return (cal + lam * reg).mean(), stats

This version normalises the regulariser per token, which makes independent of target length; the paper's equation uses the summed log-likelihood. In TRL, DPOTrainer with loss_type="hinge" implements the reference-normalised hinge from RSO, where the margin in log-ratio units is ; you can add an NLL term on the chosen responses by combining loss types (loss_type=["hinge", "sft"] with loss_weights), which approximates SLiC-HF's regulariser with . In POFE, the hinge is one of the loss options on the preference-tuning recipe, and the run page reports the active-pair fraction so you can see when training has reached its fixed point.

Further reading#

Zhao et al. (2023) is the SLiC-HF paper; Zhao et al. (2022) is the original calibration paper with the loss and regulariser ablations. Liu et al. (2023, RSO) combines SLiC-style hinge losses with a reference and better pair sampling. Rafailov et al. (2023) is DPO, published the same month. Tang et al. (2024) is the cleanest unification of DPO, IPO and SLiC as convex losses on a margin. Stiennon et al. (2020) is the source of the TL;DR preference data and the PPO baseline SLiC-HF compared against.

Frequently asked questions#

What is the SLiC-HF loss?

A hinge on the difference of sequence log-likelihoods, max(0, delta - log P(y+|x) + log P(y-|x)), plus lambda times the cross-entropy of a target sequence, which is either the SFT reference or the best-ranked decode. The paper used a margin delta of 1.0.

How is SLiC-HF different from DPO?

SLiC-HF's margin is measured on raw log-likelihoods with no reference model, and the hinge gives exactly zero gradient once a pair clears the margin. DPO measures log-ratios to a frozen reference and its logistic loss keeps pushing every pair. SLiC-HF regularises with cross-entropy instead of a reference.

What is the difference between SLiC-HF-sample-rank and SLiC-HF-direct?

Sample-rank decodes candidates from the SFT model and labels pairs with a ranking or reward model trained on human preferences. Direct trains on the human preference pairs as collected. Sample-rank performed better and converged; direct saw response length keep growing.

Does SLiC-HF need a reward model?

Only for labelling, and only in the sample-rank variant: a pairwise ranker or pointwise reward model labels decodes once, offline, before training. During training only the policy is in memory, so parameter memory is about one quarter of PPO's in the paper's comparison.

How do I run SLiC-HF in TRL?

DPOTrainer with loss_type="hinge" implements the reference-normalised hinge from RSO, max(0, 1 - beta times the log-ratio difference), so the margin is 1/beta. Adding an "sft" loss type with loss_weights approximates SLiC-HF's cross-entropy regulariser on the chosen response.

References#

  1. Yao Zhao, Rishabh Joshi, Tianqi Liu, Misha Khalman, Mohammad Saleh, Peter J. Liu (2023). SLiC-HF: Sequence Likelihood Calibration with Human Feedback. arxiv.org/abs/2305.10425
  2. Yao Zhao, Misha Khalman, Rishabh Joshi, Shashi Narayan, Mohammad Saleh, Peter J. Liu (2022). Calibrating Sequence likelihood Improves Conditional Language Generation. arxiv.org/abs/2210.00045
  3. Tianqi Liu, Yao Zhao, Rishabh Joshi, Misha Khalman, Mohammad Saleh, Peter J. Liu, Jialu Liu (2023). Statistical Rejection Sampling Improves Preference Optimization. arxiv.org/abs/2309.06657
  4. Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, Chelsea Finn (2023). Direct Preference Optimization: Your Language Model is Secretly a Reward Model. arxiv.org/abs/2305.18290
  5. Yunhao Tang, Zhaohan Daniel Guo, Zeyu Zheng, Daniele Calandriello, Rémi Munos, Mark Rowland, Pierre Harvey Richemond, Michal Valko, Bernardo Ávila Pires, Bilal Piot (2024). Generalized Preference Optimization: A Unified Approach to Offline Alignment. arxiv.org/abs/2402.05749
  6. Mohammad Gheshlaghi Azar, Mark Rowland, Bilal Piot, Daniel Guo, Daniele Calandriello, Michal Valko, Rémi Munos (2023). A General Theoretical Paradigm to Understand Learning from Human Preferences. arxiv.org/abs/2310.12036
  7. Nisan Stiennon, Long Ouyang, Jeff Wu, Daniel M. Ziegler, Ryan Lowe, Chelsea Voss, Alec Radford, Dario Amodei, Paul Christiano (2020). Learning to summarize from human feedback. arxiv.org/abs/2009.01325
  8. von Werra, L. et al. (Hugging Face) (2020). TRL: Transformer Reinforcement Learning (DPOTrainer, hinge loss). github.com/huggingface/trl

Bring a model and a metric.

Tell us what the model should get better at. A post-training engineer replies within one business day with a plan, a compute estimate and an eval design.