-
Notifications
You must be signed in to change notification settings - Fork 1.1k
[grpo] support gigpo with gym #7364
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
base: main
Are you sure you want to change the base?
Conversation
Summary of ChangesHello @londa61, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request integrates the GiGPO algorithm into the existing GRPO training framework, enhancing its capability to work with Gym environments. The core improvement lies in a more granular advantage estimation that incorporates step-level rewards, allowing for finer-grained optimization. This change provides a new, configurable approach to reinforcement learning, particularly beneficial for tasks where individual step feedback is crucial. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces support for the GIGPO algorithm, particularly for Gym environments. The changes include adding new arguments, implementing the GIGPO advantage calculation, and adjusting the reward handling for Gym environments. My review focuses on improving the efficiency of the new advantage calculation logic, reducing code duplication, and ensuring comments are up-to-date. Overall, the implementation is good, but there are opportunities for refactoring to improve performance and maintainability.
| # RLOO, REINFORCE++, GiGPO | ||
| advantage_estimator: Literal['grpo', 'rloo', 'reinforce_plus_plus', 'gigpo'] = 'grpo' | ||
| # If false, add KL into loss, otherwise add into reward | ||
| kl_in_reward: Optional[bool] = None # rloo/reinforce_plus_plus: true, grpo: false (default) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The comment for kl_in_reward is now outdated with the addition of gigpo. The docstring was updated to reflect that kl_in_reward is False for gigpo, but this inline comment was missed. Please update it for consistency and to avoid confusion for future developers.
| kl_in_reward: Optional[bool] = None # rloo/reinforce_plus_plus: true, grpo: false (default) | |
| kl_in_reward: Optional[bool] = None # rloo/reinforce_plus_plus: true, grpo/gigpo: false (default) |
| def _compute_step_advantages(inputs, trajectory_advantages): | ||
| # Extract step-level reward information from inputs | ||
| # Store (prompt_id, step) -> [rewards] mapping | ||
| step_rewards_dict = {} | ||
| for idx, input_data in enumerate(inputs): | ||
| prompt_id = input_data['prompt_id'] | ||
| rollout_info = input_data['rollout_infos'] | ||
|
|
||
| # Collect all step rewards for current trajectory | ||
| for traj_info in rollout_info.get('trajectory_info', []): | ||
| step = traj_info.get('step', 0) | ||
| reward = traj_info.get('reward', 0.0) | ||
|
|
||
| # Group rewards by prompt_id and step | ||
| key = (prompt_id, step) | ||
| if key not in step_rewards_dict: | ||
| step_rewards_dict[key] = [] | ||
| step_rewards_dict[key].append(reward) | ||
| # Calculate step-level advantage and aggregate | ||
| aggregated_step_advantages = torch.zeros_like(trajectory_advantages) | ||
| for idx, input_data in enumerate(inputs): | ||
| prompt_id = input_data['prompt_id'] | ||
| rollout_info = input_data['rollout_infos'] | ||
|
|
||
| # Calculate aggregated step-level advantage for current trajectory | ||
| step_advantages = [] | ||
| for traj_info in rollout_info.get('trajectory_info', []): | ||
| step = traj_info.get('step', 0) | ||
| reward = traj_info.get('reward', 0.0) | ||
|
|
||
| # Get all rewards for same prompt and step | ||
| key = (prompt_id, step) | ||
| all_rewards = step_rewards_dict.get(key, [reward]) | ||
|
|
||
| # Calculate step advantage (compared to group average) | ||
| mean_reward = np.mean(all_rewards) | ||
| step_advantage = reward - mean_reward | ||
| step_advantages.append(step_advantage) | ||
|
|
||
| # Aggregate step-level advantage for current trajectory (use mean of valid steps) | ||
| if step_advantages: | ||
| aggregated_step_advantages[idx] = np.mean(step_advantages) | ||
| else: | ||
| aggregated_step_advantages[idx] = 0.0 | ||
| return aggregated_step_advantages |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current implementation of _compute_step_advantages iterates over inputs twice, and computes the mean reward for each step within the second loop. This is inefficient as it leads to redundant calculations of the mean for the same (prompt_id, step) group.
You can improve performance by pre-calculating the mean rewards for all step groups in a single pass. This refactoring would reduce the complexity and make the code cleaner. I've provided a suggested implementation below that first builds a dictionary of all step rewards, then computes the means, and finally calculates the advantages in a second loop.
def _compute_step_advantages(inputs, trajectory_advantages):
# Extract step-level reward information from inputs
# Store (prompt_id, step) -> [rewards] mapping
step_rewards_dict = defaultdict(list)
for input_data in inputs:
prompt_id = input_data['prompt_id']
rollout_info = input_data['rollout_infos']
for traj_info in rollout_info.get('trajectory_info', []):
step = traj_info.get('step', 0)
reward = traj_info.get('reward', 0.0)
step_rewards_dict[(prompt_id, step)].append(reward)
# Pre-calculate mean rewards for each step
step_mean_rewards = {key: np.mean(rewards) for key, rewards in step_rewards_dict.items()}
# Calculate step-level advantage and aggregate
aggregated_step_advantages = torch.zeros_like(trajectory_advantages)
for idx, input_data in enumerate(inputs):
prompt_id = input_data['prompt_id']
rollout_info = input_data['rollout_infos']
step_advantages = []
for traj_info in rollout_info.get('trajectory_info', []):
step = traj_info.get('step', 0)
reward = traj_info.get('reward', 0.0)
# Get pre-calculated mean reward for the same prompt and step
key = (prompt_id, step)
# The key should always exist, but we use .get for safety.
mean_reward = step_mean_rewards.get(key, reward)
# Calculate step advantage
step_advantage = reward - mean_reward
step_advantages.append(step_advantage)
# Aggregate step-level advantage for current trajectory (use mean of valid steps)
if step_advantages:
aggregated_step_advantages[idx] = np.mean(step_advantages)
else:
aggregated_step_advantages[idx] = 0.0
return aggregated_step_advantagesThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
agree
| if self.advantage_estimator == 'gigpo' and self.use_gym_env: | ||
| # Get trajectory-level advantage (original GRPO advantage) | ||
| trajectory_advantages = advantages | ||
| aggregated_step_advantages = _compute_step_advantages(inputs, trajectory_advantages) | ||
| # Weighted sum of trajectory-level advantage and aggregated step-level advantage | ||
| advantages = trajectory_advantages + self.step_advantage_w * aggregated_step_advantages |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This block of code for calculating the GiGPO advantage is nearly identical to the one on lines 556-561. To improve maintainability and avoid code duplication, consider extracting this logic into a helper function.
For example, you could create a helper within _compute_advantages:
def _apply_gigpo_step_advantage(base_advantages, inputs):
aggregated_step_advantages = _compute_step_advantages(inputs, base_advantages)
return base_advantages + self.step_advantage_w * aggregated_step_advantagesThen you could call this helper in both places to compute the final advantage for GiGPO.
| def _compute_step_advantages(inputs, trajectory_advantages): | ||
| # Extract step-level reward information from inputs | ||
| # Store (prompt_id, step) -> [rewards] mapping | ||
| step_rewards_dict = {} | ||
| for idx, input_data in enumerate(inputs): | ||
| prompt_id = input_data['prompt_id'] | ||
| rollout_info = input_data['rollout_infos'] | ||
|
|
||
| # Collect all step rewards for current trajectory | ||
| for traj_info in rollout_info.get('trajectory_info', []): | ||
| step = traj_info.get('step', 0) | ||
| reward = traj_info.get('reward', 0.0) | ||
|
|
||
| # Group rewards by prompt_id and step | ||
| key = (prompt_id, step) | ||
| if key not in step_rewards_dict: | ||
| step_rewards_dict[key] = [] | ||
| step_rewards_dict[key].append(reward) | ||
| # Calculate step-level advantage and aggregate | ||
| aggregated_step_advantages = torch.zeros_like(trajectory_advantages) | ||
| for idx, input_data in enumerate(inputs): | ||
| prompt_id = input_data['prompt_id'] | ||
| rollout_info = input_data['rollout_infos'] | ||
|
|
||
| # Calculate aggregated step-level advantage for current trajectory | ||
| step_advantages = [] | ||
| for traj_info in rollout_info.get('trajectory_info', []): | ||
| step = traj_info.get('step', 0) | ||
| reward = traj_info.get('reward', 0.0) | ||
|
|
||
| # Get all rewards for same prompt and step | ||
| key = (prompt_id, step) | ||
| all_rewards = step_rewards_dict.get(key, [reward]) | ||
|
|
||
| # Calculate step advantage (compared to group average) | ||
| mean_reward = np.mean(all_rewards) | ||
| step_advantage = reward - mean_reward | ||
| step_advantages.append(step_advantage) | ||
|
|
||
| # Aggregate step-level advantage for current trajectory (use mean of valid steps) | ||
| if step_advantages: | ||
| aggregated_step_advantages[idx] = np.mean(step_advantages) | ||
| else: | ||
| aggregated_step_advantages[idx] = 0.0 | ||
| return aggregated_step_advantages |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
agree
| # If false, add KL into loss, otherwise add into reward | ||
| kl_in_reward: Optional[bool] = None # rloo/reinforce_plus_plus: true, grpo: false (default) | ||
| # GiGPO, https://arxiv.org/abs/2405.06708 | ||
| step_advantage_w = 1.0 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
gigpo_step_advantage_weight
| if self.use_gym_env: | ||
| self.reward_weights = torch.ones(1, dtype=torch.float32).to(device) | ||
| else: | ||
| self.reward_weights = torch.ones(len(self.reward_func_names), dtype=torch.float32).to(device) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When use_gym_env is enabled, len(reward_func_names) == 1
if self.use_gym_env:
self.reward_func_names = ['gym_reward']
so it's unnecessary
| advantages = rewards * K / (K - 1) - group_rewards_mean * K / (K - 1) | ||
| else: | ||
| advantages = rewards - group_rewards_mean | ||
| elif self.advantage_estimator == 'gigpo' and self.use_gym_env: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since Gigpo depends on the Gym environment, it's recommended to add proper checks.
- if self.advantage_estimator == 'gigpo' and self.use_gym_env:
+ if self.advantage_estimator == 'gigpo':
+ assert self.use_gym_env| self.advantage_estimator = args.advantage_estimator | ||
| self.kl_in_reward = args.kl_in_reward | ||
|
|
||
| # GiGPO, https://arxiv.org/abs/2405.06708 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
wrong link
| advantage_estimator: Literal['grpo', 'rloo', 'reinforce_plus_plus', 'gigpo'] = 'grpo' | ||
| # If false, add KL into loss, otherwise add into reward | ||
| kl_in_reward: Optional[bool] = None # rloo/reinforce_plus_plus: true, grpo: false (default) | ||
| # GiGPO, https://arxiv.org/abs/2405.06708 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
same here
|
Thanks for the contribution—I've left a few comments. BTW, please update the descriptions of the gigpo-related parameters in the command-line-parameters documentation. It would be even better if there were corresponding algorithm documentation as well. |
PR type
PR information
This PR implements the GIGPO algorithm based on the Gym environment on the basis of the existing GRPO. The code makes fine - grained optimizations to the existing trajectory advantages based on the step markers and step rewards provided by the Gym environment.
Experiment results
Paste your experiment result here(if needed).