Skip to content

fix worker_init_fn signature handling#2769

Merged
winglian merged 1 commit into
mainfrom
grpo-get-dataloader
Jun 9, 2025
Merged

fix worker_init_fn signature handling#2769
winglian merged 1 commit into
mainfrom
grpo-get-dataloader

Conversation

@winglian
Copy link
Copy Markdown
Collaborator

@winglian winglian commented Jun 8, 2025

Summary by CodeRabbit

  • New Features
    • Improved training data loading with enhanced batch size handling and more robust data loader configuration for training.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 8, 2025

Walkthrough

A new method, get_train_dataloader, was introduced to the AxolotlGRPOTrainer class. This method constructs and returns a training DataLoader, handling dataset validation, column removal, batch size computation, worker initialization, and DataLoader preparation with the accelerator. It explicitly incorporates steps_per_generation into batch size calculation.

Changes

File Change Summary
src/axolotl/core/trainers/grpo/trainer.py Added get_train_dataloader method to AxolotlGRPOTrainer for constructing and returning a DataLoader with custom batch size and worker initialization logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AxolotlGRPOTrainer
    participant Dataset
    participant DataLoader
    participant Accelerator

    User->>AxolotlGRPOTrainer: Call get_train_dataloader()
    AxolotlGRPOTrainer->>AxolotlGRPOTrainer: Validate train_dataset
    AxolotlGRPOTrainer->>Dataset: Remove unused columns (if applicable)
    AxolotlGRPOTrainer->>AxolotlGRPOTrainer: Compute batch size (batch_size * steps_per_generation)
    AxolotlGRPOTrainer->>DataLoader: Construct DataLoader with parameters
    AxolotlGRPOTrainer->>Accelerator: Prepare DataLoader
    Accelerator-->>AxolotlGRPOTrainer: Return prepared DataLoader
    AxolotlGRPOTrainer-->>User: Return DataLoader
Loading

Poem

Hopping through code with a dataloader new,
Batch sizes now multiplied, as rabbits do!
Columns trimmed, workers set just right,
Training flows smoothly, day or night.
With every generation, we leap ahead—
Data prepared, and well-fed!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7909bfb and ff03a95.

📒 Files selected for processing (1)
  • src/axolotl/core/trainers/grpo/trainer.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: pre-commit
  • GitHub Check: PyTest from Source Dist (3.11, 2.7.0)
  • GitHub Check: PyTest (3.11, 2.7.0)
  • GitHub Check: PyTest from Source Dist (3.11, 2.5.1)
  • GitHub Check: PyTest from Source Dist (3.11, 2.6.0)
  • GitHub Check: PyTest (3.11, 2.6.0)
  • GitHub Check: PyTest (3.11, 2.5.1)
  • GitHub Check: pre-commit
🔇 Additional comments (3)
src/axolotl/core/trainers/grpo/trainer.py (3)

6-6: LGTM! Import added for worker initialization fix.

The partial import is correctly added to support the worker_init_fn signature handling fix.


77-80: Batch size multiplication logic looks correct.

The multiplication by steps_per_generation aligns with GRPO's requirement to process multiple generations per prompt in a single batch.


89-93:

Details

❓ Verification inconclusive

Verify the seed_worker function signature.

The partial usage suggests a fix for incorrect parameter passing to seed_worker. However, I need to verify that num_workers and rank are the correct parameters that seed_worker expects.

Let me check the seed_worker function signature to ensure the parameters are correct:


🏁 Script executed:

#!/bin/bash
# Description: Check the seed_worker function signature from transformers
# Expected: Function signature showing the expected parameters

ast-grep --pattern 'def seed_worker($$$)'

Length of output: 43


#!/bin/bash
set -euo pipefail

Search for the seed_worker definition

rg -n "def seed_worker" -C3

Also search all references to seed_worker to see how it's used

rg -n "seed_worker" -C3


#!/bin/bash
set -euo pipefail

Locate the seed_worker definition and its signature

rg -n "def seed_worker" -C3

Show all usages/imports to infer expected parameters

rg -n "seed_worker" -C3


#!/bin/bash
set -euo pipefail

Locate the seed_worker definition (if present) and its signature

rg -n "^def seed_worker" -C5 .

Find all import sites and usages to infer expected parameters

rg -n "seed_worker" -C5 .


Confirm seed_worker signature for DataLoader worker_init_fn

I couldn’t locate the seed_worker implementation in the repo to verify that it accepts num_workers and rank as keyword arguments. Please double-check its signature and adjust the partial(...) call if the parameter names differ.

• File: src/axolotl/core/trainers/grpo/trainer.py
Lines: 89–93

