Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RLOO] fix token_level_kl #2575

Merged
merged 8 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion trl/trainer/rloo_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,6 @@ class RLOOConfig(OnPolicyConfig):
metadata={"help": "Whether to normalize advantages"},
)
token_level_kl: bool = field(
default=True,
default=False,
metadata={"help": "Whether to use token-level KL penalty or sequence-level KL penalty"},
)
11 changes: 7 additions & 4 deletions trl/trainer/rloo_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,13 +397,16 @@ def repeat_generator():
# Compute total reward with KL penalty
if args.token_level_kl:
# Token-level KL penalty: apply KL penalty per token
token_kl_penalty = -args.kl_coef * kl
non_score_reward = token_kl_penalty.sum(1)
kl_reward = -args.kl_coef * kl
# Apply reward at the last non-padded token position for each sequence
eos_indices = sequence_lengths.unsqueeze(1) - 1
last_reward = torch.zeros_like(kl).scatter_(dim=1, index=eos_indices, src=scores.unsqueeze(1))
non_score_reward = kl_reward.sum(1) + last_reward.sum(1)
else:
# Sequence-level KL penalty: sum KL across tokens first
sequence_kl = kl.sum(1)
non_score_reward = -args.kl_coef * sequence_kl
rlhf_reward = scores + non_score_reward
non_score_reward = -args.kl_coef * sequence_kl + scores
rlhf_reward = non_score_reward
kashif marked this conversation as resolved.
Show resolved Hide resolved

# vectorized RLOO advantages implementation
rlhf_reward = rlhf_reward.reshape(args.rloo_k, -1)
Expand Down
Loading