Skip to content

Conversation

@mnoukhov
Copy link
Contributor

@mnoukhov mnoukhov commented Oct 27, 2025

Note

Introduce active refill of filtered prompts with chunked aggregation, add truncated-completion masking and richer metrics, tweak iterator robustness, and adjust training/save logic.

  • GRPO Data Pipeline:
    • Implement active batch refill via new chunked aggregation loop to request additional prompts after zero-std filtering; aggregate responses, scores, advantages, logprobs, and token stats across chunks.
    • Replace truncated-completion filtering with masking: zero scores/advantages and response masks for non-stop outputs.
    • Return prompt_lengths and response_lengths from accumulate_inference_batches and propagate through packing and utilization metrics.
    • Add combine_reward_metrics, FilteredChunk, and AggregationState to merge per-chunk data and metrics.
    • Expand logged metrics: all-zero/all-solved group counts/ratios, total filtered groups, packed ratio, guarded tokens/sec.
  • Args/Config:
    • Remove fill_completions; add active_fill_completions and active_fill_max_attempts to control active refill.
  • Iterator:
    • Refactor ShufflingIterator to recompute effective size via _update_effective_size, update on state restore, and handle empty data with StopIteration.
  • Training Loop:
    • Track filtered_prompts_count and queue extra prompt batches (with fractional training_step) to backfill after filtering.
    • Adjust save condition to also save at step 1 when eval_on_step_0 is set.

Written by Cursor Bugbot for commit 79282ce. This will update automatically on new commits. Configure here.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @mnoukhov, 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 significantly refactors the data preparation and sampling pipeline within the GRPO training framework. The core change is the introduction of an "active sampling" strategy, which intelligently replaces filtered-out prompts with new ones to maintain batch size and improve training efficiency. This involves updates to the data iterator, batch processing, and the addition of new configuration options and metrics.

Highlights

  • Active Sampling Implementation: Introduced a new "active sampling" mechanism to dynamically refill training batches with new prompts when previous samples are filtered out due to low-quality or zero-gradient issues. This replaces the previous fill_completions logic.
  • Configurable Active Sampling: Added active_sampling boolean flag and active_sampling_max_attempts integer parameter to control the behavior of the new sampling strategy.
  • Enhanced Data Iterator: The ShufflingIterator now supports excluding specific data points from future sampling, enabling the active sampling mechanism to request new, unique prompts.
  • Evaluation GPU Multiplier: Added oe_eval_gpu_multiplier argument to allow specifying the number of GPUs for evaluation jobs.
  • Improved Metric Tracking: Introduced new metrics (val/all_solved_reward_groups, val/total_filtered_groups) to provide more detailed insights into the effectiveness of the reward and filtering processes.
  • Batch Index Preservation: Modified accumulate_inference_batches to preserve original dataset indices within the Batch object, which is crucial for tracking prompts across filtering steps.
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 a significant and valuable feature: active sampling. This refactors the data preparation pipeline to dynamically request new prompts when the initial batch is heavily filtered, which should improve training efficiency and stability. The changes are extensive, particularly in the data_preparation_thread.

My review focuses on a few key areas:

  1. A fragile implementation detail in the main training loop for generating unique step IDs.
  2. Potential state management issues in the ShufflingIterator.
  3. An unused parameter that suggests an incomplete or abandoned feature implementation.
  4. A minor typo in a log message.

Overall, the active sampling logic itself appears well-designed, with good safeguards against infinite loops. The changes to handle truncated completions by masking instead of filtering are also a solid improvement.

Comment on lines +3148 to +3163
i = 0.1
while filtered_prompts_count > args.num_unique_prompts_rollout:
another_batch = next_batch(next(iter_dataloader), train_dataset)
# little hack to make sure that we don't have the same training step, otherwise vllm requests can break
# putting both batches in the same training step might also break if we accidentally sample the same dataset index twice
split_and_insert_batch(
another_batch,
iter_dataloader.epoch_number,
training_step + i,
pending_queries_map,
param_prompt_Q,
generation_configs["train"],
is_eval=False,
)
filtered_prompts_count -= args.num_unique_prompts_rollout
i += 0.1
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The use of training_step + i with a floating-point increment i to generate unique request identifiers is fragile and not best practice. This can lead to precision issues and subtle bugs, especially if the step logic changes in the future. A more robust approach should be used for generating unique IDs.

For example, you could introduce a separate request counter that is initialized before the main training loop and incremented for each batch submitted to the queue. This would provide a simple, unique, and reliable integer identifier for each request.

