Skip to content

feat(pt): add plugin for data modifier #4661

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

Open
wants to merge 15 commits into
base: devel
Choose a base branch
from

Conversation

ChiahsinChu
Copy link
Contributor

@ChiahsinChu ChiahsinChu commented Mar 20, 2025

  • Add plugin for data modifier in pytorch backend
  • Modify data in training
  • todo: add wrapper for frozen model

Summary by CodeRabbit

  • New Features

    • Introduced a configurable data modifier for training that dynamically adjusts input data during both training and validation.
    • Enabled the modifier’s state to be preserved when saving models, ensuring consistency of training modifications.
    • Added a new base modifier class to support data modification capabilities.
  • Refactor

    • Improved logging and batch handling logic to allow for flexible processing of all available data batches.

box = data["box"][:get_nframes, :]
atype = data["atype"][:get_nframes, :]
atype = atype[0]
nframes = coord.shape[0]

Check notice

Code scanning / CodeQL

Unused local variable Note

Variable nframes is not used.
Copy link
Contributor

coderabbitai bot commented Mar 20, 2025

📝 Walkthrough

"""

Walkthrough

The pull request introduces a public data modifier API by adding two new files in the modifier package. A new class, BaseModifier, is implemented to handle data modifications and expose its functionality. Furthermore, the training process is updated to integrate the data modifier by adding a constructor parameter, applying modifications during model training, and including modifier state during model saving. Minor changes in the stats utility adjust logging and batch processing logic.

Changes

Files Change Summary
deepmd/pt/modifier/init.py
deepmd/pt/modifier/base_modifier.py
New files introduced to establish the public API for data modifiers. The BaseModifier class is defined with a modify_data method for adjusting training data.
deepmd/pt/train/training.py Modified the Trainer to accept and apply a data modifier. Added modifier initialization via get_data_modifier, integrated modifier state in training and saving.
deepmd/pt/utils/stat.py Updated the make_stat_input function to conditionally log when batches are available and refined batch count determination based on nbatches value.

Sequence Diagram(s)

sequenceDiagram
    participant Trainer
    participant Modifier
    participant Data
    Trainer->>Modifier: get_data_modifier(modifier_params)
    Trainer->>Data: Fetch training/validation sample
    Trainer->>Modifier: modify_data(sample)
    Modifier->>Modifier: Process data (slice inputs, call forward)
    Modifier-->>Trainer: Return modified data
Loading

Suggested labels

Python

Suggested reviewers

  • njzjz
  • iProzd
    """

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Pylint (3.3.7)
deepmd/pt/train/training.py

No files to lint: exiting.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e6bca31 and 5369e80.

