Skip to content

Conversation

@mnoukhov
Copy link
Contributor

@mnoukhov mnoukhov commented Oct 27, 2025

Note

Introduce active sampling to refill batches after filtering, refactor data preparation into aggregated chunks with safer iterators and enriched metrics, and adjust save/eval flow.

  • GRPO pipeline:
    • Add args.active_sampling and args.active_sampling_max_attempts; remove args.fill_completions.
    • Refactor data_preparation_thread to iteratively accumulate, score, filter (zero-std), optionally refill with new prompts, aggregate chunks, and pack sequences.
    • Mask truncated completions by zeroing scores/advantages and response masks when enabled.
    • Compute and log new metrics: per-batch filtered group counts, zero/solved reward group ratios, packed ratio, and guarded tokens/sec; propagate prompt_lengths/response_lengths.
  • Batch/inference handling:
    • accumulate_inference_batches now returns (GenerationResult, Batch, prompt_lengths, response_lengths) and preserves indices field.
    • Add combine_reward_metrics, FilteredChunk, and AggregationState to merge multi-iteration results and stats.
  • Iterator robustness:
    • ShufflingIterator now guards empty data, centralizes effective-size computation, and updates it on state restore.
  • Training loop:
    • Track val/total_filtered_groups to submit extra prompt batches when filtering shrinks data; avoid step collisions via fractional training_step offsets.
    • Save condition updated to allow save at step 1 when eval_on_step_0 is true.

Written by Cursor Bugbot for commit f8181e5. 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.

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


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.

@mnoukhov mnoukhov closed this Nov 25, 2025
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