Skip to content
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

chore: refactor training loop #4435

Merged
merged 5 commits into from
Nov 30, 2024
Merged

Conversation

caic99
Copy link
Member

@caic99 caic99 commented Nov 27, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced training loop to support multi-task training, allowing for more flexible model selection.
  • Improvements

    • Streamlined step function to accept only the step ID, simplifying its usage.
    • Adjusted logging and model saving mechanisms for consistency with the new training flow.
    • Improved random seed management for enhanced reproducibility in data processing.
    • Enhanced error handling in data retrieval to ensure seamless operation during data loading.
    • Added type hints for better clarity in data loader attributes.

Copy link
Contributor

coderabbitai bot commented Nov 27, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in the pull request focus on enhancing the Trainer class within deepmd/pt/train/training.py to support multi-task training. Modifications include a new conditional block in the step function for model key selection based on a probability distribution when multi-tasking is enabled. The training loop has been simplified by iterating directly over the defined step range, and the method signature of step has been updated to accept only the step ID. Adjustments to logging and model saving mechanisms ensure consistency with the new training flow.

Changes

File Path Change Summary
deepmd/pt/train/training.py Updated step method signature to accept only _step_id. Enhanced training loop for multi-tasking, simplifying iteration and model key selection based on probability distribution. Adjusted logging and model saving mechanisms.
deepmd/pt/utils/dataloader.py Modified setup_seed to set NumPy random seed. Added type hints for systems and sampler_list attributes in DpLoaderSet. Updated __getitem__ to handle StopIteration exceptions and reinitialize iterators. Adjusted collate_batch to skip processing for keys matching "type".

Sequence Diagram(s)

sequenceDiagram
    participant Trainer
    participant Model
    participant Logger
    participant Saver

    Trainer->>Trainer: Start training loop
    Trainer->>Model: Select model key based on probability distribution
    Trainer->>Model: Call step with _step_id
    Model-->>Trainer: Perform training step
    Trainer->>Logger: Log training status
    Trainer->>Saver: Save model state
    Trainer->>Trainer: Repeat for next step
Loading

Possibly related PRs

  • perf: optimize training loop #4426: The changes in this PR also modify the Trainer class in deepmd/pt/train/training.py, specifically enhancing the training loop, which is directly related to the multi-task training improvements made in the main PR.

Suggested reviewers

  • njzjz

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between f343a3b and f281565.

📒 Files selected for processing (1)
  • deepmd/pt/train/training.py (2 hunks)
🔇 Additional comments (1)
deepmd/pt/train/training.py (1)

938-939: Simplified training loop is appropriate

The changes to the training loop enhance readability by directly iterating over the step range and removing unnecessary checks. This simplification aligns with best practices and improves code maintainability.

deepmd/pt/train/training.py Outdated Show resolved Hide resolved
deepmd/pt/train/training.py Outdated Show resolved Hide resolved
Copy link
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: 0

🧹 Outside diff range and nitpick comments (1)
deepmd/pt/train/training.py (1)

938-939: Consider adding progress tracking for long training runs.

While the simplified training loop is clean and correct, consider adding a progress tracking mechanism (e.g., tqdm) for better visibility during long training runs.

+from tqdm import tqdm
 
-        for step_id in range(self.start_step, self.num_steps):
+        for step_id in tqdm(range(self.start_step, self.num_steps), 
+                           desc="Training", 
+                           disable=self.rank != 0):
             step(step_id)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f281565 and 64e310a.

📒 Files selected for processing (1)
  • deepmd/pt/train/training.py (2 hunks)
🔇 Additional comments (1)
deepmd/pt/train/training.py (1)

656-661: LGTM: Multi-task model selection is well implemented.

The implementation:

  • Uses dp_random for reproducible randomization
  • Correctly specifies integer dtype for the array
  • Properly uses pre-computed probability distribution

Copy link

codecov bot commented Nov 27, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.72%. Comparing base (f343a3b) to head (e6f81a5).
Report is 9 commits behind head on devel.

Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4435      +/-   ##
==========================================
- Coverage   84.64%   83.72%   -0.93%     
==========================================
  Files         614      667      +53     
  Lines       57138    61441    +4303     
  Branches     3487     3486       -1     
==========================================
+ Hits        48367    51442    +3075     
- Misses       7646     8875    +1229     
+ Partials     1125     1124       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

🧹 Outside diff range and nitpick comments (1)
deepmd/pt/utils/dataloader.py (1)

53-53: LGTM! Consider adding CUDNN benchmark disable for complete determinism.

The addition of np.random.seed(seed) is a good improvement as it ensures reproducibility across both PyTorch and NumPy random operations, which is particularly important for multi-task training.

For complete determinism, consider also adding:

 def setup_seed(seed) -> None:
     torch.manual_seed(seed)
     torch.cuda.manual_seed_all(seed)
     torch.backends.cudnn.deterministic = True
