Skip to content

chore(array-api): implement scatter_sum #4654

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

Draft
wants to merge 1 commit into
base: devel
Choose a base branch
from

Conversation

njzjz
Copy link
Member

@njzjz njzjz commented Mar 13, 2025

Address #4649 (comment). This PR depends on array_api_extra.at.

Summary by CodeRabbit

  • New Features
    • Enhanced array processing to support a broader range of array types.
    • Introduced new operations for flattening arrays and aggregating values, streamlining data transformations.
  • Chores
    • Updated project dependencies to integrate an enhanced array API library.

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 implements a scatter_sum operation using the array-api-extra package to support generalized array APIs. Key changes include:

  • Adding the "array-api-extra>=0.5.0" dependency in pyproject.toml.
  • Introducing new utility functions xp_ravel and xp_scatter_sum in deepmd/dpmodel/array_api.py with revised handling for various array types.
  • Updating deepmd/dpmodel/model/transform_output.py to use xp_scatter_sum instead of a JAX-specific version.

Reviewed Changes

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

File Description
pyproject.toml Adds dependency on array-api-extra to support the new scatter_sum functionality.
deepmd/dpmodel/array_api.py Adds xp_ravel and xp_scatter_sum; refines xp_take_along_axis for broader support.
deepmd/dpmodel/model/transform_output.py Replaces JAX-specific scatter_sum with the new, generalized xp_scatter_sum.
deepmd/jax/common.py Removes the now redundant scatter_sum function.
Comments suppressed due to low confidence (2)

deepmd/dpmodel/array_api.py:90

  • [nitpick] Consider renaming the parameter 'input' to avoid shadowing the built-in function and improve clarity, e.g., use 'inp' or 'input_array'.
def xp_scatter_sum(input, dim, index: np.ndarray, src: np.ndarray) -> np.ndarray:

deepmd/dpmodel/array_api.py:90

  • Ensure that xp_scatter_sum is covered by unit tests for various array types (e.g., numpy, JAX) to verify its correct behavior across supported array APIs.
def xp_scatter_sum(input, dim, index: np.ndarray, src: np.ndarray) -> np.ndarray:

Copy link
Contributor

coderabbitai bot commented Mar 13, 2025

📝 Walkthrough

Walkthrough

This PR extends the array manipulation functionality by updating the xp_take_along_axis function to include checks for NumPy and JAX arrays. It adds two new functions, xp_ravel (for flattening tensors) and xp_scatter_sum (to perform scatter summation). The scatter sum logic in the output transformation is now refactored to use xp_scatter_sum, and the older JAX-specific scatter_sum has been removed. Additionally, a new dependency on array-api-extra>=0.5.0 has been introduced in the project configuration.

Changes

File(s) Change Summary
deepmd/dpmodel/array_api.py Expanded xp_take_along_axis to support NumPy and JAX arrays; added new functions xp_ravel (flatten tensor) and xp_scatter_sum (scatter summation operation).
deepmd/dpmodel/model/transform_output.py Replaced JAX-specific scatter sum logic with direct call to xp_scatter_sum, removing conditional imports.
deepmd/jax/common.py Removed the scatter_sum function, eliminating redundant JAX-specific reduction functionality.
pyproject.toml Added a new dependency: 'array-api-extra>=0.5.0'.

Sequence Diagram(s)

sequenceDiagram
    participant CO as communicate_extended_output
    participant XSS as xp_scatter_sum
    participant XR as xp_ravel
    participant XTA as xp_take_along_axis

    CO->>XSS: Invoke scatter sum for force/virial tensors
    XSS->>XR: Flatten input tensor via xp_ravel
    XSS->>XTA: Adjust values based on indices via xp_take_along_axis
    XSS-->>CO: Return computed tensor
Loading

Possibly related PRs

Suggested labels

Python, Docs

Suggested reviewers

  • iProzd
  • wanghan-iapcm

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 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 5831505 and ba5c265.

