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

[WIP] Padding bug in GRPO #2425

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
49 changes: 48 additions & 1 deletion recipes/dev/grpo_full_finetune_distributed.py
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,18 @@ def generate_trajectory(
seq_lens=seq_lens,
)

def _pad_tensor(
self, tensor: torch.Tensor, target_dim: int, pad_value: float, dim: int = 1
) -> torch.Tensor:
pad_size = target_dim - tensor.shape[dim]
if pad_size <= 0:
return tensor

pad = [0] * (2 * tensor.ndim)
pad[-2 * (dim + 1)] = 0
pad[-2 * (dim + 1) + 1] = pad_size
return torch.nn.functional.pad(tensor, pad, value=pad_value)

def generate_trajectory_batched(
self, input_ids: torch.Tensor, answers: List[str]
) -> GRPOTrajectory:
Expand Down Expand Up @@ -842,7 +854,42 @@ def generate_trajectory_batched(
self.generate_trajectory(batch_input_ids, batch_answers)
)
torch.cuda.empty_cache()
return GRPOTrajectory(*map(torch.cat, zip(*trajectories)))

# We need to pad, to ensure that concation will not fail with error
max_p_plus_l = max(t.query_responses.shape[1] for t in trajectories)
max_l = max(t.logprobs.shape[1] for t in trajectories)

padded_trajectories = []
for traj in trajectories:
padded_masks = self._pad_tensor(
self._pad_tensor(traj.masks, max_p_plus_l, 0, dim=2),
max_p_plus_l,
0,
dim=1,
)

padded_trajectories.append(
GRPOTrajectory(
query_responses=self._pad_tensor(
traj.query_responses, max_p_plus_l, 1, dim=1
),
logprobs=self._pad_tensor(traj.logprobs, max_l, 1.0, dim=1),
ref_logprobs=self._pad_tensor(traj.ref_logprobs, max_l, 1.0, dim=1),
rewards=traj.rewards,
successes=traj.successes,
advantages=traj.advantages,
masks=padded_masks,
position_ids=self._pad_tensor(
traj.position_ids, max_p_plus_l, 0, dim=1
),
response_padding_masks=self._pad_tensor(
traj.response_padding_masks, max_l, False, dim=1
),
seq_lens=traj.seq_lens,
)
)

return GRPOTrajectory(*map(torch.cat, zip(*padded_trajectories)))

def grpo_step(
self,
Expand Down