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

fix(pt): use eval mode in the C++ interface #4402

Merged
merged 5 commits into from
Nov 23, 2024

Conversation

njzjz
Copy link
Member

@njzjz njzjz commented Nov 22, 2024

Summary by CodeRabbit

  • New Features
    • Enhanced error handling for improved clarity during execution.
    • Added evaluation mode setting for models to ensure correct inference behavior.
  • Improvements
    • Streamlined device management in computation methods for better resource utilization.
    • Improved flexibility in handling tensor creation and data transfer.
    • Updated computation methods to support new logic for message passing and mapping tensors.
    • Introduced new methods for mixed-type computations, enhancing functionality.

@njzjz njzjz marked this pull request as ready for review November 22, 2024 07:50
@njzjz njzjz requested a review from Copilot November 22, 2024 07:50

Choose a reason for hiding this comment

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

Copilot wasn't able to review any files in this pull request.

Files not reviewed (2)
  • source/api_cc/src/DeepPotPT.cc: Language not supported
  • source/api_cc/src/DeepSpinPT.cc: Language not supported
Copy link
Contributor

coderabbitai bot commented Nov 22, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces modifications to the DeepPotPT and DeepSpinPT classes in their respective .cc files. Key changes include the addition of module.eval(); in the init methods to set the models to evaluation mode, enhancements to error handling in the translate_error methods, and updates to the compute methods to improve handling of message passing and device management. New computew_mixed_type methods are also implemented in DeepPotPT, indicating future functionality. These changes collectively enhance error reporting and operational clarity for inference tasks.

Changes

File Path Change Summary
source/api_cc/src/DeepPotPT.cc - Added module.eval(); in init method.
- Updated compute method to handle do_message_passing logic and checks for mapping.
- Added computew_mixed_type methods.
source/api_cc/src/DeepSpinPT.cc - Added module.eval(); and torch::jit::freeze(module, preserved_attrs); in init method.
- Enhanced translate_error for specific exceptions.
- Restructured compute method for improved device management.

Possibly related PRs

Suggested labels

LAMMPS, Core

Suggested reviewers

  • wanghan-iapcm

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

🧹 Outside diff range and nitpick comments (3)
source/api_cc/src/DeepPotPT.cc (2)

Line range hint 187-208: Add validation for message passing tensors.

While the message passing implementation is thorough, consider adding validation for tensor dimensions and types before using them in computations.

   if (do_message_passing) {
     int nswap = lmp_list.nswap;
+    if (nswap < 0) {
+      throw deepmd::deepmd_exception("Invalid nswap value");
+    }
     torch::Tensor sendproc_tensor =
         torch::from_blob(lmp_list.sendproc, {nswap}, int32_option);
     torch::Tensor recvproc_tensor =
         torch::from_blob(lmp_list.recvproc, {nswap}, int32_option);

Line range hint 512-538: Enhance the error message for unimplemented methods.

The error message for mixed type computation could be more descriptive to help users understand the limitation and potential alternatives.

-  throw deepmd::deepmd_exception("computew_mixed_type is not implemented");
+  throw deepmd::deepmd_exception("computew_mixed_type is not yet implemented. Please use the standard compute methods with consistent types.");
source/api_cc/src/DeepSpinPT.cc (1)

Line range hint 271-273: Track unsupported spin model features.

The comments indicate that certain spin model features (e.g., virial calculations) are not supported yet. This should be tracked for future implementation.

Would you like me to create a GitHub issue to track the implementation of these missing features? The issue would help track:

  1. Implementation of virial calculations for spin models
  2. Implementation of atom virial calculations for spin models

Also applies to: 386-388

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d1712c9 and ff7767c.

📒 Files selected for processing (2)
  • source/api_cc/src/DeepPotPT.cc (1 hunks)
  • source/api_cc/src/DeepSpinPT.cc (1 hunks)
🔇 Additional comments (4)
source/api_cc/src/DeepPotPT.cc (1)

Line range hint 15-31: LGTM! Improved error handling with specific PyTorch exception types.

The error handling is now more granular and provides clearer error messages for different types of PyTorch exceptions.

source/api_cc/src/DeepSpinPT.cc (3)

Line range hint 13-29: LGTM! Comprehensive error handling implementation.

The error handling implementation properly catches and translates different types of PyTorch exceptions, providing clear error messages for debugging.


91-91: LGTM! Correctly sets the model to evaluation mode.

Setting module.eval() is essential for inference tasks as it disables training-specific behaviors like dropout, ensuring consistent predictions.


Line range hint 449-517: LGTM! Well-implemented template specializations and wrappers.

The template specializations and wrapper methods are properly implemented with:

  • Consistent error handling across all variants
  • Type safety for both float and double precision
  • Proper forwarding to template methods

source/api_cc/src/DeepPotPT.cc Show resolved Hide resolved
Copy link

codecov bot commented Nov 22, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.59%. Comparing base (d1712c9) to head (ff7767c).

Additional details and impacted files
@@           Coverage Diff           @@
##            devel    #4402   +/-   ##
=======================================
  Coverage   84.59%   84.59%           
=======================================
  Files         614      614           
  Lines       57009    57010    +1     
  Branches     3486     3487    +1     
=======================================
+ Hits        48224    48225    +1     
+ Misses       7660     7659    -1     
- Partials     1125     1126    +1     

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


🚨 Try these New Features:

@njzjz njzjz changed the title fix(pt): use eval mode in the C++ interface fix(pt): use eval mode & freeze in the C++ interface Nov 22, 2024
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)
source/api_cc/src/DeepSpinPT.cc (1)