📒 Files selected for processing (4)
  • deepmd/dpmodel/array_api.py (3 hunks)
  • deepmd/dpmodel/model/transform_output.py (3 hunks)
  • deepmd/jax/common.py (0 hunks)
  • pyproject.toml (1 hunks)
💤 Files with no reviewable changes (1)
  • deepmd/jax/common.py
⏰ Context from checks skipped due to timeout of 90000ms (23)
  • GitHub Check: Test Python (6, 3.12)
  • GitHub Check: Test Python (5, 3.12)
  • 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 (3, 3.12)
  • GitHub Check: Build wheels for cp311-macosx_arm64
  • GitHub Check: Build C++ (clang, clang)
  • GitHub Check: Test Python (2, 3.12)
  • GitHub Check: Build C++ (rocm, rocm)
  • GitHub Check: Build wheels for cp311-macosx_x86_64
  • GitHub Check: Build wheels for cp311-manylinux_x86_64
  • GitHub Check: Build C++ (cuda120, cuda)
  • GitHub Check: Analyze (python)
  • GitHub Check: Build wheels for cp311-manylinux_x86_64
  • GitHub Check: Test Python (1, 3.12)
  • GitHub Check: Build C++ (cuda, cuda)
  • GitHub Check: Build C library (2.14, >=2.5.0rc0,<2.15, libdeepmd_c_cu11.tar.gz)
  • GitHub Check: Test C++ (false)
  • GitHub Check: Build C++ (cpu, cpu)
  • GitHub Check: Analyze (c-cpp)
  • GitHub Check: Build C library (2.18, libdeepmd_c.tar.gz)
  • GitHub Check: Test C++ (true)
🔇 Additional comments (8)
pyproject.toml (1)

56-56: LGTM: New dependency for array-api-extra is appropriately added

This change correctly adds the required dependency for array-api-extra>=0.5.0, which is needed for the implementation of the scatter_sum functionality as specified in the PR objectives. The minimum version requirement is properly set.

deepmd/dpmodel/model/transform_output.py (3)

6-8: LGTM: Appropriate import added for the new xp_scatter_sum function

The import of xp_scatter_sum from deepmd.dpmodel.array_api is correctly added. This is needed for the refactored implementation below.


104-109: LGTM: Improved force calculation with xp_scatter_sum

The implementation now uses the more generic xp_scatter_sum function, replacing what was likely JAX-specific code. This enhances compatibility across different array library backends.


125-130: LGTM: Improved virial calculation with xp_scatter_sum

Similar to the force calculation, the virial calculation now uses the generic xp_scatter_sum function. This creates a more consistent implementation that works across different array libraries.

deepmd/dpmodel/array_api.py (4)

5-6: LGTM: Required imports added for new functionality

The imports for array_api_extra and numpy are correctly added to support the new functionality. The array_api_extra is specifically needed for the at method used in the scatter sum implementation.


53-57: LGTM: Enhanced compatibility in xp_take_along_axis

The condition has been extended to also check for NumPy and JAX arrays, broadening the applicability of the xp_take_along_axis function to more array types. This is a good enhancement that makes the function more versatile.


84-88: LGTM: Well-implemented xp_ravel utility function

The new xp_ravel function provides a clean abstraction for flattening tensors across different array libraries. The implementation is concise and uses the correct namespace for array operations.


90-100: LGTM: Robust implementation of xp_scatter_sum

This implementation of xp_scatter_sum correctly handles scatter addition operations across different array libraries. The function:

  1. Creates appropriate indices
  2. Uses xp_take_along_axis to extract indices at positions specified by the index tensor
  3. Uses the array-api-extra's at method to perform the actual scatter addition
  4. Preserves the original shape of the input tensor

This is a clean implementation that satisfies the PR objective of implementing scatter_sum functionality.

✨ 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.
    • 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.
  • @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.

@njzjz
Copy link
Member Author

njzjz commented Mar 13, 2025

It seems that array_api_extra only supports Python 3.10...

@njzjz njzjz mentioned this pull request Mar 13, 2025
@njzjz njzjz marked this pull request as draft March 13, 2025 11:00
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