Comment on lines 1965 to 1972
if prompts_kept_this_iter == 0 and fill_iteration > args.active_sampling_max_attempts:
logger.warning(
"[Active fill completions] Unable to collect non-zero advantage prompts in iteration %d; "
"set as max by args.active_fill_max_attempts, proceeding with existing batch of size %d.",
fill_iteration,
len(aggregated_responses),
)
break
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

There appears to be a typo in the warning message. It references args.active_fill_max_attempts, but the relevant argument defined in the Args class is args.active_sampling_max_attempts. This could cause confusion when debugging.

Suggested change
if prompts_kept_this_iter == 0 and fill_iteration > args.active_sampling_max_attempts:
logger.warning(
"[Active fill completions] Unable to collect non-zero advantage prompts in iteration %d; "
"set as max by args.active_fill_max_attempts, proceeding with existing batch of size %d.",
fill_iteration,
len(aggregated_responses),
)
break
if prompts_kept_this_iter == 0 and fill_iteration > args.active_sampling_max_attempts:
logger.warning(
"[Active fill completions] Unable to collect non-zero advantage prompts in iteration %d; "
"set as max by args.active_sampling_max_attempts, proceeding with existing batch of size %d.",
fill_iteration,
len(aggregated_responses),
)
break

cursor[bot]

This comment was marked as outdated.

cursor[bot]

This comment was marked as outdated.

@finbarrtimbers finbarrtimbers self-requested a review October 30, 2025 03:44

# Ensure the effective dataset size is divisible by batch_size
self.effective_size = len(self.data) - (len(self.data) % batch_size)
self._update_effective_size()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why don't we just remove this and always have batches of size batch_size?

Either by throwing away the extra data or refilling across epoch numbers.


return batch

def exclude_indices(self, exclude_list: List) -> None:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why would we use this?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

my bad, this is holdovers from my next PR which will remove resampling of batches with 90% solve rate

stop_rate = sum(int(finish_reason == "stop") for finish_reason in result.finish_reasons) / len(
result.finish_reasons
)
def combine_reward_metrics(metric_records: list[tuple[Dict[str, Any], int]]) -> Dict[str, Any]:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can you add a docstring?

result.finish_reasons
)
def combine_reward_metrics(metric_records: list[tuple[Dict[str, Any], int]]) -> Dict[str, Any]:
if not metric_records:
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't think we need this, everything else should be empty and not iterate if metric_records is empty


buckets: Dict[str, list[tuple[Any, int]]] = {}
for metrics, weight in metric_records:
if not metrics:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Similarly, this is not needed as the for loop will not execute if metrics is empty

if isinstance(sample_value, np.ndarray):
combined[key] = np.concatenate([np.asarray(value) for value, _ in records])
elif isinstance(sample_value, (list, tuple)):
concatenated: list[Any] = []
Copy link
Collaborator

Choose a reason for hiding this comment

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

what about:

combined[key] = [x for value, _ in records for x in value]

if total_weight == 0:
combined[key] = float(sample_value)
else:
combined[key] = sum(float(value) * weight for value, weight in records) / total_weight
Copy link
Collaborator

Choose a reason for hiding this comment

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

what about:

weighted_sum = 0
total_weight = 0
for value, weight in records:
    weighted_sum += float(value) * weight
    total_weight += weight
combined[key] = weighted_sum / total_weight if total_weight < 1e-6 else sample_value

this way we 1) don't compare a sum of floats directly to 0 and 2) we avoid iterating over records twice.

oe_eval_beaker_image: Optional[str] = None
"""the docker image for evaluation for oe-eval"""
oe_eval_gpu_multiplier: Optional[int] = 1
"""gpu mulitplier for eval jobs"""
Copy link
Collaborator

Choose a reason for hiding this comment

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

multiplier

"""the max generation length for evaluation for oe-eval"""
oe_eval_beaker_image: Optional[str] = None
"""the docker image for evaluation for oe-eval"""
oe_eval_gpu_multiplier: Optional[int] = 1
Copy link
Collaborator

Choose a reason for hiding this comment

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

What does this do? Why would I want to multiply GPUs for eval jobs?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

also holdover from another PR


active_sampling: bool = False
"""Whether to refill the batch with *new prompts/completions* after filtering."""
active_sampling_max_attempts: int = 3
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do we actually want a max number of attempts? Let's have it wait indefinitely.

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.

3 participants