Skip to content

Remove all restrictions to MPI rank zero #353

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

jan-janssen
Copy link
Member

@jan-janssen jan-janssen commented Aug 1, 2025

Summary by CodeRabbit

  • Refactor
    • Simplified data return logic in MPI-related functions, ensuring results are always returned regardless of MPI rank. This change unifies and streamlines the behavior of data extraction and gathering functions for all users.

Copy link

coderabbitai bot commented Aug 1, 2025

Walkthrough

The update modifies the control flow in several functions within pylammpsmpi/mpi/lmpmpi.py by removing explicit checks for MPI.COMM_WORLD.rank == 0. Now, functions always return their results regardless of MPI rank, and data gathering logic is unified and simplified. No function signatures were changed.

Changes

Cohort / File(s) Change Summary
MPI Rank Handling Simplification
pylammpsmpi/mpi/lmpmpi.py
Removed all explicit MPI.COMM_WORLD.rank == 0 checks; functions now return results unconditionally and always gather data without rank-based gating. Helper function _gather_data_from_all_processors simplified accordingly. No changes to function signatures.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

A hop and a skip, the ranks are now free,
No more checks for zero, just pure MPI glee!
Results for all bunnies, no matter the rank,
Data flows smoothly, as easy as a prank.
With code now much cleaner, we leap with delight—
Hooray for the changes that make things so right!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch remove_rank_zero

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 generate unit tests to generate unit tests 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.

Copy link

codecov bot commented Aug 1, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.12%. Comparing base (a8d280c) to head (7234eb5).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #353   +/-   ##
=======================================
  Coverage   81.12%   81.12%           
=======================================
  Files           5        5           
  Lines         551      551           
=======================================
  Hits          447      447           
  Misses        104      104           

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

@jan-janssen jan-janssen mentioned this pull request Aug 1, 2025
Copy link

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a8d280c and 7234eb5.

📒 Files selected for processing (1)
  • pylammpsmpi/mpi/lmpmpi.py (6 hunks)
🔇 Additional comments (16)
pylammpsmpi/mpi/lmpmpi.py (16)

82-83: Verify performance impact of unconditional execution on all ranks.

The removal of rank restrictions means all MPI ranks will now execute job.get_natoms() and process compute data. While this aligns with the PR objective, consider the potential performance overhead of redundant computations across all ranks.


89-89: LGTM - Version information accessible on all ranks.

Making version information available on all MPI ranks is a reasonable change with minimal performance impact.


108-108: LGTM - Settings extraction available on all ranks.

Allowing all ranks to extract settings is consistent with the PR objective and poses minimal risk.


112-112: LGTM - Global data extraction available on all ranks.

Extracting global data on all ranks should be safe since global data is consistent across MPI ranks, though it may result in redundant operations.


116-116: LGTM - Box extraction available on all ranks.

Box information should be consistent across MPI ranks, making this change safe and aligned with the PR objective.


149-149: LGTM - Fix extraction available on all ranks.

Allowing fix data extraction on all ranks is consistent with the overall changes and should be safe.


159-160: LGTM - Variable extraction properly handles both array and scalar cases.

The function correctly uses _gather_data_from_all_processors for array variables while making scalar variables available on all ranks. This maintains data consistency while achieving the PR objective.


170-170: LGTM - Atom count available on all ranks.

The number of atoms should be consistent across ranks, making this change safe and appropriate.


297-297: LGTM - Neighbor list access available on all ranks.

Making neighbor list access available on all ranks is reasonable, though note that each rank may return its local neighbor list data.


301-301: LGTM - Pair neighbor list finding available on all ranks.

This change is consistent with other neighbor list related functions and should be safe.


305-305: LGTM - Fix neighbor list finding available on all ranks.

This change maintains consistency with other neighbor list operations.


309-309: LGTM - Compute neighbor list finding available on all ranks.

This change is consistent with the pattern established for other neighbor list functions.


313-313: LGTM - Neighbor list size available on all ranks.

This change allows all ranks to query neighbor list sizes, which is reasonable and safe.


317-317: LGTM - Neighbor list element access available on all ranks.

Allowing all ranks to access neighbor list elements is consistent with the overall changes.


321-321: LGTM - Thermodynamic data available on all ranks.

Thermodynamic data should be consistent across MPI ranks, making this a safe change that aligns with the PR objective.


431-431: Verify memory implications of replicating gathered data on all ranks.

The helper function now returns gathered data on all ranks instead of just rank 0. While this aligns with the PR objective, it could significantly increase memory usage when large datasets are replicated across all MPI ranks.

Consider the memory footprint impact, especially for large simulations with many atoms or extensive computed data.

Comment on lines +120 to +145
# extract atoms return an internal data type
# this has to be reformatted
name = str(funct_args[0])
if name not in atom_properties:
return []

# this block prevents error when trying to access values
# that do not exist
try:
val = job.extract_atom(name, atom_properties[name]["type"])
except ValueError:
return []
# this is per atom quantity - so get
# number of atoms - first dimension
natoms = job.get_natoms()
# second dim is from dict
dim = atom_properties[name]["dim"]
data = []
if dim > 1:
for i in range(int(natoms)):
dummy = [val[i][x] for x in range(dim)]
data.append(dummy)
else:
data = [val[x] for x in range(int(natoms))]
# this block prevents error when trying to access values
# that do not exist
try:
val = job.extract_atom(name, atom_properties[name]["type"])
except ValueError:
return []
# this is per atom quantity - so get
# number of atoms - first dimension
natoms = job.get_natoms()
# second dim is from dict
dim = atom_properties[name]["dim"]
data = []
if dim > 1:
for i in range(int(natoms)):
dummy = [val[i][x] for x in range(dim)]
data.append(dummy)
else:
data = [val[x] for x in range(int(natoms))]

return np.array(data)
return np.array(data)
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify completeness of atom data across MPI ranks.

The extract_atom function now executes on all ranks, but unlike extract_compute or extract_variable, it doesn't use _gather_data_from_all_processors() to collect data from all ranks. This means each rank will only return its local subset of atoms, potentially leading to incomplete datasets.

Consider whether this function should gather data from all processors or if the current behavior is intentional:


🏁 Script executed:

#!/bin/bash
# Search for other atom extraction functions to compare patterns
rg -A 10 -B 2 "_gather_data_from_all_processors" 

Length of output: 2401


Gather per-atom data across all MPI ranks in extract_atom

The extract_atom implementation in pylammpsmpi/mpi/lmpmpi.py (lines 120–145) currently returns only the local subset of atoms on each MPI rank. To mirror the behavior of extract_compute and extract_variable, you should collect data from all ranks using _gather_data_from_all_processors.

Suggested changes:

• File: pylammpsmpi/mpi/lmpmpi.py
• Function: extract_atom
• Location: just before return np.array(data)

     else:
         data = [val[x] for x in range(int(natoms))]

-    return np.array(data)
+    # gather lists from all ranks into a single list on rank 0
+    data = _gather_data_from_all_processors(data)
+    return np.array(data)

This ensures the root process returns the complete per-atom dataset rather than only its local slice.

📝 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
# extract atoms return an internal data type
# this has to be reformatted
name = str(funct_args[0])
if name not in atom_properties:
return []
# this block prevents error when trying to access values
# that do not exist
try:
val = job.extract_atom(name, atom_properties[name]["type"])
except ValueError:
return []
# this is per atom quantity - so get
# number of atoms - first dimension
natoms = job.get_natoms()
# second dim is from dict
dim = atom_properties[name]["dim"]
data = []
if dim > 1:
for i in range(int(natoms)):
dummy = [val[i][x] for x in range(dim)]
data.append(dummy)
else:
data = [val[x] for x in range(int(natoms))]
# this block prevents error when trying to access values
# that do not exist
try:
val = job.extract_atom(name, atom_properties[name]["type"])
except ValueError:
return []
# this is per atom quantity - so get
# number of atoms - first dimension
natoms = job.get_natoms()
# second dim is from dict
dim = atom_properties[name]["dim"]
data = []
if dim > 1:
for i in range(int(natoms)):
dummy = [val[i][x] for x in range(dim)]
data.append(dummy)
else:
data = [val[x] for x in range(int(natoms))]
return np.array(data)
return np.array(data)
# extract atoms return an internal data type
# this has to be reformatted
name = str(funct_args[0])
if name not in atom_properties:
return []
# this block prevents error when trying to access values
# that do not exist
try:
val = job.extract_atom(name, atom_properties[name]["type"])
except ValueError:
return []
# this is per atom quantity - so get
# number of atoms - first dimension
natoms = job.get_natoms()
# second dim is from dict
dim = atom_properties[name]["dim"]
data = []
if dim > 1:
for i in range(int(natoms)):
dummy = [val[i][x] for x in range(dim)]
data.append(dummy)
else:
data = [val[x] for x in range(int(natoms))]
# gather lists from all ranks into a single list on rank 0
data = _gather_data_from_all_processors(data)
return np.array(data)
🤖 Prompt for AI Agents
In pylammpsmpi/mpi/lmpmpi.py between lines 120 and 145, the extract_atom
function currently returns only the local atom data for each MPI rank. To fix
this, before the line returning np.array(data), call the
_gather_data_from_all_processors function with data as the argument to collect
and combine data from all MPI ranks. This will ensure the root process returns
the complete per-atom dataset instead of just its local portion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant