Skip to content

fix(pd): correct tensor reshaping and indexing #4827

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

Closed
wants to merge 2 commits into from

Conversation

caic99
Copy link
Member

@caic99 caic99 commented Jun 30, 2025

I've encountered some minor problems while trying out Paddle.

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of zero counts in aggregation to prevent division by zero errors.
    • Corrected shape handling in data reshaping operations for more robust processing.
  • New Features

    • Added an option to control index mapping behavior when processing graph data, providing greater flexibility for advanced users.

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 addresses tensor reshaping and indexing issues in the Paddle-based code.

  • Replaces the chained tensor method call with a direct call to paddle.where for bin_count initialization in aggregate.
  • Introduces a new boolean parameter (use_loc_mapping) in get_graph_index to adjust the frame shift computation.
  • Updates reshape calls and modifies how dimensions are extracted in repflow_layer to align tensor operations correctly.

Reviewed Changes

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

File Description
deepmd/pd/model/network/utils.py Uses paddle.where for bin_count and adds use_loc_mapping to control frame shift logic.
deepmd/pd/model/descriptor/repflow_layer.py Updates reshape calls for clarity and changes dimension extraction in forward for indexing.
Comments suppressed due to low confidence (2)

deepmd/pd/model/network/utils.py:105

  • Ensure that the conditional logic for computing frame_shift using 'use_loc_mapping' is clearly documented in the function's docstring, as its behavior significantly affects tensor indexing.
        nall if not use_loc_mapping else nloc

deepmd/pd/model/descriptor/repflow_layer.py:749

  • Changing the dimension unpacking source from 'edge_ebd' to 'nlist' may lead to misaligned dimensions; verify that nlist.shape reliably provides nb, nloc, and nnei as intended.
        nb, nloc, nnei = nlist.shape

Copy link
Contributor

coderabbitai bot commented Jun 30, 2025

📝 Walkthrough

Walkthrough

The changes update tensor manipulation calls to ensure correct argument formatting and improve logic consistency. Shape arguments in reshape are now explicitly tuples. The aggregate function corrects how zero counts are replaced to avoid division by zero. The get_graph_index function introduces a new boolean parameter to control index mapping logic.

Changes

File(s) Change Summary
deepmd/pd/model/descriptor/repflow_layer.py Updated reshape calls to use shape tuples; adjusted shape unpacking in forward method.
deepmd/pd/model/network/utils.py Replaced tensor method .where with paddle.where in aggregate; added use_loc_mapping param to get_graph_index and updated index shift logic.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Utils as utils.py
    Caller->>Utils: get_graph_index(nlist, nlist_mask, a_nlist_mask, nall, use_loc_mapping)
    alt use_loc_mapping is True
        Utils->>Utils: frame_shift = frame * nloc
    else use_loc_mapping is False
        Utils->>Utils: frame_shift = frame * nall
    end
    Utils-->>Caller: graph_index
Loading
sequenceDiagram
    participant Caller
    participant Utils as utils.py
    Caller->>Utils: aggregate(x, bin_index, bin_count)
    Utils->>Utils: bin_count = paddle.where(bin_count == 0, 1, bin_count)
    Utils-->>Caller: aggregated_result
Loading

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/pd/model/descriptor/repflow_layer.py

No files to lint: exiting.

deepmd/pd/model/network/utils.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 f8f01cb and 10a7424.

📒 Files selected for processing (2)
  • deepmd/pd/model/descriptor/repflow_layer.py (5 hunks)
  • deepmd/pd/model/network/utils.py (3 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: njzjz
PR: deepmodeling/deepmd-kit#4144
File: source/api_cc/tests/test_deeppot_dpa_pt.cc:166-246
Timestamp: 2024-10-08T15:32:11.479Z
Learning: Refactoring between test classes `TestInferDeepPotDpaPt` and `TestInferDeepPotDpaPtNopbc` is addressed in PR #3905.
Learnt from: njzjz
PR: deepmodeling/deepmd-kit#4144
File: source/api_cc/tests/test_deeppot_dpa_pt.cc:166-246
Timestamp: 2024-09-19T04:25:12.408Z
Learning: Refactoring between test classes `TestInferDeepPotDpaPt` and `TestInferDeepPotDpaPtNopbc` is addressed in PR #3905.
Learnt from: njzjz
PR: deepmodeling/deepmd-kit#4001
File: deepmd/tf/descriptor/se_a_mask.py:191-191
Timestamp: 2024-07-22T20:17:31.995Z
Learning: When suggesting changes that are correct but out of the scope of the current PR, acknowledge the user's preference and suggest addressing them in a separate PR.
deepmd/pd/model/network/utils.py (2)
Learnt from: njzjz
PR: deepmodeling/deepmd-kit#4160
File: deepmd/dpmodel/utils/env_mat.py:52-64
Timestamp: 2024-09-24T01:59:37.973Z
Learning: Negative indices in `nlist` are properly handled by masking later in the computation, so they do not cause issues in indexing operations.
Learnt from: njzjz
PR: deepmodeling/deepmd-kit#4160
File: deepmd/dpmodel/utils/env_mat.py:52-64
Timestamp: 2024-10-08T15:32:11.479Z
Learning: Negative indices in `nlist` are properly handled by masking later in the computation, so they do not cause issues in indexing operations.
⏰ Context from checks skipped due to timeout of 90000ms (29)
  • GitHub Check: Build wheels for cp311-win_amd64
  • GitHub Check: Build wheels for cp311-manylinux_x86_64
  • GitHub Check: Build wheels for cp310-manylinux_aarch64
  • GitHub Check: Build wheels for cp311-manylinux_x86_64
  • GitHub Check: Build wheels for cp311-macosx_arm64
  • GitHub Check: Build wheels for cp311-macosx_x86_64
  • GitHub Check: Test Python (5, 3.12)
  • GitHub Check: Test Python (6, 3.12)
  • GitHub Check: Test Python (6, 3.9)
  • GitHub Check: Test Python (4, 3.12)
  • GitHub Check: Test Python (5, 3.9)
  • GitHub Check: Test Python (3, 3.9)
  • GitHub Check: Test Python (4, 3.9)
  • GitHub Check: Test Python (3, 3.12)
  • GitHub Check: Test Python (2, 3.9)
  • GitHub Check: Test Python (1, 3.9)
  • GitHub Check: Test Python (1, 3.12)
  • GitHub Check: Test Python (2, 3.12)
  • 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)
  • GitHub Check: Test C++ (true)
  • GitHub Check: Test C++ (false)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (c-cpp)
  • GitHub Check: Build C++ (cuda120, cuda)
  • GitHub Check: Build C++ (cpu, cpu)
  • GitHub Check: Build C++ (rocm, rocm)
  • GitHub Check: Build C++ (clang, clang)
  • GitHub Check: Build C++ (cuda, cuda)
🔇 Additional comments (7)
deepmd/pd/model/descriptor/repflow_layer.py (5)

589-592: LGTM: Improved tensor reshaping syntax.

The change makes the reshape operation more explicit by using a tuple argument, which is the preferred Paddle API usage.


671-673: LGTM: Consistent tensor reshaping syntax.

Same improvement as the previous reshape change - using explicit tuple syntax for better API consistency.


680-680: LGTM: Consistent tensor reshaping syntax.

Another consistent application of the explicit tuple syntax for reshape operations.


901-901: LGTM: Consistent tensor reshaping syntax.

Final consistent application of the explicit tuple syntax for reshape operations.


751-751: Shape unpacking in repflow_layer is correct.

Both edge_ebd and nlist have matching leading dimensions (nb, nloc, nnei), as confirmed by their doc comments and usage across the PT/PD implementations.

• File deepmd/pd/model/descriptor/repflow_layer.py, line 751:
Replaced
nb, nloc, nnei, _ = edge_ebd.shape
with
nb, nloc, nnei = nlist.shape

No further action needed.

deepmd/pd/model/network/utils.py (2)

33-33: LGTM: Improved consistency with functional API.

The change from the tensor method bin_count.where() to the functional paddle.where() call improves consistency and ensures zero counts are properly replaced to avoid division by zero.


54-106: LGTM: Well-designed parameter addition with backward compatibility.

The new use_loc_mapping parameter provides control over index mapping behavior while maintaining backward compatibility with the default value True. The logic change in frame_shift calculation allows for different indexing strategies depending on whether local or extended node mapping is used.

The implementation correctly:

  • Maintains backward compatibility with default use_loc_mapping=True
  • Uses nloc for local mapping and nall for extended mapping
  • Documents the parameter's purpose clearly
✨ 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.

@HydrogenSulfate
Copy link
Collaborator

Thanks, I have made other PR for full modification, I guess this PR can be closed for better review.

#4828

@caic99 caic99 closed this Jun 30, 2025
Copy link

codecov bot commented Jun 30, 2025

Codecov Report

Attention: Patch coverage is 33.33333% with 2 lines in your changes missing coverage. Please review.

Project coverage is 84.57%. Comparing base (f8f01cb) to head (10a7424).

Files with missing lines Patch % Lines
deepmd/pd/model/network/utils.py 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4827      +/-   ##
==========================================
- Coverage   84.57%   84.57%   -0.01%     
==========================================
  Files         699      699              
  Lines       68036    68035       -1     
  Branches     3540     3540              
==========================================
- Hits        57540    57539       -1     
+ Misses       9361     9360       -1     
- Partials     1135     1136       +1     

☔ 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.

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