OPD icon indicating copy to clipboard operation
OPD copied to clipboard

Question about `REWARD_WEIGHT_MODE="teacher_p"` and forward KL in OPD

Open Ppp-Ttt opened this issue 5 months ago • 3 comments

Hi, I have a question about the KL direction when using the following configuration:

TOP_K = 16
TOP_K_STRATEGY = "only_stu"
REWARD_WEIGHT_MODE = "student_p" / "teacher_p"

My understanding is:

When TOP_K_STRATEGY="only_stu" and REWARD_WEIGHT_MODE="student_p", the objective corresponds to the Reverse KL form used in standard OPD:

p_s * log(p_s / p_t)

However, when REWARD_WEIGHT_MODE="teacher_p", it seems to correspond to:

p_t * log(p_s / p_t)

rather than the Forward KL version of OPD:

p_t * log(p_t / p_s)

Is this understanding correct?

If I want to modify the implementation to use the forward KL form, would the simplest change be in:

verl/verl/workers/actor/dp_actor.py

around lines 522– where the current logic is:

        def compute_reward_weights(S_logp, T_logp, valid_mask, weight_mode, normalize=True):
            """Compute weights for reward calculation.
            
            Args:
                S_logp: Student log probabilities (batch, seq, K)
                T_logp: Teacher log probabilities (batch, seq, K)
                valid_mask: Boolean mask for valid tokens (batch, seq, K)
                weight_mode: "student_p", "teacher_p", or "none"
                normalize: If True, apply softmax normalization across K dim.
                          If False, use raw probabilities (masked by valid_mask).
            
            Returns:
                Weights (batch, seq, K)
            """
            if weight_mode == "student_p":
                log_probs = S_logp
            elif weight_mode == "teacher_p":
                log_probs = T_logp
            elif weight_mode == "none":
                # 对于"none"模式,使用均匀分布
                log_probs = torch.zeros_like(S_logp)
            else:
                raise ValueError(f"Unknown reward_weight_mode: {weight_mode}")
            
            log_probs = torch.where(valid_mask, log_probs, torch.full_like(log_probs, -float('inf')))
            
            if normalize:
                norm_log_weights = log_probs - torch.logsumexp(log_probs, dim=-1, keepdim=True)
                weights = torch.exp(norm_log_weights)
            else:
                weights = torch.exp(log_probs)
            
            weights = torch.nan_to_num(weights, nan=0.0, posinf=0.0, neginf=0.0)
            
            return weights

change to:

        def compute_reward_weights(S_logp, T_logp, valid_mask, weight_mode, normalize=True):
            """Compute weights for reward calculation.
            
            Args:
                S_logp: Student log probabilities (batch, seq, K)
                T_logp: Teacher log probabilities (batch, seq, K)
                valid_mask: Boolean mask for valid tokens (batch, seq, K)
                weight_mode: "student_p", "teacher_p", or "none"
                normalize: If True, apply softmax normalization across K dim.
                          If False, use raw probabilities (masked by valid_mask).
            
            Returns:
                Weights (batch, seq, K)
            """
            if weight_mode == "student_p":
                log_probs = S_logp
            elif weight_mode == "teacher_p":
                log_probs = T_logp
            elif weight_mode == "none":
                # 对于"none"模式,使用均匀分布
                log_probs = torch.zeros_like(S_logp)
            else:
                raise ValueError(f"Unknown reward_weight_mode: {weight_mode}")
            
            log_probs = torch.where(valid_mask, log_probs, torch.full_like(log_probs, -float('inf')))
            
            if normalize:
                norm_log_weights = log_probs - torch.logsumexp(log_probs, dim=-1, keepdim=True)
                weights = torch.exp(norm_log_weights)
            else:
                weights = torch.exp(log_probs)
            
            weights = torch.nan_to_num(weights, nan=0.0, posinf=0.0, neginf=0.0)

            # new
            if weight_mode == "teacher_p":
                return -weights

            return weights

for the Forward KL OPD case?

Could you please confirm whether this is the intended behavior, or whether I am misunderstanding how REWARD_WEIGHT_MODE="teacher_p" is implemented?

Thanks!

Ppp-Ttt avatar Jun 24 '26 09:06 Ppp-Ttt

I think your understanding is correct. In our initial implementation, we used -weights for reweighting, aiming to make the final loss resemble a forward-KL objective. However, for reasons that are still unclear, this variant performed very poorly in practice.

Image Image Image

The purple curve uses student_p weighting, the gray curve uses teacher_p weighting, and the green curve uses -teacher_p weighting. The intuition behind this choice is that weighting by $$-p_{tch}$$ is equivalent to adding a negative sign to the log term, yielding $$\sum p_{tch}\log \frac{p_{tch}}{p_{stu}}$$, which corresponds to minimizing the forward KL. As shown, teacher_p weighting does have some effect, but the improvement is generally limited. Using the negative weighting performs poorly.

Image Image

As shown, after adding the negative sign, the loss does indeed become positive (it is consistent with forward KL >0 ), but it is unclear why the training becomes unstable and diverges. I suspect this may be attributed to the issue of implementing KL through the reward (that is KL in reward) , but the exact reason probably requires deriving the formula in detail.

Turingzero0 avatar Jun 24 '26 20:06 Turingzero0

I also observed the gradient explosion phenomenon caused by -weights Image

In fact, I think it is caused by the the gradient generated by this implementation is different from the gradient of the FKL constraint:

Standard Reverse KL Loss:
$$\nabla_\theta \text{KL}\left(p_s\Vert p_t \right)== \sum_k p_s\log\tfrac{p_s}{p_t}\nabla\log p_s $$ we need $$\text{rmscore}=-p_s\log\tfrac{p_s}{p_t}$$ in ppo-style OPD

Right Reverse KL implement by student_p:

if weight_mode == "student_p":
    log_probs = S_logp
weights = torch.exp(log_probs)
kl_val = S_logp - T_on_S
rm_scores = -kl_val * norm_weights

in code, it has been correctly implemented


Standard Forward KL Loss:
$$\nabla_\theta \text{KL}\left(p_t\Vert p_s \right)== - \sum_k p_t\nabla\log p_s$$ we need $$\text{rmscore}=p_t$$

Wrong Forward KL implement by original teacher_p:

if weight_mode == "teacher_p":
    log_probs = T_logp
weights = torch.exp(log_probs)
kl_val = S_logp - T_on_S
rm_scores = -kl_val * weights

where $$\text{rmscore}=-p_t\log\tfrac{p_s}{p_t}$$

Wrong Forward KL implement by -weights:

if weight_mode == "teacher_p":
    log_probs = T_logp
weights = - torch.exp(log_probs)
kl_val = S_logp - T_on_S
rm_scores = -kl_val * weights

where $$\text{rmscore}=-p_t\log\tfrac{p_t}{p_s}$$

Right Forward KL implement:

if weight_mode == "teacher_p":
    log_probs = T_logp
weights =  torch.exp(log_probs)
rm_scores =  weights

where $$\text{rmscore}=p_t$$

If we need forward KL for OPD in ppo-style, we need to set rm_scores = torch.exp(T_logp)

Ppp-Ttt avatar Jun 25 '26 05:06 Ppp-Ttt

I think your derivation is completely correct. When taking the derivative of the forward KL, $$p_t$$ is treated as a constant, so the KL-in-reward implementation should set rm_score = p_t.

Thank you very much for the derivation.

Turingzero0 avatar Jun 25 '26 06:06 Turingzero0