Correct for Two Systems That Disagree on the Same Tokens
In modern RL frameworks the completions are generated by a fast inference engine (the sampler, e.g. vLLM) and trained by a separate training framework (the learner). Even with identical weights, the two compute slightly different log-probabilities for the same tokens. Lambert's RLHF book corrects for this with a truncated importance weight per token,
ρtlearner=πsampler(at)πlearner(at),ρ~t=min(ρtlearner, C)
computed as the exponential of the log-probability difference, clamped to [−10,10] before exponentiating for numerical safety, then capped at C (2.0 in Open Instruct). The weight is a fixed correction (no gradient flows through it). Implement it and apply it to two losses.
tis_weights(learner_lp, sampler_lp, C=2.0)
- Inputs: arrays of the same shape. Return the float array of weights ρ~, not rounded.
reinforce_tis_loss(learner_lp, sampler_lp, advantages, mask, C=2.0)
- One gradient step, no policy drift. Per token, the loss is −ρ~tAlogπlearner(at), with
advantages of shape (B,) shared by each completion's tokens and ρ~ from tis_weights(learner_lp, sampler_lp, C).
- Return the masked mean over all response tokens of the batch (sum over mask-1 tokens divided by their count), a Python float rounded to 4 decimals.
ppo_tis_loss(new_lp, old_lp, sampler_lp, advantages, mask, eps=0.2, C=2.0)
- Several gradient steps.
new_lp are the current learner log-probs, old_lp the learner log-probs recomputed at the generation checkpoint, sampler_lp the sampler's. Per token: max(−Aρ, −Aclip(ρ,1−ϵ,1+ϵ))⋅ρ~ with ρ=enew_lp−old_lp and ρ~ = tis_weights(old_lp, sampler_lp, C).
- Return the same masked token mean, rounded to 4 decimals.
Hints
- A weight below 1 is left alone; only large weights are cut.
- If the learner's old log-probs equal the sampler's, the weight is 1 and the PPO loss is unchanged.