📒 Files selected for processing (1)
  • deepmd/pt/train/training.py (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • deepmd/pt/train/training.py
⏰ Context from checks skipped due to timeout of 90000ms (29)
  • GitHub Check: Build wheels for cp310-manylinux_aarch64
  • GitHub Check: Build wheels for cp311-win_amd64
  • GitHub Check: Build wheels for cp311-macosx_x86_64
  • GitHub Check: Test Python (6, 3.9)
  • GitHub Check: Analyze (c-cpp)
  • GitHub Check: Build wheels for cp311-manylinux_x86_64
  • GitHub Check: Build wheels for cp311-macosx_arm64
  • GitHub Check: Build wheels for cp311-manylinux_x86_64
  • GitHub Check: Test Python (5, 3.9)
  • GitHub Check: Test Python (5, 3.12)
  • GitHub Check: Test Python (4, 3.12)
  • GitHub Check: Test Python (6, 3.12)
  • GitHub Check: Analyze (python)
  • GitHub Check: Test Python (1, 3.12)
  • GitHub Check: Test Python (3, 3.9)
  • GitHub Check: Test Python (2, 3.9)
  • GitHub Check: Test C++ (true)
  • GitHub Check: Test Python (3, 3.12)
  • GitHub Check: Test Python (2, 3.12)
  • GitHub Check: Test Python (1, 3.9)
  • GitHub Check: Test Python (4, 3.9)
  • GitHub Check: Build C++ (rocm, rocm)
  • GitHub Check: Build C++ (cuda120, cuda)
  • GitHub Check: Build C++ (cuda, cuda)
  • GitHub Check: Build C++ (clang, clang)
  • GitHub Check: Build C++ (cpu, cpu)
  • GitHub Check: Test C++ (false)
  • GitHub Check: Build C library (2.18, libdeepmd_c.tar.gz)
  • GitHub Check: Build C library (2.14, >=2.5.0rc0,<2.15, libdeepmd_c_cu11.tar.gz)
✨ 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
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

🧹 Nitpick comments (2)
deepmd/pt/modifier/base_modifier.py (2)

41-44: Consider simplifying the box assignment.
A ternary operator can reduce verbosity here:

- if data["box"] is None:
-     box = None
- else:
-     box = data["box"][:get_nframes, :]
+ box = None if data["box"] is None else data["box"][:get_nframes, :]
🧰 Tools
🪛 Ruff (0.8.2)

41-44: Use ternary operator box = None if data["box"] is None else data["box"][:get_nframes, :] instead of if-else-block

Replace if-else-block with box = None if data["box"] is None else data["box"][:get_nframes, :]

(SIM108)


47-47: Remove or use the nframes variable.
Currently, nframes = coord.shape[0] is not used, which may confuse future maintainers.

🧰 Tools
🪛 Ruff (0.8.2)

47-47: Local variable nframes is assigned to but never used

Remove assignment to unused variable nframes

(F841)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between baaaa17 and e6bca31.

📒 Files selected for processing (4)
  • deepmd/pt/modifier/__init__.py (1 hunks)
  • deepmd/pt/modifier/base_modifier.py (1 hunks)
  • deepmd/pt/train/training.py (7 hunks)
  • deepmd/pt/utils/stat.py (1 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
deepmd/pt/modifier/__init__.py (1)
deepmd/pt/modifier/base_modifier.py (1) (1)
  • BaseModifier (9-56)
deepmd/pt/train/training.py (3)
deepmd/pt/modifier/base_modifier.py (2) (2)
  • BaseModifier (9-56)
  • modify_data (14-56)
deepmd/pd/train/training.py (1) (1)
  • get_additional_data_requirement (1163-1187)
deepmd/pd/utils/stat.py (1) (1)
  • make_stat_input (40-85)
🪛 Ruff (0.8.2)
deepmd/pt/modifier/base_modifier.py

41-44: Use ternary operator box = None if data["box"] is None else data["box"][:get_nframes, :] instead of if-else-block

Replace if-else-block with box = None if data["box"] is None else data["box"][:get_nframes, :]

(SIM108)


47-47: Local variable nframes is assigned to but never used

Remove assignment to unused variable nframes

(F841)

⏰ Context from checks skipped due to timeout of 90000ms (29)
  • GitHub Check: Test Python (6, 3.12)
  • GitHub Check: Test Python (6, 3.9)
  • GitHub Check: Test Python (5, 3.12)
  • GitHub Check: Test Python (5, 3.9)
  • GitHub Check: Build wheels for cp310-manylinux_aarch64
  • GitHub Check: Test Python (4, 3.12)
  • GitHub Check: Build wheels for cp311-win_amd64
  • GitHub Check: Test Python (4, 3.9)
  • GitHub Check: Build wheels for cp311-macosx_arm64
  • GitHub Check: Test Python (3, 3.12)
  • GitHub Check: Build C++ (clang, clang)
  • GitHub Check: Build wheels for cp311-macosx_x86_64
  • GitHub Check: Test Python (3, 3.9)
  • GitHub Check: Build C library (2.14, >=2.5.0rc0,<2.15, libdeepmd_c_cu11.tar.gz)
  • GitHub Check: Test C++ (false)
  • GitHub Check: Test Python (2, 3.12)
  • GitHub Check: Analyze (python)
  • GitHub Check: Build wheels for cp311-manylinux_x86_64
  • GitHub Check: Build C++ (rocm, rocm)
  • GitHub Check: Build C library (2.18, libdeepmd_c.tar.gz)
  • GitHub Check: Test C++ (true)
  • GitHub Check: Build C++ (cuda120, cuda)
  • GitHub Check: Build wheels for cp311-manylinux_x86_64
  • GitHub Check: Test Python (2, 3.9)
  • GitHub Check: Analyze (c-cpp)
  • GitHub Check: Build C++ (cuda, cuda)
  • GitHub Check: Test Python (1, 3.12)
  • GitHub Check: Build C++ (cpu, cpu)
  • GitHub Check: Test Python (1, 3.9)
🔇 Additional comments (11)
deepmd/pt/modifier/__init__.py (1)

1-8: Good job exposing the BaseModifier API.
This new __init__.py cleanly re-exports the BaseModifier class and ensures users can import it directly from deepmd.pt.modifier.

deepmd/pt/utils/stat.py (2)

50-51: Conditional logging is well-handled.
Only logging when nbatches > 0 helps keep logs cleaner in scenarios where no batches are processed.


56-59: Logic for handling nbatches == -1 is clear and correct.
This new condition ensures the entire dataset is used when nbatches is -1. No issues found.

deepmd/pt/train/training.py (8)

39-41: Import of BaseModifier is appropriate.
This import makes the newly introduced functionality available where needed.


140-149: Modifier parameter handling is well-structured.
The assertion preventing usage in multi-task scenarios is clear and avoids incompatible configurations.


231-231: Defaulting modifier to None is appropriate.
Makes the modifier usage optional without complicating the training interface.


239-250: Verify data modification logic.
Applying modifier.modify_data to every system might lead to repeated transformations if single_model_stat is called multiple times. Confirm this matches your intended workflow.


345-345: Single-model signature usage is consistent.
Passing modifier=self.modifier ensures the same modifier instance is applied throughout the training flow.


384-384: Multi-task signature usage is consistent.
Again, passing modifier=self.modifier allows uniform data processing across tasks if needed.


1075-1081: Storing the data_modifier state is a good idea.
Consider providing a loading mechanism in the future so that data_modifier can be restored automatically.


1389-1400: Factory function for data modifiers looks good.
Encapsulates logic for dynamically obtaining modifier classes, making the code more extensible.

Copy link

codecov bot commented Mar 20, 2025

Codecov Report

Attention: Patch coverage is 37.03704% with 34 lines in your changes missing coverage. Please review.

Project coverage is 84.76%. Comparing base (ab6e300) to head (5369e80).
Report is 1 commits behind head on devel.

Files with missing lines Patch % Lines
deepmd/pt/modifier/base_modifier.py 21.73% 18 Missing ⚠️
deepmd/pt/train/training.py 37.50% 15 Missing ⚠️
deepmd/pt/utils/stat.py 80.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4661      +/-   ##
==========================================
- Coverage   84.80%   84.76%   -0.05%     
==========================================
  Files         698      700       +2     
  Lines       67798    67849      +51     
  Branches     3542     3542              
==========================================
+ Hits        57494    57509      +15     
- Misses       9171     9205      +34     
- Partials     1133     1135       +2     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Collaborator

@wanghan-iapcm wanghan-iapcm left a comment

Choose a reason for hiding this comment

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

please add UT for the implementation.

@wanghan-iapcm wanghan-iapcm requested review from njzjz and iProzd March 21, 2025 03:53
@njzjz njzjz linked an issue Mar 21, 2025 that may be closed by this pull request
@njzjz njzjz requested a review from Copilot March 21, 2025 17:19
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR introduces a new plugin for modifying data in the PyTorch backend and integrates it into the training workflow. Key changes include:

  • Creation of a new BaseModifier class and registration in the modifier package.
  • Integration of the data modifier into the training process, including saving its state.
  • Minor adjustments to the statistics data preparation in the utils module.

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
deepmd/pt/modifier/init.py Exposes BaseModifier for external use.
deepmd/pt/modifier/base_modifier.py Adds a new BaseModifier class for data modification.
deepmd/pt/train/training.py Integrates the data modifier into training data preparation and model saving.
deepmd/pt/utils/stat.py Tweaks logging and batch calculation in the statistics utility.
Comments suppressed due to low confidence (2)

deepmd/pt/modifier/base_modifier.py:9

  • Ensure that make_base_modifier() returns a valid class to use for multiple inheritance with torch.nn.Module. If it does not, consider revising the inheritance structure or renaming for clarity.
class BaseModifier(torch.nn.Module, make_base_modifier()):

deepmd/pt/modifier/base_modifier.py:40

  • The variable get_nframes is explicitly set to None, which will slice the full array; if a limit on the number of frames was intended, assign get_nframes an appropriate value.
coord = data["coord"][:get_nframes, :]

# modifier for the training data
modifier_params = model_params.get("modifier", None)
if modifier_params is not None:
assert self.multi_task is False, (
Copy link
Member

Choose a reason for hiding this comment

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

NotImplementedError is preferred to assert.

Comment on lines +1079 to +1080
if self.modifier is not None:
save_dict["data_modifier"] = self.modifier.state_dict()
Copy link
Member

Choose a reason for hiding this comment

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

I see this is saved, but how is it recovered?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I plan to restore it by adapting wrapper. Do you have any other idea for this?

Comment on lines +238 to +249
# modify data
if modifier is not None:
log.info(f"Using {modifier.modifier_type} as data modifier")
for _data in [_training_data, _validation_data]:
if _data is not None:
all_sampled = make_stat_input(
_data.systems,
_data.dataloaders,
-1,
)
for sampled in all_sampled:
modifier.modify_data(sampled)
Copy link
Collaborator

Choose a reason for hiding this comment

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

I noticed that this modification only affects the data statistics. It still uses the original data in get_data for actual training.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't think so. modifier.modify_data(sampled) in line 267 has directly modify the training data sampled.

Copy link
Collaborator

Choose a reason for hiding this comment

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

The sampled data is only used for data statistics, while it uses the original data from get_data function in Line 1092.

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.

[Feature Request] Data modifier in pytorch
4 participants