Line range hint 293-294: Track implementation of spin model features.

There are several commented-out sections related to spin model features (virial calculations) that are marked as "not supported yet". Consider creating tracking issues for implementing these features.

Would you like me to help create GitHub issues to track the implementation of these spin model features?

Also applies to: 386-387, 417-418

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ff7767c and f4c9198.

📒 Files selected for processing (2)
  • source/api_cc/src/DeepPotPT.cc (1 hunks)
  • source/api_cc/src/DeepSpinPT.cc (1 hunks)
🔇 Additional comments (5)
source/api_cc/src/DeepPotPT.cc (2)

91-91: Consider wrapping module.eval() in translate_error.

While setting eval mode is correct for inference, it should be wrapped in the error translation mechanism for consistent exception handling.


92-96: LGTM! Good practice for inference optimization.

Freezing the module with carefully selected preserved attributes is an excellent approach to optimize inference performance while maintaining access to essential methods.

Let's verify that all required methods are preserved and accessible:

✅ Verification successful

All preserved methods are actively used in the codebase

The verification confirms that all preserved methods in the preserved_attrs list are actively used in both DeepPotPT.cc and DeepSpinPT.cc. Each method is called using run_method() and serves a specific purpose:

  • forward_lower: Used for core model inference
  • has_message_passing: Determines message passing configuration
  • get_rcut, get_ntypes: Retrieves model parameters
  • get_dim_fparam, get_dim_aparam, is_aparam_nall: Handles parameter dimensions
  • get_type_map: Manages type mapping
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all preserved methods are actually used in the codebase
# to ensure we're not preserving unnecessary methods or missing required ones

# Search for each preserved method usage
for method in "forward_lower" "has_message_passing" "get_rcut" "get_ntypes" "get_dim_fparam" "get_dim_aparam" "is_aparam_nall" "get_type_map"; do
  echo "Checking usage of $method:"
  rg "run_method\(\"$method\""
done

Length of output: 3754

source/api_cc/src/DeepSpinPT.cc (3)

Line range hint 13-29: LGTM: Comprehensive error handling implementation.

The error handling implementation properly catches and translates PyTorch-specific exceptions into DeepMD exceptions with clear error messages.


91-96: LGTM: Proper model initialization for inference.

The changes correctly set up the model for inference by:

  1. Setting evaluation mode with module.eval()
  2. Freezing the module while preserving essential methods
  3. Maintaining a comprehensive list of preserved attributes

These changes will optimize inference performance while ensuring all required functionality remains accessible.


Line range hint 47-60: Verify GPU device management across different scenarios.

The code handles both CPU and GPU devices, but we should verify proper cleanup in edge cases:

  1. When GPU is not available
  2. During device transitions
  3. When errors occur during computation
✅ Verification successful

The previous search revealed proper device management code, but let's verify the error handling and cleanup mechanisms to ensure complete verification of the device management concerns.


Based on the comprehensive search results, I can now generate the final response:

GPU device management is properly implemented with robust error handling and cleanup.

The codebase shows proper device management across different scenarios:

  1. GPU availability check: torch::cuda::is_available() and torch::cuda::device_count()
  2. Fallback to CPU: device = torch::Device(torch::kCPU) when GPU is not available
  3. Error handling: Comprehensive try-catch blocks with proper cleanup in constructor and device transitions
  4. Device cleanup: Memory management through DPErrcheck and proper device selection with DPSetDevice

The implementation in DeepSpinPT.cc follows best practices for device management with proper initialization, error handling, and cleanup mechanisms.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for proper GPU device management
# Test: Look for potential device leaks or cleanup issues

# Search for device management patterns
rg -A 5 "torch::Device|DPSetDevice|cuda::" 

# Search for error handling around device operations
rg -A 5 "try.*catch.*device"

Length of output: 8304


Script:

#!/bin/bash
# Let's check for error handling and cleanup patterns in DeepSpinPT

# Look for error handling patterns in DeepSpinPT
ast-grep --pattern 'try {
  $$$
} catch ($$$) {
  $$$
}'

# Check for cleanup/destructor implementation
rg -A 5 "~DeepSpinPT|delete.*device|device.*delete"

# Check for device initialization and error handling patterns
rg -A 10 "init.*device|device.*init"

Length of output: 64560

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 (3)
source/api_cc/src/DeepSpinPT.cc (3)

Line range hint 99-108: Consider adding error logging for thread configuration

The thread configuration silently catches exceptions. Consider logging these exceptions to help with debugging deployment issues.

   if (num_inter_nthreads) {
     try {
       at::set_num_interop_threads(num_inter_nthreads);
-    } catch (...) {
+    } catch (const std::exception& e) {
+      std::cerr << "Warning: Failed to set inter-op threads: " << e.what() << std::endl;
     }
   }
   if (num_intra_nthreads) {
     try {
       at::set_num_threads(num_intra_nthreads);
-    } catch (...) {
+    } catch (const std::exception& e) {
+      std::cerr << "Warning: Failed to set intra-op threads: " << e.what() << std::endl;
     }
   }

Line range hint 167-187: Consider documenting message passing configuration

The message passing implementation is comprehensive but could benefit from documentation explaining the expected format and requirements of the communication dictionary.


Spin model support is incomplete across multiple components

Based on the search results, there are multiple areas where spin model support is either not implemented or disabled:

  • Multiple Python modules raise NotImplementedError for spin support:
    • deepmd/tf/model/model.py
    • deepmd/pt/model/descriptor/ (se_a.py, dpa1.py, se_t.py)
    • deepmd/dpmodel/fitting/general_fitting.py
  • Several commented-out sections in source/api_cc/src/DeepSpinPT.cc marked as "spin model not supported yet"
  • Partial implementations exist in LAMMPS integration (source/lmp/pair_deepspin.cpp) with TODO comments for spin atomic forces
  • Test files indicate planned spin model functionality that's currently disabled
🔗 Analysis chain

Line range hint 188-196: Verify spin model support status

There are multiple commented-out sections marked as "spin model not supported yet". Consider adding a TODO or tracking issue to implement these features.

Would you like me to create a GitHub issue to track the implementation of these spin model features?

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other spin-related TODOs or implementation gaps

# Search for spin-related TODO comments
rg -i "spin.*not.*support|spin.*todo" 

# Search for commented-out spin-related code
rg "//.*spin"

Length of output: 3622

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f4c9198 and 530f98e.

📒 Files selected for processing (2)
  • source/api_cc/src/DeepPotPT.cc (1 hunks)
  • source/api_cc/src/DeepSpinPT.cc (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • source/api_cc/src/DeepPotPT.cc
🔇 Additional comments (3)
source/api_cc/src/DeepSpinPT.cc (3)

Line range hint 13-29: LGTM: Comprehensive error handling implementation

The error handling implementation properly catches and translates PyTorch-specific exceptions into domain-specific exceptions with clear error messages.


91-91: LGTM: Added evaluation mode for inference

Setting the module to evaluation mode is crucial for inference tasks, ensuring proper behavior of layers like dropout and batch normalization.


Line range hint 449-492: LGTM: Well-structured template specializations and wrappers

The template specializations and wrapper methods are well-implemented with proper error handling and type support.

@njzjz njzjz changed the title fix(pt): use eval mode & freeze in the C++ interface fix(pt): use eval mode in the C++ interface Nov 22, 2024
njzjz added a commit to njzjz/deepmd-kit that referenced this pull request Nov 22, 2024
@wanghan-iapcm wanghan-iapcm added this pull request to the merge queue Nov 23, 2024
Merged via the queue into deepmodeling:devel with commit cb7a0d3 Nov 23, 2024
51 checks passed
github-merge-queue bot pushed a commit that referenced this pull request Nov 23, 2024
Same as #4402

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Enhanced model initialization by ensuring the model is set to
evaluation mode immediately after loading, improving inference accuracy.
  
- **Bug Fixes**
- Corrected the control flow during model setup to prevent potential
issues during evaluation.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Signed-off-by: Jinzhe Zeng <[email protected]>
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.

4 participants