Comment on lines +62 to +97
def get_train_dataloader(self):
if self.train_dataset is None:
raise ValueError("Trainer: training requires a train_dataset.")

train_dataset = self.train_dataset
data_collator = self.data_collator
if isinstance(train_dataset, datasets.Dataset):
train_dataset = self._remove_unused_columns(
train_dataset, description="training"
)
else:
data_collator = self._get_collator_with_removed_columns(
data_collator, description="training"
)

dataloader_params = {
"batch_size": self._train_batch_size
* self.args.steps_per_generation, # < this is the change
"collate_fn": data_collator,
"num_workers": self.args.dataloader_num_workers,
"pin_memory": self.args.dataloader_pin_memory,
"persistent_workers": self.args.dataloader_persistent_workers,
}

if not isinstance(train_dataset, torch.utils.data.IterableDataset):
dataloader_params["sampler"] = self._get_train_sampler()
dataloader_params["drop_last"] = self.args.dataloader_drop_last
dataloader_params["worker_init_fn"] = partial(
seed_worker,
num_workers=self.args.dataloader_num_workers,
rank=self.args.process_index,
)
dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor

return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Inconsistency with AxolotlGRPOSequenceParallelTrainer implementation.

The AxolotlGRPOSequenceParallelTrainer class has a different get_train_dataloader method (line 276) that handles worker_init_fn differently - it uses seed_worker directly without partial. This inconsistency could lead to different behavior between the two trainer classes.

Consider aligning both implementations to use the same approach for worker_init_fn. If the partial approach is the correct fix, the AxolotlGRPOSequenceParallelTrainer should be updated accordingly:

# In AxolotlGRPOSequenceParallelTrainer.get_train_dataloader method around line 255
- dataloader_params["worker_init_fn"] = seed_worker
+ dataloader_params["worker_init_fn"] = partial(
+     seed_worker,
+     num_workers=self.args.dataloader_num_workers,
+     rank=self.args.process_index,
+ )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def get_train_dataloader(self):
if self.train_dataset is None:
raise ValueError("Trainer: training requires a train_dataset.")
train_dataset = self.train_dataset
data_collator = self.data_collator
if isinstance(train_dataset, datasets.Dataset):
train_dataset = self._remove_unused_columns(
train_dataset, description="training"
)
else:
data_collator = self._get_collator_with_removed_columns(
data_collator, description="training"
)
dataloader_params = {
"batch_size": self._train_batch_size
* self.args.steps_per_generation, # < this is the change
"collate_fn": data_collator,
"num_workers": self.args.dataloader_num_workers,
"pin_memory": self.args.dataloader_pin_memory,
"persistent_workers": self.args.dataloader_persistent_workers,
}
if not isinstance(train_dataset, torch.utils.data.IterableDataset):
dataloader_params["sampler"] = self._get_train_sampler()
dataloader_params["drop_last"] = self.args.dataloader_drop_last
dataloader_params["worker_init_fn"] = partial(
seed_worker,
num_workers=self.args.dataloader_num_workers,
rank=self.args.process_index,
)
dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor
return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params))
def get_train_dataloader(self):
# … earlier in the method …
if not isinstance(train_dataset, torch.utils.data.IterableDataset):
dataloader_params["sampler"] = self._get_train_sampler()
dataloader_params["drop_last"] = self.args.dataloader_drop_last
- dataloader_params["worker_init_fn"] = seed_worker
+ dataloader_params["worker_init_fn"] = partial(
+ seed_worker,
+ num_workers=self.args.dataloader_num_workers,
+ rank=self.args.process_index,
+ )
dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor
return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params))
🤖 Prompt for AI Agents
In src/axolotl/core/trainers/grpo/trainer.py between lines 62 and 97, the
get_train_dataloader method uses partial to wrap seed_worker for the
worker_init_fn parameter, while the AxolotlGRPOSequenceParallelTrainer class
uses seed_worker directly. To fix this inconsistency, review both
implementations and decide on one approach for worker_init_fn; if partial is
preferred, update the AxolotlGRPOSequenceParallelTrainer's get_train_dataloader
method to use partial with the same arguments, ensuring consistent behavior
across both trainer classes.

@codecov
Copy link
Copy Markdown

codecov Bot commented Jun 8, 2025

Codecov Report

Attention: Patch coverage is 12.50000% with 14 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/axolotl/core/trainers/grpo/trainer.py 12.50% 14 Missing ⚠️

📢 Thoughts on this report? Let us know!

@winglian winglian merged commit 09c685f into main Jun 9, 2025
16 of 17 checks passed
@winglian winglian deleted the grpo-get-dataloader branch June 9, 2025 06:14
@coderabbitai coderabbitai Bot mentioned this pull request Jul 10, 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.

1 participant