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

Feat(pt): Support fitting_net statistics. #4504

Draft
wants to merge 4 commits into
base: devel
Choose a base branch
from

Conversation

Chengqian-Zhang
Copy link
Collaborator

@Chengqian-Zhang Chengqian-Zhang commented Dec 25, 2024

Support fitting_net statistics to calculate the mean value and standard deviation of fparam/aparam. So that fparam/aparam can be normalized automatically before concatenating to descriptor.

Summary by CodeRabbit

  • New Features

    • Introduced a method to compute input statistics, including mean and standard deviation for fitting parameters.
    • Enhanced functionality to compute additional statistics alongside existing ones.
  • Bug Fixes

    • Improved error handling for input data dimensions to ensure consistency.

@Chengqian-Zhang Chengqian-Zhang marked this pull request as draft December 25, 2024 10:44
Copy link
Contributor

coderabbitai bot commented Dec 25, 2024

📝 Walkthrough

Walkthrough

The pull request introduces a new method compute_input_stats in the GeneralFitting class within the fitting module, and modifies the compute_or_load_stat method in the DPAtomicModel class. The changes enhance the statistical computation capabilities for input data in the deep potential model, specifically adding the ability to compute input statistics for the fitting network alongside existing descriptor statistics.

Changes

File Change Summary
deepmd/pt/model/task/fitting.py Added compute_input_stats method to GeneralFitting class for computing input statistics from frame parameters
deepmd/pt/model/atomic_model/dp_atomic_model.py Updated compute_or_load_stat method to call compute_input_stats on the fitting network

Sequence Diagram

sequenceDiagram
    participant AM as Atomic Model
    participant FN as Fitting Network
    participant Sampler as Data Sampler

    AM->>Sampler: Prepare sampled data
    AM->>FN: compute_input_stats(sampled_data)
    FN-->>FN: Calculate mean and std dev
    FN-->>AM: Statistics computed
Loading

Possibly related PRs

Suggested reviewers

  • njzjz
  • wanghan-iapcm
  • iProzd

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

🧹 Nitpick comments (2)
deepmd/pt/model/task/fitting.py (2)

437-440: Use a ternary operator for compactness.
Ruff suggests replacing the if callable(...) block with a ternary operator. This is a minor readability enhancement.

- if callable(merged):
-     sampled = merged()
- else:
-     sampled = merged
+ sampled = merged() if callable(merged) else merged
🧰 Tools
🪛 Ruff (0.8.2)

437-440: Use ternary operator sampled = merged() if callable(merged) else merged instead of if-else-block

Replace if-else-block with sampled = merged() if callable(merged) else merged

(SIM108)


457-457: Implement aparam statistics.
The TODO suggests you plan to handle aparam similarly to fparam. Let me know if you’d like help implementing that.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between beeb3d9 and af5e589.

📒 Files selected for processing (2)
  • deepmd/pt/model/atomic_model/dp_atomic_model.py (1 hunks)
  • deepmd/pt/model/task/fitting.py (3 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
deepmd/pt/model/task/fitting.py

437-440: Use ternary operator sampled = merged() if callable(merged) else merged instead of if-else-block

Replace if-else-block with sampled = merged() if callable(merged) else merged

(SIM108)

🔇 Additional comments (3)
deepmd/pt/model/atomic_model/dp_atomic_model.py (1)

301-301: Consider verifying that fitting_net is defined before usage.
If fitting_net were ever None, invoking compute_input_stats would raise an exception. A quick check ensures safe execution.

deepmd/pt/model/task/fitting.py (2)

7-7: New import statements look good.
Thanks for adding Callable, Union, and DPPath; these additions enable clearer type hints and better modularity.

Also applies to: 43-45


416-436: Comprehensive documentation.
The docstring clearly explains the purpose and usage of compute_input_stats. This addition aligns with the PR objective to compute input statistics for fitting parameters.

Comment on lines +442 to +456
if self.numb_fparam > 0:
cat_data = torch.cat([frame["fparam"] for frame in sampled], dim=0)
cat_data = torch.reshape(cat_data, [-1, self.numb_fparam])
fparam_avg = torch.mean(cat_data, axis=0)
fparam_std = torch.std(cat_data, axis=0)
fparam_inv_std = 1.0 / fparam_std
self.fparam_avg.copy_(
torch.tensor(fparam_avg, device=env.DEVICE, dtype=self.fparam_avg.dtype)
)
self.fparam_inv_std.copy_(
torch.tensor(
fparam_inv_std, device=env.DEVICE, dtype=self.fparam_inv_std.dtype
)
)
# TODO: stat aparam
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Handle potential zero or near-zero standard deviation.
Currently, the code divides by fparam_std, potentially leading to inf or NaN values if std == 0. Consider adding a small epsilon or performing a check to avoid division by zero.

 fparam_std = torch.std(cat_data, axis=0)
+epsilon = 1e-12
+fparam_std = torch.where(fparam_std < epsilon, torch.tensor(epsilon, dtype=fparam_std.dtype, device=fparam_std.device), fparam_std)
 fparam_inv_std = 1.0 / fparam_std
📝 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
if self.numb_fparam > 0:
cat_data = torch.cat([frame["fparam"] for frame in sampled], dim=0)
cat_data = torch.reshape(cat_data, [-1, self.numb_fparam])
fparam_avg = torch.mean(cat_data, axis=0)
fparam_std = torch.std(cat_data, axis=0)
fparam_inv_std = 1.0 / fparam_std
self.fparam_avg.copy_(
torch.tensor(fparam_avg, device=env.DEVICE, dtype=self.fparam_avg.dtype)
)
self.fparam_inv_std.copy_(
torch.tensor(
fparam_inv_std, device=env.DEVICE, dtype=self.fparam_inv_std.dtype
)
)
# TODO: stat aparam
if self.numb_fparam > 0:
cat_data = torch.cat([frame["fparam"] for frame in sampled], dim=0)
cat_data = torch.reshape(cat_data, [-1, self.numb_fparam])
fparam_avg = torch.mean(cat_data, axis=0)
fparam_std = torch.std(cat_data, axis=0)
epsilon = 1e-12
fparam_std = torch.where(fparam_std < epsilon, torch.tensor(epsilon, dtype=fparam_std.dtype, device=fparam_std.device), fparam_std)
fparam_inv_std = 1.0 / fparam_std
self.fparam_avg.copy_(
torch.tensor(fparam_avg, device=env.DEVICE, dtype=self.fparam_avg.dtype)
)
self.fparam_inv_std.copy_(
torch.tensor(
fparam_inv_std, device=env.DEVICE, dtype=self.fparam_inv_std.dtype
)
)
# TODO: stat aparam

Copy link

codecov bot commented Dec 25, 2024

Codecov Report

Attention: Patch coverage is 92.85714% with 1 line in your changes missing coverage. Please review.

Project coverage is 84.59%. Comparing base (beeb3d9) to head (af5e589).

Files with missing lines Patch % Lines
deepmd/pt/model/task/fitting.py 92.30% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##            devel    #4504   +/-   ##
=======================================
  Coverage   84.59%   84.59%           
=======================================
  Files         675      675           
  Lines       63574    63589   +15     
  Branches     3490     3486    -4     
=======================================
+ Hits        53778    53791   +13     
- Misses       8670     8672    +2     
  Partials     1126     1126           

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

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.

1 participant