+    torch.backends.cudnn.benchmark = False
     np.random.seed(seed)

This ensures CUDNN doesn't auto-tune algorithms, maintaining complete reproducibility at the cost of some performance.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b88ab3d and e0ace97.

📒 Files selected for processing (1)
  • deepmd/pt/utils/dataloader.py (1 hunks)

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

🧹 Outside diff range and nitpick comments (1)
deepmd/pt/utils/dataloader.py (1)

Line range hint 82-83: Consider adding type hints to other attributes for consistency

Good addition of type hints for systems and sampler_list. For consistency, consider adding type hints to other attributes in the class such as:

  • dataloaders
  • batch_sizes
  • index
  • iters
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e0ace97 and e6f81a5.

📒 Files selected for processing (1)
  • deepmd/pt/utils/dataloader.py (2 hunks)
🔇 Additional comments (2)
deepmd/pt/utils/dataloader.py (2)

31-31: LGTM: Import addition is appropriate

The addition of dp_random import is well-placed and necessary for the seed initialization enhancement.


54-54: Verify seed propagation in distributed training

The addition of dp_random.seed(seed) improves reproducibility by ensuring consistent randomization across all components. However, let's verify that this seed is properly propagated in distributed training scenarios.

✅ Verification successful

Let me analyze the distributed training setup further to make a conclusive verification.


Seed setup is properly handled in distributed training

The seed initialization is correctly implemented for distributed training scenarios because:

  1. The seed is set before distributed training initialization (dist.init_process_group)
  2. Each rank receives the same global seed value from the config via data_seed = config["training"].get("seed", None)
  3. The dp_random.seed() call is made before any rank-specific operations, ensuring consistent randomization across all processes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the seed setup is used in distributed training contexts
# Look for distributed training setup code that might need seed synchronization

# Search for distributed training initialization code
echo "Checking distributed training initialization patterns:"
rg -l "dist\.init_process_group|DistributedDataParallel"

# Search for other seed initialization points that might need dp_random
echo "Checking other seed initialization points:"
rg "seed\(" --type py

Length of output: 14026


Script:

#!/bin/bash
# Check how seed is handled in distributed training code
echo "Checking seed handling in distributed training files:"
rg -A 5 "setup_seed|dp_random\.seed" deepmd/pt/train/training.py deepmd/pt/entrypoints/main.py

# Check if there's any specific distributed seed handling
echo "Checking distributed seed synchronization:"
rg "setup_seed.*rank|dist.*seed" --type py

Length of output: 353


Script:

#!/bin/bash
# Let's try a broader search to understand the training initialization
echo "Checking training initialization and seed setup:"
rg -B 3 -A 7 "def train|def main" deepmd/pt/train/training.py deepmd/pt/entrypoints/main.py

# Also check for any rank-specific initialization
echo "Checking rank-specific initialization:"
rg -B 2 -A 5 "local_rank|world_rank|dist\.get_rank" deepmd/pt/train/training.py deepmd/pt/entrypoints/main.py

Length of output: 5477

@njzjz njzjz enabled auto-merge November 30, 2024 02:14
@njzjz njzjz added this pull request to the merge queue Nov 30, 2024
Merged via the queue into deepmodeling:devel with commit 03c6e49 Nov 30, 2024
60 checks passed
@caic99 caic99 deleted the refactor-training branch November 30, 2024 05:27
@njzjz njzjz linked an issue Dec 6, 2024 that may be closed by this pull request
@njzjz njzjz added this to the v3.0.1 milestone Dec 6, 2024
njzjz pushed a commit to njzjz/deepmd-kit that referenced this pull request Dec 22, 2024
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Enhanced training loop to support multi-task training, allowing for
more flexible model selection.

- **Improvements**
- Streamlined `step` function to accept only the step ID, simplifying
its usage.
- Adjusted logging and model saving mechanisms for consistency with the
new training flow.
- Improved random seed management for enhanced reproducibility in data
processing.
- Enhanced error handling in data retrieval to ensure seamless operation
during data loading.
	- Added type hints for better clarity in data loader attributes.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Chun Cai <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
(cherry picked from commit 03c6e49)
njzjz pushed a commit that referenced this pull request Dec 23, 2024
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Enhanced training loop to support multi-task training, allowing for
more flexible model selection.

- **Improvements**
- Streamlined `step` function to accept only the step ID, simplifying
its usage.
- Adjusted logging and model saving mechanisms for consistency with the
new training flow.
- Improved random seed management for enhanced reproducibility in data
processing.
- Enhanced error handling in data retrieval to ensure seamless operation
during data loading.
	- Added type hints for better clarity in data loader attributes.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Chun Cai <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
(cherry picked from commit 03c6e49)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants