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: fix for __array__ removal from array-api-strict #4325

Merged
merged 11 commits into from
Nov 9, 2024

Conversation

njzjz
Copy link
Member

@njzjz njzjz commented Nov 7, 2024

See: https://github.com/data-apis/array-api-strict/blob/main/docs/changelog.md#major-changes

Summary by CodeRabbit

  • New Features
    • Enhanced array conversion capability to handle device-specific data for improved performance.
    • Introduced a robust error handling mechanism for array conversions.
    • Updated serialization methods to consistently format data as NumPy arrays.
    • Standardized the conversion process across various evaluation methods in tests.
  • Bug Fixes
    • Improved handling of input arrays from the CPU to ensure seamless conversion to NumPy arrays.
  • Chores
    • Refined dependency specifications in pyproject.toml for better compatibility.

@njzjz njzjz requested a review from wanghan-iapcm November 7, 2024 21:34
@github-actions github-actions bot added the Python label Nov 7, 2024
Copy link
Contributor

coderabbitai bot commented Nov 7, 2024

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes involve modifications to the to_numpy_array function in the deepmd/dpmodel/common.py file, which now includes a try-except block to handle exceptions when calling np.asarray(x). If a ValueError or AttributeError occurs, the function attempts to convert the input using array_api_compat.array_namespace(x) followed by xp.asarray(x, copy=True) and returns the result of np.from_dlpack(x). Additionally, the function is imported and utilized in various test methods, replacing previous uses of np.asarray. The overall logic of returning None for a None input remains unchanged.

Changes

File Change Summary
deepmd/dpmodel/common.py Modified to_numpy_array to include a try-except block for handling exceptions from np.asarray; if an exception occurs, it attempts conversion using array_api_compat.array_namespace(x) and xp.asarray(x, copy=True), returning np.from_dlpack(x).
source/tests/consistent/descriptor/common.py Imported to_numpy_array and replaced np.asarray in eval_array_api_strict_descriptor; updated internal logic without changing method signature.
source/tests/consistent/test_type_embedding.py Imported to_numpy_array and replaced np.asarray in eval_array_api_strict; updated internal logic without changing method signature.
deepmd/dpmodel/descriptor/dpa1.py Imported to_numpy_array and used it in serialize methods of DescrptDPA1 and DescrptBlockSeAtten to convert davg and dstd attributes.
source/tests/consistent/fitting/test_dipole.py Imported to_numpy_array and replaced np.asarray in eval_array_api_strict; updated internal logic without changing method signature.
source/tests/consistent/fitting/test_dos.py Imported to_numpy_array and replaced np.asarray in eval_array_api_strict; updated internal logic without changing method signature.
source/tests/consistent/fitting/test_ener.py Imported to_numpy_array and replaced np.asarray in eval_array_api_strict; updated internal logic without changing method signature.
source/tests/consistent/fitting/test_polar.py Imported to_numpy_array and replaced np.asarray in eval_array_api_strict; updated internal logic without changing method signature.
source/tests/consistent/fitting/test_property.py Imported to_numpy_array and replaced np.asarray in eval_array_api_strict; updated internal logic without changing method signature.
pyproject.toml Updated dependency specification for array-api-strict to exclude version 2.1.1 while maintaining the minimum version requirement.
source/tests/common/dpmodel/array_api/test_env_mat.py Removed line setting array API version in test_compute_smooth_weight, simplifying the test method.
source/tests/consistent/test_activation.py Removed line setting array API strict flags and updated assertion to use to_numpy_array(test) instead of np.array(test).

Possibly related PRs

  • feat(jax/array-api): dpa1 #4160: The changes in this PR modify the to_numpy_array function in deepmd/dpmodel/common.py, which is directly related to the main PR's modifications to the same function, enhancing its error handling and array conversion logic.
  • feat(jax/array-api): DOS fitting #4218: This PR also involves the to_numpy_array function in the context of the DOSFittingNet class, which uses it for serialization, linking it to the main PR's focus on the same function.
  • feat(jax/array-api): hybrid descriptor #4275: The changes in this PR include modifications to the DescrptHybrid class that utilize the to_numpy_array function, establishing a connection to the main PR's updates to that function.
  • feat(jax/array-api): dipole/polarizability fitting #4278: This PR introduces changes to the DipoleFitting and PolarFitting classes that involve the to_numpy_array function for serialization, which relates to the main PR's enhancements to the same function.
  • feat(jax/array-api): se_e3 #4286: The modifications in this PR to the DescrptSeT class to utilize to_numpy_array for serialization are directly related to the changes made in the main PR.
  • feat(jax/array-api): se_atten_v2 #4289: The DescrptSeAttenV2 class's serialize method now processes variables through to_numpy_array, which is a direct application of the changes made in the main PR.
  • feat(jax/array-api): DPA-2 #4294: The changes in this PR to the DescrptDPA2 class include the use of the to_numpy_array function, which relates to the main PR's modifications to that function.

Suggested reviewers

  • wanghan-iapcm
  • iProzd

Suggested labels

Docs


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

🧹 Outside diff range and nitpick comments (1)
deepmd/dpmodel/common.py (1)

111-111: Consider adding error handling for the fallback path.

The comment indicates that np.asarray may fail as it's not within Array API standard. Consider adding try-catch error handling with a more informative error message to help users understand why the conversion failed.

-    # asarray is not within Array API standard, so may fail
-    return np.asarray(x)
+    # asarray is not within Array API standard, so may fail
+    try:
+        return np.asarray(x)
+    except Exception as e:
+        raise ValueError(
+            f"Failed to convert array to numpy array. For non-CPU devices, "
+            f"the array implementation must support __array__ protocol: {str(e)}"
+        ) from e
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3236db5 and cde3039.

📒 Files selected for processing (1)
  • deepmd/dpmodel/common.py (1 hunks)
🔇 Additional comments (2)
deepmd/dpmodel/common.py (2)

108-111: Good solution using DLPack for array conversion.

The addition of device-specific handling using np.from_dlpack(x) is a good solution to address the removal of __array__ from array-api-strict. DLPack is a stable and standardized protocol for array interchange between different array libraries.


108-111: Verify the array-api-strict compatibility.

Let's verify that this change aligns with array-api-strict requirements and that we're handling all necessary device cases.

✅ Verification successful

Based on the code inspection and search results, I can now provide a definitive response about the array-api-strict compatibility:

The code is already array-api-strict compatible and the change is correct.

The key findings that support this:

  1. The code uses x.device check which is part of the array API standard
  2. The comment "asarray is not within Array API standard" is accurate - the code correctly handles this by using dlpack for CPU arrays
  3. The project has array-api-strict as a dependency and extensive test coverage for array-api-strict compatibility
  4. The code follows array API practices by using array namespace checks and array API compatible operations

The change in question:

if x.device == "cpu":
    # dlpack needs the device to be the same  
    return np.from_dlpack(x)
# asarray is not within Array API standard, so may fail

This is the correct approach because:

  • It uses the standard array API device attribute
  • It handles CPU arrays via dlpack which is the array API recommended way
  • The comment accurately notes that asarray is not part of the standard
  • The fallback is properly documented
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any other array conversion patterns that might need updating
# and verify array-api-strict compatibility requirements

# Look for other array conversion patterns
echo "Checking for other array conversion patterns..."
rg -l "asarray|array|__array__" --type python

# Look for device-specific handling
echo "Checking for other device-specific array handling..."
rg -l "\.device\s*==" --type python

# Look for array-api-strict imports or references
echo "Checking for array-api-strict usage..."
rg -l "array-api|array_api" --type python

Length of output: 529


Script:

#!/bin/bash
# Let's try without specifying the file type since the previous attempt failed
# Look for array conversion patterns
echo "Checking for array conversion patterns..."
rg "asarray|array|__array__"

# Look for device-specific handling
echo "Checking for device-specific array handling..."
rg "\.device\s*=="

# Look for array-api imports or references
echo "Checking for array-api usage..."
rg "array_api|array-api"

# Also check imports specifically in the file under review
echo "Checking imports in the specific file..."
cat deepmd/dpmodel/common.py | grep -E "^import|^from.*import"

Length of output: 411604

Signed-off-by: Jinzhe Zeng <[email protected]>
@njzjz njzjz marked this pull request as draft November 7, 2024 22:53
njzjz added 4 commits November 7, 2024 17:54
Signed-off-by: Jinzhe Zeng <[email protected]>
Signed-off-by: Jinzhe Zeng <[email protected]>
Signed-off-by: Jinzhe Zeng <[email protected]>
Signed-off-by: Jinzhe Zeng <[email protected]>
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)
pyproject.toml (1)

88-88: LGTM! Consider adding a comment about version exclusion.

The dependency update correctly excludes array-api-strict version 2.1.1 while maintaining the minimum version requirement. This aligns with the PR objective to handle the removal of the __array__ method.

Consider adding an inline comment explaining why version 2.1.1 is excluded, to help future maintainers understand the rationale:

-    'array-api-strict>=2,!=2.1.1;python_version>="3.9"',
+    # Exclude version 2.1.1 due to __array__ method removal
+    'array-api-strict>=2,!=2.1.1;python_version>="3.9"',
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c80942f and 7a65567.

📒 Files selected for processing (7)
  • pyproject.toml (1 hunks)
  • source/tests/common/dpmodel/array_api/test_env_mat.py (0 hunks)
  • source/tests/consistent/descriptor/common.py (2 hunks)
  • source/tests/consistent/fitting/test_dos.py (2 hunks)
  • source/tests/consistent/fitting/test_ener.py (2 hunks)
  • source/tests/consistent/fitting/test_property.py (2 hunks)
  • source/tests/consistent/test_activation.py (0 hunks)
💤 Files with no reviewable changes (2)
  • source/tests/common/dpmodel/array_api/test_env_mat.py
  • source/tests/consistent/test_activation.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • source/tests/consistent/descriptor/common.py
  • source/tests/consistent/fitting/test_dos.py
  • source/tests/consistent/fitting/test_ener.py
  • source/tests/consistent/fitting/test_property.py

Copy link

codecov bot commented Nov 8, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.50%. Comparing base (6c66be9) to head (9794c86).
Report is 4 commits behind head on devel.

Additional details and impacted files
@@           Coverage Diff           @@
##            devel    #4325   +/-   ##
=======================================
  Coverage   84.50%   84.50%           
=======================================
  Files         570      570           
  Lines       53162    53169    +7     
  Branches     3059     3061    +2     
=======================================
+ Hits        44927    44933    +6     
  Misses       7272     7272           
- Partials      963      964    +1     

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

@njzjz njzjz marked this pull request as ready for review November 8, 2024 06:54
github-merge-queue bot pushed a commit that referenced this pull request Nov 8, 2024
See #4325.

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

## Summary by CodeRabbit

- **Chores**
	- Updated dependency constraints for improved reliability.
	- Expanded testing commands to enhance the testing suite.
- Improved setup process with additional installation commands for
specific environments.

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

Signed-off-by: Jinzhe Zeng <[email protected]>
@wanghan-iapcm wanghan-iapcm added this pull request to the merge queue Nov 9, 2024
Merged via the queue into deepmodeling:devel with commit 8f11bc7 Nov 9, 2024
60 checks passed
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