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

Fix NaNs in RL loss #184

Merged
merged 1 commit into from
Feb 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
10 changes: 8 additions & 2 deletions tapeagents/finetune/rl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,15 +136,20 @@ def rl_step(model: PreTrainedModel, batch: dict, config: RLConfig) -> tuple[torc

assert approx_kl.shape == masks_.shape
assert approx_kl.shape == surrogate_loss.shape
loss = -masked_sum(surrogate_loss - config.kl_coef * approx_kl, masks_)
loss = surrogate_loss - config.kl_coef * approx_kl
# loss = -masked_sum(surrogate_loss - config.kl_coef * approx_kl, masks_)
case "reinforce":
surr1 = torch.zeros_like(ratio_new_old)
surr2 = torch.zeros_like(ratio_new_old)
loss = -masked_sum(new_log_probs * log_p_weights - config.kl_coef * approx_kl, masks_)
loss = new_log_probs * log_p_weights - config.kl_coef * approx_kl
# loss = -masked_sum(new_log_probs * log_p_weights - config.kl_coef * approx_kl, masks_)
case _:
raise ValueError(f"Unknown algorithm {config.algo}")

num_nans = torch.isnan(loss).sum()
loss = -masked_sum(loss, masks_)
assert torch.isfinite(loss).all(), f"Loss is not finite: {loss}"

# normalize the loss by the micro batch size
loss = loss / masks.shape[0]
stats = {
Expand Down Expand Up @@ -181,6 +186,7 @@ def rl_step(model: PreTrainedModel, batch: dict, config: RLConfig) -> tuple[torc
"ratio_ref_new": masked_mean(torch.exp(log_ratio_ref_new), masks_).item(),
"ratio_ref_old": masked_mean(torch.exp(ref_logprobs - old_logprobs), masks_).item(),
"clamp_log_ratio_ref_new_indicators": masked_mean(clamp_log_ratio_ref_new_indicators, masks_).item(),
"num_nans": num_nans.item(),
}
return loss, stats

Expand Down
8 changes: 4 additions & 4 deletions tapeagents/finetune/rl/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,17 @@ def get_avg_rl_stats(rl_stats):
def masked_sum(values: torch.Tensor, mask: torch.Tensor, axis: Optional[bool] = None) -> torch.Tensor:
"""Compute sum of tensor with a masked values."""
if axis is not None:
return (values * mask).sum(axis=axis) # type: ignore
return (values * mask).nan_to_num(0).sum(axis=axis) # type: ignore
else:
return (values * mask).sum()
return (values * mask).nan_to_num(0).sum()


def masked_mean(values: torch.Tensor, mask: torch.Tensor, axis: Optional[bool] = None) -> torch.Tensor:
"""Compute mean of tensor with a masked values."""
if axis is not None:
return (values * mask).sum(axis=axis) / mask.sum(axis=axis) # type: ignore
return (values * mask).nan_to_num(0).sum(axis=axis) / mask.sum(axis=axis) # type: ignore
else:
return (values * mask).sum() / mask.sum()
return (values * mask).nan_to_num(0).sum() / mask.sum()


def calculate_rewards_with_implicit_kl(row, reward_minus_kl_coef):
Expand Down