Skip to content

Conversation

@londa61
Copy link

@londa61 londa61 commented Jan 12, 2026

PR type

  • Bug Fix
  • [✅] New Feature
  • Document Updates
  • More Models or Datasets Support

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).

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @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

  • GiGPO Algorithm Support: Introduced support for the GiGPO (Group-wise Importance-weighted Policy Optimization) algorithm, specifically tailored for Gym environments, building upon the existing GRPO framework.
  • Step-Level Advantage Calculation: Implemented a new mechanism to compute step-level advantages, which refines the advantage estimation by considering individual step rewards within a trajectory, grouped by prompt ID and step.
  • Configurable Step Advantage Weight: Added a new configuration parameter, step_advantage_w, allowing users to control the weighting of the newly introduced step-level advantages in the overall advantage calculation for GiGPO.
  • Argument and Parameter Updates: Updated the GRPOArgumentsMixin to include gigpo as a valid advantage_estimator and adjusted the default kl_in_reward behavior for GiGPO. The step_advantage_w parameter is also integrated into the trainer's algorithm preparation.
  • Gym Environment Reward Handling: Modified the reward weight initialization logic to specifically handle Gym environments, ensuring appropriate reward weighting when use_gym_env is enabled.

🧠 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 Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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)

Comment on lines +429 to +473
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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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_advantages

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agree

Comment on lines +710 to +715
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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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_advantages

Then you could call this helper in both places to compute the final advantage for GiGPO.

@hjh0119 hjh0119 self-assigned this Jan 12, 2026
Comment on lines +429 to +473
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
Copy link
Collaborator

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
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gigpo_step_advantage_weight

Comment on lines +2293 to +2296
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)
Copy link
Collaborator

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:
Copy link
Collaborator

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
Copy link
Collaborator

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
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here

@hjh0119
Copy link
Collaborator

hjh0119 commented Jan 15, 2026

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants